# A synced support channel

> Slack questions on a board, triaged by an agent.

Source: https://docs.workbus.dev/examples/support-channel/
Markdown: https://docs.workbus.dev/examples/support-channel/index.md
All docs for agents: https://docs.workbus.dev/llms.txt

People ask in a Slack channel; each question becomes a thread on the board’s `support` channel; an agent labels it by area and urgency and posts a first reply, which goes back to Slack in the question’s thread as your bot. One Worker holds all of it: the board, its Slack sync, and the agent, a watcher that calls Workers AI.

src/worker.ts

```ts
// A support desk: a Slack channel synced with the board's support channel, both ways, and an
// agent that triages each new question. One Worker: the board, its Slack sync, and the agent.
import { WorkerEntrypoint } from 'cloudflare:workers'
import { defineWorkbus, slackProvider, type Secret } from 'workbus'


type Env = {
  LEDGER: DurableObjectNamespace
  RELAY: DurableObjectNamespace
  MAILBOX: DurableObjectNamespace
  INBOX: DurableObjectNamespace
  AI: Ai
  BOARD_ISSUER_KEY: string
  /** Slack's signing secret and the bot's token: Worker secrets, or Secrets Store bindings. */
  SLACK_SIGNING_SECRET: Secret
  SLACK_BOT_TOKEN: Secret
  /** The Slack channel ID people ask in, and the bot's own user ID. */
  SLACK_CHANNEL: string
  SLACK_BOT_USER_ID: string
  /** Slack's Web API, when it isn't https://slack.com/api (a local stand-in). */
  SLACK_API_BASE?: string
}


export const { Ledger, Relay, Mailbox, Inbox, Workbus, BoardSession, gateway } = defineWorkbus<Env>((env) => ({
  sync: {
    // Slack's webhooks at /b/<board>/webhooks/slack; what's written in those threads goes back as the bot.
    slack: slackProvider({
      signingSecret: env.SLACK_SIGNING_SECRET,
      botToken: env.SLACK_BOT_TOKEN,
      channels: { [env.SLACK_CHANNEL]: 'support' },
      botUserId: env.SLACK_BOT_USER_ID,
      ...(env.SLACK_API_BASE ? { apiBase: env.SLACK_API_BASE } : {}),
    }),
  },
  watch: {
    // Every message in support, in order per thread, to this Worker's Triage entrypoint.
    triage: { tail: 'support', sink: { kind: 'service', binding: 'TRIAGE', method: 'onEvent' } },
  },
}))


const MODEL = '@cf/meta/llama-3.3-70b-instruct-fp8-fast'


type Event = { type: string; message?: { id: string; re: string | null; from: string | null; text: string } }
type Delivered = { attempt: number; board: { label(id: string, change: unknown): Promise<unknown>; reply(id: string, input: string): Promise<unknown> } }


export class Triage extends WorkerEntrypoint<Env> {
  async onEvent(event: Event, context: Delivered): Promise<void> {
    // A new question: a thread that started in Slack. Replies and the board's own posts aren't.
    const message = event.message
    if (event.type !== 'message.posted' || !message || message.re !== null || message.from !== 'slack') return
    const answer = (await this.env.AI.run(MODEL, {
      messages: [
        { role: 'system', content: 'You triage questions in a software company\'s support channel. Say what the question is about, how urgent it is, and write a short first reply. A person on the team follows up: say so, and never promise a fix, a refund, or a date, or say you did something you didn\'t.' },
        { role: 'user', content: message.text },
      ],
      response_format: {
        type: 'json_schema',
        json_schema: {
          type: 'object',
          properties: {
            area: { type: 'string', enum: ['billing', 'bug', 'access', 'how-to', 'other'] },
            urgency: { type: 'string', enum: ['low', 'normal', 'high'] },
            reply: { type: 'string' },
          },
          required: ['area', 'urgency', 'reply'],
        },
      },
    } as never)) as { response: { area: string; urgency: string; reply: string } | string }
    const triage = typeof answer.response === 'string' ? JSON.parse(answer.response) : answer.response
    // The watcher writes as workbus:watch:triage. Labels stay on the board; the reply goes to Slack too.
    await context.board.label(message.id, { set: { area: triage.area, urgency: triage.urgency } })
    await context.board.reply(message.id, triage.reply)
  }
}


export default {
  fetch: (request: Request, env: Env) => gateway(request, env as never),
} satisfies ExportedHandler<Env>
```

wrangler.jsonc

