workflow 5.0.0-beta.2 → 5.0.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/api-workflow.d.ts +1 -1
  2. package/dist/api-workflow.d.ts.map +1 -1
  3. package/dist/api-workflow.js +2 -2
  4. package/docs/cookbook/{common-patterns → advanced}/child-workflows.mdx +1 -1
  5. package/docs/cookbook/advanced/distributed-abort-controller.mdx +318 -0
  6. package/docs/cookbook/advanced/meta.json +2 -3
  7. package/docs/cookbook/advanced/publishing-libraries.mdx +83 -26
  8. package/docs/cookbook/advanced/serializable-steps.mdx +15 -3
  9. package/docs/cookbook/agent-patterns/agent-cancellation.mdx +205 -0
  10. package/docs/cookbook/agent-patterns/durable-agent.mdx +50 -91
  11. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +148 -171
  12. package/docs/cookbook/agent-patterns/meta.json +1 -7
  13. package/docs/cookbook/common-patterns/batching.mdx +44 -118
  14. package/docs/cookbook/common-patterns/meta.json +4 -4
  15. package/docs/cookbook/common-patterns/saga.mdx +126 -31
  16. package/docs/cookbook/common-patterns/scheduling.mdx +70 -194
  17. package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +155 -0
  18. package/docs/cookbook/common-patterns/timeouts.mdx +99 -0
  19. package/docs/cookbook/common-patterns/workflow-composition.mdx +118 -0
  20. package/docs/cookbook/index.mdx +13 -16
  21. package/docs/cookbook/integrations/ai-sdk.mdx +296 -140
  22. package/docs/cookbook/integrations/chat-sdk.mdx +251 -151
  23. package/docs/cookbook/integrations/sandbox.mdx +469 -81
  24. package/docs/cookbook/meta.json +1 -1
  25. package/docs/foundations/index.mdx +0 -3
  26. package/docs/foundations/meta.json +0 -1
  27. package/docs/foundations/serialization.mdx +1 -1
  28. package/docs/foundations/starting-workflows.mdx +1 -1
  29. package/docs/migration-guides/migrating-from-aws-step-functions.mdx +60 -8
  30. package/docs/migration-guides/migrating-from-inngest.mdx +38 -6
  31. package/docs/migration-guides/migrating-from-temporal.mdx +38 -4
  32. package/docs/migration-guides/migrating-from-trigger-dev.mdx +52 -11
  33. package/package.json +11 -11
  34. package/docs/cookbook/advanced/custom-serialization.mdx +0 -168
  35. package/docs/cookbook/advanced/durable-objects.mdx +0 -148
  36. package/docs/cookbook/advanced/isomorphic-packages.mdx +0 -145
  37. package/docs/cookbook/agent-patterns/stop-workflow.mdx +0 -216
  38. package/docs/cookbook/agent-patterns/tool-orchestration.mdx +0 -255
  39. package/docs/cookbook/agent-patterns/tool-streaming.mdx +0 -181
  40. package/docs/cookbook/common-patterns/content-router.mdx +0 -207
  41. package/docs/cookbook/common-patterns/fan-out.mdx +0 -208
  42. package/docs/foundations/common-patterns.mdx +0 -265
@@ -1,203 +1,303 @@
1
1
  ---
2
2
  title: Chat SDK
3
- description: Build durable chat sessions by combining workflow persistence with AI SDK's chat primitives.
3
+ description: Make Chat SDK bot sessions durable one workflow run per conversation thread, with hooks bridging inbound platform events into long-running agent logic.
4
4
  type: guide
5
- summary: Use workflow hooks and streaming to create chat sessions that survive disconnects and server restarts.
5
+ summary: Chat SDK normalizes Slack, Teams, Discord, Telegram and friends into one thread/message model. Workflow SDK gives each thread a durable run that owns multi-turn state, can sleep for hours, and survives restarts.
6
6
  related:
