agents 0.16.2 → 0.17.1

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 (126) hide show
  1. package/README.md +11 -8
  2. package/dist/{agent-tool-types-CTw3UJUP.d.ts → agent-tool-types-CNyE1iz_.d.ts} +671 -138
  3. package/dist/agent-tool-types.d.ts +34 -18
  4. package/dist/agent-tool-types.js +20 -1
  5. package/dist/agent-tool-types.js.map +1 -0
  6. package/dist/agent-tools-BXlsuX0d.js +304 -0
  7. package/dist/agent-tools-BXlsuX0d.js.map +1 -0
  8. package/dist/agent-tools-CSnyGvJ2.d.ts +119 -0
  9. package/dist/agent-tools.d.ts +24 -18
  10. package/dist/agent-tools.js.map +1 -1
  11. package/dist/ai-chat-agent.d.ts +1 -1
  12. package/dist/ai-chat-agent.js +1 -2
  13. package/dist/ai-chat-agent.js.map +1 -1
  14. package/dist/ai-chat-v5-migration.d.ts +1 -1
  15. package/dist/ai-chat-v5-migration.js +1 -2
  16. package/dist/ai-chat-v5-migration.js.map +1 -1
  17. package/dist/ai-react.d.ts +1 -1
  18. package/dist/ai-react.js +1 -2
  19. package/dist/ai-react.js.map +1 -1
  20. package/dist/ai-types.d.ts +1 -7
  21. package/dist/ai-types.js +2 -8
  22. package/dist/ai-types.js.map +1 -1
  23. package/dist/browser/ai.js +1 -1
  24. package/dist/browser/index.js +1 -1
  25. package/dist/chat/index.d.ts +2033 -77
  26. package/dist/chat/index.js +1828 -245
  27. package/dist/chat/index.js.map +1 -1
  28. package/dist/chat/react.d.ts +602 -0
  29. package/dist/chat/react.js +1506 -0
  30. package/dist/chat/react.js.map +1 -0
  31. package/dist/chat-sdk/index.d.ts +4 -4
  32. package/dist/{classPrivateFieldGet2-CZ7QjTXN.js → classPrivateFieldGet2-DZBYAB34.js} +5 -5
  33. package/dist/{classPrivateMethodInitSpec-D-0__zd9.js → classPrivateMethodInitSpec-qMjJ6sHQ.js} +2 -2
  34. package/dist/{client-BXJ9n2f7.js → client-BZ-B3NhC.js} +2 -2
  35. package/dist/client-BZ-B3NhC.js.map +1 -0
  36. package/dist/client-tools-aIBO0Fk7.d.ts +53 -0
  37. package/dist/client.d.ts +76 -57
  38. package/dist/client.js +33 -5
  39. package/dist/client.js.map +1 -1
  40. package/dist/{connector-CrKhowfD.js → connector-CdldGF3h.js} +5 -5
  41. package/dist/{connector-CrKhowfD.js.map → connector-CdldGF3h.js.map} +1 -1
  42. package/dist/email.js +1 -1
  43. package/dist/email.js.map +1 -1
  44. package/dist/{index-B7IbEeze.d.ts → index-BRnybD6X.d.ts} +197 -14
  45. package/dist/index.d.ts +95 -73
  46. package/dist/index.js +694 -25
  47. package/dist/index.js.map +1 -1
  48. package/dist/mcp/client.d.ts +18 -14
  49. package/dist/mcp/client.js +1 -1
  50. package/dist/mcp/index.d.ts +30 -30
  51. package/dist/mcp/index.js +7 -7
  52. package/dist/mcp/index.js.map +1 -1
  53. package/dist/{agent-tools-3zLG7MgA.js → message-builder-BymO4N_D.js} +45 -126
  54. package/dist/message-builder-BymO4N_D.js.map +1 -0
  55. package/dist/observability/index.d.ts +1 -1
  56. package/dist/observability/index.js +4 -2
  57. package/dist/observability/index.js.map +1 -1
  58. package/dist/react.d.ts +123 -110
  59. package/dist/react.js +44 -11
  60. package/dist/react.js.map +1 -1
  61. package/dist/{retries-CwlpAGet.d.ts → retries-CvHJwSuh.d.ts} +15 -6
  62. package/dist/retries.d.ts +8 -6
  63. package/dist/retries.js +44 -1
  64. package/dist/retries.js.map +1 -1
  65. package/dist/serializable.d.ts +1 -1
  66. package/dist/skills/compile.js +1 -1
  67. package/dist/skills/compile.js.map +1 -1
  68. package/dist/skills/index.js +5 -5
  69. package/dist/skills/index.js.map +1 -1
  70. package/dist/sub-routing.d.ts +6 -6
  71. package/dist/utils.js +1 -1
  72. package/dist/utils.js.map +1 -1
  73. package/dist/vite.js +5 -5
  74. package/dist/vite.js.map +1 -1
  75. package/dist/wire-types-nflOzNuU.js +240 -0
  76. package/dist/wire-types-nflOzNuU.js.map +1 -0
  77. package/dist/{workflow-types-SrZK_o9p.d.ts → workflow-types-Baz_PO5v.d.ts} +42 -22
  78. package/dist/workflow-types.d.ts +25 -21
  79. package/dist/workflow-types.js.map +1 -1
  80. package/dist/workflows.d.ts +22 -21
  81. package/dist/workflows.js +31 -7
  82. package/dist/workflows.js.map +1 -1
  83. package/docs/adding-to-existing-project.md +450 -0
  84. package/docs/agent-class.md +503 -0
  85. package/docs/agent-tools.md +552 -0
  86. package/docs/browse-the-web.md +430 -0
  87. package/docs/callable-methods.md +627 -0
  88. package/docs/chat-agents.md +1696 -0
  89. package/docs/chat-sdk.md +181 -0
  90. package/docs/client-sdk.md +520 -0
  91. package/docs/client-tools-continuation.md +177 -0
  92. package/docs/codemode.md +440 -0
  93. package/docs/configuration.md +775 -0
  94. package/docs/cross-domain-authentication.md +171 -0
  95. package/docs/durable-execution.md +537 -0
  96. package/docs/email.md +663 -0
  97. package/docs/get-current-agent.md +204 -0
  98. package/docs/getting-started.md +305 -0
  99. package/docs/http-websockets.md +668 -0
  100. package/docs/human-in-the-loop.md +661 -0
  101. package/docs/index.md +151 -0
  102. package/docs/long-running-agents.md +730 -0
  103. package/docs/mcp-client.md +620 -0
  104. package/docs/mcp-servers.md +526 -0
  105. package/docs/mcp-transports.md +308 -0
  106. package/docs/migration-to-ai-sdk-v5.md +96 -0
  107. package/docs/migration-to-ai-sdk-v6.md +163 -0
  108. package/docs/observability.md +261 -0
  109. package/docs/push-notifications.md +367 -0
  110. package/docs/queue.md +329 -0
  111. package/docs/readonly-connections.md +278 -0
  112. package/docs/resumable-streaming.md +127 -0
  113. package/docs/retries.md +444 -0
  114. package/docs/routing.md +749 -0
  115. package/docs/scheduling.md +898 -0
  116. package/docs/securing-mcp-servers.md +359 -0
  117. package/docs/server-driven-messages.md +477 -0
  118. package/docs/sessions.md +1024 -0
  119. package/docs/state.md +512 -0
  120. package/docs/sub-agents.md +389 -0
  121. package/docs/webhooks.md +604 -0
  122. package/docs/workflows.md +877 -0
  123. package/package.json +41 -14
  124. package/dist/agent-tools-3zLG7MgA.js.map +0 -1
  125. package/dist/agent-tools-DZhI5F6Q.d.ts +0 -14
  126. package/dist/client-BXJ9n2f7.js.map +0 -1
