Skip to content

Commit 76a2019

Browse files
committed
feat(sdk,slack): webhook sources, agent channels, and human-in-the-loop
1 parent 656541f commit 76a2019

26 files changed

Lines changed: 2940 additions & 12 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
"@trigger.dev/core": minor
3+
"@trigger.dev/sdk": minor
4+
"@trigger.dev/slack": minor
5+
"trigger.dev": minor
6+
---
7+
8+
Add hosted webhooks: receive and verify provider webhooks as a task, with no ingress or verification code of your own.
9+
10+
- `webhook()` declares an endpoint that routes a verified, typed event to an `onEvent` handler. Choose a source with a preset (`webhooks.stripe()`, `webhooks.github()`, and others) or `webhooks.custom<T>(config)`. Declared webhooks are discovered like tasks and synced to a hosted URL on deploy.
11+
- `filter` gates which deliveries run, using a type-safe expression checked against the event at author time (`event.`/`header.`/`webhook.` paths, `&&`/`||`, comparison and `in`/`contains` operators, field-to-field comparison, and array quantifiers). A non-matching delivery is still recorded, not routed.
12+
- `chat.event({ source, key, type })` routes deliveries that share a `key` to one durable session (per customer, installation, or issue) and delivers them to an agent's `onAction` as a typed envelope.
13+
- Channels turn a chat surface into an agent frontend: `chat.channels.custom({ source, key, inbound, send })`, or the new `@trigger.dev/slack` package's `slack()` (Slack Events API verification, per-thread sessions, `chat.postMessage`/`chat.update` egress, `mentions()`, `startOn`, lifecycle reactions). Inbound messages run as turns and the reply posts back. Human-in-the-loop is built in: a tool with no `execute` pauses the turn, the connector posts controls (Slack ships Approve / Deny buttons), and a verified click resolves the tool and resumes the run.
14+
- HTTP API for listing webhook endpoints and deliveries, plus rotate-secret, enable/disable, and replay.