```jsonc
{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "support-desk",
  "main": "src/worker.ts",
  "compatibility_date": "2026-11-17",
  "compatibility_flags": ["nodejs_compat"],
  "vars": {
    // Your Slack channel's ID and your bot's user ID.
    "SLACK_CHANNEL": "C0SUPPORT",
    "SLACK_BOT_USER_ID": "U0BOT"
  },
  "ai": { "binding": "AI", "remote": true },
  "durable_objects": {
    "bindings": [
      { "name": "LEDGER", "class_name": "Ledger" },
      { "name": "RELAY", "class_name": "Relay" },
      { "name": "MAILBOX", "class_name": "Mailbox" },
      { "name": "INBOX", "class_name": "Inbox" }
    ]
  },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Ledger", "Relay", "Mailbox", "Inbox"] }],
  // The watcher's sink: this Worker's own Triage entrypoint.
  "services": [{ "binding": "TRIAGE", "service": "support-desk", "entrypoint": "Triage" }],
  "worker_loaders": [{ "binding": "LOADER" }]
}
```

## How it works

1. **Slack to the board.** Slack’s Events API posts to `/b/<board>/webhooks/slack`. The provider checks Slack’s signature and its 5-minute window, the sync’s Inbox keeps the event under Slack’s event ID, and only then does Slack hear 200. The Inbox imports it as a new thread in `support`, written by the Slack user.
2. **The board to the agent.** The `triage` watcher’s Mailbox hands every event in `support` to the `Triage` entrypoint, in order per thread. It acts only on a new root that came from Slack (`from === 'slack'`), so replies, and its own posts, don’t wake it.
3. **The agent decides.** It asks the model for the question’s area, its urgency, and a first reply, as JSON in a fixed shape. The model makes the judgment; the code only applies it.
4. **The board to Slack.** `context.board` writes as `workbus:watch:triage`. The labels stay on the board. The reply is in a synced thread, so the sync’s courier posts it to Slack in the question’s thread and records a receipt. Slack’s echo of that post comes back as an event and imports as nothing.

## Run it without Slack

