Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 90 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,92 @@
# ai-slackbot

[Vercel's AI SDK Slackbot](https://github.com/vercel-labs/ai-sdk-slackbot) on
**Cloudflare Workers**, deployed by [Orun](https://github.com/sourceplane/orun) to stage
and prod on every merge, and then packaged as an Orun baseline.

This commit is the repository's frame: `intent.yaml` (with the placeholder
workspace `ws_CHANGE_ME`, so CI plans nothing until it is linked), the Orun
CI workflow, the shared TypeScript and ESLint configuration, and the spec
index. The work is tracked as an epic under [`specs/epics`](specs/epics/README.md).
Vercel's [AI SDK Slackbot](https://github.com/vercel-labs/ai-sdk-slackbot)
template — an AI chatbot for Slack that answers app mentions and direct
messages with an LLM and tools (weather, dice, a sandboxed bash, web search),
every tool call gated by an Open Policy Agent policy compiled to WebAssembly —
running natively as a **Cloudflare Worker**, deployed by
[Orun](https://github.com/sourceplane/orun) to stage and prod on every merge.
Packaging it as an Orun baseline is the next milestone (SB2).

Upstream's `api/events.ts` (a Vercel function) is a [Hono](https://hono.dev)
route here, at the same path: Hono's `fetch` handler is the Worker's, no
adapter. It verifies Slack's signature with WebCrypto before anything else,
acknowledges at once and answers in `waitUntil`. The model is Workers AI
through the Worker's own `AI` binding, so a fresh bot needs no AI key;
upstream's OpenAI is used, directly, once its key is stored. The policy, the
agent loop and the tools are upstream's. The bot is born **not connected**: it
deploys and `/api/events` says so until its owner creates a Slack app and
stores its two keys. See
[`specs/epics/ai-slackbot`](specs/epics/ai-slackbot/README.md) for the
design, the milestones and the as-built status.

## What is here (the product)

| Surface | Where |
|---|---|
| The routes — Slack's events at `POST /api/events`; `GET /` a JSON welcome, `GET /health` the bot's name, environment and what it is connected to | `apps/api/src/index.ts` |
| Slack: the signature check, the client, mentions, assistant threads and DMs | `apps/api/src/lib/slack-utils.ts`, `apps/api/src/lib/handle-*.ts` |
| The agent, its tools and the model | `apps/api/src/lib/run-agent.ts`, `generate-response.ts`, `model.ts` |
| The tool-call policy (Rego, and the WASM the Worker bundles) and its loader | `apps/api/policies/`, `apps/api/src/lib/policy/` |
| just-bash's browser build for the Worker | `apps/api/src/vendor/just-bash.js` (`wrangler.jsonc` → `alias`) |
| The bot's name (the rename's seam; what `/` and `/health` answer with) | `apps/api/src/identity.ts` |
| The template's licence (MIT, as its README declares) | `apps/api/LICENSE.md` |
| Worker config (name, Workers AI binding, per-environment vars) | `apps/api/wrangler.jsonc` |
| Deploy contract (and the keys it pushes as Worker secrets) | `apps/api/component.yaml` (`cloudflare-worker-turbo`) |
| Tests | `tests/api` (vitest: the routes and Slack's events in-process against stand-ins for Slack and Workers AI, the signature check, every policy rule) |

## Getting started

```bash
pnpm install
pnpm typecheck
pnpm lint
pnpm test
pnpm build # wrangler deploy --dry-run → apps/api/dist (the bundle, no upload)
```

Run the Worker locally under workerd (Workers AI has no local mode, so
`wrangler dev` needs `wrangler login`; Slack's two keys go in
`apps/api/.dev.vars`):

```bash
pnpm --filter @app/api dev # http://localhost:8787
curl http://localhost:8787/health # {"status":"ok","name":"AI SDK Slackbot","environment":"local","slack":…}
```

Connecting Slack: create a Slack app, put its signing secret and bot token in
`apps/api/.dev.vars` for local work (or store them as the environment's Orun
secrets and redeploy), and set its Request URL to the Worker's `/api/events`.

## How it maps to Vercel

| Vercel | Here |
|---|---|
| `api/events.ts`, a Vercel function | A Hono route at the same path, `POST /api/events`, on a plain Worker: `export default app` is the module handler; wrangler bundles `src/index.ts` with `nodejs_compat` |
| `waitUntil` from `@vercel/functions`, `maxDuration: 60` | The Worker's own `c.executionCtx.waitUntil`, after an immediate acknowledgement. A Worker keeps that work alive for about 30 s after the response, not 60 |
| Slack's signature checked with `node:crypto` — and the result dropped (`verifyRequest` returned a 400 nobody returned), the URL verification answered before it | WebCrypto HMAC-SHA256 over `v0:<ts>:<body>`, a constant-time compare and a five-minute window, checked FIRST for every request, the challenge included; a refusal is a 400 before any work |
| The bot's own id (`auth.test`) looked up before acknowledging | Looked up after, in the background, so Slack's 3 s go to the acknowledgement |
| Slack's retries (`X-Slack-Retry-Num`) handled as new events | Acknowledged (`X-Slack-No-Retry: 1`) and not answered again |
| `process.env` read at import; one `WebClient` per process | The Worker's secrets per request; a `WebClient` per event |
| OpenAI `gpt-4o` by default (`OPENAI_API_KEY`), or a local Ollama | Workers AI (`@cf/moonshotai/kimi-k2.6`) through the `AI` binding by default, no key; OpenAI directly once `OPENAI_API_KEY` is stored. Ollama is not carried: a Worker cannot reach `localhost` |
| AI SDK 7 canaries (`ai` 7.0.0-canary.164, `@ai-sdk/policy-opa` 1.0.0-canary.1, `@ai-sdk/openai` 4.0.0-canary.67) | Their stable releases (`ai` 7.0.155, `@ai-sdk/policy-opa` 1.0.155, `@ai-sdk/openai` 4.0.104), which `workers-ai-provider` 4 supports |
| `policies/policy.wasm` read from disk (`node:fs`) and compiled at runtime | Imported as a `WebAssembly.Module` that wrangler compiles at upload — a Worker refuses to compile bytes at runtime |
| `bash-tool` over `just-bash`'s Node build | The same `bash-tool`, over `just-bash`'s browser build (`src/vendor/just-bash.js`): the Node build's `python3`/`js` commands need `worker_threads` and its decompressors native addons. Two classes only bash-tool's opt-in tee transform uses are stubs that refuse |
| `searchWeb` always offered (Exa) | Offered, and named in the prompt, only when `EXA_API_KEY` is stored |
| `/` redirected to the template's GitHub repository | A JSON welcome naming the bot and its endpoints |
| Env vars in the Vercel project | Orun secrets per environment, pushed to the Worker as Worker secrets after each deploy (`runtimeSecrets`) |
| `vc dev` · `vc deploy` | `wrangler dev` · `wrangler deploy --env <stage\|prod>` |
| Deploy on push | Orun deploys `<repo>-api-{stage,prod}` on merge to `main` and smoke-tests `/health` and the signed events door (`apps/api/component.yaml`) |

## CI

| Workflow | What it runs | Ships to a bot |
|---|---|---|
| `ci.yml` | the Orun pipeline, and the only workflow a bot carries: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes (the Worker built, type-checked and dry-deployed per environment; the tests' `quick-check` lane installs and checks the package, it does not run them), except the bootstrap's own landings (`orun/BASE-*`), where `plan` alone is the check; a merge deploys stage → prod. It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does. A manual run (Orunbase's Deploy button, or Run workflow on `main`) plans the environment and components it names under the push-to-main trigger, so they deploy as a merge deploys them | yes |

## Credits

The bot is Vercel's AI SDK Slackbot template
([vercel-labs/ai-sdk-slackbot](https://github.com/vercel-labs/ai-sdk-slackbot),
MIT as its README declares; the repository has no LICENSE file —
`apps/api/LICENSE.md`).
26 changes: 26 additions & 0 deletions apps/api/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
The bot in this directory is ported from Vercel's AI SDK Slackbot template,
[vercel-labs/ai-sdk-slackbot](https://github.com/vercel-labs/ai-sdk-slackbot).
That repository ships no LICENSE file; its README declares its licence as MIT
("## License — MIT"). Those terms follow, for the template's code here.

MIT License

Copyright (c) the ai-sdk-slackbot authors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
100 changes: 100 additions & 0 deletions apps/api/component.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
apiVersion: sourceplane.io/v1
kind: Component
metadata:
name: api
description: The AI SDK Slackbot — Slack's Events API at /api/events on a plain Cloudflare Worker, answering with Workers AI and policy-gated tools (per environment)
spec:
type: cloudflare-worker-turbo
lifecycle: production
owner: platform
# Its pages, attached to it in the workspace's catalog: what the Docs
# library shows for it, and what the catalog's docs and runbook checks read.
# Generated from what this manifest and its sources declare.
docs:
overview: docs/overview.md
pages:
- { path: docs/architecture.md, role: architecture, title: Architecture }
- { path: docs/runbook.md, role: runbook, title: Runbook }
# `app`, not `api`: a domain and a component share one name space in the
# catalog, and a domain called `api` would take this component's place in
# it — the API missing from its own catalog.
domain: app
path: apps/api
# No dependsOn: the bot reads no wiring and binds nothing Terraform makes —
# its one binding, Workers AI (wrangler.jsonc), is the account's own.
#
# The bot's keys, stored per environment as the product's secrets of the
# same names (README → Connect Slack). The Worker reads them at request time
# (src/env.ts), so no build ever sees one: the composition's secrets-live
# step hands those that are set to the Worker as Worker SECRETS after the
# deploy (runtimeSecrets below). BEST-EFFORT references,
# wire-now-seed-later: a key nobody has stored is skipped when the job
# resolves its secrets (no env var, no failure), so a fresh product deploys,
# answers /health and says on /api/events that Slack is not connected,
# before its owner has created a Slack app at all.
optionalSecretEnv:
SLACK_SIGNING_SECRET: "secret://ai-slackbot/ai-slackbot/{{ .environment }}/SLACK_SIGNING_SECRET"
SLACK_BOT_TOKEN: "secret://ai-slackbot/ai-slackbot/{{ .environment }}/SLACK_BOT_TOKEN"
OPENAI_API_KEY: "secret://ai-slackbot/ai-slackbot/{{ .environment }}/OPENAI_API_KEY"
OPENAI_MODEL: "secret://ai-slackbot/ai-slackbot/{{ .environment }}/OPENAI_MODEL"
EXA_API_KEY: "secret://ai-slackbot/ai-slackbot/{{ .environment }}/EXA_API_KEY"
subscribe:
environments:
- name: dev
profile: verify
- name: stage
profile: verify
profileRules:
- profile: deploy
when:
triggerRef: github-push-main
- name: prod
profile: verify
profileRules:
- profile: deploy
when:
triggerRef: github-push-main
parameters:
nodeVersion: "22"
pnpmVersion: "10.12.1"

workspaceDir: ../..
appDir: .

turboFilter: "@app/api"
# Committed, not rendered: the Worker's one binding (Workers AI) has no
# resource ID to wire, and the lanes' structure check (`test -f`, before
# any build) finds it in a fresh checkout. Per-env names come from `--env`:
# ai-slackbot-api-{stage,prod}.
wranglerConfig: wrangler.jsonc

installCommand: pnpm install --frozen-lockfile
buildCommand: pnpm exec turbo run build --filter=@app/api
typecheckCommand: pnpm exec turbo run typecheck --filter=@app/api

dryRunCommand: pnpm exec wrangler deploy --dry-run --config wrangler.jsonc --env prod
deployCommand: pnpm exec wrangler deploy --config wrangler.jsonc --env prod

# The keys secrets-live pushes as Worker secrets after each deploy — the
# ones the environment has stored, named only in the log, never a value.
runtimeSecrets: SLACK_SIGNING_SECRET,SLACK_BOT_TOKEN,OPENAI_API_KEY,OPENAI_MODEL,EXA_API_KEY

preDeployCommand: "echo 'No pre-deploy step configured.'"
migrationCommand: "echo 'No migrations configured.'"
# Smoke: /health answers `"status":"ok"` for THIS environment — the
# environment comes from the `env.<name>` vars the deploy used, so a stale
# or wrong Worker fails it — and then Slack's door: POST /api/events with
# no signature must be REFUSED, a 400 once Slack is connected or a 503
# before (never a 500, never a 200 — a door that answers an unsigned event
# would answer a forged one). Not the bot's name, which is the owner's to
# change. The Worker composition exports no deployed URL, so the command
# names its own workers.dev URL; ${DEPLOYED_URL} overrides it (a custom
# domain, or a local `wrangler dev`). ${ORUN_ENVIRONMENT} the runner sets
# for every step. Each body is buffered before grep so an early match
# cannot SIGPIPE curl.
smokeCommand: 'base="${DEPLOYED_URL:-https://ai-slackbot-api-${ORUN_ENVIRONMENT}.your-workers-subdomain.workers.dev}" && health="$(curl -sf --max-time 20 "${base}/health")" && echo "${health}" | grep -q "\"status\":\"ok\"" && echo "${health}" | grep -q "\"environment\":\"${ORUN_ENVIRONMENT}\"" && code="$(curl -s -o /dev/null -w "%{http_code}" --max-time 20 -X POST "${base}/api/events" -H "content-type: application/json" -d "{\"type\":\"url_verification\",\"challenge\":\"orun-smoke\"}")" && case "${code}" in 400|503) ;; *) echo "POST /api/events without a signature answered ${code}, not 400 or 503" >&2; false ;; esac'
labels:
team: platform
layer: runtime
surface: api
runtime: cloudflare
28 changes: 28 additions & 0 deletions apps/api/docs/architecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# api — architecture

Built by the turbo pipeline from `apps/api` and deployed with wrangler.

| | |
| ------------------- | ------------------------- |
| Worker config | `apps/api/wrangler.jsonc` |
| Entry | `src/index.ts` |
| Compatibility date | `2026-10-01` |
| Compatibility flags | `nodejs_compat` |

## Bindings

| Binding | Kind | Source |
| ------- | ---------- | --------------------------------------- |
| `AI` | Workers AI | account-level; no resource to provision |

## Variables

`ENVIRONMENT` — overridden per environment (`dev`, `prod`, `stage`).

## Secrets resolved by the lane (names only)

- `EXA_API_KEY` (optional)
- `OPENAI_API_KEY` (optional)
- `OPENAI_MODEL` (optional)
- `SLACK_BOT_TOKEN` (optional)
- `SLACK_SIGNING_SECRET` (optional)
20 changes: 20 additions & 0 deletions apps/api/docs/overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# api

The AI SDK Slackbot — Slack's Events API at /api/events on a plain Cloudflare Worker, answering with Workers AI and policy-gated tools (per environment)

A Cloudflare Worker, deployed per environment by its CI lane.

| | |
| ------------ | ------------------------------------------------------------------------------------------------------------------ |
| Type | `cloudflare-worker-turbo` |
| Source | `apps/api` |
| Package | `@app/api` |
| Environments | `dev`: `verify` · `stage`: `verify`, `deploy` on a push to `main` · `prod`: `verify`, `deploy` on a push to `main` |

## Depends on

- (none)

## Depended on by

- (none)
36 changes: 36 additions & 0 deletions apps/api/docs/runbook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# api — runbook

## How it runs

Pull requests verify it; a merge to `main` deploys it to `stage`, `prod`.
CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`;
the plan orders a component after everything it depends on.

## Local commands

```bash
pnpm --filter @app/api dev
pnpm --filter @app/api build
pnpm --filter @app/api typecheck
pnpm --filter @app/api lint
```

## Verify

After a deploy the lane runs this smoke against the environment it
deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL:

```bash
base="${DEPLOYED_URL:-https://ai-slackbot-api-${ORUN_ENVIRONMENT}.your-workers-subdomain.workers.dev}" && health="$(curl -sf --max-time 20 "${base}/health")" && echo "${health}" | grep -q "\"status\":\"ok\"" && echo "${health}" | grep -q "\"environment\":\"${ORUN_ENVIRONMENT}\"" && code="$(curl -s -o /dev/null -w "%{http_code}" --max-time 20 -X POST "${base}/api/events" -H "content-type: application/json" -d "{\"type\":\"url_verification\",\"challenge\":\"orun-smoke\"}")" && case "${code}" in 400|503) ;; *) echo "POST /api/events without a signature answered ${code}, not 400 or 503" >&2; false ;; esac
```

## Rollback

Revert the commit on `main`. The next convergence applies the previous desired
state; nothing was changed out of band, so there is nothing else to undo.

## Common failures

- **The smoke fails right after a first deploy**: a new workers.dev route can
answer 4xx for a few seconds and the lane retries. A failure that persists
is a regression in the deployed code.
2 changes: 2 additions & 0 deletions apps/api/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import config from "../../tooling/eslint/index.js";
export default config;
36 changes: 36 additions & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "@app/api",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "wrangler dev",
"build": "wrangler deploy --dry-run --outdir dist",
"deploy": "wrangler deploy",
"typecheck": "tsc --noEmit",
"lint": "eslint src",
"policy:build": "opa build -t wasm -e agent/call/decision -o policies/bundle.tar.gz policies/decision.rego && tar -xzf policies/bundle.tar.gz -C policies /policy.wasm && rm policies/bundle.tar.gz",
"policy:test": "opa test policies/"
},
"dependencies": {
"@ai-sdk/openai": "4.0.104",
"@ai-sdk/policy-opa": "1.0.155",
"@open-policy-agent/opa": "2.0.0",
"@open-policy-agent/opa-wasm": "1.10.0",
"@slack/web-api": "7.16.0",
"ai": "7.0.155",
"bash-tool": "1.3.17",
"exa-js": "1.10.3",
"hono": "^4.13.0",
"just-bash": "3.0.1",
"workers-ai-provider": "4.0.1",
"zod": "4.4.3"
},
"devDependencies": {
"@app/eslint-config": "workspace:*",
"@app/tsconfig": "workspace:*",
"@cloudflare/workers-types": "^5.20261006.1",
"typescript": "^5.8.3",
"wrangler": "^4.151.0"
}
}
Loading
Loading