docs/ai-chat/backend.mdx

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,37 @@ Custom actions let the frontend send structured commands (undo, rollback, edit,
470470

471471
See [Actions](/ai-chat/actions).
472472

473+
### Webhook events and channels
474+
475+
Two `chat.agent()` options wire an agent to verified inbound webhooks. `events` claims [`chat.event(...)`](/webhooks/session-routing) descriptors: each verified delivery is routed to this agent's session and arrives at `onAction` as an action (not a turn), so [session routing](/webhooks/session-routing) decides which conversation it lands on. `channels` claims channel connectors that turn an external chat surface into a frontend for the agent: an inbound message runs as a turn through `run()` and the reply is posted back. `slack()` ships in `@trigger.dev/slack`, and `chat.channels.custom(...)` builds a connector for any source without a preset.
476+
477+
```ts
478+
import { webhooks } from "@trigger.dev/sdk";
479+
import { chat } from "@trigger.dev/sdk/ai";
480+
import { slack } from "@trigger.dev/slack";
481+
482+
export const orderEvents = chat.event({
483+
id: "order-events",
484+
source: webhooks.stripe(),
485+
key: "{body.data.object.customer}",
486+
type: "order.event",
487+
});
488+
489+
export const myChat = chat.agent({
490+
id: "my-chat",
491+
events: [orderEvents],
492+
channels: [slack({ id: "support-slack", token: process.env.SLACK_BOT_TOKEN! })],
493+
onAction: async ({ action }) => {
494+
// A verified order-events delivery arrives here as an action.
495+
},
496+
run: async (payload) => {
497+
// Inbound Slack messages run here as normal turns.
498+
},
499+
});
500+
```
501+
502+
See [session routing](/webhooks/session-routing) and [channels](/webhooks/channels). For the interactive approvals layer, where a turn pauses on a human decision (buttons in the thread) and resumes on the click, see [human-in-the-loop](/webhooks/human-in-the-loop).
503+
473504
### Chat history
474505

475506
Imperative API for reading and modifying the accumulated message history. Works from any hook (`onAction`, `onTurnStart`, `onBeforeTurnComplete`, `onTurnComplete`, `hydrateMessages`) or from `run()` and AI SDK tools.

docs/ai-chat/reference.mdx

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ Options for `chat.agent()`.
4747
| `hydrateMessages` | `(event: HydrateMessagesEvent) => UIMessage[] \| Promise<UIMessage[]>` || Load message history from backend, replacing the linear accumulator. See [hydrateMessages](/ai-chat/lifecycle-hooks#hydratemessages) |
4848
| `actionSchema` | `TaskSchema` || Schema for validating custom actions sent via `transport.sendAction()`. See [Actions](/ai-chat/actions) |
4949
| `onAction` | `(event: ActionEvent) => Promise<unknown> \| unknown` || Handle custom actions. Actions are not turns — only `hydrateMessages` + `onAction` fire. Return a `StreamTextResult` (or `string` / `UIMessage`) for a model response; return `void` for side-effect-only. See [Actions](/ai-chat/actions) |
50+
| `events` | `ChatEvent[]` || Webhook event descriptors (from `chat.event()`) whose verified deliveries are routed to this agent as actions and handled in `onAction`. See [session routing](/webhooks/session-routing). |
51+
| `channels` | `ChannelConnector[]` || Channel connectors (for example `slack()`) that turn an external chat surface into a frontend for the agent: inbound messages run as turns and the reply posts back. See [channels](/webhooks/channels). |
5052
| `onTurnStart` | `(event: TurnStartEvent) => Promise<void> \| void` || Fires every turn before `run()` |
5153
| `onBeforeTurnComplete` | `(event: BeforeTurnCompleteEvent) => Promise<void> \| void` || Fires after response but before stream closes. Includes `writer`. |
5254
| `onTurnComplete` | `(event: TurnCompleteEvent) => Promise<void> \| void` || Fires after each turn completes (stream closed) |
@@ -501,6 +503,8 @@ All methods available on the `chat` object from `@trigger.dev/sdk/ai`.
501503
| Method | Description |
502504
| ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
503505
| `chat.agent(options)` | Create a chat agent |
506+
| `chat.event(options)` | Declare an inbound webhook event descriptor an agent claims via `chat.agent({ events })`. See [session routing](/webhooks/session-routing). |
507+
| `chat.channels.custom(options)` | Create a generic chat-frontend channel over any verified webhook source (you supply the egress). The `slack()` preset ships in `@trigger.dev/slack`. See [channels](/webhooks/channels). |
504508
| `chat.createSession(payload, options)` | Create an async iterator for chat turns |
505509
| `chat.pipe(source, options?)` | Pipe a stream to the frontend (from anywhere inside a task) |
506510
| `chat.pipeAndCapture(source, options?)` | Pipe and capture the response; returns `{ message, status, error }` |
@@ -530,6 +534,42 @@ All methods available on the `chat` object from `@trigger.dev/sdk/ai`.
530534
| `chat.withUIMessage(config?)` | Returns a [ChatBuilder](/ai-chat/types#chatbuilder) with a fixed `UIMessage` subtype. See [Types](/ai-chat/types) |
531535
| `chat.withClientData({ schema })` | Returns a [ChatBuilder](/ai-chat/types#chatbuilder) with a fixed client data schema. See [Types](/ai-chat/types#typed-client-data-with-chatwithclientdata) |
532536

537+
## `chat.event`
538+
539+
Declare an inbound webhook event that an agent claims via [`events`](#chatagentoptions) on `chat.agent()`. It is a descriptor only, with no handler: it names a [source](/webhooks/sources) to verify, a `key` template that resolves each delivery to a durable [session](/ai-chat/sessions), and an optional `type` label (defaults to the descriptor `id`). Verified deliveries are routed to that session and arrive at `onAction` as a `{ type, event, source, headers, deliveryId }` envelope, not as a chat turn. See [session routing](/webhooks/session-routing).
540+
541+
```ts
542+
import { webhooks } from "@trigger.dev/sdk";
543+
import { chat } from "@trigger.dev/sdk/ai";
544+
545+
export const orderEvents = chat.event({
546+
id: "order-events",
547+
source: webhooks.stripe(),
548+
key: "{body.data.object.customer}",
549+
type: "order.event",
550+
});
551+
```
552+
553+
## `chat.channels.custom`
554+
555+
Create a generic chat-frontend channel over any verified [source](/webhooks/sources), claimed via [`channels`](#chatagentoptions) on `chat.agent()`. You supply the session `key`, the `inbound` map from event to turn message, and your own `send` egress that posts the reply back, so the whole round-trip is under your control. Inbound messages run as normal turns and the reply is posted back. The `slack()` preset ships in `@trigger.dev/slack` and wires the egress for you. See [channels](/webhooks/channels), and the interactive approvals layer at [human-in-the-loop](/webhooks/human-in-the-loop).
556+
557+
```ts
558+
import { webhooks } from "@trigger.dev/sdk";
559+
import { chat } from "@trigger.dev/sdk/ai";
560+
561+
export const mySurface = chat.channels.custom({
562+
id: "my-surface",
563+
source: webhooks.custom<MyEvent>({ /* verifier config */ }),
564+
key: "{body.conversationId}",
565+
inbound: (event) => event.text,
566+
send: async (message, ctx) => {
567+
const ref = await postToMySurface(ctx.event, message.text, ctx.previousRef);
568+
return { ref };
569+
},
570+
});
571+
```
572+
533573
## `chat.withUIMessage`
534574

535575
Returns a [`ChatBuilder`](/ai-chat/types#chatbuilder) with a fixed `UIMessage` subtype. Chain `.withClientData()`, hook methods, and `.agent()`.

docs/docs.json

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,19 @@
147147
}
148148
]
149149
},
150+
{
151+
"group": "Webhooks",
152+
"pages": [
153+
"webhooks/overview",
154+
"webhooks/sources",
155+
"webhooks/connect",
156+
"webhooks/deliveries",
157+
"webhooks/filters",
158+
"webhooks/session-routing",
159+
"webhooks/channels",
160+
"webhooks/human-in-the-loop"
161+
]
162+
},
150163
{
151164
"group": "Configuration",
152165
"pages": [

docs/webhooks/channels.mdx

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
---
2+
title: "Channels (chat frontends)"
3+
description: "Point Slack (or any chat surface) at an agent: messages become turns and replies post back."
4+
sidebarTitle: "Channels"
5+
---
6+
7+
A [session route](/webhooks/session-routing) delivers a verified event to an agent as an [action](/ai-chat/actions): the agent reacts, and the response is a side effect. A **channel** is the other half: the webhook IS the chat surface. Inbound messages become **turns** (the normal `run()` loop), and the agent's reply is posted **back** to the surface. A Slack thread becomes a real conversation with the agent, exactly like the browser chat, just a different frontend.
8+
9+
List channels on a [`chat.agent`](/ai-chat/overview) alongside (or instead of) `events`:
10+
11+
```ts
12+
import { chat } from "@trigger.dev/sdk/ai";
13+
import { slack } from "@trigger.dev/slack";
14+
15+
export const supportAgent = chat.agent({
16+
id: "support-agent",
17+
channels: [slack({ id: "support-slack", token: process.env.SLACK_BOT_TOKEN! })],
18+
run: async ({ messages }) => streamText({ model: anthropic("claude-sonnet-4-5"), messages }),
19+
});
20+
```
21+
22+
The `run()` loop is unchanged: the agent does not know or care that it is talking to Slack. One verified Slack message in a thread is routed to a durable [session](/ai-chat/sessions) keyed to that thread, run as a turn, and the reply is posted into the thread.
23+
24+
## Slack
25+
26+
`slack()` (from `@trigger.dev/slack`) is a channel connector: it verifies inbound Slack events, maps a message to the turn, and posts the reply back with `chat.postMessage` / `chat.update`.
27+
28+
<Steps>
29+
<Step title="Create a Slack app">
30+
Create an app at [api.slack.com/apps](https://api.slack.com/apps). Add the `chat:write` bot scope and install it to your workspace to get a bot token (`xoxb-...`).
31+
</Step>
32+
<Step title="Deploy the agent + connect the endpoint">
33+
Deploying registers a hosted [endpoint](/webhooks/connect) for the channel. Set its signing secret to your Slack app's **Signing Secret**, and pass the bot token as `token`.
34+
</Step>
35+
<Step title="Subscribe to events">
36+
In the app's **Event Subscriptions**, set the request URL to the endpoint's webhook URL. Slack sends a one-time `url_verification` handshake, which the endpoint answers automatically. Subscribe the bot to `message.channels`, then invite the bot to the channel (`/invite @yourapp`).
37+
</Step>
38+
</Steps>
39+
40+
By default `slack()` keys one session per thread, strips the leading bot mention from the message, posts an "on it..." placeholder while the agent works, and edits it to the answer. Override any of that:
41+
42+
```ts
43+
slack({
44+
id: "support-slack",
45+
token: process.env.SLACK_BOT_TOKEN!,
46+
// ignore anything but questions (composed with the built-in self-message guard)
47+
filter: "event.event.text contains '?'",
48+
inbound: (e) => e.event?.text ?? "",
49+
outbound: (reply) => ({ text: reply.text }),
50+
ack: (e) => ({ text: "thinking..." }), // pass `null` to post only the final answer
51+
});
52+
```
53+
54+
<Note>
55+
`slack()` always drops the bot's own messages (and their edits) before they reach the agent, so the
56+
agent never replies to itself. A multi-workspace app can pass a `token` resolver keyed on the event's
57+
team instead of a single string.
58+
</Note>
59+
60+
### Summoning with a mention
61+
62+
By default `slack()` starts (or resumes) a session for every non-bot message in a subscribed channel. To make the agent respond only when it is @mentioned, pass `startOn` with the `mentions` helper. The first mention in a thread starts the session, and the agent then follows the rest of the thread without needing to be mentioned again.
63+
64+
```ts
65+
import { slack, mentions } from "@trigger.dev/slack";
66+
67+
slack({
68+
id: "support-slack",
69+
token: process.env.SLACK_BOT_TOKEN!,
70+
startOn: mentions("U012BOT"), // your bot's user id (pass several for multiple bots)
71+
});
72+
```
73+
74+
### Reacting to messages
75+
76+
`slack()` can add an emoji reaction to the triggering message to signal progress. Set `reactions` with any of `working`, `done`, and `error`: the connector adds `working` when the turn starts, swaps it to `done` when the turn finishes, and reacts with `error` if it fails. This needs the `reactions:write` scope.
77+
78+
```ts
79+
slack({
80+
id: "support-slack",
81+
token: process.env.SLACK_BOT_TOKEN!,
82+
reactions: { working: "eyes", done: "white_check_mark", error: "warning" },
83+
});
84+
```
85+
86+
### Options
87+
88+
| Option | Type | Description |
89+
| --- | --- | --- |
90+
| `id` | `string` | Connector id, unique per agent. |
91+
| `token` | `string` or resolver | Bot token (`xoxb-...`), or a function of the event's team for multi-workspace apps. |
92+
| `key` | `string` | Session [key](/webhooks/session-routing) template. Defaults to one session per thread. |
93+
| `filter` | `string` | Extra [filter](/webhooks/filters), composed with the built-in self-message guard. |
94+
| `startOn` | `string` | Only start a session when the event matches (see `mentions`). Existing sessions always resume. |
95+
| `ack` | message, `null`, or function | Placeholder posted while the agent works. Pass `null` to post only the final answer. |
96+
| `reactions` | `{ working?, done?, error? }` | Lifecycle emoji reactions on the triggering message. |
97+
| `inbound` / `outbound` | functions | Map the Slack event to the turn, and the reply to a Slack message. |
98+
| `delivery` | `"final"` or `"stream"` | `"final"` (default) posts a placeholder and edits it to the answer. `"stream"` edits live as the reply streams. |
99+
| `apiBaseUrl` | `string` | Override the Slack Web API base, for testing against a mock. |
100+
101+
## Approvals and interactive controls
102+
103+
An agent on a channel can pause a turn to get a human decision, approving a refund or confirming a deletion, and resume once someone clicks a button in the thread. `slack()` renders Approve / Deny buttons for you and collapses them to the decision once clicked. See [human-in-the-loop](/webhooks/human-in-the-loop).
104+
105+
## Any surface: `chat.channels.custom`
106+
107+
For a surface without a preset, `chat.channels.custom` is the generic connector. You supply the [source](/webhooks/sources) to verify, the session `key`, the `inbound` map, and the egress `send`:
108+
109+
```ts
110+
import { chat } from "@trigger.dev/sdk/ai";
111+
import { webhooks } from "@trigger.dev/sdk";
112+
113+
const mySurface = chat.channels.custom({
114+
id: "my-surface",
115+
source: webhooks.custom<MyEvent>({ /* verifier config */ }),
116+
key: "{body.conversationId}",
117+
inbound: (e) => e.text,
118+
outbound: (reply) => (reply.text ? { text: reply.text } : null), // null posts nothing
119+
send: async (message, ctx) => {
120+
const ref = await postToMySurface(ctx.event, message.text, ctx.previousRef);
121+
return { ref }; // an existing ref means edit-in-place on the next turn
122+
},
123+
});
124+
```
125+
126+
`send` is called to post the reply. `ctx.previousRef` is the ref you returned last time, so streaming or a follow-up edits the same message instead of posting a new one. Return `null` from `outbound` to stay silent (a tool-only turn, say).
127+
128+
## Channels vs events
129+
130+
Both are inbound surfaces on a `chat.agent`, and an agent can list both:
131+
132+
- [`events`](/webhooks/session-routing) (`chat.event`): the webhook is a signal. Delivered to `onAction`; the agent acts, no reply is sent back.
133+
- `channels` (`slack`, `chat.channels.custom`): the webhook is a chat frontend. Delivered as a turn to `run()`; the reply is posted back.

docs/webhooks/connect.mdx

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
---
2+
title: "Connecting a provider"
3+
description: "Point a provider at the webhook URL and set the signing secret."
4+
sidebarTitle: "Connecting a provider"
5+
---
6+
7+
When you deploy (or run `dev`), each webhook task gets an **endpoint** with a unique, unguessable webhook URL. Open the webhook in the dashboard, go to **Endpoints**, and open the endpoint to find its **Connect** panel.
8+
9+
<Steps>
10+
<Step title="Copy the webhook URL">
11+
Copy it from the endpoint's Connect panel. On Trigger.dev Cloud it looks like
12+
`https://webhooks.trigger.dev/webhooks/v1/ingest/<id>`. A self-hosted instance serves it from that
13+
instance's own base URL. This is what you give the provider as its webhook destination.
14+
</Step>
15+
<Step title="Set the signing secret">
16+
A webhook can't accept deliveries until its signing secret is set. Until then every request is
17+
rejected. There are two flows, and the Connect panel shows the right one for the provider:
18+
19+
- **The provider generates the secret** (Stripe, Svix): copy it from the provider and paste it
20+
into **Set secret**.
21+
- **You choose the secret** (GitHub, or a service you control): click **Generate secret** and
22+
Trigger.dev mints a strong secret and shows it once. Paste that into the provider's webhook config.
23+
</Step>
24+
<Step title="Point the provider at the webhook URL">
25+
Add the webhook URL as the destination in your provider's dashboard. The Connect panel
26+
shows the exact signature scheme (header, algorithm, signing string) the provider should use.
27+
</Step>
28+
</Steps>
29+
30+
<Warning>
31+
The signing secret is stored encrypted and is never shown again after it's set. To rotate it,
32+
use **Rotate secret** (or **Regenerate**) and update the provider with the new value.
33+
</Warning>
34+
35+
Once a provider is sending events, watch them arrive on the [Deliveries](/webhooks/deliveries) page, which also explains what an [endpoint](/webhooks/deliveries#endpoints) is.

0 commit comments

Comments
 (0)