@@ -0,0 +1,1696 @@
1
+ # Chat Agents
2
+
3
+ Build AI-powered chat interfaces with `AIChatAgent` and `useAgentChat`. Messages are automatically persisted to SQLite, streams resume on disconnect, and tool calls work across server and client.
4
+
5
+ ## Overview
6
+
7
+ `@cloudflare/ai-chat` provides two main exports:
8
+
9
+ | Export | Import | Purpose |
10
+ | -------------- | --------------------------- | -------------------------------------------------------------- |
11
+ | `AIChatAgent` | `@cloudflare/ai-chat` | Server-side agent class with message persistence and streaming |
12
+ | `useAgentChat` | `@cloudflare/ai-chat/react` | React hook for building chat UIs |
13
+
14
+ Built on the [AI SDK](https://ai-sdk.dev) and Cloudflare Durable Objects, you get:
15
+
16
+ - **Automatic message persistence** — conversations stored in SQLite, survive restarts
17
+ - **Resumable streaming** — disconnected clients resume mid-stream without data loss
18
+ - **Real-time sync** — messages broadcast to all connected clients via WebSocket
19
+ - **Tool support** — server-side, client-side, and human-in-the-loop tool patterns
20
+ - **Data parts** — attach typed JSON (citations, progress, usage) to messages alongside text
21
+ - **Row size protection** — automatic compaction when messages approach SQLite limits
22
+
23
+ ## Quick Start
24
+
25
+ ### Install
26
+
27
+ ```sh
28
+ npm install @cloudflare/ai-chat agents ai workers-ai-provider
29
+ ```
30
+
31
+ ### Server
32
+
33
+ ```typescript
34
+ import { AIChatAgent } from "@cloudflare/ai-chat";
35
+ import { createWorkersAI } from "workers-ai-provider";
36
+ import { streamText, convertToModelMessages } from "ai";
37
+
38
+ export class ChatAgent extends AIChatAgent {
39
+ async onChatMessage() {
40
+ const workersai = createWorkersAI({ binding: this.env.AI });
41
+
42
+ const result = streamText({
43
+ model: workersai("@cf/moonshotai/kimi-k2.7-code"),
44
+ messages: await convertToModelMessages(this.messages)
45
+ });
46
+
47
+ return result.toUIMessageStreamResponse();
48
+ }
49
+ }
50
+ ```
51
+
52
+ ### Client
53
+
54
+ ```tsx
55
+ import { useAgent } from "agents/react";
56
+ import { useAgentChat } from "@cloudflare/ai-chat/react";
57
+
58
+ function Chat() {
59
+ const agent = useAgent({ agent: "ChatAgent" });
60
+ const { messages, sendMessage, status } = useAgentChat({ agent });
61
+
62
+ return (
63
+ <div>
64
+ {messages.map((msg) => (
65
+ <div key={msg.id}>
66
+ <strong>{msg.role}:</strong>
67
+ {msg.parts.map((part, i) =>
68
+ part.type === "text" ? <span key={i}>{part.text}</span> : null
69
+ )}
70
+ </div>
71
+ ))}
72
+
73
+ <form
74
+ onSubmit={(e) => {
75
+ e.preventDefault();
76
+ const input = e.currentTarget.elements.namedItem(
77
+ "input"
78
+ ) as HTMLInputElement;
79
+ sendMessage({ text: input.value });
80
+ input.value = "";
81
+ }}
82
+ >
83
+ <input name="input" placeholder="Type a message..." />
84
+ <button type="submit" disabled={status === "streaming"}>
85
+ Send
86
+ </button>
87
+ </form>
88
+ </div>
89
+ );
90
+ }
91
+ ```
92
+
93
+ ### Wrangler Config
94
+
95
+ ```jsonc
96
+ // wrangler.jsonc
97
+ {
98
+ "ai": { "binding": "AI" },
99
+ "durable_objects": {
100
+ "bindings": [{ "name": "ChatAgent", "class_name": "ChatAgent" }]
101
+ },
102
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ChatAgent"] }]
103
+ }
104
+ ```
105
+
106
+ The `new_sqlite_classes` migration is required — `AIChatAgent` uses SQLite for message persistence and stream chunk buffering.
107
+
108
+ ## How It Works
109
+
110
+ ```
111
+ ┌──────────┐ WebSocket ┌──────────────┐
112
+ │ Client │ ◀──────────────────────────────────▶ │ AIChatAgent │
113
+ │ │ │ │
114
+ │ useAgent │ CF_AGENT_USE_CHAT_REQUEST ──────▶ │ onChatMessage│
115
+ │ Chat │ │ │
116
+ │ │ ◀────── CF_AGENT_USE_CHAT_RESPONSE │ streamText │
117
+ │ │ (UIMessageChunk stream) │ │
118
+ │ │ │ SQLite │
119
+ │ │ ◀────── CF_AGENT_CHAT_MESSAGES │ (messages, │
120
+ │ │ (broadcast to all clients) │ chunks) │
121
+ └──────────┘ └──────────────┘
122
+ ```
123
+
124
+ 1. The client sends a message via WebSocket
125
+ 2. `AIChatAgent` persists messages to SQLite and calls your `onChatMessage` method
126
+ 3. Your method returns a streaming `Response` (typically from `streamText`)
127
+ 4. Chunks stream back over WebSocket in real-time
128
+ 5. When the stream completes, the final message is persisted and broadcast to all connections
129
+
130
+ ## Server API
131
+
132
+ ### `AIChatAgent`
133
+
134
+ Extends `Agent` from the `agents` package. Manages conversation state, persistence, and streaming.
135
+
136
+ ```typescript
137
+ import { AIChatAgent } from "@cloudflare/ai-chat";
138
+
139
+ export class ChatAgent extends AIChatAgent {
140
+ // Access current messages
141
+ // this.messages: ChatMessage[]
142
+
143
+ // Limit stored messages (optional)
144
+ maxPersistedMessages = 200;
145
+
146
+ // Collapse overlapping user submits to the latest one (optional)
147
+ // messageConcurrency = "latest";
148
+
149
+ async onChatMessage(onFinish?, options?) {
150
+ // onFinish: optional callback for streamText (cleanup is automatic)
151
+ // options.abortSignal: cancel signal
152
+ // options.body: custom data from client
153
+ // Return a Response (streaming or plain text)
154
+ }
155
+ }
156
+ ```
157
+
158
+ ### `onChatMessage`
159
+
160
+ This is the main method you override. It receives the conversation context and should return a `Response`.
161
+
162
+ **Streaming response** (most common):
163
+
164
+ ```typescript
165
+ async onChatMessage() {
166
+ const workersai = createWorkersAI({ binding: this.env.AI });
167
+
168
+ const result = streamText({
169
+ model: workersai("@cf/moonshotai/kimi-k2.7-code"),
170
+ system: "You are a helpful assistant.",
171
+ messages: await convertToModelMessages(this.messages)
172
+ });
173
+
174
+ return result.toUIMessageStreamResponse();
175
+ }
176
+ ```
177
+
178
+ **Plain text response**:
179
+
180
+ ```typescript
181
+ async onChatMessage() {
182
+ return new Response("Hello! I am a simple agent.", {
183
+ headers: { "Content-Type": "text/plain" }
184
+ });
185
+ }
186
+ ```
187
+
188
+ **Accessing custom body data and request ID**:
189
+
190
+ ```typescript
191
+ async onChatMessage(_onFinish, options) {
192
+ const { timezone, userId } = options?.body ?? {};
193
+ // Use these values in your LLM call or business logic
194
+
195
+ // options.requestId — unique identifier for this chat request,
196
+ // useful for logging and correlating events
197
+ console.log("Request ID:", options?.requestId);
198
+ }
199
+ ```
200
+
201
+ ### `this.messages`
202
+
203
+ The current conversation history, loaded from SQLite. This is an array of `UIMessage` objects from the AI SDK. Messages are automatically persisted after each interaction.
204
+
205
+ ### `maxPersistedMessages`
206
+
207
+ Cap the number of messages stored in SQLite. When the limit is exceeded, the oldest messages are deleted. This controls storage only — it does not affect what is sent to the LLM.
208
+
209
+ ```typescript
210
+ export class ChatAgent extends AIChatAgent {
211
+ maxPersistedMessages = 200;
212
+ }
213
+ ```
214
+
215
+ To control what is sent to the model, use the AI SDK's `pruneMessages()`:
216
+
217
+ ```typescript
218
+ import { streamText, convertToModelMessages, pruneMessages } from "ai";
219
+
220
+ async onChatMessage() {
221
+ const workersai = createWorkersAI({ binding: this.env.AI });
222
+
223
+ const result = streamText({
224
+ model: workersai("@cf/moonshotai/kimi-k2.7-code"),
225
+ messages: pruneMessages({
226
+ messages: await convertToModelMessages(this.messages),
227
+ reasoning: "before-last-message",
228
+ toolCalls: "before-last-2-messages"
229
+ })
230
+ });
231
+
232
+ return result.toUIMessageStreamResponse();
233
+ }
234
+ ```
235
+
236
+ ### `messageConcurrency`
237
+
238
+ Controls what happens when a new `sendMessage()` submit arrives while another
239
+ chat turn is already active or queued.
240
+
241
+ | Value | Behavior |
242
+ | ------------------------------- | -------------------------------------------------------------------- |
243
+ | `"queue"` | Process every submit in order (default, existing behavior) |
244
+ | `"latest"` | Keep only the newest overlapping submit |
245
+ | `"merge"` | Collapse overlapping queued user messages into one follow-up submit |
246
+ | `"drop"` | Ignore overlapping submits entirely |
247
+ | `{ strategy: "debounce", ... }` | Wait for a quiet period, then run only the latest overlapping submit |
248
+
249
+ ```typescript
250
+ export class ChatAgent extends AIChatAgent {
251
+ messageConcurrency = "latest";
252
+ }
253
+ ```
254
+
255
+ Debounce uses the same trailing-edge semantics as chat apps that wait for the
256
+ user to finish sending a burst of short messages:
257
+
258
+ ```typescript
259
+ export class ChatAgent extends AIChatAgent {
260
+ messageConcurrency = {
261
+ strategy: "debounce",
262
+ debounceMs: 1000
263
+ };
264
+ }
265
+ ```
266
+
267
+ **Choosing a strategy:**
268
+
269
+ - Building a focused assistant where each turn matters? Use `"latest"` — the user can correct themselves mid-stream and only the final message gets a response.
270
+ - Building a messaging or chat app where every message should be processed? Use `"queue"` (default) or `"merge"` to collapse rapid-fire messages into one turn.
271
+ - Want to prevent accidental double-sends? Use `"drop"` — overlapping submits are rejected and the client rolls back.
272
+ - Users send bursts of short messages (like a messaging app)? Use `"debounce"` to wait for a quiet window before responding.
273
+
274
+ **What the user sees:**
275
+
276
+ - `"queue"` — every message gets its own assistant response, in order. Standard chat behavior.
277
+ - `"latest"` — all user messages appear in the transcript, but only the last overlapping message gets an assistant response. Earlier overlapping messages sit in the history with no reply.
278
+ - `"merge"` — overlapping user messages are collapsed into one combined message in the transcript, which gets a single assistant response.
279
+ - `"drop"` — the overlapping message briefly appears (optimistic), then disappears when the server sends back the rollback.
280
+ - `"debounce"` — same as `"latest"`, but the response waits for a quiet period before starting.
281
+
282
+ Notes:
283
+
284
+ - This setting only applies to overlapping `sendMessage()` submits (`trigger: "submit-message"`)
285
+ - `regenerate()`, tool continuations, approvals, clears, and programmatic `saveMessages()` calls keep the existing serialized behavior
286
+ - `"latest"` and `"debounce"` still persist the skipped user messages in `this.messages`; they only suppress extra model turns
287
+ - `"drop"` rejects the overlapping submit before it is persisted
288
+
289
+ ### `waitForMcpConnections`
290
+
291
+ Controls whether `AIChatAgent` waits for MCP server connections to settle before calling `onChatMessage`. This ensures `this.mcp.getAITools()` returns the full set of tools, especially after Durable Object hibernation when connections are being restored in the background.
292
+
293
+ | Value | Behavior |
294
+ | --------------------- | --------------------------------------------- |
295
+ | `{ timeout: 10_000 }` | Wait up to 10 seconds (default) |
296
+ | `{ timeout: N }` | Wait up to `N` milliseconds |
297
+ | `true` | Wait indefinitely until all connections ready |
298
+ | `false` | Do not wait (old behavior before 0.2.0) |
299
+
300
+ ```typescript
301
+ export class ChatAgent extends AIChatAgent {
302
+ // Default — waits up to 10 seconds
303
+ // waitForMcpConnections = { timeout: 10_000 };
304
+
305
+ // Wait forever
306
+ waitForMcpConnections = true;
307
+
308
+ // Disable waiting
309
+ waitForMcpConnections = false;
310
+ }
311
+ ```
312
+
313
+ For lower-level control, call `this.mcp.waitForConnections()` directly inside your `onChatMessage` instead.
314
+
315
+ ### `persistMessages` and `saveMessages`
316
+
317
+ For advanced cases (schedule callbacks, webhook handlers, background tasks),
318
+ you can manually persist messages or queue programmatic turns:
319
+
320
+ ```typescript
321
+ // Persist messages without triggering a new response
322
+ await this.persistMessages(messages);
323
+
324
+ // Persist messages AND trigger onChatMessage
325
+ await this.saveMessages([...this.messages, newMessage]);
326
+
327
+ // Functional form: derive from latest transcript at execution time
328
+ // (e.g., from a schedule() callback or webhook handler)
329
+ await this.saveMessages((messages) => [...messages, syntheticMessage]);
330
+ ```
331
+
332
+ Use the functional form when background work needs to append or transform
333
+ messages against the latest persisted transcript when the turn actually starts.
334
+ This avoids stale baselines when multiple `saveMessages()` calls queue up
335
+ behind active work.
336
+
337
+ `saveMessages()` returns `{ requestId, status, error? }`. The `status` is
338
+ `"completed"` when the turn ran, `"error"` when the stream reported an error,
339
+ `"skipped"` when it was invalidated (chat cleared mid-flight), or `"aborted"`
340
+ when an external `AbortSignal` cancelled it before completion. When `status` is
341
+ `"error"`, `error` contains the stream error message when available.
342
+
343
+ Pass `options.signal` to cancel the turn from outside. Useful for forwarding
344
+ an upstream `AbortSignal` (e.g. an AI SDK tool `execute`'s `abortSignal` on a
345
+ parent agent) into a child DO's `saveMessages` call without knowing the
346
+ internally-generated request id:
347
+
348
+ ```typescript
349
+ const result = await this.saveMessages([...this.messages, newMessage], {
350
+ signal: abortController.signal
351
+ });
352
+ if (result.status === "aborted") {
353
+ // Partial chunks already streamed are persisted; the inference
354
+ // loop terminated when the signal aborted.
355
+ }
356
+ ```
357
+
358
+ The same `options.signal` is accepted by `continueLastTurn()`. See
359
+ [`cloudflare/agents#1406`](https://github.com/cloudflare/agents/issues/1406)
360
+ for the agent-tool orchestration pattern that motivated the API, and
361
+ [Agent Tools](./agent-tools.md) for using `AIChatAgent` and Think subclasses as
362
+ retained, streaming tools.
363
+
364
+ ### `onChatResponse`
365
+
366
+ Called after a chat turn reaches a terminal state. Override this to react when the agent finishes responding — broadcast state, process queued work, track analytics, or trigger follow-up messages. Successful turns and errors that produced partial assistant chunks persist the assistant message before the hook runs; errors that occur before any assistant chunks still fire the hook with an empty assistant message and `status: "error"`.
367
+
368
+ ```typescript
369
+ import { AIChatAgent, type ChatResponseResult } from "@cloudflare/ai-chat";
370
+
371
+ export class ChatAgent extends AIChatAgent {
372
+ protected async onChatResponse(result: ChatResponseResult) {
373
+ if (result.status === "completed") {
374
+ this.broadcast(JSON.stringify({ streaming: false }));
375
+ }
376
+ }
377
+ }
378
+ ```
379
+
380
+ The turn lock is released before `onChatResponse` runs, so it is safe to call `saveMessages` from inside the hook. This enables sequential queue processing:
381
+
382
+ ```typescript
383
+ protected async onChatResponse(result: ChatResponseResult) {
384
+ if (result.status === "completed" && this.workQueue.length > 0) {
385
+ const next = this.workQueue.shift()!;
386
+ await this.saveMessages([
387
+ ...this.messages,
388
+ { id: nanoid(), role: "user", parts: [{ type: "text", text: next }] }
389
+ ]);
390
+ }
391
+ }
392
+ ```
393
+
394
+ When `saveMessages` is called from `onChatResponse`, the inner turn's response is automatically drained — `onChatResponse` fires again for the inner response, allowing the queue to progress naturally. This continues until the queue is empty.
395
+
396
+ Responses triggered from inside `onChatResponse` do not fire the hook concurrently. They are drained sequentially after the outer hook returns.
397
+
398
+ **`ChatResponseResult` fields:**
399
+
400
+ | Field | Type | Description |
401
+ | -------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
402
+ | `message` | `UIMessage` | The finalized assistant message from this turn. Error turns can provide an empty assistant message if no chunks were produced. |
403
+ | `requestId` | `string` | The request ID associated with this turn |
404
+ | `continuation` | `boolean` | Whether this turn was a continuation (auto-continue) |
405
+ | `status` | `"completed" \| "error" \| "aborted"` | How the turn ended |
406
+ | `error` | `string \| undefined` | Error message when `status` is `"error"` |
407
+
408
+ `onChatResponse` fires for all turn completion paths: WebSocket chat requests, `saveMessages`, and auto-continuation after tool results or approvals.
409
+
410
+ ### Turn coordination helpers
411
+
412
+ `AIChatAgent` serializes chat turns — WebSocket requests, tool continuations,
413
+ `saveMessages()` calls all run one at a time. Most subclasses do not need to
414
+ think about this; the SDK handles the queuing automatically. If you configure
415
+ `messageConcurrency`, that policy decides which overlapping `sendMessage()` submits
416
+ make it into the queue.
417
+
418
+ Coordination becomes relevant when your subclass runs code **outside** the
419
+ normal `onChatMessage()` flow — for example, a `schedule()` callback that
420
+ injects a message, a workflow-switching method, or a custom clear handler that
421
+ scopes deletes to a particular workflow. In these situations, the subclass
422
+ needs to know whether the conversation is mid-stream or waiting on user input
423
+ before it can safely act on `this.messages`.
424
+
425
+ Three protected helpers cover these cases:
426
+
427
+ | Helper | Returns | When to use |
428
+ | ------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
429
+ | `waitUntilStable()` | `Promise<boolean>` | Before reading or writing messages — waits for any active stream, pending tool interactions, and queued continuations to finish |
430
+ | `resetTurnState()` | `void` | When discarding the current conversation state — aborts the active stream and invalidates queued continuations |
431
+ | `hasPendingInteraction()` | `boolean` | When you need a synchronous check for whether a tool is waiting on user input or approval |
432
+
433
+ #### How the turn lifecycle works
434
+
435
+ A chat turn starts when a WebSocket message or `saveMessages()` call enters the
436
+ queue and ends after the `_reply()` stream
437
+ finishes and the final assistant message is persisted. If a tool result or
438
+ approval arrives with
439
+ `autoContinue: true`, a continuation turn is queued automatically — the
440
+ conversation is not stable until that continuation finishes too.
441
+
442
+ A pending interaction is different from an active turn. The stream has finished,
443
+ but a tool part in the assistant message is in `input-available` or
444
+ `approval-requested` state — the SDK is waiting for the client to send a result
445
+ or approval. Until the user responds, `this.messages` reflects the pending
446
+ state.
447
+
448
+ `waitUntilStable()` handles both cases: it drains the turn queue, checks for
449
+ pending interactions, waits for any in-flight tool applies, and loops until
450
+ nothing is left. It only returns `true` once the conversation is genuinely
451
+ idle.
452
+
453
+ #### Waiting before injecting messages
454
+
455
+ The most common pattern is a `schedule()` callback or `onConnect()` method that
456
+ needs to inject a synthetic message into the conversation. Call
457
+ `waitUntilStable()` before reading `this.messages` or calling `saveMessages()`:
458
+
459
+ ```typescript
460
+ async onTaskComplete(payload: { result: string }) {
461
+ const ready = await this.waitUntilStable({ timeout: 30_000 });
462
+ if (!ready) return; // timed out — a pending interaction was not resolved
463
+
464
+ const syntheticMessage = {
465
+ id: nanoid(),
466
+ role: "user" as const,
467
+ parts: [{ type: "text" as const, text: `Task result: ${payload.result}` }]
468
+ };
469
+
470
+ await this.saveMessages((messages) => [...messages, syntheticMessage]);
471
+ }
472
+ ```
473
+
474
+ Always pass a `timeout`. Without one, `waitUntilStable()` waits indefinitely —
475
+ if a tool is pending user approval and the user closes their browser, the
476
+ promise never resolves. The timeout lets you fail gracefully and retry later.
477
+
478
+ When `waitUntilStable()` returns `true`, `this.messages` is safe to read and
479
+ `saveMessages()` will not overlap with another turn. When it returns `false`,
480
+ the conversation is still in flux and you should not assume message state is
481
+ settled.
482
+
483
+ #### Checking pending interactions synchronously
484
+
485
+ `hasPendingInteraction()` is a synchronous check — it scans `this.messages`
486
+ for any assistant message with a tool part in `input-available` or
487
+ `approval-requested` state. Use it when you need to branch without awaiting:
488
+
489
+ ```typescript
490
+ async onConnect(connection, ctx) {
491
+ if (this.hasPendingInteraction()) {
492
+ connection.send(JSON.stringify({
493
+ type: "status",
494
+ message: "Waiting for your input on a pending tool action"
495
+ }));
496
+ }
497
+ }
498
+ ```
499
+
500
+ This does not tell you whether a stream is active — only whether a tool is
501
+ waiting on user input. For most coordination needs, prefer `waitUntilStable()`.
502
+
503
+ #### Resetting on workflow switch
504
+
505
+ Call `resetTurnState()` when the user switches context and the current stream
506
+ and any queued continuations are no longer relevant. It does three things:
507
+ increments the internal epoch (so queued continuations skip themselves), fires
508
+ the abort signal on the active stream, and clears any pending interaction
509
+ bookkeeping.
510
+
511
+ ```typescript
512
+ async switchWorkflow(newWorkflowId: string) {
513
+ this.resetTurnState();
514
+ this.workflowId = newWorkflowId;
515
+ }
516
+ ```
517
+
518
+ After `resetTurnState()`, the turn queue drains quickly — aborted turns finish
519
+ their cleanup and skipped continuations return immediately.
520
+
521
+ #### Overriding the clear handler
522
+
523
+ The SDK's built-in `CF_AGENT_CHAT_CLEAR` handler calls `resetTurnState()`
524
+ automatically. If your `onMessage` override intercepts `CF_AGENT_CHAT_CLEAR`
525
+ and returns before the SDK sees the message — for example, to scope the delete
526
+ to a specific workflow — the built-in handler never runs. The active stream
527
+ continues and queued continuations persist into the newly-cleared conversation.
528
+
529
+ Call `this.resetTurnState()` before performing your scoped delete:
530
+
531
+ ```typescript
532
+ import { MessageType } from "@cloudflare/ai-chat/types";
533
+
534
+ const _onMessage = this.onMessage.bind(this);
535
+ this.onMessage = async (connection, message) => {
536
+ if (typeof message === "string") {
537
+ const data = JSON.parse(message);
538
+ if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
539
+ this.resetTurnState();
540
+ this.sql`
541
+ DELETE FROM cf_ai_chat_agent_messages
542
+ WHERE workflow_id = ${this.workflowId}
543
+ `;
544
+ await this.saveMessages([]);
545
+ return;
546
+ }
547
+ }
548
+ return _onMessage(connection, message);
549
+ };
550
+ ```
551
+
552
+ ### Lifecycle Hooks
553
+
554
+ Override `onConnect` and `onClose` to add custom logic. Stream resumption and message sync are handled for you automatically — you do not need to call `super`:
555
+
556
+ ```typescript
557
+ export class ChatAgent extends AIChatAgent {
558
+ async onConnect(connection, ctx) {
559
+ // Your custom logic (e.g., logging, auth checks)
560
+ console.log("Client connected:", connection.id);
561
+ // Stream resumption and message sync are handled automatically
562
+ }
563
+
564
+ async onClose(connection, code, reason, wasClean) {
565
+ console.log("Client disconnected:", connection.id);
566
+ // Connection cleanup is handled automatically
567
+ }
568
+ }
569
+ ```
570
+
571
+ The `destroy()` method cancels any pending chat requests and cleans up stream state. It is called automatically when the Durable Object is evicted, but you can call it manually if needed.
572
+
573
+ ### Request Cancellation
574
+
575
+ When a user clicks "stop" in the chat UI, the client sends a `CF_AGENT_CHAT_REQUEST_CANCEL` message. The server propagates this to the `abortSignal` in `options`:
576
+
577
+ ```typescript
578
+ async onChatMessage(_onFinish, options) {
579
+ const result = streamText({
580
+ model: workersai("@cf/moonshotai/kimi-k2.7-code"),
581
+ messages: await convertToModelMessages(this.messages),
582
+ abortSignal: options?.abortSignal // Pass through for cancellation
583
+ });
584
+
585
+ return result.toUIMessageStreamResponse();
586
+ }
587
+ ```
588
+
589
+ If you do not pass `abortSignal` to `streamText`, the LLM call will continue running in the background even after the user cancels. Always forward it when possible.
590
+
591
+ ### Stream Recovery
592
+
593
+ When a Durable Object is evicted mid-stream (code update, inactivity timeout, resource limit), the LLM connection is severed permanently and the in-memory streaming state is lost. `chatRecovery` wraps each chat turn in a [`runFiber()`](./durable-execution.md), providing automatic `keepAlive` during streaming and a recovery hook on restart.
594
+
595
+ ```typescript
596
+ export class ChatAgent extends AIChatAgent {
597
+ override chatRecovery = true;
598
+ }
599
+ ```
600
+
601
+ When enabled, every `onChatMessage` call runs inside a fiber. If the agent is evicted mid-stream, the fiber row survives in SQLite. On the next activation, the framework detects the interrupted fiber, reconstructs the partial response from buffered stream chunks, and calls `onChatRecovery`.
602
+
603
+ `AIChatAgent` defaults `chatRecovery` to `false` so existing chat agents only get client reconnect/resumable-stream behavior. `Think` defaults it to `true`.
604
+
605
+ > **Assign `chatRecovery` as a class field or in the constructor — never in `onStart()`.** On every wake the SDK evaluates recovery budgets (and may seal an interrupted turn, firing `onExhausted`) _before_ your `onStart()` body runs. A config produced inside `onStart()` is therefore read as the built-in defaults at the moment recovery decides, so your `maxRecoveryWork` / `shouldKeepRecovering` / `onExhausted` silently never apply to the recovery that matters. The SDK logs a one-time warning if it detects `chatRecovery` being assigned during `onStart()`.
606
+
607
+ #### `onChatRecovery`
608
+
609
+ Override to implement provider-specific recovery. The default behavior persists the partial response and schedules a continuation via `continueLastTurn()`.
610
+
611
+ ```typescript
612
+ export class ChatAgent extends AIChatAgent {
613
+ override chatRecovery = true;
614
+
615
+ override async onChatRecovery(
616
+ ctx: ChatRecoveryContext
617
+ ): Promise<ChatRecoveryOptions> {
618
+ // Inspect what was generated before eviction
619
+ console.log(`Recovered ${ctx.partialText.length} chars of partial text`);
620
+
621
+ // Default: persist partial + schedule continuation
622
+ return {};
623
+ }
624
+ }
625
+ ```
626
+
627
+ **`ChatRecoveryContext`:**
628
+
629
+ | Field | Type | Description |
630
+ | ----------------- | -------------------------------------- | ---------------------------------------------------------------------------------------- |
631
+ | `incidentId` | `string` | Stable ID for this recovery incident |
632
+ | `attempt` | `number` | Current attempt number for this incident, starting at 1 |
633
+ | `maxAttempts` | `number` | Configured attempt cap before terminal exhaustion |
634
+ | `recoveryKind` | `"retry" \| "continue"` | Whether recovery will retry an unanswered user turn or continue a partial assistant turn |
635
+ | `streamId` | `string` | ID of the interrupted stream |
636
+ | `requestId` | `string` | ID of the original chat request |
637
+ | `partialText` | `string` | Text generated before eviction |
638
+ | `partialParts` | `MessagePart[]` | Message parts (text, reasoning, tool calls) generated before eviction |
639
+ | `recoveryData` | `unknown \| null` | Data from `this.stash()` — entirely user-controlled |
640
+ | `messages` | `ChatMessage[]` | Full conversation history |
641
+ | `lastBody` | `Record<string, unknown> \| undefined` | The original request body |
642
+ | `lastClientTools` | `ClientToolSchema[] \| undefined` | Client tool schemas from the original request |
643
+ | `createdAt` | `number` | Epoch milliseconds when the underlying fiber started |
644
+
645
+ **`ChatRecoveryOptions`:**
646
+
647
+ | Field | Default | Description |
648
+ | ---------- | ------- | ------------------------------------------------- |
649
+ | `persist` | `true` | Save the partial response as an assistant message |
650
+ | `continue` | `true` | Schedule a continuation via `continueLastTurn()` |
651
+
652
+ Common return values:
653
+
654
+ - `{}` — persist partial + auto-continue (default, works with providers that support assistant prefill)
655
+ - `{ continue: false }` — persist partial but do not auto-continue (handle continuation yourself)
656
+ - `{ persist: false, continue: false }` — do not persist the unsettled remainder and handle everything yourself (e.g., retrieve a completed response from the provider)
657
+
658
+ Settled work is never dropped: `persist: false` only suppresses persistence of a partial that has nothing settled to lose. A partial that already carries settled tool results (completed, often non-idempotent work) is persisted regardless, so an app cannot accidentally discard completed tool calls — and never needs `{ persist: true }` just to stay safe.
659
+
660
+ When recovery happens before any stream chunks were written, there is no partial assistant message to continue. If the latest persisted message is still the unanswered user message from the interrupted turn, the framework retries that turn automatically unless `continue` is `false`.
661
+
662
+ `chatRecovery` can also be configured with budgets and terminal behavior:
663
+
664
+ ```typescript
665
+ override chatRecovery = {
666
+ maxAttempts: 10,
667
+ stableTimeoutMs: 10_000,
668
+ terminalMessage: "The assistant was interrupted and could not recover.",
669
+ // Primary stuck-turn bound. Resets on every progress-bearing attempt, so a
670
+ // turn that keeps producing content survives unbounded interruption.
671
+ noProgressTimeoutMs: 5 * 60 * 1000,
672
+ // Runaway-loop guard. Defaults to a finite backstop (1000). Set a different
673
+ // value to tune when a turn that keeps emitting content but never converges
674
+ // is sealed.
675
+ maxRecoveryWork: 200,
676
+ // Tight retry budget for a Durable Object memory-limit reset (the isolate
677
+ // exceeded its 128 MB limit). Defaults to 3; an OOM usually re-OOMs on
678
+ // re-run, so recovery seals it with `out_of_memory` after a few attempts.
679
+ maxOomRetries: 3,
680
+ // Caller policy consulted from the second recovery attempt onward. Return
681
+ // false to stop recovery. This is where you enforce a token/cost budget.
682
+ // Note: this is called as `config.shouldKeepRecovering(ctx)`, so it is not
683
+ // bound to the agent instance — track spend in your own store keyed by the
684
+ // incident.
685
+ async shouldKeepRecovering(ctx) {
686
+ return (await getSpendForTurn(ctx.recoveryRootRequestId)) < MAX_SPEND;
687
+ },
688
+ async onExhausted(ctx) {
689
+ console.warn("Chat recovery exhausted", ctx.incidentId, ctx.reason);
690
+ }
691
+ };
692
+ ```
693
+
694
+ **`chatRecovery` configuration:**
695
+
696
+ | Field | Default | Description |
697
+ | ---------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
698
+ | `maxAttempts` | `10` | Attempt cap before terminal exhaustion. Resets on forward progress, so it catches a tight no-progress alarm loop, not a healthy long turn. |
699
+ | `stableTimeoutMs` | `10_000` | How long a recovery attempt waits for the isolate to reach stable state before rescheduling. |
700
+ | `terminalMessage` | generic message | The message shown to the user when recovery is given up on. |
701
+ | `noProgressTimeoutMs` | `300_000` (5 min) | Primary stuck-turn bound: how long an incident may go without forward progress before it is sealed (`no_progress_timeout`). **Resets on every progress-bearing attempt**, so a turn that keeps producing content survives unbounded interruption. |
702
+ | `maxRecoveryWork` | `1000` | Runaway-loop guard. Maximum produced content/tool units since the incident began before a still-progressing turn is sealed (`work_budget_exceeded`). A generous finite backstop so an agent that keeps emitting a little content but never converges (for example an isolate that runs out of memory mid-stream on every recovery) cannot loop forever. Work only accrues from the first interruption until the turn completes. Set a higher value, or `Infinity`, for a very long agentic turn that legitimately needs more. |
703
+ | `maxOomRetries` | `3` | Tight retry budget for the specific case of a Durable Object isolate exceeding its memory limit and being reset mid-turn. An OOM is usually deterministic (the turn's working set no longer fits in 128 MB) so re-running re-OOMs, but a single OOM can be a transient spike — so recovery retries this many times before sealing with `out_of_memory`. Counts only attempts that ended in an OOM (not total attempts), so a turn interrupted by deploys is unaffected. Set `0` to seal on the first OOM. Far tighter than `maxRecoveryWork` because an OOM is attributable and each re-run re-runs the model. |
704
+ | `shouldKeepRecovering` | — | Caller policy consulted from the second recovery attempt onward (never on the first detection, never once a hard bound has sealed the incident). Return `false` to stop recovery. The hook point for a token/cost budget — `ctx.work` is a coarse segment count, not tokens, so track real spend yourself. |
705
+ | `onExhausted` | — | Called once when recovery is given up on, before the terminal message is delivered. Inspect `ctx.reason` for why. |
706
+
707
+ **`ChatRecoveryProgressContext`** (the `ctx` passed to `shouldKeepRecovering`):
708
+
709
+ | Field | Type | Description |
710
+ | ----------------------- | ----------------------- | ------------------------------------------------------------------------------------------------- |
711
+ | `incidentId` | `string` | Stable ID for this recovery incident. |
712
+ | `requestId` | `string` | Request ID for the current continuation (changes per chained continuation). |
713
+ | `recoveryRootRequestId` | `string` | Stable ID for the whole continuation chain — the right key for per-incident budget tracking. |
714
+ | `attempt` | `number` | Attempt number for this incident (2 or greater when this hook runs). |
715
+ | `maxAttempts` | `number` | Configured attempt cap. |
716
+ | `recoveryKind` | `"retry" \| "continue"` | Whether recovery retries an unanswered user turn or continues a partial assistant turn. |
717
+ | `work` | `number` | Coarse, monotonic count of content/tool segments produced since the incident opened (not tokens). |
718
+ | `ageMs` | `number` | Wall-clock ms since the incident's first interruption. |
719
+
720
+ A progressing turn survives unbounded interruption (for example a dense deploy window) as long as it keeps making forward progress and stays under the `maxRecoveryWork` backstop. Recovery is sealed only by one of these `ctx.reason` values:
721
+
722
+ - `no_progress_timeout` — no forward progress within the no-progress window (a stuck turn).
723
+ - `max_attempts_exceeded` — the attempt cap was spent on a tight no-progress alarm loop.
724
+ - `work_budget_exceeded` — the turn kept producing content but exceeded `maxRecoveryWork` (a runaway loop).
725
+ - `out_of_memory` — recovery attempts kept hitting a Durable Object memory-limit reset until the tight `maxOomRetries` budget drained.
726
+ - `recovery_aborted` — your `shouldKeepRecovering` hook returned `false`.
727
+ - `stable_timeout` — recovery attempts kept timing out waiting for stable state until the budget drained (extreme churn).
728
+
729
+ > `maxRecoveryWork` defaults to a generous finite backstop (`1000`) rather than no cap, so a runaway turn cannot loop forever out of the box. The default is far above what a healthy interrupted turn produces; if you lower it, pick a cap well above a healthy turn's output, and for a precise budget prefer `shouldKeepRecovering` with real token/cost accounting. A very long agentic turn that legitimately produces a large amount of content under heavy interruption can raise the cap or set it to `Infinity` to restore fully-unbounded recovery.
730
+
731
+ > **Out-of-memory crash loops have a last-resort backstop.** A severe memory-limit reset can bypass the recovery budgets above entirely — for example if the Durable Object out-of-memories while _loading its state on wake_, before recovery even evaluates, or if the budget's own bookkeeping writes also out-of-memory. Left unhandled, the platform auto-retries the alarm forever, re-running the doomed (billable) turn each cycle. The SDK guards this at the alarm boundary: after `maxAlarmMemoryLimitStrikes` (a base `Agent` static option, default `3`) consecutive alarms end in a memory-limit reset, it seals the interrupted turn with `out_of_memory` and stops the loop, emitting an `alarm:memory_limit_reset` observability event. This bounds the blast radius (and the bill); it does not shrink the working set — a turn whose context genuinely no longer fits in 128 MB needs a smaller transcript/fewer or smaller tool results.
732
+
733
+ #### Turns waiting on a human are not sealed
734
+
735
+ A turn parked on a pending **client** interaction — a tool part in `input-available` state for a client-side tool (one with no server `execute`, whose result the client replays), or a part in `approval-requested` state — is _waiting on the human_, not stuck. While such an interaction is pending, the turn is exempt from every recovery budget: the no-progress window, attempt cap, `maxRecoveryWork`, and `shouldKeepRecovering` are all suspended, so a slow human (for example, a user who takes minutes to answer a confirmation prompt that was interrupted by a deploy) never trips a seal. Instead of rescheduling or exhausting, recovery **parks** the incident (status `skipped`, reason `awaiting_client_interaction`) and clears the live "recovering…" indicator; the client's eventual reconnect-and-replay resumes the turn through the normal continuation path. A client that never returns is reclaimed by the incident TTL sweep and Durable Object idle eviction.
736
+
737
+ This exemption is intentionally **client-only**. A server tool whose `execute()` died with the evicted isolate is a genuine orphan — nothing will ever resolve it — so server-tool interruptions are not exempt and recover normally through the transcript-repair pass.
738
+
739
+ Monitor recovery through observability:
740
+
741
+ ```ts
742
+ import { subscribe } from "agents/observability";
743
+
744
+ const unsubscribe = subscribe("chat", (event) => {
745
+ if (event.type === "chat:recovery:exhausted") {
746
+ console.error("Chat recovery exhausted", event.payload);
747
+ }
748
+ });
749
+ ```
750
+
751
+ #### Recovering status on the client
752
+
753
+ While a turn is being recovered, the agent broadcasts a `cf_agent_chat_recovering` status frame so clients can show a "recovering…" indicator instead of looking frozen. It is set when a recovery continuation is scheduled and cleared on every terminal outcome (so the indicator never spins forever). `@cloudflare/think` also replays it on connect, so a client that joins mid-recovery still learns the turn is working. Consume it via `useAgentChat`'s `isRecovering` flag (see [Client API](#useagentchat)). The signal is purely advisory and backward-compatible — clients that do not understand it ignore it.
754
+
755
+ > `@cloudflare/ai-chat` broadcasts the live signal but does not yet replay it on connect (a client connecting mid-recovery will not be re-told until it reconnects to an active stream).
756
+
757
+ Transcript repairs — healing orphaned tool calls (preserving them as errored results rather than deleting them, so the record survives and the model does not silently re-run the tool) and normalizing malformed/stringified or missing tool inputs before a provider call — are emitted on the `transcript` channel.
758
+
759
+ #### Guarding against stale recoveries
760
+
761
+ After a long outage (an eviction combined with a slow reactivation, or a tool/container that became unreachable mid-stream), auto-continuing can replay a turn the user has already moved on from — or worse, kick off a continuation that keeps failing in the same way and occupies the turn queue while new messages pile up behind it.
762
+
763
+ Use `ctx.createdAt` to suppress continuation for turns that have been orphaned too long:
764
+
765
+ ```typescript
766
+ override async onChatRecovery(
767
+ ctx: ChatRecoveryContext
768
+ ): Promise<ChatRecoveryOptions> {
769
+ const ageMs = Date.now() - ctx.createdAt;
770
+ if (ageMs > 2 * 60 * 1000) {
771
+ // Persist whatever was already streamed so the user sees it, but do not
772
+ // spawn a fresh inference against a potentially broken tool state.
773
+ return { continue: false };
774
+ }
775
+ return {};
776
+ }
777
+ ```
778
+
779
+ For loop protection (suppressing continuation after N recoveries of the same turn), pair this with a small per-assistant-message counter that `onChatResponse` clears on successful completion. The counter lives entirely in your agent — no framework support required:
780
+
781
+ ```typescript
782
+ override async onChatRecovery(
783
+ ctx: ChatRecoveryContext
784
+ ): Promise<ChatRecoveryOptions> {
785
+ const target = ctx.messages.filter((m) => m.role === "assistant").at(-1);
786
+ if (!target) return {};
787
+
788
+ const row = this.sql<{ count: number }>`
789
+ SELECT count FROM my_recoveries WHERE assistant_id = ${target.id}
790
+ `;
791
+ const count = (row[0]?.count ?? 0) + 1;
792
+ this.sql`
793
+ INSERT INTO my_recoveries (assistant_id, count, last_at)
794
+ VALUES (${target.id}, ${count}, ${Date.now()})
795
+ ON CONFLICT(assistant_id) DO UPDATE SET count = excluded.count, last_at = excluded.last_at
796
+ `;
797
+ if (count >= 2) return { continue: false };
798
+ return {};
799
+ }
800
+
801
+ override async onChatResponse(result: ChatResponseResult): Promise<void> {
802
+ if (result.status === "completed") {
803
+ this.sql`DELETE FROM my_recoveries WHERE assistant_id = ${result.message.id}`;
804
+ }
805
+ }
806
+ ```
807
+
808
+ #### `continueLastTurn`
809
+
810
+ Appends to the last assistant message by re-calling `onChatMessage` with the saved request body. The response is streamed as a continuation — appended to the existing assistant message, not a new one. No synthetic user message is created.
811
+
812
+ ```typescript
813
+ protected continueLastTurn(
814
+ body?: Record<string, unknown>,
815
+ options?: SaveMessagesOptions
816
+ ): Promise<SaveMessagesResult>;
817
+ ```
818
+
819
+ The optional `options.signal` accepts an external `AbortSignal` for cancellation, matching the `saveMessages` contract.
820
+
821
+ Called automatically by the default recovery path. Can also be called manually from scheduled callbacks or other entry points. The optional `body` parameter merges with the saved `_lastBody`.
822
+
823
+ #### Stashing recovery data
824
+
825
+ Use `this.stash()` inside `onChatMessage` to persist provider-specific data for recovery. The stash is stored in the fiber's SQLite row, separate from agent state, and available as `ctx.recoveryData` in `onChatRecovery`.
826
+
827
+ ```typescript
828
+ async onChatMessage(_onFinish, options) {
829
+ const result = streamText({
830
+ model: openai("gpt-5.4"),
831
+ messages: await convertToModelMessages(this.messages),
832
+ providerOptions: { openai: { store: true } },
833
+ includeRawChunks: true,
834
+ onChunk: ({ chunk }) => {
835
+ if (chunk.type === "raw") {
836
+ const raw = chunk.rawValue as { type?: string; response?: { id?: string } };
837
+ if (raw?.type === "response.created" && raw.response?.id) {
838
+ this.stash({ responseId: raw.response.id });
839
+ }
840
+ }
841
+ }
842
+ });
843
+ return result.toUIMessageStreamResponse();
844
+ }
845
+ ```
846
+
847
+ #### Recovery strategies by provider
848
+
849
+ The right strategy depends on whether the provider supports assistant prefill and whether the response continues server-side after disconnection:
850
+
851
+ | Provider | Strategy | Token cost |
852
+ | ---------------------- | ------------------------------------------------------------ | ---------- |
853
+ | Workers AI | `continueLastTurn()` — model continues via assistant prefill | Low |
854
+ | OpenAI (Responses API) | Retrieve completed response by ID — zero wasted tokens | Zero |
855
+ | Anthropic | Persist partial, send a synthetic user message to continue | Medium |
856
+
857
+ For a complete multi-provider implementation, see the [`forever-chat` example](https://github.com/cloudflare/agents/tree/main/experimental/forever-chat) and the [`forever.md` design doc](https://github.com/cloudflare/agents/tree/main/experimental/forever.md). For how chat recovery fits into the broader long-running agents story, see [Long-Running Agents: Recovering interrupted LLM streams](./long-running-agents.md#recovering-interrupted-llm-streams).
858
+
859
+ ## Client API
860
+
861
+ ### `useAgentChat`
862
+
863
+ React hook that connects to an `AIChatAgent` over WebSocket. Wraps the AI SDK's `useChat` with a native WebSocket transport.
864
+
865
+ ```tsx
866
+ import { useAgent } from "agents/react";
867
+ import { useAgentChat } from "@cloudflare/ai-chat/react";
868
+
869
+ function Chat() {
870
+ const agent = useAgent({ agent: "ChatAgent" });
871
+ const {
872
+ messages,
873
+ sendMessage,
874
+ clearHistory,
875
+ addToolOutput,
876
+ addToolApprovalResponse,
877
+ setMessages,
878
+ status,
879
+ isServerStreaming,
880
+ isStreaming,
881
+ isRecovering
882
+ } = useAgentChat({ agent });
883
+
884
+ // ...
885
+ }
886
+ ```
887
+
888
+ ### Options
889
+
890
+ | Option | Type | Default | Description |
891
+ | ----------------------------- | ----------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
892
+ | `agent` | `ReturnType<typeof useAgent>` | Required | Agent connection from `useAgent` |
893
+ | `onToolCall` | `({ toolCall, addToolOutput }) => void` | — | Handle client-side tool execution |
894
+ | `autoContinueAfterToolResult` | `boolean` | `true` | Auto-continue conversation after client tool results and approvals |
895
+ | `resume` | `boolean` | `true` | Enable automatic stream resumption on reconnect |
896
+ | `cancelOnClientAbort` | `boolean` | `false` | Cancel the server turn when generic client stream abort/cleanup occurs. Explicit `stop()` always cancels the server turn |
897
+ | `body` | `object \| () => object` | — | Custom data sent with every request |
898
+ | `prepareSendMessagesRequest` | `(options) => { body?, headers? }` | — | Advanced per-request customization |
899
+ | `tools` | `Record<string, AITool>` | — | Dynamic client-defined tools for SDK/platform use cases. Schemas are sent to the server automatically |
900
+ | `getInitialMessages` | `(options) => Promise<ChatMessage[]>` or `null` | — | Custom initial message loader. Set to `null` to skip the HTTP fetch entirely (useful when providing `messages` directly) |
901
+ | `syncMessagesToServer` | `boolean` | `true` | When `true`, `setMessages` pushes the transcript to the server. Set to `false` for hosts with server-authoritative transcript storage so `setMessages` updates the local view only |
902
+
903
+ ### Return Values
904
+
905
+ | Property | Type | Description |
906
+ | ------------------------- | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
907
+ | `messages` | `ChatMessage[]` | Current conversation messages |
908
+ | `sendMessage` | `(message) => void` | Send a message |
909
+ | `clearHistory` | `() => void` | Clear conversation (client and server) |
910
+ | `addToolOutput` | `({ toolCallId, output }) => void` | Provide output for a client-side tool |
911
+ | `addToolApprovalResponse` | `({ id, approved }) => void` | Approve or reject a tool requiring approval |
912
+ | `setMessages` | `(messages \| updater) => void` | Set messages directly (syncs to server) |
913
+ | `status` | `string` | `"idle"`, `"submitted"`, `"streaming"`, or `"error"` |
914
+ | `isServerStreaming` | `boolean` | `true` when a server-initiated stream is active (e.g. from `saveMessages`) |
915
+ | `isStreaming` | `boolean` | `true` when any stream is active (client or server-initiated) |
916
+ | `isRecovering` | `boolean` | `true` while a durable turn is being recovered (interrupted and resuming). Distinct from `isStreaming` — a recovering turn is not producing tokens yet. Render a "recovering…" hint; most UIs treat `isStreaming \|\| isRecovering` as "busy" |
917
+
918
+ ## Tools
919
+
920
+ `AIChatAgent` supports three tool patterns, all using the AI SDK's `tool()` function:
921
+
922
+ | Pattern | Where it runs | When to use |
923
+ | ----------- | ---------------------------- | --------------------------------------------- |
924
+ | Server-side | Server (automatic) | API calls, database queries, computations |
925
+ | Client-side | Browser (via `onToolCall`) | Geolocation, clipboard, camera, local storage |
926
+ | Approval | Server (after user approval) | Payments, deletions, external actions |
927
+
928
+ ### Server-Side Tools
929
+
930
+ Tools with an `execute` function run automatically on the server:
931
+
932
+ ```typescript
933
+ import { streamText, convertToModelMessages, tool, stepCountIs } from "ai";
934
+ import { z } from "zod";
935
+
936
+ async onChatMessage() {
937
+ const workersai = createWorkersAI({ binding: this.env.AI });
938
+
939
+ const result = streamText({
940
+ model: workersai("@cf/moonshotai/kimi-k2.7-code"),
941
+ messages: await convertToModelMessages(this.messages),
942
+ tools: {
943
+ getWeather: tool({
944
+ description: "Get weather for a city",
945
+ inputSchema: z.object({ city: z.string() }),
946
+ execute: async ({ city }) => {
947
+ const data = await fetchWeather(city);
948
+ return { temperature: data.temp, condition: data.condition };
949
+ }
950
+ })
951
+ },
952
+ stopWhen: stepCountIs(5)
953
+ });
954
+
955
+ return result.toUIMessageStreamResponse();
956
+ }
957
+ ```
958
+
959
+ ### Client-Side Tools
960
+
961
+ Define a tool on the server without `execute`, then handle it on the client with `onToolCall`. Use this for tools that need browser APIs:
962
+
963
+ **Server:**
964
+
965
+ ```typescript
966
+ tools: {
967
+ getLocation: tool({
968
+ description: "Get the user's location from the browser",
969
+ inputSchema: z.object({})
970
+ // No execute — the client handles it
971
+ });
972
+ }
973
+ ```
974
+
975
+ **Client:**
976
+
977
+ ```tsx
978
+ const { messages, sendMessage } = useAgentChat({
979
+ agent,
980
+ onToolCall: async ({ toolCall, addToolOutput }) => {
981
+ if (toolCall.toolName === "getLocation") {
982
+ const pos = await new Promise((resolve, reject) =>
983
+ navigator.geolocation.getCurrentPosition(resolve, reject)
984
+ );
985
+ addToolOutput({
986
+ toolCallId: toolCall.toolCallId,
987
+ output: { lat: pos.coords.latitude, lng: pos.coords.longitude }
988
+ });
989
+ }
990
+ }
991
+ });
992
+ ```
993
+
994
+ When the LLM invokes `getLocation`, the stream pauses. The `onToolCall` callback fires, your code provides the output, and the conversation continues.
995
+
996
+ ### Dynamic Client Tools (SDK/Platform Pattern)
997
+
998
+ For SDKs and platforms where tools are defined dynamically by the embedding application at runtime, use the `tools` option on `useAgentChat` and `createToolsFromClientSchemas()` on the server:
999
+
1000
+ **Server:**
1001
+
1002
+ ```typescript
1003
+ import { createToolsFromClientSchemas } from "@cloudflare/ai-chat";
1004
+
1005
+ async onChatMessage(_onFinish, options) {
1006
+ const result = streamText({
1007
+ model: workersai("@cf/moonshotai/kimi-k2.7-code"),
1008
+ messages: await convertToModelMessages(this.messages),
1009
+ tools: createToolsFromClientSchemas(options?.clientTools)
1010
+ });
1011
+ return result.toUIMessageStreamResponse();
1012
+ }
1013
+ ```
1014
+
1015
+ **Client:**
1016
+
1017
+ ```tsx
1018
+ import { useAgentChat, type AITool } from "@cloudflare/ai-chat/react";
1019
+
1020
+ const tools: Record<string, AITool> = {
1021
+ getPageTitle: {
1022
+ description: "Get the current page title",
1023
+ parameters: { type: "object", properties: {} },
1024
+ execute: async () => ({ title: document.title })
1025
+ }
1026
+ };
1027
+
1028
+ const { messages, sendMessage } = useAgentChat({
1029
+ agent,
1030
+ tools,
1031
+ onToolCall: async ({ toolCall, addToolOutput }) => {
1032
+ const tool = tools[toolCall.toolName];
1033
+ if (tool?.execute) {
1034
+ const output = await tool.execute(toolCall.input);
1035
+ addToolOutput({ toolCallId: toolCall.toolCallId, output });
1036
+ }
1037
+ }
1038
+ });
1039
+ ```
1040
+
1041
+ For most apps, server-side tools with `tool()` and `onToolCall` are simpler and provide full Zod type safety. Use dynamic client tools when the server does not know the tool surface at deploy time.
1042
+
1043
+ ### Tool Approval (Human-in-the-Loop)
1044
+
1045
+ Use `needsApproval` for tools that require user confirmation before executing:
1046
+
1047
+ **Server:**
1048
+
1049
+ ```typescript
1050
+ tools: {
1051
+ processPayment: tool({
1052
+ description: "Process a payment",
1053
+ inputSchema: z.object({
1054
+ amount: z.number(),
1055
+ recipient: z.string()
1056
+ }),
1057
+ needsApproval: async ({ amount }) => amount > 100,
1058
+ execute: async ({ amount, recipient }) => charge(amount, recipient)
1059
+ });
1060
+ }
1061
+ ```
1062
+
1063
+ **Client:**
1064
+
1065
+ ```tsx
1066
+ import { isToolUIPart, getToolName } from "ai";
1067
+
1068
+ const { messages, addToolApprovalResponse } = useAgentChat({ agent });
1069
+
1070
+ // Render pending approvals from message parts
1071
+ {
1072
+ messages.map((msg) =>
1073
+ msg.parts
1074
+ .filter(
1075
+ (part) =>
1076
+ isToolUIPart(part) &&
1077
+ "approval" in part &&
1078
+ part.state === "approval-requested"
1079
+ )
1080
+ .map((part) => (
1081
+ <div key={part.toolCallId}>
1082
+ <p>Approve {getToolName(part)}?</p>
1083
+ <button
1084
+ onClick={() =>
1085
+ addToolApprovalResponse({
1086
+ id: part.approval?.id,
1087
+ approved: true
1088
+ })
1089
+ }
1090
+ >
1091
+ Approve
1092
+ </button>
1093
+ <button
1094
+ onClick={() =>
1095
+ addToolApprovalResponse({
1096
+ id: part.approval?.id,
1097
+ approved: false
1098
+ })
1099
+ }
1100
+ >
1101
+ Reject
1102
+ </button>
1103
+ </div>
1104
+ ))
1105
+ );
1106
+ }
1107
+ ```
1108
+
1109
+ When denied, the tool part transitions to `output-denied`. You can also use `addToolOutput` with `state: "output-error"` for custom denial messages — see [Human in the Loop](./human-in-the-loop.md) for details.
1110
+
1111
+ ## Custom Request Data
1112
+
1113
+ Include custom data with every chat request using the `body` option:
1114
+
1115
+ ```tsx
1116
+ const { messages, sendMessage } = useAgentChat({
1117
+ agent,
1118
+ body: {
1119
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
1120
+ userId: currentUser.id
1121
+ }
1122
+ });
1123
+ ```
1124
+
1125
+ For dynamic values, use a function:
1126
+
1127
+ ```tsx
1128
+ body: () => ({
1129
+ token: getAuthToken(),
1130
+ timestamp: Date.now()
1131
+ });
1132
+ ```
1133
+
1134
+ Access these fields on the server:
1135
+
1136
+ ```typescript
1137
+ async onChatMessage(_onFinish, options) {
1138
+ const { timezone, userId } = options?.body ?? {};
1139
+ // ...
1140
+ }
1141
+ ```
1142
+
1143
+ For advanced per-request customization (custom headers, different body per request), use `prepareSendMessagesRequest`:
1144
+
1145
+ ```tsx
1146
+ const { messages, sendMessage } = useAgentChat({
1147
+ agent,
1148
+ prepareSendMessagesRequest: async ({ messages, trigger }) => ({
1149
+ headers: { Authorization: `Bearer ${await getToken()}` },
1150
+ body: { requestedAt: Date.now() }
1151
+ })
1152
+ });
1153
+ ```
1154
+
1155
+ ## Data Parts
1156
+
1157
+ Data parts let you attach typed JSON to messages alongside text — progress indicators, source citations, token usage, or any structured data your UI needs.
1158
+
1159
+ ### Writing Data Parts (Server)
1160
+
1161
+ Use `createUIMessageStream` with `writer.write()` to send data parts from the server:
1162
+
1163
+ ```ts
1164
+ import {
1165
+ streamText,
1166
+ convertToModelMessages,
1167
+ createUIMessageStream,
1168
+ createUIMessageStreamResponse
1169
+ } from "ai";
1170
+
1171
+ export class ChatAgent extends AIChatAgent {
1172
+ async onChatMessage() {
1173
+ const workersai = createWorkersAI({ binding: this.env.AI });
1174
+
1175
+ const stream = createUIMessageStream({
1176
+ execute: async ({ writer }) => {
1177
+ const result = streamText({
1178
+ model: workersai("@cf/moonshotai/kimi-k2.7-code"),
1179
+ messages: await convertToModelMessages(this.messages)
1180
+ });
1181
+
1182
+ // Merge the LLM stream
1183
+ writer.merge(result.toUIMessageStream());
1184
+
1185
+ // Write a data part — persisted to message.parts
1186
+ writer.write({
1187
+ type: "data-sources",
1188
+ id: "src-1",
1189
+ data: { query: "agents", status: "searching", results: [] }
1190
+ });
1191
+
1192
+ // Later: update the same part in-place (same type + id)
1193
+ writer.write({
1194
+ type: "data-sources",
1195
+ id: "src-1",
1196
+ data: {
1197
+ query: "agents",
1198
+ status: "found",
1199
+ results: ["Agents SDK docs", "Durable Objects guide"]
1200
+ }
1201
+ });
1202
+ }
1203
+ });
1204
+
1205
+ return createUIMessageStreamResponse({ stream });
1206
+ }
1207
+ }
1208
+ ```
1209
+
1210
+ ### Three Patterns
1211
+
1212
+ | Pattern | How | Persisted? | Use case |
1213
+ | ------------------ | ------------------------------------------------ | ---------- | ------------------------------------- |
1214
+ | **Reconciliation** | Same `type` + `id` → updates in-place | Yes | Progressive state (searching → found) |
1215
+ | **Append** | No `id`, or different `id` → appends | Yes | Log entries, multiple citations |
1216
+ | **Transient** | `transient: true` → not added to `message.parts` | No | Ephemeral status (thinking indicator) |
1217
+
1218
+ Transient parts are broadcast to connected clients in real time but excluded from SQLite persistence and `message.parts`. Use the `onData` callback to consume them.
1219
+
1220
+ ### Reading Data Parts (Client)
1221
+
1222
+ Non-transient data parts appear in `message.parts`. Use the `UIMessage` generic to type them:
1223
+
1224
+ ```ts
1225
+ import { useAgentChat } from "@cloudflare/ai-chat/react";
1226
+ import type { UIMessage } from "ai";
1227
+
1228
+ type ChatMessage = UIMessage<
1229
+ unknown,
1230
+ {
1231
+ sources: { query: string; status: string; results: string[] };
1232
+ usage: { model: string; inputTokens: number; outputTokens: number };
1233
+ }
1234
+ >;
1235
+
1236
+ const { messages } = useAgentChat<unknown, ChatMessage>({ agent });
1237
+
1238
+ // Typed access — no casts needed
1239
+ for (const msg of messages) {
1240
+ for (const part of msg.parts) {
1241
+ if (part.type === "data-sources") {
1242
+ console.log(part.data.results); // string[]
1243
+ }
1244
+ }
1245
+ }
1246
+ ```
1247
+
1248
+ ### Transient Parts with `onData`
1249
+
1250
+ Transient data parts are not in `message.parts`. Use the `onData` callback instead:
1251
+
1252
+ ```ts
1253
+ const [thinking, setThinking] = useState(false);
1254
+
1255
+ const { messages } = useAgentChat<unknown, ChatMessage>({
1256
+ agent,
1257
+ onData(part) {
1258
+ if (part.type === "data-thinking") {
1259
+ setThinking(true);
1260
+ }
1261
+ }
1262
+ });
1263
+ ```
1264
+
1265
+ On the server, write transient parts with `transient: true`:
1266
+
1267
+ ```ts
1268
+ writer.write({
1269
+ transient: true,
1270
+ type: "data-thinking",
1271
+ data: { model: "glm-4.7-flash", startedAt: new Date().toISOString() }
1272
+ });
1273
+ ```
1274
+
1275
+ `onData` fires on all code paths — new messages, stream resumption, and cross-tab broadcasts.
1276
+
1277
+ ## Resumable Streaming
1278
+
1279
+ Streams automatically resume when a client disconnects and reconnects. No configuration is needed — it works out of the box.
1280
+
1281
+ When streaming is active:
1282
+
1283
+ 1. All chunks are buffered in SQLite as they are generated
1284
+ 2. If the client disconnects, the server continues streaming and buffering
1285
+ 3. When the client reconnects, it receives all buffered chunks and resumes live streaming
1286
+
1287
+ Generic client stream abort/cleanup stays local to the browser by default, so the server turn keeps running and can be resumed later. An explicit `stop()` still sends server cancellation:
1288
+
1289
+ ```tsx
1290
+ const { messages, stop } = useAgentChat({ agent });
1291
+ ```
1292
+
1293
+ If your app intentionally wants client lifecycle to own server lifecycle, set `cancelOnClientAbort: true`.
1294
+ This is useful for request-lifetime or token-saving flows; explicit `stop()` is
1295
+ always server-side cancellation regardless of this option.
1296
+
1297
+ Disable resume with `resume: false`:
1298
+
1299
+ ```tsx
1300
+ const { messages } = useAgentChat({ agent, resume: false });
1301
+ ```
1302
+
1303
+ For more details, see [Resumable Streaming](./resumable-streaming.md).
1304
+
1305
+ ## Storage Management
1306
+
1307
+ ### Row Size Protection
1308
+
1309
+ SQLite rows have a maximum size of 2 MB. When a message approaches this limit (for example, a tool returning a very large output), `AIChatAgent` automatically compacts the message:
1310
+
1311
+ 1. **Tool output compaction** — Large tool outputs are replaced with an LLM-friendly summary that instructs the model to suggest re-running the tool
1312
+ 2. **Text truncation** — If the message is still too large after tool compaction, text parts are truncated with a note
1313
+
1314
+ Compacted messages include `metadata.compactedToolOutputs` so clients can detect and display this gracefully.
1315
+
1316
+ ### `sanitizeMessageForPersistence`
1317
+
1318
+ Override this method to transform messages before they are written to SQLite. It runs after the built-in sanitization (OpenAI metadata stripping, Anthropic provider-executed tool payload truncation, empty reasoning part removal), so built-in cleanup is never bypassed.
1319
+
1320
+ The default implementation returns the message unchanged.
1321
+
1322
+ ```typescript
1323
+ import type { UIMessage } from "ai";
1324
+
1325
+ export class ChatAgent extends AIChatAgent {
1326
+ protected sanitizeMessageForPersistence(message: UIMessage): UIMessage {
1327
+ return {
1328
+ ...message,
1329
+ parts: message.parts.map((part) => {
1330
+ // Strip large tool outputs you do not need to persist
1331
+ if (
1332
+ "output" in part &&
1333
+ typeof part.output === "string" &&
1334
+ part.output.length > 2000
1335
+ ) {
1336
+ return { ...part, output: "[redacted — too large to store]" };
1337
+ }
1338
+ return part;
1339
+ })
1340
+ };
1341
+ }
1342
+ }
1343
+ ```
1344
+
1345
+ Built-in sanitization already handles:
1346
+
1347
+ - **OpenAI** — strips ephemeral `itemId` and `reasoningEncryptedContent` from `providerMetadata`
1348
+ - **Anthropic** — truncates large strings in `input`/`output` of provider-executed tool parts (code execution, text editor)
1349
+ - **Reasoning** — removes empty reasoning parts left after metadata stripping
1350
+
1351
+ Use `sanitizeMessageForPersistence` for anything the built-in logic does not cover, such as redacting sensitive fields or trimming domain-specific tool outputs.
1352
+
1353
+ ### Controlling LLM Context vs Storage
1354
+
1355
+ Storage (`maxPersistedMessages`) and LLM context are independent:
1356
+
1357
+ | Concern | Control | Scope |
1358
+ | ------------------------------- | --------------------------------- | ----------- |
1359
+ | How many messages SQLite stores | `maxPersistedMessages` | Persistence |
1360
+ | What the model sees | `pruneMessages()` | LLM context |
1361
+ | Custom pre-persist transforms | `sanitizeMessageForPersistence()` | Per-message |
1362
+ | Row size limits | Automatic compaction | Per-message |
1363
+
1364
+ ```typescript
1365
+ export class ChatAgent extends AIChatAgent {
1366
+ maxPersistedMessages = 200; // Storage limit
1367
+
1368
+ async onChatMessage() {
1369
+ const result = streamText({
1370
+ model: workersai("@cf/moonshotai/kimi-k2.7-code"),
1371
+ messages: pruneMessages({
1372
+ // LLM context limit
1373
+ messages: await convertToModelMessages(this.messages),
1374
+ reasoning: "before-last-message",
1375
+ toolCalls: "before-last-2-messages"
1376
+ })
1377
+ });
1378
+
1379
+ return result.toUIMessageStreamResponse();
1380
+ }
1381
+ }
1382
+ ```
1383
+
1384
+ ## Using Different AI Providers
1385
+
1386
+ `AIChatAgent` works with any AI SDK-compatible provider. The server code determines which model to use — the client does not need to change.
1387
+
1388
+ ### Workers AI (Cloudflare)
1389
+
1390
+ ```typescript
1391
+ import { createWorkersAI } from "workers-ai-provider";
1392
+
1393
+ const workersai = createWorkersAI({ binding: this.env.AI });
1394
+ const result = streamText({
1395
+ model: workersai("@cf/moonshotai/kimi-k2.7-code"),
1396
+ messages: await convertToModelMessages(this.messages)
1397
+ });
1398
+ ```
1399
+
1400
+ ### OpenAI
1401
+
1402
+ ```typescript
1403
+ import { createOpenAI } from "@ai-sdk/openai";
1404
+
1405
+ const openai = createOpenAI({ apiKey: this.env.OPENAI_API_KEY });
1406
+ const result = streamText({
1407
+ model: openai.chat("gpt-4o"),
1408
+ messages: await convertToModelMessages(this.messages)
1409
+ });
1410
+ ```
1411
+
1412
+ ### Anthropic
1413
+
1414
+ ```typescript
1415
+ import { createAnthropic } from "@ai-sdk/anthropic";
1416
+
1417
+ const anthropic = createAnthropic({ apiKey: this.env.ANTHROPIC_API_KEY });
1418
+ const result = streamText({
1419
+ model: anthropic("claude-sonnet-4-20250514"),
1420
+ messages: await convertToModelMessages(this.messages)
1421
+ });
1422
+ ```
1423
+
1424
+ ## Advanced Patterns
1425
+
1426
+ Since `onChatMessage` gives you full control over the `streamText` call, you can use any AI SDK feature directly. The patterns below all work out of the box — no special `AIChatAgent` configuration is needed.
1427
+
1428
+ ### Dynamic Model and Tool Control
1429
+
1430
+ Use [`prepareStep`](https://ai-sdk.dev/docs/agents/loop-control) to change the model, available tools, or system prompt between steps in a multi-step agent loop:
1431
+
1432
+ ```typescript
1433
+ import { streamText, convertToModelMessages, tool, stepCountIs } from "ai";
1434
+ import { z } from "zod";
1435
+
1436
+ async onChatMessage() {
1437
+ const result = streamText({
1438
+ model: cheapModel, // Default model for simple steps
1439
+ messages: await convertToModelMessages(this.messages),
1440
+ tools: {
1441
+ search: searchTool,
1442
+ analyze: analyzeTool,
1443
+ summarize: summarizeTool
1444
+ },
1445
+ stopWhen: stepCountIs(10),
1446
+ prepareStep: async ({ stepNumber, messages }) => {
1447
+ // Phase 1: Search (steps 0-2)
1448
+ if (stepNumber <= 2) {
1449
+ return {
1450
+ activeTools: ["search"],
1451
+ toolChoice: "required" // Force tool use
1452
+ };
1453
+ }
1454
+
1455
+ // Phase 2: Analyze with a stronger model (steps 3-5)
1456
+ if (stepNumber <= 5) {
1457
+ return {
1458
+ model: expensiveModel,
1459
+ activeTools: ["analyze"]
1460
+ };
1461
+ }
1462
+
1463
+ // Phase 3: Summarize
1464
+ return { activeTools: ["summarize"] };
1465
+ }
1466
+ });
1467
+
1468
+ return result.toUIMessageStreamResponse();
1469
+ }
1470
+ ```
1471
+
1472
+ `prepareStep` runs before each step and can return overrides for `model`, `activeTools`, `toolChoice`, `system`, and `messages`. Use it to:
1473
+
1474
+ - **Switch models** — use a cheap model for simple steps, escalate for reasoning
1475
+ - **Phase tools** — restrict which tools are available at each step
1476
+ - **Manage context** — prune or transform messages to stay within token limits
1477
+ - **Force tool calls** — use `toolChoice: { type: "tool", toolName: "search" }` to require a specific tool
1478
+
1479
+ ### Language Model Middleware
1480
+
1481
+ Use [`wrapLanguageModel`](https://ai-sdk.dev/docs/ai-sdk-core/middleware) to add guardrails, RAG, caching, or logging without modifying your chat logic:
1482
+
1483
+ ```typescript
1484
+ import { streamText, convertToModelMessages, wrapLanguageModel } from "ai";
1485
+ import type { LanguageModelV3Middleware } from "@ai-sdk/provider";
1486
+
1487
+ const guardrailMiddleware: LanguageModelV3Middleware = {
1488
+ wrapGenerate: async ({ doGenerate }) => {
1489
+ const { text, ...rest } = await doGenerate();
1490
+ // Filter PII or sensitive content from the response
1491
+ const cleaned = text?.replace(/\b\d{3}-\d{2}-\d{4}\b/g, "[REDACTED]");
1492
+ return { text: cleaned, ...rest };
1493
+ }
1494
+ };
1495
+
1496
+ async onChatMessage() {
1497
+ const model = wrapLanguageModel({
1498
+ model: baseModel,
1499
+ middleware: [guardrailMiddleware]
1500
+ });
1501
+
1502
+ const result = streamText({
1503
+ model,
1504
+ messages: await convertToModelMessages(this.messages)
1505
+ });
1506
+
1507
+ return result.toUIMessageStreamResponse();
1508
+ }
1509
+ ```
1510
+
1511
+ The AI SDK includes built-in middlewares:
1512
+
1513
+ - `extractReasoningMiddleware` — surface chain-of-thought from models like DeepSeek R1
1514
+ - `defaultSettingsMiddleware` — apply default temperature, max tokens, etc.
1515
+ - `simulateStreamingMiddleware` — add streaming to non-streaming models
1516
+
1517
+ Multiple middlewares compose in order: `middleware: [first, second]` applies as `first(second(model))`.
1518
+
1519
+ ### Structured Output
1520
+
1521
+ Use [`generateObject`](https://ai-sdk.dev/docs/ai-sdk-core/generating-structured-data) inside tools for structured data extraction:
1522
+
1523
+ ```typescript
1524
+ import {
1525
+ streamText, generateObject, convertToModelMessages, tool, stepCountIs
1526
+ } from "ai";
1527
+ import { z } from "zod";
1528
+
1529
+ async onChatMessage() {
1530
+ const result = streamText({
1531
+ model: myModel,
1532
+ messages: await convertToModelMessages(this.messages),
1533
+ tools: {
1534
+ extractContactInfo: tool({
1535
+ description: "Extract structured contact information from the conversation",
1536
+ inputSchema: z.object({
1537
+ text: z.string().describe("The text to extract contact info from")
1538
+ }),
1539
+ execute: async ({ text }) => {
1540
+ const { object } = await generateObject({
1541
+ model: myModel,
1542
+ schema: z.object({
1543
+ name: z.string(),
1544
+ email: z.string().email(),
1545
+ phone: z.string().optional()
1546
+ }),
1547
+ prompt: `Extract contact information from: ${text}`
1548
+ });
1549
+ return object;
1550
+ }
1551
+ })
1552
+ },
1553
+ stopWhen: stepCountIs(5)
1554
+ });
1555
+
1556
+ return result.toUIMessageStreamResponse();
1557
+ }
1558
+ ```
1559
+
1560
+ ### Subagent Delegation
1561
+
1562
+ Tools can delegate work to focused sub-calls with their own context. Use [`ToolLoopAgent`](https://ai-sdk.dev/docs/reference/ai-sdk-core/tool-loop-agent) to define a reusable agent, then call it from a tool's `execute`:
1563
+
1564
+ ```typescript
1565
+ import {
1566
+ ToolLoopAgent, streamText, convertToModelMessages, tool, stepCountIs
1567
+ } from "ai";
1568
+ import { z } from "zod";
1569
+
1570
+ // Define a reusable research agent with its own tools and instructions
1571
+ const researchAgent = new ToolLoopAgent({
1572
+ model: researchModel,
1573
+ instructions: "You are a research assistant. Be thorough and cite sources.",
1574
+ tools: { webSearch: webSearchTool },
1575
+ stopWhen: stepCountIs(10)
1576
+ });
1577
+
1578
+ async onChatMessage() {
1579
+ const result = streamText({
1580
+ model: orchestratorModel,
1581
+ messages: await convertToModelMessages(this.messages),
1582
+ tools: {
1583
+ deepResearch: tool({
1584
+ description: "Research a topic in depth",
1585
+ inputSchema: z.object({
1586
+ topic: z.string().describe("The topic to research")
1587
+ }),
1588
+ execute: async ({ topic }) => {
1589
+ const { text } = await researchAgent.generate({ prompt: topic });
1590
+ return { summary: text };
1591
+ }
1592
+ })
1593
+ },
1594
+ stopWhen: stepCountIs(5)
1595
+ });
1596
+
1597
+ return result.toUIMessageStreamResponse();
1598
+ }
1599
+ ```
1600
+
1601
+ The research agent runs in its own context — its token budget is separate from the orchestrator's. Only the summary goes back to the parent model.
1602
+
1603
+ `ToolLoopAgent` is best suited for subagents, not as a replacement for `streamText` in `onChatMessage` itself. The main `onChatMessage` benefits from direct access to `this.env`, `this.messages`, and `options.body` — things that a pre-configured `ToolLoopAgent` instance cannot reference.
1604
+
1605
+ #### Streaming progress with preliminary results
1606
+
1607
+ By default, a tool part appears as loading until `execute` returns. Use an async generator (`async function*`) to stream progress updates to the client while the tool is still working:
1608
+
1609
+ ```typescript
1610
+ deepResearch: tool({
1611
+ description: "Research a topic in depth",
1612
+ inputSchema: z.object({
1613
+ topic: z.string().describe("The topic to research")
1614
+ }),
1615
+ async *execute({ topic }) {
1616
+ // Preliminary result — the client sees "searching" immediately
1617
+ yield { status: "searching", topic, summary: undefined };
1618
+
1619
+ const { text } = await researchAgent.generate({ prompt: topic });
1620
+
1621
+ // Final result — sent to the model for its next step
1622
+ yield { status: "done", topic, summary: text };
1623
+ }
1624
+ });
1625
+ ```
1626
+
1627
+ Each `yield` updates the tool part on the client in real-time (with `preliminary: true`). The last yielded value becomes the final output that the model sees. This is useful for long-running tools where you want to show status (searching, analyzing, summarizing) as the work progresses.
1628
+
1629
+ This pattern is useful when:
1630
+
1631
+ - A task requires exploring large amounts of information that would bloat the main context
1632
+ - You want to show real-time progress for long-running tools
1633
+ - You want to parallelize independent research (multiple tool calls run concurrently)
1634
+ - You need different models or system prompts for different subtasks
1635
+
1636
+ For more, see the [AI SDK Agents docs](https://ai-sdk.dev/docs/agents/overview), [Subagents](https://ai-sdk.dev/docs/agents/subagents), and [Preliminary Tool Results](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling#preliminary-tool-results).
1637
+
1638
+ ## Multi-Client Sync
1639
+
1640
+ When multiple clients connect to the same agent instance, messages are automatically broadcast to all connections. If one client sends a message, all other connected clients receive the updated message list.
1641
+
1642
+ ```
1643
+ Client A ──── sendMessage("Hello") ────▶ AIChatAgent
1644
+
1645
+ persist + stream
1646
+
1647
+ Client A ◀── CF_AGENT_USE_CHAT_RESPONSE ──────┤
1648
+ Client B ◀── CF_AGENT_CHAT_MESSAGES ──────────┘
1649
+ ```
1650
+
1651
+ The originating client receives the streaming response. All other clients receive the final messages via a `CF_AGENT_CHAT_MESSAGES` broadcast.
1652
+
1653
+ ## API Reference
1654
+
1655
+ ### Exports
1656
+
1657
+ | Import path | Exports |
1658
+ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1659
+ | `@cloudflare/ai-chat` | `AIChatAgent`, `createToolsFromClientSchemas`, `ChatRecoveryContext`, `ChatRecoveryOptions`, `ChatRecoveryConfig`, `ChatRecoveryExhaustedContext`, `ResolvedChatRecoveryConfig` |
1660
+ | `@cloudflare/ai-chat/react` | `useAgentChat` |
1661
+ | `@cloudflare/ai-chat/types` | `MessageType`, `OutgoingMessage`, `IncomingMessage` |
1662
+
1663
+ ### WebSocket Protocol
1664
+
1665
+ The chat protocol uses typed JSON messages over WebSocket:
1666
+
1667
+ | Message | Direction | Purpose |
1668
+ | -------------------------------- | --------------- | --------------------------- |
1669
+ | `CF_AGENT_USE_CHAT_REQUEST` | Client → Server | Send a chat message |
1670
+ | `CF_AGENT_USE_CHAT_RESPONSE` | Server → Client | Stream response chunks |
1671
+ | `CF_AGENT_CHAT_MESSAGES` | Server → Client | Broadcast updated messages |
1672
+ | `CF_AGENT_CHAT_CLEAR` | Bidirectional | Clear conversation |
1673
+ | `CF_AGENT_CHAT_REQUEST_CANCEL` | Client → Server | Cancel active stream |
1674
+ | `CF_AGENT_TOOL_RESULT` | Client → Server | Provide tool output |
1675
+ | `CF_AGENT_TOOL_APPROVAL` | Client → Server | Approve or reject a tool |
1676
+ | `CF_AGENT_MESSAGE_UPDATED` | Server → Client | Notify of message update |
1677
+ | `CF_AGENT_STREAM_RESUMING` | Server → Client | Notify of stream resumption |
1678
+ | `CF_AGENT_STREAM_RESUME_REQUEST` | Client → Server | Request stream resume check |
1679
+
1680
+ ## Examples
1681
+
1682
+ - [AI Chat Example](https://github.com/cloudflare/agents/tree/main/examples/ai-chat) — Modern example with server tools, client tools, and approval
1683
+ - [Dynamic Tools](https://github.com/cloudflare/agents/tree/main/examples/dynamic-tools) — SDK/platform pattern with dynamic client-defined tools
1684
+ - [Resumable Stream Chat](https://github.com/cloudflare/agents/tree/main/examples/resumable-stream-chat) — Automatic stream resumption demo
1685
+ - [Human in the Loop Guide](https://github.com/cloudflare/agents/tree/main/guides/human-in-the-loop) — Tool approval with `needsApproval` and `onToolCall`
1686
+ - [Playground](https://github.com/cloudflare/agents/tree/main/examples/playground) — Kitchen-sink demo of all SDK features
1687
+
1688
+ ## Related Docs
1689
+
1690
+ - [Client SDK](./client-sdk.md) — `useAgent` hook and `AgentClient` class
1691
+ - [Durable Execution](./durable-execution.md) — `runFiber()`, `stash()`, and crash recovery
1692
+ - [Long-Running Agents](./long-running-agents.md) — lifecycle, recovery patterns, and provider-specific strategies
1693
+ - [Human in the Loop](./human-in-the-loop.md) — Approval flows and manual intervention patterns
1694
+ - [Resumable Streaming](./resumable-streaming.md) — How stream resumption works
1695
+ - [Client Tools Continuation](./client-tools-continuation.md) — Advanced client-side tool patterns
1696
+ - [Migration to AI SDK v6](./migration-to-ai-sdk-v6.md) — Upgrading from AI SDK v5