7
- - /docs/ai/chat-session-modeling
8
- - /docs/ai/resumable-streams
9
- - /docs/ai/message-queueing
10
- - /docs/api-reference/workflow-ai/durable-agent
7
+ - /docs/cookbook/integrations/ai-sdk
8
+ - /docs/cookbook/integrations/sandbox
11
9
  - /docs/api-reference/workflow/define-hook
10
+ - /docs/api-reference/workflow-api/start
11
+ - /docs/api-reference/workflow-api/get-run
12
12
  ---
13
13
 
14
- AI SDK provides chat primitives (`useChat`, message types, streaming utilities) for building chat interfaces. Workflow SDK makes those chat sessions durable -- surviving disconnects, cold starts, and server restarts -- by persisting every message and LLM response as workflow events.
14
+ [Chat SDK](https://chat-sdk.dev/) is a unified TypeScript SDK for building bots across Slack, Microsoft Teams, Google Chat, Discord, Telegram, GitHub, Linear, and WhatsApp. Write the bot once, deploy to every platform. It handles webhook verification, event normalization, subscriptions, and cross-platform features like cards and modals.
15
15
 
16
- ## What It Enables
16
+ Workflow SDK complements it by making bot **sessions** durable. Each conversation thread maps to a long-running workflow run that:
17
17
 
18
- - **Durable chat history** -- Messages and responses are persisted in the workflow event log, not just client state
19
- - **Resumable sessions** -- Users reconnect and pick up where they left off, even after server restarts
20
- - **Multi-turn conversations** -- A single workflow manages an entire chat session with hook-based message injection
21
- - **Server-side message queueing** -- Inject follow-up messages while the agent is still processing
18
+ - Owns multi-turn state in the durable event log instead of Redis-by-hand bookkeeping
19
+ - Can `sleep()` for hours or days waiting for a user reply, an approval, or a scheduled follow-up
20
+ - Survives deploys, cold starts, and crashes the session picks up from the last step on replay
21
+ - Receives follow-up messages via hooks, so the bot stays responsive while the workflow is still running
22
22
 
23
- ## When to Use
23
+ The rest of this page covers the integration pattern. For a full Slack + Next.js + Redis walkthrough, see the [Durable chat sessions guide](https://chat-sdk.dev/docs/guides/durable-chat-sessions-nextjs) on chat-sdk.dev.
24
24
 
25
- Use this pattern when your chat application needs:
25
+ ## How It Fits Together
26
26
 
27
- - Persistence beyond the browser session
28
- - Recovery from server failures mid-conversation
29
- - Long-running agent sessions (minutes to hours)
30
- - Server-driven message injection (system messages, external events)
27
+ Chat SDK owns the edge — webhook verification, event routing, `thread.post()` / `thread.stream()`. Workflow owns the session — state, loops, sleeps, retries. They meet at exactly two points:
31
28
 
32
- ## Single-Turn: Stateless Sessions
29
+ ```mermaid
30
+ flowchart TD
31
+ A["Platform webhook"] --> B["Chat SDK event handler<br/>(onNewMention, onSubscribedMessage, …)"]
32
+ B -->|"no runId in thread state"| C["start(durableChatSession, …)"]
33
+ B -->|"runId in thread state"| D["resumeHook(runId, { message })"]
34
+ C --> E["Workflow run (durable)<br/>one per thread; suspends between turns"]
35
+ D --> E
36
+ E --> F["&quot;use step&quot; helpers<br/>thread.post(), thread.subscribe(), thread.setState(), …"]
37
+ ```
33
38
 
34
- Each user message starts a new workflow run. The client owns the message history and sends the full array with each request. This is the simplest pattern.
39
+ - **Inbound** Chat SDK handlers decide whether to `start(workflow, [thread, message])` or `resumeHook(runId, { message })`. The `runId` lives in Chat SDK's thread state (Redis, Postgres, or any state adapter).
40
+ - **Outbound** — the workflow calls Chat SDK APIs (`thread.post()`, `thread.subscribe()`, `thread.setState()`) from inside step functions. Never from the top level of a workflow file — adapter packages use Node-only modules that aren't available in the workflow sandbox.
35
41
 
36
- ```typescript title="workflows/chat.ts" lineNumbers
37
- import { DurableAgent } from "@workflow/ai/agent";
38
- import { convertToModelMessages, type UIMessage, type UIMessageChunk } from "ai";
39
- import { getWritable } from "workflow";
42
+ ## Why Workflow + Chat SDK
40
43
 
41
- export async function chat(messages: UIMessage[]) {
42
- "use workflow";
44
+ Without Workflow, a long-running bot session usually means one of:
45
+ - Holding a webhook request open while the agent runs (doesn't survive restarts, blows past platform timeouts)
46
+ - Writing session state to Redis manually, plus a scheduler for timeouts and retries, plus custom reconnection logic
43
47
 
44
- const agent = new DurableAgent({
45
- model: "anthropic/claude-sonnet-4-20250514",
46
- instructions: "You are a helpful assistant.",
47
- tools: { /* your tools here */ },
48
- });
48
+ Workflow replaces all of that with a single durable function. The bot can:
49
49
 
50
- const result = await agent.stream({ // [!code highlight]
51
- messages: await convertToModelMessages(messages),
52
- writable: getWritable<UIMessageChunk>(),
53
- });
50
+ - Run a tool loop for minutes while the user watches typing indicators
51
+ - Wait for a human approval in another thread before continuing
52
+ - Schedule a follow-up message 24 hours later via `sleep("24h")`
53
+ - Pause on sandbox snapshot, resume when the user sends the next command (see the [Sandbox integration](/docs/cookbook/integrations/sandbox))
54
54
 
55
- return { messages: result.messages };
56
- }
57
- ```
55
+ Because the session *is* a workflow run, its history is recoverable from the event log — no separate message store to keep in sync.
58
56
 
59
- ```typescript title="app/api/chat/route.ts" lineNumbers
60
- import { createUIMessageStreamResponse } from "ai";
61
- import { start } from "workflow/api";
62
- import { chat } from "@/workflows/chat";
57
+ ## The Pattern: One Thread = One Workflow Run
63
58
 
64
- export async function POST(request: Request) {
65
- const { messages } = await request.json();
66
- const run = await start(chat, [messages]); // [!code highlight]
59
+ Three files. The bot definition is separate from the workflow so adapter packages stay out of the workflow sandbox.
67
60
 
68
- return createUIMessageStreamResponse({
69
- stream: run.readable,
70
- headers: { "x-workflow-run-id": run.runId },
71
- });
72
- }
73
- ```
61
+ <Tabs items={['Bot Setup', 'Workflow', 'Event Handlers']}>
62
+
63
+ <Tab value="Bot Setup">
64
+
65
+ Register the `Chat` instance as a singleton so step functions can dynamically import it and resolve adapters + state:
74
66
 
75
- The client uses `WorkflowChatTransport` for automatic stream resumption.
76
-
77
- ```typescript title="components/chat.tsx" lineNumbers
78
- "use client";
79
-
80
- import { useChat } from "@ai-sdk/react";
81
- import { WorkflowChatTransport } from "@workflow/ai";
82
-
83
- export function Chat() {
84
- const chat = useChat({
85
- transport: new WorkflowChatTransport({ api: "/api/chat" }), // [!code highlight]
86
- });
87
-
88
- return (
89
- <div>
90
- {chat.messages.map((m) => (
91
- <div key={m.id}>{m.content}</div>
92
- ))}
93
- <form onSubmit={chat.handleSubmit}>
94
- <input value={chat.input} onChange={chat.handleInputChange} />
95
- </form>
96
- </div>
97
- );
67
+ ```typescript title="lib/bot.ts" lineNumbers
68
+ import { Chat } from "chat";
69
+ import { createSlackAdapter } from "@chat-adapter/slack";
70
+ import { createRedisState } from "@chat-adapter/state-redis";
71
+
72
+ const adapters = {
73
+ slack: createSlackAdapter(),
74
+ };
75
+
76
+ export interface ThreadState {
77
+ runId?: string; // [!code highlight]
98
78
  }
79
+
80
+ export const bot = new Chat<typeof adapters, ThreadState>({
81
+ userName: "durable-bot",
82
+ adapters,
83
+ state: createRedisState(),
84
+ dedupeTtlMs: 600_000,
85
+ }).registerSingleton(); // [!code highlight]
99
86
  ```
100
87
 
101
- ## Multi-Turn: Durable Sessions
88
+ `registerSingleton()` is important: Chat SDK re-hydrates `Thread` objects inside step functions, and it needs a registered singleton to resolve adapters and state for those rehydrated instances.
102
89
 
103
- A single workflow manages the entire conversation. The workflow loops, waiting for new messages via a hook. This gives you server-side ownership of the full chat history.
90
+ </Tab>
104
91
 
105
- ```typescript title="workflows/durable-chat.ts" lineNumbers
106
- import { DurableAgent } from "@workflow/ai/agent";
107
- import {
108
- convertToModelMessages,
109
- type UIMessage,
110
- type UIMessageChunk,
111
- } from "ai";
112
- import { defineHook, getWritable, getWorkflowMetadata } from "workflow";
113
- import { z } from "zod";
92
+ <Tab value="Workflow">
114
93
 
115
- const chatMessageHook = defineHook({ // [!code highlight]
116
- schema: z.object({
117
- messages: z.array(z.any()),
118
- }),
119
- });
94
+ The workflow is a plain loop over a hook. It receives the serialized thread + first message from the handler, revives them via Chat SDK's standalone `reviver`, and every platform-side effect goes inside a `"use step"` helper:
95
+
96
+ ```typescript title="workflows/durable-chat-session.ts" lineNumbers
97
+ import { Message, reviver, type Thread } from "chat";
98
+ import { defineHook, getWorkflowMetadata } from "workflow";
99
+ import type { ThreadState } from "@/lib/bot";
100
+
101
+ // Hook payload lives in its own file so the webhook side can import it without
102
+ // pulling in the workflow module.
103
+ import type { ChatTurnPayload } from "@/workflows/chat-turn-hook";
104
+
105
+ const chatTurnHook = defineHook<ChatTurnPayload>(); // [!code highlight]
106
+
107
+ async function postAssistantMessage(
108
+ thread: Thread<ThreadState>,
109
+ text: string
110
+ ) {
111
+ "use step";
112
+ // Dynamic import keeps adapter packages out of the workflow sandbox.
113
+ const { bot } = await import("@/lib/bot"); // [!code highlight]
114
+ await bot.initialize();
115
+ await thread.post(text);
116
+ }
117
+
118
+ async function runTurn(text: string) {
119
+ "use step";
120
+ // Your AI SDK call, database lookup, tool loop, etc.
121
+ return `You said: ${text}`;
122
+ }
123
+
124
+ async function handleMessage(
125
+ thread: Thread<ThreadState>,
126
+ message: Message
127
+ ) {
128
+ const text = message.text.trim();
129
+ if (text.toLowerCase() === "done") return false;
120
130
 
121
- export async function durableChat(initialMessages: UIMessage[]) {
131
+ const reply = await runTurn(text);
132
+ await postAssistantMessage(thread, reply);
133
+ return true;
134
+ }
135
+
136
+ export async function durableChatSession(payload: string) {
122
137
  "use workflow";
123
138
 
124
139
  const { workflowRunId } = getWorkflowMetadata();
125
- let allMessages = await convertToModelMessages(initialMessages);
126
-
127
- const agent = new DurableAgent({
128
- model: "anthropic/claude-sonnet-4-20250514",
129
- instructions: "You are a helpful assistant.",
130
- tools: { /* your tools here */ },
131
- });
132
-
133
- // First turn
134
- const firstResult = await agent.stream({
135
- messages: allMessages,
136
- writable: getWritable<UIMessageChunk>(),
137
- preventClose: true,
138
- });
139
- allMessages = firstResult.messages;
140
-
141
- // Subsequent turns -- wait for new messages via hook
140
+ const { thread, message } = JSON.parse(payload, reviver) as { // [!code highlight]
141
+ thread: Thread<ThreadState>;
142
+ message: Message;
143
+ };
144
+
145
+ const hook = chatTurnHook.create({ token: workflowRunId });
146
+
147
+ await postAssistantMessage(thread, "Session started. Reply here; send `done` to stop.");
148
+
149
+ if (!(await handleMessage(thread, message))) return;
150
+
151
+ // Each hook resumption is one turn. The workflow stays suspended between
152
+ // messages — zero compute cost while idle.
142
153
  while (true) {
143
- const hook = chatMessageHook.create({ token: workflowRunId });
144
- const { messages: newMessages } = await hook; // [!code highlight]
145
-
146
- allMessages = [
147
- ...allMessages,
148
- ...await convertToModelMessages(newMessages),
149
- ];
150
-
151
- const result = await agent.stream({
152
- messages: allMessages,
153
- writable: getWritable<UIMessageChunk>(),
154
- preventClose: true,
155
- });
156
- allMessages = result.messages;
154
+ const { message: nextRaw } = await hook; // [!code highlight]
155
+ const next = Message.fromJSON(nextRaw);
156
+ if (!(await handleMessage(thread, next))) return;
157
157
  }
158
158
  }
159
159
  ```
160
160
 
161
- ### Multi-Turn API Routes
161
+ ```typescript title="workflows/chat-turn-hook.ts" lineNumbers
162
+ import type { SerializedMessage } from "chat";
163
+
164
+ export type ChatTurnPayload = {
165
+ message: SerializedMessage;
166
+ };
167
+ ```
168
+
169
+ </Tab>
162
170
 
163
- You need two routes: one to start the session, another to send follow-up messages.
171
+ <Tab value="Event Handlers">
164
172
 
165
- ```typescript title="app/api/chat/route.ts" lineNumbers
166
- import { createUIMessageStreamResponse } from "ai";
167
- import { start } from "workflow/api";
168
- import { durableChat } from "@/workflows/durable-chat";
173
+ Handlers live outside the workflow file so adapter dependencies don't leak in. They decide whether to start a new workflow or resume an existing one, then store the `runId` in thread state:
169
174
 
170
- export async function POST(request: Request) {
171
- const { messages } = await request.json();
172
- const run = await start(durableChat, [messages]); // [!code highlight]
175
+ ```typescript title="lib/chat-session-handlers.ts" lineNumbers
176
+ import type { Message, Thread } from "chat";
177
+ import { getRun, resumeHook, start } from "workflow/api";
178
+ import { bot, type ThreadState } from "@/lib/bot";
179
+ import { durableChatSession } from "@/workflows/durable-chat-session";
180
+ import type { ChatTurnPayload } from "@/workflows/chat-turn-hook";
173
181
 
174
- return createUIMessageStreamResponse({
175
- stream: run.readable,
176
- headers: { "x-workflow-run-id": run.runId },
177
- });
182
+ async function startSession(thread: Thread<ThreadState>, message: Message) {
183
+ const run = await start(durableChatSession, [ // [!code highlight]
184
+ JSON.stringify({
185
+ thread: thread.toJSON(),
186
+ message: message.toJSON(),
187
+ }),
188
+ ]);
189
+ await thread.setState({ runId: run.runId });
178
190
  }
191
+
192
+ async function routeTurn(thread: Thread<ThreadState>, message: Message) {
193
+ const state = await thread.state;
194
+
195
+ // No run yet, or the previous run finished — start fresh.
196
+ if (!state?.runId || !(await getRun(state.runId).exists)) {
197
+ await startSession(thread, message);
198
+ return;
199
+ }
200
+
201
+ try {
202
+ await resumeHook<ChatTurnPayload>(state.runId, { // [!code highlight]
203
+ message: message.toJSON(),
204
+ });
205
+ } catch (err) {
206
+ const msg = err instanceof Error ? err.message.toLowerCase() : "";
207
+ if (msg.includes("not found") || msg.includes("expired")) {
208
+ // Stale runId — start a new session rather than dropping the message.
209
+ await startSession(thread, message);
210
+ return;
211
+ }
212
+ throw err;
213
+ }
214
+ }
215
+
216
+ bot.onNewMention(async (thread, message) => {
217
+ await thread.subscribe();
218
+ await routeTurn(thread, message);
219
+ });
220
+
221
+ bot.onSubscribedMessage(async (thread, message) => {
222
+ await routeTurn(thread, message);
223
+ });
179
224
  ```
180
225
 
181
- ```typescript title="app/api/chat/follow-up/route.ts" lineNumbers
182
- import { resumeHook } from "workflow/api";
226
+ Wire Chat SDK's webhook handler into a catch-all route. Importing `chat-session-handlers` for side effects registers the event handlers before the first webhook arrives:
227
+
228
+ ```typescript title="app/api/webhooks/[platform]/route.ts" lineNumbers
229
+ import "@/lib/chat-session-handlers";
230
+ import { after } from "next/server";
231
+ import { bot } from "@/lib/bot";
232
+
233
+ type Platform = keyof typeof bot.webhooks;
234
+
235
+ export async function POST(
236
+ req: Request,
237
+ { params }: { params: Promise<{ platform: string }> }
238
+ ) {
239
+ const { platform } = await params;
240
+ const handler = bot.webhooks[platform as Platform];
241
+ if (!handler) return new Response(`Unknown platform: ${platform}`, { status: 404 });
183
242
 
184
- export async function POST(request: Request) {
185
- const { runId, messages } = await request.json();
186
- await resumeHook(runId, { messages }); // [!code highlight]
187
- return new Response("OK");
243
+ return handler(req, { waitUntil: (task) => after(() => task) }); // [!code highlight]
188
244
  }
189
245
  ```
190
246
 
191
- ## Choosing a Pattern
247
+ </Tab>
248
+
249
+ </Tabs>
250
+
251
+ ## How It Works
252
+
253
+ 1. **Thread state stores the `runId`.** Chat SDK's state adapter (Redis, Postgres, memory) holds `{ runId }` per thread. That's the only piece of glue between the two SDKs.
254
+ 2. **First mention → `start()`.** Handler serializes `thread` + `message` with `toJSON()`, passes them through `start(durableChatSession, [payload])`, stashes the returned `runId` in thread state.
255
+ 3. **Subsequent messages → `resumeHook()`.** Handler looks up the `runId`, serializes the new message, and resumes the workflow's hook. The workflow picks up on the next `await hook` iteration.
256
+ 4. **Workflow posts back via steps.** All Chat SDK side effects (`thread.post`, `thread.subscribe`, `thread.setState`) happen inside `"use step"` helpers that dynamically import the bot. This keeps adapter packages outside the workflow sandbox.
257
+ 5. **Session ends — two ways.** The workflow returns normally (user said `done`, approval granted, etc.), or the workflow throws. Either way the run completes; the next inbound message with the stale `runId` falls through to `startSession()`.
258
+
259
+ The workflow is fully durable between turns: `await hook` suspends with zero compute cost, and platform webhooks can fire from anywhere without concern for which server instance handled the previous turn.
260
+
261
+ ## Extending the Pattern
262
+
263
+ Because the session is just a workflow, everything else from the cookbook composes naturally:
264
+
265
+ - **Stream AI SDK responses into the thread.** Use the [AI SDK integration](/docs/cookbook/integrations/ai-sdk) pattern inside a step, then pass `result.fullStream` to `thread.post()` — Chat SDK handles platform-specific streaming (Slack edit-in-place, Telegram message-per-chunk, etc.).
266
+ - **Give the bot a sandbox.** Combine with the [Sandbox integration](/docs/cookbook/integrations/sandbox): each thread gets its own persistent sandbox session, snapshots on idle, resumes on the next message. That's effectively a coding-agent bot.
267
+ - **Human-in-the-loop approvals.** `Promise.race([hook, approvalHook])` inside the workflow, post buttons in the thread via [cards](https://chat-sdk.dev/docs/cards), resume `approvalHook` from `bot.onAction(...)`.
268
+ - **Scheduled follow-ups.** `sleep("24h")` before a proactive check-in. Surviving restarts is free.
269
+
270
+ ## Pitfalls
271
+
272
+ ### Don't import the bot at the top of workflow files
273
+
274
+ Adapter packages (`@chat-adapter/slack`, `@chat-adapter/telegram`, etc.) depend on Node-only modules that aren't available in the workflow bundler's sandbox. Keep `import { bot } from "@/lib/bot"` inside `"use step"` functions with `await import(...)`. Use `reviver` from `chat` for deserialization inside the workflow — it's standalone and has no adapter dependencies.
275
+
276
+ ### Register the bot as a singleton
277
+
278
+ `new Chat({...}).registerSingleton()`. Chat SDK rehydrates `Thread` objects inside step functions via `reviver`, and it looks up adapters + state from the registered singleton. Without it, thread methods throw when called from step contexts.
279
+
280
+ ### Hook payloads must be JSON-serializable
281
+
282
+ `Message` and `Thread` have methods, so pass them through `.toJSON()` / `Message.fromJSON()` across the hook boundary. Define a `ChatTurnPayload` type in its own file so both the webhook handler (in the Node bundle) and the workflow (in the workflow sandbox) can share it without dragging in adapter code.
283
+
284
+ ### Handle stale `runId`s
285
+
286
+ A workflow run ends but its `runId` is still cached in thread state. The next message calls `resumeHook` on a dead run and throws `not found` / `expired`. Gate on `getRun(runId).exists` before resuming, or catch the error and fall through to `startSession`. Either way the user's message must not be dropped.
287
+
288
+ ### Keep the hook outside the loop
289
+
290
+ One `chatTurnHook.create({ token: workflowRunId })` per workflow run, reused every iteration. Creating a new hook with the same token throws `HookConflictError`. This is the same rule as the [AI SDK](/docs/cookbook/integrations/ai-sdk) and [Sandbox](/docs/cookbook/integrations/sandbox) session patterns.
291
+
292
+ ### Platform timeouts are separate from workflow timeouts
192
293
 
193
- | | Single-Turn | Multi-Turn |
194
- |---|---|---|
195
- | **State ownership** | Client | Server (workflow event log) |
196
- | **Message injection** | Not needed | Via hooks |
197
- | **Complexity** | Low | Medium |
198
- | **Session duration** | Per-request | Minutes to hours |
199
- | **Crash recovery** | Client resends full history | Workflow replays from event log |
294
+ Slack wants a 200 within 3 seconds. The webhook handler returns immediately after `resumeHook` (which is fast) — the workflow then runs in the background and posts back via `thread.post`. Don't try to `await` the whole turn inside the webhook handler; that's what breaks in the naive integration.
200
295
 
201
- Start with single-turn. Move to multi-turn when you need server-owned state, message injection from external sources, or sessions that outlive the browser tab.
296
+ ## Key APIs
202
297
 
203
- See [Chat Session Modeling](/docs/ai/chat-session-modeling) for the full guide including multiplayer patterns and message queueing.
298
+ - [`Chat`](https://chat-sdk.dev/docs/api/chat) / [`Thread`](https://chat-sdk.dev/docs/api/thread) / [`Message`](https://chat-sdk.dev/docs/api/message) Chat SDK primitives. `toJSON()` / `fromJSON()` / `reviver` are the serialization layer.
299
+ - [`start()`](/docs/api-reference/workflow-api/start) — start a new session workflow. Store the returned `runId` in thread state.
300
+ - [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) — forward a new platform message to the running workflow.
301
+ - [`getRun()`](/docs/api-reference/workflow-api/get-run) — `run.exists` before resuming, to detect stale `runId`s.
302
+ - [`defineHook()`](/docs/api-reference/workflow/define-hook) — per-turn suspension point inside the workflow.
303
+ - [`registerSingleton()`](https://chat-sdk.dev/docs/api/chat) — makes the bot resolvable from inside step functions.