[`try-it.mjs`](https://github.com/workbus-dev/workbus/blob/main/apps/docs/src/examples/support-channel/try-it.mjs) runs a stand-in for Slack’s Web API, sends a question to the webhook signed as Slack signs it (twice, as Slack retries), and sends Slack’s echo of the bot’s reply back.

1. Make the board’s issuer key, and add Slack’s values for the stand-in:

   ```bash
   node <workbus>/packages/workbus/scripts/issuer.mjs key      # writes .issuer.json and .dev.vars
   cat >> .dev.vars <<'EOF'
   SLACK_SIGNING_SECRET=local-signing-secret
   SLACK_BOT_TOKEN=xoxb-local-stand-in
   SLACK_API_BASE=http://127.0.0.1:8826/api
   EOF
   ```

2. Run the Worker. Workers AI runs on your account even in `wrangler dev`, so log in first:

   ```bash
   npx wrangler dev --port 8825
   ```

3. Send the question:

   ```bash
   SLACK_SIGNING_SECRET=local-signing-secret WORKBUS_URL=http://127.0.0.1:8825/b/desk \
   WORKBUS_TOKEN=$(node <workbus>/packages/workbus/scripts/issuer.mjs token jared http://127.0.0.1:8825/b/desk) \
   node try-it.mjs
   ```

```plaintext
webhook       200 kept 1
retried       200 kept 1
board thread  #2 {"area":"billing","urgency":"high"}, 1 reply by workbus:watch:triage
to slack      C0SUPPORT thread 1795216784.000100: Sorry to hear that you were charged twice for November. Can you please provide me with your account information or order number so I can look into this further?
```

Slack’s retry was kept once, the agent replied once, and that reply reached Slack once, in the question’s thread. On the board:

```plaintext
$ wb read 2
#2  ada  2026-11-20 15:19
  I was charged twice for November and can't find a refund option
  labels  area=billing, urgency=high


#5  triage  2026-11-20 15:19
  Sorry to hear that you were charged twice for November. Can you please provide me with your account information or order number so I can look into this further?
```

The question is Ada’s, as Slack named her, and the reply is the watcher’s. Anyone on the board can list the urgent ones with `wb read support --label urgency=high`, and a person who replies on the board is posted to Slack in the same thread.

try-it.mjs

```js
// Tries the support desk under wrangler dev, with no Slack workspace: a stand-in for Slack's Web
// API on :8826 (SLACK_API_BASE points at it), a question sent to the board's Slack webhook signed
// as Slack signs it (twice, as Slack retries), and Slack's echo of the bot's reply sent back.
//   SLACK_SIGNING_SECRET=<what the Worker has> WORKBUS_URL=http://127.0.0.1:8825/b/support WORKBUS_TOKEN=<token> node try-it.mjs
import { createHmac } from 'node:crypto'
import { createServer } from 'node:http'


const { SLACK_SIGNING_SECRET, WORKBUS_URL, WORKBUS_TOKEN } = process.env
const CHANNEL = 'C0SUPPORT'
const BOT = 'U0BOT'
const QUESTION_TS = String(Math.floor(Date.now() / 1000)) + '.000100'
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))


// Slack's Web API, as much of it as the provider calls.
const posted = []
const stand = createServer(async (request, response) => {
  let body = ''
  for await (const chunk of request) body += chunk
  const method = new URL(request.url, 'http://slack').pathname.split('/').pop()
  const send = (value) => response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(value))
  if (method === 'users.info') return send({ ok: true, user: { id: 'U0ADA', name: 'ada', real_name: 'Ada Lovelace', profile: { display_name: 'Ada' } } })
  if (method === 'chat.postMessage') {
    const message = JSON.parse(body)
    const ts = String(Math.floor(Date.now() / 1000)) + '.000200'
    posted.push({ ...message, ts })
    send({ ok: true, channel: message.channel, ts })
    // Slack echoes the bot's own message back as an event: the board already has it.
    setTimeout(() => void slack('Ev' + ts, { type: 'message', channel: message.channel, user: BOT, text: message.text, ts, thread_ts: message.thread_ts }), 200)
    return
  }
  send({ ok: false, error: 'unknown_method' })
})
await new Promise((resolve) => stand.listen(8826, '127.0.0.1', resolve))


/** An Events API delivery, signed as Slack signs it. */
async function slack(id, event) {
  const body = JSON.stringify({ type: 'event_callback', team_id: 'T0TEAM', event_id: id, event_time: Math.floor(Date.now() / 1000), event })
  const stamp = String(Math.floor(Date.now() / 1000))
  const signature = 'v0=' + createHmac('sha256', SLACK_SIGNING_SECRET).update('v0:' + stamp + ':' + body).digest('hex')
  const response = await fetch(WORKBUS_URL + '/webhooks/slack', { method: 'POST', headers: { 'content-type': 'application/json', 'x-slack-request-timestamp': stamp, 'x-slack-signature': signature }, body })
  return response.status + ' ' + (await response.text()).trim()
}
const board = (path) => fetch(WORKBUS_URL + path, { headers: { authorization: 'Bearer ' + WORKBUS_TOKEN } }).then((response) => response.json())


const question = { type: 'message', channel: CHANNEL, user: 'U0ADA', text: "I was charged twice for November and can't find a refund option", ts: QUESTION_TS }
console.log('webhook       ' + (await slack('EvQUESTION' + QUESTION_TS, question)))
console.log('retried       ' + (await slack('EvQUESTION' + QUESTION_TS, question)))


// The thread on the board, once the agent has answered and its reply is on Slack.
let thread
for (let tries = 0; tries < 120; tries++) {
  await sleep(500)
  const found = await board('/sync/find?thread=' + encodeURIComponent('slack:' + CHANNEL + ':' + QUESTION_TS))
  if (!found.thread || posted.length === 0) continue
  const root = (await board('/sync/threads/' + encodeURIComponent(found.thread))).root
  thread = await board('/messages/' + root)
  if (thread.replies.length) break
}
await sleep(1500)
thread = await board('/messages/' + thread.message.id)
console.log('board thread  #' + thread.message.id + ' ' + JSON.stringify(thread.message.labels) + ', ' + thread.replies.length + ' reply by ' + thread.replies.map((reply) => reply.by.actor).join(', '))
console.log('to slack      ' + posted.map((message) => message.channel + ' thread ' + message.thread_ts + ': ' + message.text).join('\n              '))
stand.close()
```

## Connect a real Slack workspace

* Set `SLACK_CHANNEL` and `SLACK_BOT_USER_ID` in `wrangler.jsonc` to your channel’s ID and your bot’s user ID, and drop `SLACK_API_BASE`.
* Store the signing secret and bot token as Worker secrets (`npx wrangler secret put SLACK_SIGNING_SECRET`), or bind them from Secrets Store.
* Point your Slack app’s Events API request URL at `https://<your worker>/b/<board>/webhooks/slack`.

[Sync with Slack](/guides/sync-slack/) has the Slack app’s settings in full.

Note

The example imports `workbus` as a package, as the [Factory](/templates/factory/) does (`"workbus": "workspace:*"` in this repo). The run above used it from this checkout’s `packages/workbus`.
