@cloudflare/ai-chat 0.1.5 → 0.1.6

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 (67) hide show
  1. package/dist/experimental/forever.d.ts +4 -13
  2. package/dist/experimental/forever.js +1 -46
  3. package/dist/experimental/forever.js.map +1 -1
  4. package/dist/index.d.ts +59 -4
  5. package/dist/index.js +170 -28
  6. package/dist/index.js.map +1 -1
  7. package/dist/{message-builder-Bwc_Umye.js → message-builder-uSvexDl2.js} +17 -4
  8. package/dist/message-builder-uSvexDl2.js.map +1 -0
  9. package/dist/react.js +96 -10
  10. package/dist/react.js.map +1 -1
  11. package/dist/{resumable-stream-DqXxQVjf.d.ts → resumable-stream-DTLAk9XC.d.ts} +25 -2
  12. package/dist/types.d.ts +2 -1
  13. package/dist/types.js.map +1 -1
  14. package/package.json +7 -3
  15. package/CHANGELOG.md +0 -251
  16. package/dist/message-builder-Bwc_Umye.js.map +0 -1
  17. package/e2e/chat.spec.ts +0 -1703
  18. package/e2e/client-tools.spec.ts +0 -504
  19. package/e2e/llm.spec.ts +0 -637
  20. package/e2e/playwright.config.ts +0 -27
  21. package/e2e/worker.ts +0 -174
  22. package/e2e/wrangler.jsonc +0 -23
  23. package/scripts/build.ts +0 -32
  24. package/src/ai-chat-v5-migration.ts +0 -403
  25. package/src/experimental/forever.ts +0 -66
  26. package/src/index.ts +0 -2269
  27. package/src/message-builder.ts +0 -384
  28. package/src/react-tests/setup.ts +0 -3
  29. package/src/react-tests/use-agent-chat.test.tsx +0 -1435
  30. package/src/react-tests/vitest.config.ts +0 -20
  31. package/src/react.tsx +0 -1447
  32. package/src/resumable-stream.ts +0 -441
  33. package/src/tests/cancel-request.test.ts +0 -280
  34. package/src/tests/chat-context.test.ts +0 -85
  35. package/src/tests/chat-persistence.test.ts +0 -426
  36. package/src/tests/clear-history.test.ts +0 -132
  37. package/src/tests/client-tool-duplicate-message.test.ts +0 -1957
  38. package/src/tests/client-tools-broadcast.test.ts +0 -138
  39. package/src/tests/client-tools-continuation.test.ts +0 -314
  40. package/src/tests/client-tools-reconnect.test.ts +0 -143
  41. package/src/tests/cloudflare-test.d.ts +0 -5
  42. package/src/tests/custom-body-continuation.test.ts +0 -309
  43. package/src/tests/custom-body.test.ts +0 -186
  44. package/src/tests/destroy.test.ts +0 -57
  45. package/src/tests/get-messages-endpoint.test.ts +0 -153
  46. package/src/tests/max-persisted-messages.test.ts +0 -201
  47. package/src/tests/merge-server-state.test.ts +0 -343
  48. package/src/tests/message-builder.test.ts +0 -808
  49. package/src/tests/migration.test.ts +0 -282
  50. package/src/tests/non-sse-response.test.ts +0 -186
  51. package/src/tests/onfinish-cleanup.test.ts +0 -362
  52. package/src/tests/plaintext-response.test.ts +0 -87
  53. package/src/tests/request-id.test.ts +0 -312
  54. package/src/tests/resumable-streaming.test.ts +0 -758
  55. package/src/tests/row-size-guard.test.ts +0 -374
  56. package/src/tests/sanitize-messages.test.ts +0 -325
  57. package/src/tests/test-utils.ts +0 -39
  58. package/src/tests/tsconfig.json +0 -10
  59. package/src/tests/validate-messages.test.ts +0 -269
  60. package/src/tests/vitest.config.ts +0 -30
  61. package/src/tests/worker.ts +0 -456
  62. package/src/tests/wrangler.jsonc +0 -50
  63. package/src/tests/ws-transport-abort.test.ts +0 -198
  64. package/src/types.ts +0 -152
  65. package/src/ws-chat-transport.ts +0 -227
  66. package/tsconfig.json +0 -4
  67. package/vitest.config.ts +0 -7
package/src/index.ts DELETED
@@ -1,2269 +0,0 @@
1
- import type {
2
- UIMessage as ChatMessage,
3
- JSONSchema7,
4
- ProviderMetadata,
5
- ReasoningUIPart,
6
- StreamTextOnFinishCallback,
7
- TextUIPart,
8
- Tool,
9
- ToolSet,
10
- UIMessageChunk
11
- } from "ai";
12
- import { tool, jsonSchema } from "ai";
13
- import {
14
- Agent,
15
- __DO_NOT_USE_WILL_BREAK__agentContext as agentContext,
16
- type AgentContext,
17
- type Connection,
18
- type ConnectionContext,
19
- type WSMessage
20
- } from "agents";
21
-
22
- import {
23
- MessageType,
24
- type IncomingMessage,
25
- type OutgoingMessage
26
- } from "./types";
27
- import { autoTransformMessages } from "./ai-chat-v5-migration";
28
- import { applyChunkToParts } from "./message-builder";
29
- import { ResumableStream } from "./resumable-stream";
30
- import { nanoid } from "nanoid";
31
-
32
- /** Shared encoder for UTF-8 byte length measurement */
33
- const textEncoder = new TextEncoder();
34
-
35
- /**
36
- * Validates that a parsed message has the minimum required structure.
37
- * Returns false for messages that would cause runtime errors downstream
38
- * (e.g. in convertToModelMessages or the UI layer).
39
- *
40
- * Checks:
41
- * - `id` is a non-empty string
42
- * - `role` is one of the valid roles
43
- * - `parts` is an array (may be empty — the AI SDK enforces nonempty
44
- * on incoming messages, but we are lenient on persisted data)
45
- */
46
- function isValidMessageStructure(msg: unknown): msg is ChatMessage {
47
- if (typeof msg !== "object" || msg === null) return false;
48
- const m = msg as Record<string, unknown>;
49
-
50
- if (typeof m.id !== "string" || m.id.length === 0) return false;
51
-
52
- if (m.role !== "user" && m.role !== "assistant" && m.role !== "system") {
53
- return false;
54
- }
55
-
56
- if (!Array.isArray(m.parts)) return false;
57
-
58
- return true;
59
- }
60
-
61
- /**
62
- * Schema for a client-defined tool sent from the browser.
63
- * These tools are executed on the client, not the server.
64
- *
65
- * **For most apps**, define tools on the server with `tool()` from `"ai"` —
66
- * you get full Zod type safety, server-side execution, and simpler code.
67
- * Use `onToolCall` in `useAgentChat` for tools that need client-side execution.
68
- *
69
- * **For SDKs and platforms** where the tool surface is determined dynamically
70
- * by the embedding application at runtime, client tool schemas let the
71
- * client register tools the server does not know about at deploy time.
72
- *
73
- * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema`
74
- * because this is the wire format. Zod schemas cannot be serialized.
75
- */
76
- export type ClientToolSchema = {
77
- /** Unique name for the tool */
78
- name: string;
79
- /** Human-readable description of what the tool does */
80
- description?: Tool["description"];
81
- /** JSON Schema defining the tool's input parameters */
82
- parameters?: JSONSchema7;
83
- };
84
-
85
- /**
86
- * Options passed to the onChatMessage handler.
87
- */
88
- export type OnChatMessageOptions = {
89
- /**
90
- * Unique ID for this chat message exchange.
91
- *
92
- * For initial user messages this is the client-generated ID from the
93
- * `CF_AGENT_USE_CHAT_REQUEST` WebSocket frame. For tool continuations
94
- * (auto-continue after client tool results or approvals) this is a
95
- * server-generated ID.
96
- */
97
- requestId: string;
98
- /** AbortSignal for cancelling the request */
99
- abortSignal?: AbortSignal;
100
- /**
101
- * Tool schemas sent from the client for dynamic tool registration.
102
- * These represent tools that will be executed on the client side.
103
- * Use `createToolsFromClientSchemas()` to convert these to AI SDK tool format.
104
- *
105
- * **For most apps**, you do not need this — define tools on the server with
106
- * `tool()` from `"ai"` and use `onToolCall` for client-side execution.
107
- *
108
- * **For SDKs and platforms** where tools are defined dynamically by the
109
- * client at runtime and the server does not know the tool surface ahead
110
- * of time, this field carries the client-provided tool schemas.
111
- */
112
- clientTools?: ClientToolSchema[];
113
- /**
114
- * Custom body data sent from the client via `prepareSendMessagesRequest`
115
- * or the AI SDK's `body` option in `sendMessage`.
116
- *
117
- * Contains all fields from the request body except `messages` and `clientTools`,
118
- * which are handled separately.
119
- *
120
- * During tool continuations (auto-continue after client tool results), this
121
- * contains the body from the most recent chat request. The value is persisted
122
- * to SQLite so it survives Durable Object hibernation. It is cleared when the
123
- * chat is cleared via `CF_AGENT_CHAT_CLEAR`.
124
- */
125
- body?: Record<string, unknown>;
126
- };
127
-
128
- /**
129
- * Converts client tool schemas to AI SDK tool format.
130
- *
131
- * These tools have no `execute` function — when the AI model calls them,
132
- * the tool call is sent back to the client for execution.
133
- *
134
- * **For most apps**, define tools on the server with `tool()` from `"ai"`
135
- * for full Zod type safety. This helper is intended for SDK/platform use
136
- * cases where the tool surface is determined dynamically by the client.
137
- *
138
- * @param clientTools - Array of tool schemas from the client
139
- * @returns Record of AI SDK tools that can be spread into your tools object
140
- *
141
- * @example
142
- * ```typescript
143
- * // In onChatMessage:
144
- * const tools = {
145
- * ...createToolsFromClientSchemas(options.clientTools),
146
- * // server-defined tools with execute:
147
- * myServerTool: tool({ ... }),
148
- * };
149
- * ```
150
- */
151
- export function createToolsFromClientSchemas(
152
- clientTools?: ClientToolSchema[]
153
- ): ToolSet {
154
- if (!clientTools || clientTools.length === 0) {
155
- return {};
156
- }
157
-
158
- // Check for duplicate tool names
159
- const seenNames = new Set<string>();
160
- for (const t of clientTools) {
161
- if (seenNames.has(t.name)) {
162
- console.warn(
163
- `[createToolsFromClientSchemas] Duplicate tool name "${t.name}" found. Later definitions will override earlier ones.`
164
- );
165
- }
166
- seenNames.add(t.name);
167
- }
168
-
169
- return Object.fromEntries(
170
- clientTools.map((t) => [
171
- t.name,
172
- tool({
173
- description: t.description ?? "",
174
- inputSchema: jsonSchema(t.parameters ?? { type: "object" })
175
- // No execute function = tool call is sent back to client
176
- })
177
- ])
178
- );
179
- }
180
-
181
- const decoder = new TextDecoder();
182
-
183
- /**
184
- * Extension of Agent with built-in chat capabilities
185
- * @template Env Environment type containing bindings
186
- */
187
- export class AIChatAgent<
188
- Env extends Cloudflare.Env = Cloudflare.Env,
189
- State = unknown
190
- > extends Agent<Env, State> {
191
- /**
192
- * Map of message `id`s to `AbortController`s
193
- * useful to propagate request cancellation signals for any external calls made by the agent
194
- */
195
- private _chatMessageAbortControllers: Map<string, AbortController>;
196
-
197
- /**
198
- * Resumable stream manager -- handles chunk buffering, persistence, and replay.
199
- * @internal Protected for testing purposes.
200
- */
201
- protected _resumableStream!: ResumableStream;
202
-
203
- /**
204
- * The message currently being streamed. Used to apply tool results
205
- * before the message is persisted.
206
- * @internal
207
- */
208
- private _streamingMessage: ChatMessage | null = null;
209
-
210
- /**
211
- * Tracks the ID of a streaming message that was persisted early due to
212
- * a tool entering approval-requested state. When set, stream completion
213
- * updates the existing persisted message instead of appending a new one.
214
- * @internal
215
- */
216
- private _approvalPersistedMessageId: string | null = null;
217
-
218
- /**
219
- * Promise that resolves when the current stream completes.
220
- * Used to wait for message persistence before continuing after tool results.
221
- * @internal
222
- */
223
- private _streamCompletionPromise: Promise<void> | null = null;
224
- private _streamCompletionResolve: (() => void) | null = null;
225
-
226
- /**
227
- * Set of connection IDs that are pending stream resume.
228
- * These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
229
- * They should be excluded from live stream broadcasts until they ACK.
230
- * @internal
231
- */
232
- private _pendingResumeConnections: Set<string> = new Set();
233
-
234
- /**
235
- * Client tool schemas from the most recent chat request.
236
- * Stored so they can be passed to onChatMessage during tool continuations.
237
- * @internal
238
- */
239
- private _lastClientTools: ClientToolSchema[] | undefined;
240
-
241
- /**
242
- * Custom body data from the most recent chat request.
243
- * Stored so it can be passed to onChatMessage during tool continuations.
244
- * @internal
245
- */
246
- private _lastBody: Record<string, unknown> | undefined;
247
-
248
- /**
249
- * Cache of last-persisted JSON for each message ID.
250
- * Used for incremental persistence: skip SQL writes for unchanged messages.
251
- * Lost on hibernation, repopulated from SQLite on wake.
252
- * @internal
253
- */
254
- private _persistedMessageCache: Map<string, string> = new Map();
255
-
256
- /** Maximum serialized message size before compaction (bytes). 1.8MB with headroom below SQLite's 2MB limit. */
257
- private static ROW_MAX_BYTES = 1_800_000;
258
-
259
- /** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
260
- private static _byteLength(s: string): number {
261
- return textEncoder.encode(s).byteLength;
262
- }
263
-
264
- /**
265
- * Maximum number of messages to keep in SQLite storage.
266
- * When the conversation exceeds this limit, oldest messages are deleted
267
- * after each persist. Set to `undefined` (default) for no limit.
268
- *
269
- * This controls storage only — it does not affect what's sent to the LLM.
270
- * Use `pruneMessages()` from the AI SDK in your `onChatMessage` to control
271
- * LLM context separately.
272
- *
273
- * @example
274
- * ```typescript
275
- * class MyAgent extends AIChatAgent<Env> {
276
- * maxPersistedMessages = 100; // Keep last 100 messages in storage
277
- * }
278
- * ```
279
- */
280
- maxPersistedMessages: number | undefined = undefined;
281
-
282
- /** Array of chat messages for the current conversation */
283
- messages: ChatMessage[];
284
-
285
- constructor(ctx: AgentContext, env: Env) {
286
- super(ctx, env);
287
- this.sql`create table if not exists cf_ai_chat_agent_messages (
288
- id text primary key,
289
- message text not null,
290
- created_at datetime default current_timestamp
291
- )`;
292
-
293
- // Key-value table for request context that must survive hibernation
294
- // (e.g., custom body fields, client tools from the last chat request).
295
- this.sql`create table if not exists cf_ai_chat_request_context (
296
- key text primary key,
297
- value text not null
298
- )`;
299
-
300
- // Restore request context from SQLite (survives hibernation)
301
- this._restoreRequestContext();
302
-
303
- // Initialize resumable stream manager (creates its own tables + restores state)
304
- this._resumableStream = new ResumableStream(this.sql.bind(this));
305
-
306
- // Load messages and automatically transform them to v5 format.
307
- // Note: _loadMessagesFromDb() runs structural validation which requires
308
- // `parts` to be an array. Legacy v4 messages (with `content` instead of
309
- // `parts`) would fail this check — but that's fine because autoTransformMessages
310
- // already migrated them on a previous load, and persistMessages wrote them back.
311
- // Any message still without `parts` at this point is genuinely corrupt.
312
- const rawMessages = this._loadMessagesFromDb();
313
-
314
- // Automatic migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages
315
- this.messages = autoTransformMessages(rawMessages);
316
-
317
- this._chatMessageAbortControllers = new Map();
318
- const _onConnect = this.onConnect.bind(this);
319
- this.onConnect = async (connection: Connection, ctx: ConnectionContext) => {
320
- // Notify client about active streams that can be resumed
321
- if (this._resumableStream.hasActiveStream()) {
322
- this._notifyStreamResuming(connection);
323
- }
324
- // Call consumer's onConnect
325
- return _onConnect(connection, ctx);
326
- };
327
-
328
- // Wrap onClose to clean up pending resume connections
329
- const _onClose = this.onClose.bind(this);
330
- this.onClose = async (
331
- connection: Connection,
332
- code: number,
333
- reason: string,
334
- wasClean: boolean
335
- ) => {
336
- // Clean up pending resume state for this connection
337
- this._pendingResumeConnections.delete(connection.id);
338
- // Call consumer's onClose
339
- return _onClose(connection, code, reason, wasClean);
340
- };
341
-
342
- // Wrap onMessage
343
- const _onMessage = this.onMessage.bind(this);
344
- this.onMessage = async (connection: Connection, message: WSMessage) => {
345
- // Ensure jsonSchema is initialized for getAITools() (matches base Agent pattern)
346
- await this.mcp.ensureJsonSchema();
347
-
348
- // Handle AIChatAgent's internal messages first
349
- if (typeof message === "string") {
350
- let data: IncomingMessage;
351
- try {
352
- data = JSON.parse(message) as IncomingMessage;
353
- } catch (_error) {
354
- // Not JSON, forward to consumer
355
- return _onMessage(connection, message);
356
- }
357
-
358
- // Handle chat request
359
- if (
360
- data.type === MessageType.CF_AGENT_USE_CHAT_REQUEST &&
361
- data.init.method === "POST"
362
- ) {
363
- const { body } = data.init;
364
- if (!body) {
365
- console.warn(
366
- "[AIChatAgent] Received chat request with empty body, ignoring"
367
- );
368
- return;
369
- }
370
-
371
- let parsed: Record<string, unknown>;
372
- try {
373
- parsed = JSON.parse(body as string);
374
- } catch (_parseError) {
375
- console.warn(
376
- "[AIChatAgent] Received chat request with invalid JSON body, ignoring"
377
- );
378
- return;
379
- }
380
-
381
- const { messages, clientTools, ...customBody } = parsed as {
382
- messages: ChatMessage[];
383
- clientTools?: ClientToolSchema[];
384
- [key: string]: unknown;
385
- };
386
-
387
- // Store client tools and body for use during tool continuations
388
- this._lastClientTools = clientTools?.length ? clientTools : undefined;
389
- this._lastBody =
390
- Object.keys(customBody).length > 0 ? customBody : undefined;
391
- this._persistRequestContext();
392
-
393
- // Automatically transform any incoming messages
394
- const transformedMessages = autoTransformMessages(messages);
395
-
396
- this._broadcastChatMessage(
397
- {
398
- messages: transformedMessages,
399
- type: MessageType.CF_AGENT_CHAT_MESSAGES
400
- },
401
- [connection.id]
402
- );
403
-
404
- await this.persistMessages(transformedMessages, [connection.id]);
405
-
406
- this.observability?.emit(
407
- {
408
- displayMessage: "Chat message request",
409
- id: data.id,
410
- payload: {},
411
- timestamp: Date.now(),
412
- type: "message:request"
413
- },
414
- this.ctx
415
- );
416
-
417
- const chatMessageId = data.id;
418
- const abortSignal = this._getAbortSignal(chatMessageId);
419
-
420
- return this._tryCatchChat(async () => {
421
- // Wrap in agentContext.run() to propagate connection context to onChatMessage
422
- // This ensures getCurrentAgent() returns the connection inside tool execute functions
423
- return agentContext.run(
424
- { agent: this, connection, request: undefined, email: undefined },
425
- async () => {
426
- const response = await this.onChatMessage(
427
- async (_finishResult) => {
428
- // User-provided hook. Cleanup is now handled by _reply,
429
- // so this is optional for the user to pass to streamText.
430
- },
431
- {
432
- requestId: chatMessageId,
433
- abortSignal,
434
- clientTools,
435
- body: this._lastBody
436
- }
437
- );
438
-
439
- if (response) {
440
- await this._reply(data.id, response, [connection.id], {
441
- chatMessageId
442
- });
443
- } else {
444
- console.warn(
445
- `[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`
446
- );
447
- this._broadcastChatMessage(
448
- {
449
- body: "No response was generated by the agent.",
450
- done: true,
451
- id: data.id,
452
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
453
- },
454
- [connection.id]
455
- );
456
- }
457
- }
458
- );
459
- });
460
- }
461
-
462
- // Handle clear chat
463
- if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
464
- this._destroyAbortControllers();
465
- this.sql`delete from cf_ai_chat_agent_messages`;
466
- this._resumableStream.clearAll();
467
- this._pendingResumeConnections.clear();
468
- this._lastClientTools = undefined;
469
- this._lastBody = undefined;
470
- this._persistRequestContext();
471
- this._persistedMessageCache.clear();
472
- this.messages = [];
473
- this._broadcastChatMessage(
474
- { type: MessageType.CF_AGENT_CHAT_CLEAR },
475
- [connection.id]
476
- );
477
- return;
478
- }
479
-
480
- // Handle message replacement
481
- if (data.type === MessageType.CF_AGENT_CHAT_MESSAGES) {
482
- const transformedMessages = autoTransformMessages(data.messages);
483
- await this.persistMessages(transformedMessages, [connection.id]);
484
- return;
485
- }
486
-
487
- // Handle request cancellation
488
- if (data.type === MessageType.CF_AGENT_CHAT_REQUEST_CANCEL) {
489
- this._cancelChatRequest(data.id);
490
- return;
491
- }
492
-
493
- // Handle client-initiated stream resume request.
494
- // The client sends this after its message handler is registered,
495
- // avoiding the race condition where CF_AGENT_STREAM_RESUMING sent
496
- // in onConnect arrives before the client's handler is ready.
497
- if (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {
498
- if (this._resumableStream.hasActiveStream()) {
499
- this._notifyStreamResuming(connection);
500
- }
501
- return;
502
- }
503
-
504
- // Handle stream resume acknowledgment
505
- if (data.type === MessageType.CF_AGENT_STREAM_RESUME_ACK) {
506
- this._pendingResumeConnections.delete(connection.id);
507
-
508
- if (
509
- this._resumableStream.hasActiveStream() &&
510
- this._resumableStream.activeRequestId === data.id
511
- ) {
512
- this._resumableStream.replayChunks(
513
- connection,
514
- this._resumableStream.activeRequestId
515
- );
516
- }
517
- return;
518
- }
519
-
520
- // Handle client-side tool result
521
- if (data.type === MessageType.CF_AGENT_TOOL_RESULT) {
522
- const {
523
- toolCallId,
524
- toolName,
525
- output,
526
- state,
527
- errorText,
528
- autoContinue,
529
- clientTools
530
- } = data;
531
-
532
- // Update cached client tools so subsequent continuations use the latest schemas
533
- if (clientTools?.length) {
534
- this._lastClientTools = clientTools as ClientToolSchema[];
535
- this._persistRequestContext();
536
- }
537
-
538
- const overrideState =
539
- state === "output-error" ? "output-error" : undefined;
540
-
541
- // Apply the tool result
542
- this._applyToolResult(
543
- toolCallId,
544
- toolName,
545
- output,
546
- overrideState,
547
- errorText
548
- ).then((applied) => {
549
- // Only auto-continue if client requested it (opt-in behavior)
550
- // This mimics server-executed tool behavior where the LLM
551
- // automatically continues after seeing tool results
552
- if (applied && autoContinue) {
553
- // Wait for the original stream to complete and message to be persisted
554
- // before calling onChatMessage, so this.messages includes the tool result
555
- const waitForStream = async () => {
556
- if (this._streamCompletionPromise) {
557
- await this._streamCompletionPromise;
558
- } else {
559
- // TODO: The completion promise can be null if the stream finished
560
- // before the tool result arrived (race between stream end and tool
561
- // apply). The 500ms fallback is a pragmatic workaround — consider
562
- // a more deterministic signal (e.g. always setting the promise).
563
- await new Promise((resolve) => setTimeout(resolve, 500));
564
- }
565
- };
566
-
567
- waitForStream()
568
- .then(() => {
569
- const continuationId = nanoid();
570
- const abortSignal = this._getAbortSignal(continuationId);
571
-
572
- return this._tryCatchChat(async () => {
573
- return agentContext.run(
574
- {
575
- agent: this,
576
- connection,
577
- request: undefined,
578
- email: undefined
579
- },
580
- async () => {
581
- const response = await this.onChatMessage(
582
- async (_finishResult) => {
583
- // User-provided hook. Cleanup handled by _reply.
584
- },
585
- {
586
- requestId: continuationId,
587
- abortSignal,
588
- clientTools: clientTools ?? this._lastClientTools,
589
- body: this._lastBody
590
- }
591
- );
592
-
593
- if (response) {
594
- // Pass continuation flag to merge parts into last assistant message
595
- // Note: We pass an empty excludeBroadcastIds array because the sender
596
- // NEEDS to receive the continuation stream. Unlike regular chat requests
597
- // where aiFetch handles the response, tool continuations have no listener
598
- // waiting - the client relies on the broadcast.
599
- await this._reply(
600
- continuationId,
601
- response,
602
- [], // Don't exclude sender - they need the continuation
603
- {
604
- continuation: true,
605
- chatMessageId: continuationId
606
- }
607
- );
608
- }
609
- }
610
- );
611
- });
612
- })
613
- .catch((error) => {
614
- console.error(
615
- "[AIChatAgent] Tool continuation failed:",
616
- error
617
- );
618
- });
619
- }
620
- });
621
- return;
622
- }
623
-
624
- // Handle client-side tool approval response
625
- if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
626
- const { toolCallId, approved, autoContinue } = data;
627
- this._applyToolApproval(toolCallId, approved).then((applied) => {
628
- // Auto-continue for both approvals and rejections so the LLM
629
- // sees the tool_result and can respond accordingly.
630
- if (applied && autoContinue) {
631
- const waitForStream = async () => {
632
- if (this._streamCompletionPromise) {
633
- await this._streamCompletionPromise;
634
- } else {
635
- await new Promise((resolve) => setTimeout(resolve, 500));
636
- }
637
- };
638
-
639
- waitForStream()
640
- .then(() => {
641
- const continuationId = nanoid();
642
- const abortSignal = this._getAbortSignal(continuationId);
643
-
644
- return this._tryCatchChat(async () => {
645
- return agentContext.run(
646
- {
647
- agent: this,
648
- connection,
649
- request: undefined,
650
- email: undefined
651
- },
652
- async () => {
653
- const response = await this.onChatMessage(
654
- async (_finishResult) => {},
655
- {
656
- requestId: continuationId,
657
- abortSignal,
658
- clientTools: this._lastClientTools,
659
- body: this._lastBody
660
- }
661
- );
662
-
663
- if (response) {
664
- await this._reply(continuationId, response, [], {
665
- continuation: true,
666
- chatMessageId: continuationId
667
- });
668
- }
669
- }
670
- );
671
- });
672
- })
673
- .catch((error) => {
674
- console.error(
675
- "[AIChatAgent] Tool approval continuation failed:",
676
- error
677
- );
678
- });
679
- }
680
- });
681
- return;
682
- }
683
- }
684
-
685
- // Forward unhandled messages to consumer's onMessage
686
- return _onMessage(connection, message);
687
- };
688
-
689
- const _onRequest = this.onRequest.bind(this);
690
- this.onRequest = async (request: Request) => {
691
- return this._tryCatchChat(async () => {
692
- const url = new URL(request.url);
693
- if (url.pathname.split("/").pop() === "get-messages") {
694
- return Response.json(this._loadMessagesFromDb());
695
- }
696
- return _onRequest(request);
697
- });
698
- };
699
- }
700
-
701
- /**
702
- * Notify a connection about an active stream that can be resumed.
703
- * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
704
- * @param connection - The WebSocket connection to notify
705
- */
706
- private _notifyStreamResuming(connection: Connection) {
707
- if (!this._resumableStream.hasActiveStream()) {
708
- return;
709
- }
710
-
711
- // Add connection to pending set - they'll be excluded from live broadcasts
712
- // until they send ACK to receive the full stream replay
713
- this._pendingResumeConnections.add(connection.id);
714
-
715
- // Notify client - they will send ACK when ready
716
- connection.send(
717
- JSON.stringify({
718
- type: MessageType.CF_AGENT_STREAM_RESUMING,
719
- id: this._resumableStream.activeRequestId
720
- })
721
- );
722
- }
723
-
724
- // ── Delegate methods for backward compatibility with tests ─────────
725
- // These protected methods delegate to _resumableStream so existing
726
- // test workers that call them directly continue to work.
727
-
728
- /** @internal Delegate to _resumableStream */
729
- protected get _activeStreamId(): string | null {
730
- return this._resumableStream?.activeStreamId ?? null;
731
- }
732
-
733
- /** @internal Delegate to _resumableStream */
734
- protected get _activeRequestId(): string | null {
735
- return this._resumableStream?.activeRequestId ?? null;
736
- }
737
-
738
- /** @internal Delegate to _resumableStream */
739
- protected _startStream(requestId: string): string {
740
- return this._resumableStream.start(requestId);
741
- }
742
-
743
- /** @internal Delegate to _resumableStream */
744
- protected _completeStream(streamId: string) {
745
- this._resumableStream.complete(streamId);
746
- this._pendingResumeConnections.clear();
747
- }
748
-
749
- /** @internal Delegate to _resumableStream */
750
- protected _storeStreamChunk(streamId: string, body: string) {
751
- this._resumableStream.storeChunk(streamId, body);
752
- }
753
-
754
- /** @internal Delegate to _resumableStream */
755
- protected _flushChunkBuffer() {
756
- this._resumableStream.flushBuffer();
757
- }
758
-
759
- /** @internal Delegate to _resumableStream */
760
- protected _restoreActiveStream() {
761
- this._resumableStream.restore();
762
- }
763
-
764
- /** @internal Delegate to _resumableStream */
765
- protected _markStreamError(streamId: string) {
766
- this._resumableStream.markError(streamId);
767
- }
768
-
769
- /**
770
- * Restore _lastBody and _lastClientTools from SQLite.
771
- * Called in the constructor so these values survive DO hibernation.
772
- * @internal
773
- */
774
- private _restoreRequestContext() {
775
- const rows =
776
- this.sql<{ key: string; value: string }>`
777
- select key, value from cf_ai_chat_request_context
778
- ` || [];
779
-
780
- for (const row of rows) {
781
- try {
782
- if (row.key === "lastBody") {
783
- this._lastBody = JSON.parse(row.value);
784
- } else if (row.key === "lastClientTools") {
785
- this._lastClientTools = JSON.parse(row.value);
786
- }
787
- } catch {
788
- // Corrupted row — ignore and let the next request overwrite it
789
- }
790
- }
791
- }
792
-
793
- /**
794
- * Persist _lastBody and _lastClientTools to SQLite so they survive hibernation.
795
- * Uses upsert (INSERT OR REPLACE) so repeated calls are safe.
796
- * @internal
797
- */
798
- private _persistRequestContext() {
799
- // Persist or delete body
800
- if (this._lastBody) {
801
- this.sql`
802
- insert or replace into cf_ai_chat_request_context (key, value)
803
- values ('lastBody', ${JSON.stringify(this._lastBody)})
804
- `;
805
- } else {
806
- this.sql`delete from cf_ai_chat_request_context where key = 'lastBody'`;
807
- }
808
- // Persist or delete client tools
809
- if (this._lastClientTools) {
810
- this.sql`
811
- insert or replace into cf_ai_chat_request_context (key, value)
812
- values ('lastClientTools', ${JSON.stringify(this._lastClientTools)})
813
- `;
814
- } else {
815
- this
816
- .sql`delete from cf_ai_chat_request_context where key = 'lastClientTools'`;
817
- }
818
- }
819
-
820
- private _broadcastChatMessage(message: OutgoingMessage, exclude?: string[]) {
821
- // Combine explicit exclusions with connections pending stream resume.
822
- // Pending connections should not receive live stream chunks until they ACK,
823
- // at which point they'll receive the full replay via _sendStreamChunks.
824
- const allExclusions = [
825
- ...(exclude || []),
826
- ...this._pendingResumeConnections
827
- ];
828
- this.broadcast(JSON.stringify(message), allExclusions);
829
- }
830
-
831
- /**
832
- * Broadcasts a text event for non-SSE responses.
833
- * This ensures plain text responses follow the AI SDK v5 stream protocol.
834
- *
835
- * @param streamId - The stream identifier for chunk storage
836
- * @param event - The text event payload (text-start, text-delta with delta, or text-end)
837
- * @param continuation - Whether this is a continuation of a previous stream
838
- */
839
- private _broadcastTextEvent(
840
- streamId: string,
841
- event:
842
- | { type: "text-start"; id: string }
843
- | { type: "text-delta"; id: string; delta: string }
844
- | { type: "text-end"; id: string },
845
- continuation: boolean
846
- ) {
847
- const body = JSON.stringify(event);
848
- this._storeStreamChunk(streamId, body);
849
- this._broadcastChatMessage({
850
- body,
851
- done: false,
852
- id: event.id,
853
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
854
- ...(continuation && { continuation: true })
855
- });
856
- }
857
-
858
- private _loadMessagesFromDb(): ChatMessage[] {
859
- const rows =
860
- this.sql`select * from cf_ai_chat_agent_messages order by created_at` ||
861
- [];
862
-
863
- // Populate the persistence cache from DB so incremental persistence
864
- // can skip SQL writes for messages already stored.
865
- this._persistedMessageCache.clear();
866
-
867
- return rows
868
- .map((row) => {
869
- try {
870
- const messageStr = row.message as string;
871
- const parsed = JSON.parse(messageStr) as ChatMessage;
872
-
873
- // Structural validation: ensure required fields exist and have
874
- // the correct types. This catches corrupted rows, manual tampering,
875
- // or schema drift from older versions without crashing the agent.
876
- if (!isValidMessageStructure(parsed)) {
877
- console.warn(
878
- `[AIChatAgent] Skipping invalid message ${row.id}: ` +
879
- "missing or malformed id, role, or parts"
880
- );
881
- return null;
882
- }
883
-
884
- // Cache the raw JSON keyed by message ID
885
- this._persistedMessageCache.set(parsed.id, messageStr);
886
- return parsed;
887
- } catch (error) {
888
- console.error(`Failed to parse message ${row.id}:`, error);
889
- return null;
890
- }
891
- })
892
- .filter((msg): msg is ChatMessage => msg !== null);
893
- }
894
-
895
- private async _tryCatchChat<T>(fn: () => T | Promise<T>) {
896
- try {
897
- return await fn();
898
- } catch (e) {
899
- throw this.onError(e);
900
- }
901
- }
902
-
903
- /**
904
- * Handle incoming chat messages and generate a response
905
- * @param onFinish Callback to be called when the response is finished
906
- * @param options Options including abort signal and client-defined tools
907
- * @returns Response to send to the client or undefined
908
- */
909
- async onChatMessage(
910
- // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides
911
- onFinish: StreamTextOnFinishCallback<ToolSet>,
912
- // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides
913
- options?: OnChatMessageOptions
914
- ): Promise<Response | undefined> {
915
- throw new Error(
916
- "received a chat message, override onChatMessage and return a Response to send to the client"
917
- );
918
- }
919
-
920
- /**
921
- * Save messages on the server side
922
- * @param messages Chat messages to save
923
- */
924
- async saveMessages(messages: ChatMessage[]) {
925
- await this.persistMessages(messages);
926
- await this._tryCatchChat(async () => {
927
- const requestId = nanoid();
928
- const abortSignal = this._getAbortSignal(requestId);
929
- const response = await this.onChatMessage(() => {}, {
930
- requestId,
931
- abortSignal,
932
- clientTools: this._lastClientTools,
933
- body: this._lastBody
934
- });
935
- if (response) this._reply(requestId, response);
936
- });
937
- }
938
-
939
- async persistMessages(
940
- messages: ChatMessage[],
941
- excludeBroadcastIds: string[] = []
942
- ) {
943
- // Merge incoming messages with existing server state to preserve tool outputs.
944
- // This is critical for client-side tools: the client sends messages without
945
- // tool outputs, but the server has them via _applyToolResult.
946
- const mergedMessages = this._mergeIncomingWithServerState(messages);
947
-
948
- // Persist only new or changed messages (incremental persistence).
949
- // Compares serialized JSON against a cache of last-persisted versions.
950
- for (const message of mergedMessages) {
951
- const sanitizedMessage = this._sanitizeMessageForPersistence(message);
952
- const resolved = this._resolveMessageForToolMerge(sanitizedMessage);
953
- const safe = this._enforceRowSizeLimit(resolved);
954
- const json = JSON.stringify(safe);
955
-
956
- // Skip SQL write if the message is identical to what's already persisted
957
- if (this._persistedMessageCache.get(safe.id) === json) {
958
- continue;
959
- }
960
-
961
- this.sql`
962
- insert into cf_ai_chat_agent_messages (id, message)
963
- values (${safe.id}, ${json})
964
- on conflict(id) do update set message = excluded.message
965
- `;
966
- this._persistedMessageCache.set(safe.id, json);
967
- }
968
-
969
- // Enforce maxPersistedMessages: delete oldest messages if over the limit
970
- if (this.maxPersistedMessages != null) {
971
- this._enforceMaxPersistedMessages();
972
- }
973
-
974
- // refresh in-memory messages
975
- const persisted = this._loadMessagesFromDb();
976
- this.messages = autoTransformMessages(persisted);
977
- this._broadcastChatMessage(
978
- {
979
- messages: mergedMessages,
980
- type: MessageType.CF_AGENT_CHAT_MESSAGES
981
- },
982
- excludeBroadcastIds
983
- );
984
- }
985
-
986
- /**
987
- * Merges incoming messages with existing server state.
988
- * This preserves tool outputs that the server has (via _applyToolResult)
989
- * but the client doesn't have yet.
990
- *
991
- * @param incomingMessages - Messages from the client
992
- * @returns Messages with server's tool outputs preserved
993
- */
994
- private _mergeIncomingWithServerState(
995
- incomingMessages: ChatMessage[]
996
- ): ChatMessage[] {
997
- // Build a map of toolCallId -> output from existing server messages
998
- const serverToolOutputs = new Map<string, unknown>();
999
- for (const msg of this.messages) {
1000
- if (msg.role !== "assistant") continue;
1001
- for (const part of msg.parts) {
1002
- if (
1003
- "toolCallId" in part &&
1004
- "state" in part &&
1005
- part.state === "output-available" &&
1006
- "output" in part
1007
- ) {
1008
- serverToolOutputs.set(
1009
- part.toolCallId as string,
1010
- (part as { output: unknown }).output
1011
- );
1012
- }
1013
- }
1014
- }
1015
-
1016
- // Merge server's tool outputs into incoming messages.
1017
- const withMergedToolOutputs =
1018
- serverToolOutputs.size === 0
1019
- ? incomingMessages
1020
- : incomingMessages.map((msg) => {
1021
- if (msg.role !== "assistant") return msg;
1022
-
1023
- let hasChanges = false;
1024
- const updatedParts = msg.parts.map((part) => {
1025
- // If this is a tool part in input-available state and server has the output
1026
- if (
1027
- "toolCallId" in part &&
1028
- "state" in part &&
1029
- part.state === "input-available" &&
1030
- serverToolOutputs.has(part.toolCallId as string)
1031
- ) {
1032
- hasChanges = true;
1033
- return {
1034
- ...part,
1035
- state: "output-available" as const,
1036
- output: serverToolOutputs.get(part.toolCallId as string)
1037
- };
1038
- }
1039
- return part;
1040
- }) as ChatMessage["parts"];
1041
-
1042
- return hasChanges ? { ...msg, parts: updatedParts } : msg;
1043
- });
1044
-
1045
- return this._reconcileAssistantIdsWithServerState(withMergedToolOutputs);
1046
- }
1047
-
1048
- /**
1049
- * Reconciles assistant message IDs between incoming client state and server state.
1050
- *
1051
- * The client can keep a different local ID for an assistant message than the one
1052
- * persisted on the server (e.g. optimistic/local IDs). When that full history is
1053
- * sent back, persisting by ID alone creates duplicate assistant rows. To prevent
1054
- * this, we reuse the server ID for assistant messages that match by content and
1055
- * order, while leaving tool-call messages to _resolveMessageForToolMerge.
1056
- */
1057
- private _reconcileAssistantIdsWithServerState(
1058
- incomingMessages: ChatMessage[]
1059
- ): ChatMessage[] {
1060
- if (this.messages.length === 0) {
1061
- return incomingMessages;
1062
- }
1063
-
1064
- // Tracks the earliest server index we should consider for subsequent matches.
1065
- // This preserves ordering and prevents one server message from being reused for
1066
- // multiple incoming messages with identical content.
1067
- let serverCursor = 0;
1068
-
1069
- return incomingMessages.map((incomingMessage) => {
1070
- // Fast path: exact ID already exists in server history.
1071
- // This applies to any role (user/assistant/system/tool), so in-order
1072
- // round-trips naturally advance the cursor even when assistant content
1073
- // reconciliation is skipped.
1074
- const exactMatchIndex = this.messages.findIndex(
1075
- (serverMessage, index) =>
1076
- index >= serverCursor && serverMessage.id === incomingMessage.id
1077
- );
1078
- if (exactMatchIndex !== -1) {
1079
- serverCursor = exactMatchIndex + 1;
1080
- return incomingMessage;
1081
- }
1082
-
1083
- if (
1084
- incomingMessage.role !== "assistant" ||
1085
- this._hasToolCallPart(incomingMessage)
1086
- ) {
1087
- // Content-based reconciliation is only for non-tool assistant messages.
1088
- // Tool-bearing assistant messages are reconciled by _resolveMessageForToolMerge.
1089
- return incomingMessage;
1090
- }
1091
-
1092
- const incomingKey = this._assistantMessageContentKey(incomingMessage);
1093
- if (!incomingKey) {
1094
- return incomingMessage;
1095
- }
1096
-
1097
- for (let i = serverCursor; i < this.messages.length; i++) {
1098
- const serverMessage = this.messages[i];
1099
- if (
1100
- serverMessage.role !== "assistant" ||
1101
- this._hasToolCallPart(serverMessage)
1102
- ) {
1103
- continue;
1104
- }
1105
-
1106
- if (this._assistantMessageContentKey(serverMessage) === incomingKey) {
1107
- serverCursor = i + 1;
1108
-
1109
- return {
1110
- ...incomingMessage,
1111
- id: serverMessage.id
1112
- };
1113
- }
1114
- }
1115
-
1116
- return incomingMessage;
1117
- });
1118
- }
1119
-
1120
- private _hasToolCallPart(message: ChatMessage): boolean {
1121
- return message.parts.some((part) => "toolCallId" in part);
1122
- }
1123
-
1124
- private _assistantMessageContentKey(
1125
- message: ChatMessage
1126
- ): string | undefined {
1127
- if (message.role !== "assistant") {
1128
- return undefined;
1129
- }
1130
-
1131
- const sanitized = this._sanitizeMessageForPersistence(message);
1132
- return JSON.stringify(sanitized.parts);
1133
- }
1134
-
1135
- /**
1136
- * Resolves a message for persistence, handling tool result merging.
1137
- * If the message contains tool parts with output-available state, checks if there's
1138
- * an existing message with the same toolCallId that should be updated instead of
1139
- * creating a duplicate. This prevents the "Duplicate item found" error from OpenAI
1140
- * when client-side tool results arrive in a new request.
1141
- *
1142
- * @param message - The message to potentially merge
1143
- * @returns The message with the correct ID (either original or merged)
1144
- */
1145
- private _resolveMessageForToolMerge(message: ChatMessage): ChatMessage {
1146
- if (message.role !== "assistant") {
1147
- return message;
1148
- }
1149
-
1150
- // Check if this message has tool parts with output-available state
1151
- for (const part of message.parts) {
1152
- if (
1153
- "toolCallId" in part &&
1154
- "state" in part &&
1155
- (part.state === "output-available" ||
1156
- part.state === "output-error" ||
1157
- part.state === "approval-responded" ||
1158
- part.state === "approval-requested")
1159
- ) {
1160
- const toolCallId = part.toolCallId as string;
1161
-
1162
- // Look for an existing message with this toolCallId in input-available state
1163
- const existingMessage = this._findMessageByToolCallId(toolCallId);
1164
- if (existingMessage && existingMessage.id !== message.id) {
1165
- // Found a match - merge by using the existing message's ID
1166
- // This ensures the SQL upsert updates the existing row
1167
- return {
1168
- ...message,
1169
- id: existingMessage.id
1170
- };
1171
- }
1172
- }
1173
- }
1174
-
1175
- return message;
1176
- }
1177
-
1178
- /**
1179
- * Finds an existing assistant message that contains a tool part with the given toolCallId.
1180
- * Used to detect when a tool result should update an existing message rather than
1181
- * creating a new one.
1182
- *
1183
- * @param toolCallId - The tool call ID to search for
1184
- * @returns The existing message if found, undefined otherwise
1185
- */
1186
- private _findMessageByToolCallId(
1187
- toolCallId: string
1188
- ): ChatMessage | undefined {
1189
- for (const msg of this.messages) {
1190
- if (msg.role !== "assistant") continue;
1191
-
1192
- for (const part of msg.parts) {
1193
- if ("toolCallId" in part && part.toolCallId === toolCallId) {
1194
- return msg;
1195
- }
1196
- }
1197
- }
1198
- return undefined;
1199
- }
1200
-
1201
- /**
1202
- * Sanitizes a message for persistence by removing ephemeral provider-specific
1203
- * data that should not be stored or sent back in subsequent requests.
1204
- *
1205
- * Two-step process:
1206
- *
1207
- * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
1208
- * (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
1209
- * itemIds and reasoningEncryptedContent to message parts. When persisted
1210
- * and sent back, OpenAI rejects duplicate itemIds.
1211
- *
1212
- * 2. **Filter truly empty reasoning parts**: After stripping, reasoning parts
1213
- * with no text and no remaining providerMetadata are removed. Parts that
1214
- * still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
1215
- * with providerMetadata.anthropic.redactedData) are preserved, as they
1216
- * contain data required for round-tripping with the provider API.
1217
- *
1218
- * @param message - The message to sanitize
1219
- * @returns A new message with ephemeral provider data removed
1220
- */
1221
- private _sanitizeMessageForPersistence(message: ChatMessage): ChatMessage {
1222
- // First, strip OpenAI-specific ephemeral data from all parts
1223
- const strippedParts = message.parts.map((part) => {
1224
- let sanitizedPart = part;
1225
-
1226
- // Strip providerMetadata.openai.itemId and reasoningEncryptedContent
1227
- if (
1228
- "providerMetadata" in sanitizedPart &&
1229
- sanitizedPart.providerMetadata &&
1230
- typeof sanitizedPart.providerMetadata === "object" &&
1231
- "openai" in sanitizedPart.providerMetadata
1232
- ) {
1233
- sanitizedPart = this._stripOpenAIMetadata(
1234
- sanitizedPart,
1235
- "providerMetadata"
1236
- );
1237
- }
1238
-
1239
- // Also check callProviderMetadata for tool parts
1240
- if (
1241
- "callProviderMetadata" in sanitizedPart &&
1242
- sanitizedPart.callProviderMetadata &&
1243
- typeof sanitizedPart.callProviderMetadata === "object" &&
1244
- "openai" in sanitizedPart.callProviderMetadata
1245
- ) {
1246
- sanitizedPart = this._stripOpenAIMetadata(
1247
- sanitizedPart,
1248
- "callProviderMetadata"
1249
- );
1250
- }
1251
-
1252
- return sanitizedPart;
1253
- }) as ChatMessage["parts"];
1254
-
1255
- // Then filter out reasoning parts that are truly empty (no text and no
1256
- // remaining providerMetadata). This removes OpenAI placeholders whose
1257
- // metadata was just stripped, while preserving provider-specific blocks
1258
- // like Anthropic's redacted_thinking that carry data in providerMetadata.
1259
- const sanitizedParts = strippedParts.filter((part) => {
1260
- if (part.type === "reasoning") {
1261
- const reasoningPart = part as ReasoningUIPart;
1262
- if (!reasoningPart.text || reasoningPart.text.trim() === "") {
1263
- if (
1264
- "providerMetadata" in reasoningPart &&
1265
- reasoningPart.providerMetadata &&
1266
- typeof reasoningPart.providerMetadata === "object" &&
1267
- Object.keys(reasoningPart.providerMetadata).length > 0
1268
- ) {
1269
- return true;
1270
- }
1271
- return false;
1272
- }
1273
- }
1274
- return true;
1275
- });
1276
-
1277
- return { ...message, parts: sanitizedParts };
1278
- }
1279
-
1280
- /**
1281
- * Helper to strip OpenAI-specific ephemeral fields from a metadata object.
1282
- * Removes itemId and reasoningEncryptedContent while preserving other fields.
1283
- */
1284
- private _stripOpenAIMetadata<T extends ChatMessage["parts"][number]>(
1285
- part: T,
1286
- metadataKey: "providerMetadata" | "callProviderMetadata"
1287
- ): T {
1288
- const metadata = (part as Record<string, unknown>)[metadataKey] as {
1289
- openai?: Record<string, unknown>;
1290
- [key: string]: unknown;
1291
- };
1292
-
1293
- if (!metadata?.openai) return part;
1294
-
1295
- const openaiMeta = metadata.openai;
1296
-
1297
- // Remove ephemeral fields: itemId and reasoningEncryptedContent
1298
- const {
1299
- itemId: _itemId,
1300
- reasoningEncryptedContent: _rec,
1301
- ...restOpenai
1302
- } = openaiMeta;
1303
-
1304
- // Determine what to keep
1305
- const hasOtherOpenaiFields = Object.keys(restOpenai).length > 0;
1306
- const { openai: _openai, ...restMetadata } = metadata;
1307
-
1308
- let newMetadata: ProviderMetadata | undefined;
1309
- if (hasOtherOpenaiFields) {
1310
- newMetadata = {
1311
- ...restMetadata,
1312
- openai: restOpenai
1313
- } as ProviderMetadata;
1314
- } else if (Object.keys(restMetadata).length > 0) {
1315
- newMetadata = restMetadata as ProviderMetadata;
1316
- }
1317
-
1318
- // Create new part without the old metadata
1319
- const { [metadataKey]: _oldMeta, ...restPart } = part as Record<
1320
- string,
1321
- unknown
1322
- >;
1323
-
1324
- if (newMetadata) {
1325
- return { ...restPart, [metadataKey]: newMetadata } as T;
1326
- }
1327
- return restPart as T;
1328
- }
1329
-
1330
- /**
1331
- * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
1332
- * Called after each persist to keep storage bounded.
1333
- */
1334
- private _enforceMaxPersistedMessages() {
1335
- if (this.maxPersistedMessages == null) return;
1336
-
1337
- const countResult = this.sql<{ cnt: number }>`
1338
- select count(*) as cnt from cf_ai_chat_agent_messages
1339
- `;
1340
- const count = countResult?.[0]?.cnt ?? 0;
1341
-
1342
- if (count <= this.maxPersistedMessages) return;
1343
-
1344
- const excess = count - this.maxPersistedMessages;
1345
-
1346
- // Delete the oldest messages (by created_at)
1347
- // Also remove them from the persistence cache
1348
- const toDelete = this.sql<{ id: string }>`
1349
- select id from cf_ai_chat_agent_messages
1350
- order by created_at asc
1351
- limit ${excess}
1352
- `;
1353
-
1354
- if (toDelete && toDelete.length > 0) {
1355
- for (const row of toDelete) {
1356
- this.sql`delete from cf_ai_chat_agent_messages where id = ${row.id}`;
1357
- this._persistedMessageCache.delete(row.id);
1358
- }
1359
- }
1360
- }
1361
-
1362
- /**
1363
- * Enforces SQLite row size limits by compacting tool outputs and text parts
1364
- * when a serialized message exceeds the safety threshold (1.8MB).
1365
- *
1366
- * Only fires in pathological cases (extremely large tool outputs or text).
1367
- * Returns the message unchanged if it fits within limits.
1368
- *
1369
- * Compaction strategy:
1370
- * 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
1371
- * 2. If still too big, truncate text parts from oldest to newest
1372
- * 3. Add metadata so clients can detect compaction
1373
- *
1374
- * @param message - The message to check
1375
- * @returns The message, compacted if necessary
1376
- */
1377
- private _enforceRowSizeLimit(message: ChatMessage): ChatMessage {
1378
- let json = JSON.stringify(message);
1379
- let size = AIChatAgent._byteLength(json);
1380
- if (size <= AIChatAgent.ROW_MAX_BYTES) return message;
1381
-
1382
- if (message.role !== "assistant") {
1383
- // Non-assistant messages (user/system) are harder to compact safely.
1384
- // Truncate the entire message JSON as a last resort.
1385
- console.warn(
1386
- `[AIChatAgent] Non-assistant message ${message.id} is ${size} bytes, ` +
1387
- `exceeds row limit. Truncating text parts.`
1388
- );
1389
- return this._truncateTextParts(message);
1390
- }
1391
-
1392
- console.warn(
1393
- `[AIChatAgent] Message ${message.id} is ${size} bytes, ` +
1394
- `compacting tool outputs to fit SQLite row limit`
1395
- );
1396
-
1397
- // Pass 1: compact tool outputs
1398
- const compactedToolCallIds: string[] = [];
1399
- const compactedParts = message.parts.map((part) => {
1400
- if (
1401
- "output" in part &&
1402
- "toolCallId" in part &&
1403
- "state" in part &&
1404
- part.state === "output-available"
1405
- ) {
1406
- const outputJson = JSON.stringify((part as { output: unknown }).output);
1407
- if (outputJson.length > 1000) {
1408
- compactedToolCallIds.push(part.toolCallId as string);
1409
- return {
1410
- ...part,
1411
- output:
1412
- "This tool output was too large to persist in storage " +
1413
- `(${outputJson.length} bytes). ` +
1414
- "If the user asks about this data, suggest re-running the tool. " +
1415
- `Preview: ${outputJson.slice(0, 500)}...`
1416
- };
1417
- }
1418
- }
1419
- return part;
1420
- }) as ChatMessage["parts"];
1421
-
1422
- let result: ChatMessage = {
1423
- ...message,
1424
- parts: compactedParts
1425
- };
1426
-
1427
- if (compactedToolCallIds.length > 0) {
1428
- result.metadata = {
1429
- ...(result.metadata ?? {}),
1430
- compactedToolOutputs: compactedToolCallIds
1431
- };
1432
- }
1433
-
1434
- // Check if tool compaction was enough
1435
- json = JSON.stringify(result);
1436
- size = AIChatAgent._byteLength(json);
1437
- if (size <= AIChatAgent.ROW_MAX_BYTES) return result;
1438
-
1439
- // Pass 2: truncate text parts
1440
- console.warn(
1441
- `[AIChatAgent] Message ${message.id} still ${size} bytes after tool compaction, truncating text parts`
1442
- );
1443
- return this._truncateTextParts(result);
1444
- }
1445
-
1446
- /**
1447
- * Truncates text parts in a message to fit within the row size limit.
1448
- * Truncates from the first text part forward, keeping the last text part
1449
- * as intact as possible (it is usually the most relevant).
1450
- */
1451
- private _truncateTextParts(message: ChatMessage): ChatMessage {
1452
- const compactedTextPartIndices: number[] = [];
1453
- const parts = [...message.parts];
1454
-
1455
- // Truncate text parts from oldest to newest until we fit
1456
- for (let i = 0; i < parts.length; i++) {
1457
- const part = parts[i];
1458
- if (part.type === "text" && "text" in part) {
1459
- const text = (part as { text: string }).text;
1460
- if (text.length > 1000) {
1461
- compactedTextPartIndices.push(i);
1462
- parts[i] = {
1463
- ...part,
1464
- text:
1465
- `[Text truncated for storage (${text.length} chars). ` +
1466
- `First 500 chars: ${text.slice(0, 500)}...]`
1467
- } as ChatMessage["parts"][number];
1468
-
1469
- // Check if we fit now
1470
- const candidate = { ...message, parts };
1471
- if (
1472
- AIChatAgent._byteLength(JSON.stringify(candidate)) <=
1473
- AIChatAgent.ROW_MAX_BYTES
1474
- ) {
1475
- break;
1476
- }
1477
- }
1478
- }
1479
- }
1480
-
1481
- const result: ChatMessage = { ...message, parts };
1482
- if (compactedTextPartIndices.length > 0) {
1483
- result.metadata = {
1484
- ...(result.metadata ?? {}),
1485
- compactedTextParts: compactedTextPartIndices
1486
- };
1487
- }
1488
- return result;
1489
- }
1490
-
1491
- /**
1492
- * Shared helper for finding a tool part by toolCallId and applying an update.
1493
- * Handles both streaming (in-memory) and persisted (SQLite) messages.
1494
- *
1495
- * Checks _streamingMessage first (tool results/approvals can arrive while
1496
- * the AI is still streaming), then retries persisted messages with backoff
1497
- * in case streaming completes between attempts.
1498
- *
1499
- * @param toolCallId - The tool call ID to find
1500
- * @param callerName - Name for log messages (e.g. "_applyToolResult")
1501
- * @param matchStates - Which tool part states to match
1502
- * @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
1503
- * @returns true if the update was applied, false if not found or state didn't match
1504
- */
1505
- private async _findAndUpdateToolPart(
1506
- toolCallId: string,
1507
- callerName: string,
1508
- matchStates: string[],
1509
- applyUpdate: (part: Record<string, unknown>) => Record<string, unknown>
1510
- ): Promise<boolean> {
1511
- // Find the message containing this tool call.
1512
- // Check streaming message first (in-memory, not yet persisted), then
1513
- // retry persisted messages with backoff.
1514
- let message: ChatMessage | undefined;
1515
-
1516
- if (this._streamingMessage) {
1517
- for (const part of this._streamingMessage.parts) {
1518
- if ("toolCallId" in part && part.toolCallId === toolCallId) {
1519
- message = this._streamingMessage;
1520
- break;
1521
- }
1522
- }
1523
- }
1524
-
1525
- if (!message) {
1526
- for (let attempt = 0; attempt < 10; attempt++) {
1527
- message = this._findMessageByToolCallId(toolCallId);
1528
- if (message) break;
1529
- await new Promise((resolve) => setTimeout(resolve, 100));
1530
- }
1531
- }
1532
-
1533
- if (!message) {
1534
- console.warn(
1535
- `[AIChatAgent] ${callerName}: Could not find message with toolCallId ${toolCallId} after retries`
1536
- );
1537
- return false;
1538
- }
1539
-
1540
- const isStreamingMessage = message === this._streamingMessage;
1541
- let updated = false;
1542
-
1543
- if (isStreamingMessage) {
1544
- // Update in place -- the message will be persisted when streaming completes
1545
- for (const part of message.parts) {
1546
- if (
1547
- "toolCallId" in part &&
1548
- part.toolCallId === toolCallId &&
1549
- "state" in part &&
1550
- matchStates.includes(part.state as string)
1551
- ) {
1552
- const applied = applyUpdate(part as Record<string, unknown>);
1553
- Object.assign(part, applied);
1554
- updated = true;
1555
- break;
1556
- }
1557
- }
1558
- } else {
1559
- // For persisted messages, create updated parts immutably
1560
- const updatedParts = message.parts.map((part) => {
1561
- if (
1562
- "toolCallId" in part &&
1563
- part.toolCallId === toolCallId &&
1564
- "state" in part &&
1565
- matchStates.includes(part.state as string)
1566
- ) {
1567
- updated = true;
1568
- return applyUpdate(part as Record<string, unknown>);
1569
- }
1570
- return part;
1571
- }) as ChatMessage["parts"];
1572
-
1573
- if (updated) {
1574
- const updatedMessage: ChatMessage = this._sanitizeMessageForPersistence(
1575
- { ...message, parts: updatedParts }
1576
- );
1577
- const safe = this._enforceRowSizeLimit(updatedMessage);
1578
- const json = JSON.stringify(safe);
1579
-
1580
- this.sql`
1581
- update cf_ai_chat_agent_messages
1582
- set message = ${json}
1583
- where id = ${message.id}
1584
- `;
1585
- this._persistedMessageCache.set(message.id, json);
1586
-
1587
- const persisted = this._loadMessagesFromDb();
1588
- this.messages = autoTransformMessages(persisted);
1589
- }
1590
- }
1591
-
1592
- if (!updated) {
1593
- console.warn(
1594
- `[AIChatAgent] ${callerName}: Tool part with toolCallId ${toolCallId} not in expected state (expected: ${matchStates.join("|")})`
1595
- );
1596
- return false;
1597
- }
1598
-
1599
- // Broadcast the update to all clients.
1600
- // For persisted messages, re-fetch the latest state from this.messages.
1601
- // For streaming messages, broadcast the in-memory snapshot so clients
1602
- // get immediate confirmation that the tool result/approval was applied.
1603
- if (isStreamingMessage) {
1604
- this._broadcastChatMessage({
1605
- type: MessageType.CF_AGENT_MESSAGE_UPDATED,
1606
- message
1607
- });
1608
- } else {
1609
- const broadcastMessage = this._findMessageByToolCallId(toolCallId);
1610
- if (broadcastMessage) {
1611
- this._broadcastChatMessage({
1612
- type: MessageType.CF_AGENT_MESSAGE_UPDATED,
1613
- message: broadcastMessage
1614
- });
1615
- }
1616
- }
1617
-
1618
- return true;
1619
- }
1620
-
1621
- /**
1622
- * Applies a tool result to an existing assistant message.
1623
- * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
1624
- * The server is the source of truth, so we update the message here and broadcast
1625
- * the update to all clients.
1626
- *
1627
- * @param toolCallId - The tool call ID this result is for
1628
- * @param _toolName - The name of the tool (unused, kept for API compat)
1629
- * @param output - The output from the tool execution
1630
- * @param overrideState - Optional state override ("output-error" to signal denial/failure)
1631
- * @param errorText - Error message when overrideState is "output-error"
1632
- * @returns true if the result was applied, false if the message was not found
1633
- */
1634
- private async _applyToolResult(
1635
- toolCallId: string,
1636
- _toolName: string,
1637
- output: unknown,
1638
- overrideState?: "output-error",
1639
- errorText?: string
1640
- ): Promise<boolean> {
1641
- return this._findAndUpdateToolPart(
1642
- toolCallId,
1643
- "_applyToolResult",
1644
- ["input-available", "approval-requested", "approval-responded"],
1645
- (part) => ({
1646
- ...part,
1647
- ...(overrideState === "output-error"
1648
- ? {
1649
- state: "output-error",
1650
- errorText: errorText ?? "Tool execution denied by user"
1651
- }
1652
- : { state: "output-available", output, preliminary: false })
1653
- })
1654
- );
1655
- }
1656
-
1657
- private async _streamSSEReply(
1658
- id: string,
1659
- streamId: string,
1660
- reader: ReadableStreamDefaultReader<Uint8Array>,
1661
- message: ChatMessage,
1662
- streamCompleted: { value: boolean },
1663
- continuation = false,
1664
- abortSignal?: AbortSignal
1665
- ) {
1666
- streamCompleted.value = false;
1667
-
1668
- // Cancel the reader when the abort signal fires (e.g. client pressed stop).
1669
- // This ensures we stop broadcasting chunks even if the underlying stream
1670
- // hasn't been connected to the abort signal (e.g. user forgot to pass it
1671
- // to streamText).
1672
- if (abortSignal && !abortSignal.aborted) {
1673
- abortSignal.addEventListener(
1674
- "abort",
1675
- () => {
1676
- reader.cancel().catch(() => {});
1677
- },
1678
- { once: true }
1679
- );
1680
- }
1681
-
1682
- while (true) {
1683
- if (abortSignal?.aborted) break;
1684
- let readResult: ReadableStreamReadResult<Uint8Array>;
1685
- try {
1686
- readResult = await reader.read();
1687
- } catch {
1688
- // reader.read() throws after cancel() — treat as abort
1689
- break;
1690
- }
1691
- const { done, value } = readResult;
1692
- if (done) {
1693
- this._completeStream(streamId);
1694
- streamCompleted.value = true;
1695
- this._broadcastChatMessage({
1696
- body: "",
1697
- done: true,
1698
- id,
1699
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1700
- ...(continuation && { continuation: true })
1701
- });
1702
- break;
1703
- }
1704
-
1705
- const chunk = decoder.decode(value);
1706
- const lines = chunk.split("\n");
1707
-
1708
- for (const line of lines) {
1709
- if (line.startsWith("data: ") && line !== "data: [DONE]") {
1710
- try {
1711
- const data: UIMessageChunk = JSON.parse(line.slice(6));
1712
-
1713
- // Delegate message building to the shared parser.
1714
- // It handles: text, reasoning, file, source, tool lifecycle,
1715
- // step boundaries — all the part types needed for UIMessage.
1716
- const handled = applyChunkToParts(message.parts, data);
1717
-
1718
- // When a tool enters approval-requested state, the stream is
1719
- // paused waiting for user approval. Persist the streaming message
1720
- // immediately so the approval UI survives page refresh. Without
1721
- // this, a refresh would reload from SQLite where the tool part
1722
- // is still in input-available state, showing "Running..." instead
1723
- // of the Approve/Reject buttons.
1724
- if (
1725
- data.type === "tool-approval-request" &&
1726
- this._streamingMessage
1727
- ) {
1728
- // Persist directly to SQLite without broadcasting.
1729
- // The client already has this data from the SSE stream —
1730
- // broadcasting would cause the approval UI to render twice.
1731
- // We only need the SQL write so the state survives page refresh.
1732
- const snapshot: ChatMessage = {
1733
- ...this._streamingMessage,
1734
- parts: [...this._streamingMessage.parts]
1735
- };
1736
- const sanitized = this._sanitizeMessageForPersistence(snapshot);
1737
- const json = JSON.stringify(sanitized);
1738
- this.sql`
1739
- INSERT INTO cf_ai_chat_agent_messages (id, message)
1740
- VALUES (${sanitized.id}, ${json})
1741
- ON CONFLICT(id) DO UPDATE SET message = excluded.message
1742
- `;
1743
- // Track that we persisted early so stream completion can update
1744
- // in place rather than appending a duplicate.
1745
- this._approvalPersistedMessageId = sanitized.id;
1746
- }
1747
-
1748
- // Cross-message tool output fallback:
1749
- // When a tool with needsApproval is approved, the continuation
1750
- // stream emits tool-output-available/tool-output-error for a
1751
- // tool call that lives in a *previous* assistant message.
1752
- // applyChunkToParts only searches the current message's parts,
1753
- // so the update is silently skipped. Fall back to searching
1754
- // this.messages and update the persisted message directly.
1755
- // Note: checked independently of `handled` — applyChunkToParts
1756
- // returns true for recognized chunk types even when it cannot
1757
- // find the target part, so `handled` is not a reliable signal.
1758
- if (
1759
- (data.type === "tool-output-available" ||
1760
- data.type === "tool-output-error") &&
1761
- data.toolCallId
1762
- ) {
1763
- const foundInCurrentMessage = message.parts.some(
1764
- (p) => "toolCallId" in p && p.toolCallId === data.toolCallId
1765
- );
1766
- if (!foundInCurrentMessage) {
1767
- if (data.type === "tool-output-available") {
1768
- this._findAndUpdateToolPart(
1769
- data.toolCallId,
1770
- "_streamSSEReply",
1771
- [
1772
- "input-available",
1773
- "input-streaming",
1774
- "approval-responded",
1775
- "approval-requested"
1776
- ],
1777
- (part) => ({
1778
- ...part,
1779
- state: "output-available",
1780
- output: data.output,
1781
- ...(data.preliminary !== undefined && {
1782
- preliminary: data.preliminary
1783
- })
1784
- })
1785
- );
1786
- } else {
1787
- this._findAndUpdateToolPart(
1788
- data.toolCallId,
1789
- "_streamSSEReply",
1790
- [
1791
- "input-available",
1792
- "input-streaming",
1793
- "approval-responded",
1794
- "approval-requested"
1795
- ],
1796
- (part) => ({
1797
- ...part,
1798
- state: "output-error",
1799
- errorText: data.errorText
1800
- })
1801
- );
1802
- }
1803
- }
1804
- }
1805
-
1806
- // Handle server-specific chunk types not covered by the shared parser
1807
- if (!handled) {
1808
- switch (data.type) {
1809
- case "start": {
1810
- if (data.messageId != null) {
1811
- message.id = data.messageId;
1812
- }
1813
- if (data.messageMetadata != null) {
1814
- message.metadata = message.metadata
1815
- ? { ...message.metadata, ...data.messageMetadata }
1816
- : data.messageMetadata;
1817
- }
1818
- break;
1819
- }
1820
- case "finish":
1821
- case "message-metadata": {
1822
- if (data.messageMetadata != null) {
1823
- message.metadata = message.metadata
1824
- ? { ...message.metadata, ...data.messageMetadata }
1825
- : data.messageMetadata;
1826
- }
1827
- break;
1828
- }
1829
- case "finish-step": {
1830
- // No-op for message building (shared parser handles step-start)
1831
- break;
1832
- }
1833
- case "error": {
1834
- this._broadcastChatMessage({
1835
- error: true,
1836
- body: data.errorText ?? JSON.stringify(data),
1837
- done: false,
1838
- id,
1839
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
1840
- });
1841
- break;
1842
- }
1843
- }
1844
- }
1845
-
1846
- // Convert internal AI SDK stream events to valid UIMessageStreamPart format.
1847
- // The "finish" event with "finishReason" is an internal LanguageModelV3StreamPart,
1848
- // not a UIMessageStreamPart (which expects "messageMetadata" instead).
1849
- // See: https://github.com/cloudflare/agents/issues/677
1850
- let eventToSend: unknown = data;
1851
- if (data.type === "finish" && "finishReason" in data) {
1852
- const { finishReason, ...rest } = data as {
1853
- finishReason: string;
1854
- [key: string]: unknown;
1855
- };
1856
- eventToSend = {
1857
- ...rest,
1858
- type: "finish",
1859
- messageMetadata: { finishReason }
1860
- };
1861
- }
1862
-
1863
- // Store chunk for replay and broadcast to clients
1864
- const chunkBody = JSON.stringify(eventToSend);
1865
- this._storeStreamChunk(streamId, chunkBody);
1866
- this._broadcastChatMessage({
1867
- body: chunkBody,
1868
- done: false,
1869
- id,
1870
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1871
- ...(continuation && { continuation: true })
1872
- });
1873
- } catch (_error) {
1874
- // Skip malformed JSON lines silently
1875
- }
1876
- }
1877
- }
1878
- }
1879
-
1880
- // If we exited due to abort, send a done signal so clients know the stream ended
1881
- if (!streamCompleted.value) {
1882
- console.warn(
1883
- "[AIChatAgent] Stream was still active when cancel was received. " +
1884
- "Pass options.abortSignal to streamText() in your onChatMessage() " +
1885
- "to cancel the upstream LLM call and avoid wasted work."
1886
- );
1887
- this._completeStream(streamId);
1888
- streamCompleted.value = true;
1889
- this._broadcastChatMessage({
1890
- body: "",
1891
- done: true,
1892
- id,
1893
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1894
- ...(continuation && { continuation: true })
1895
- });
1896
- }
1897
- }
1898
-
1899
- // Handle plain text responses (e.g., from generateText)
1900
- private async _sendPlaintextReply(
1901
- id: string,
1902
- streamId: string,
1903
- reader: ReadableStreamDefaultReader<Uint8Array>,
1904
- message: ChatMessage,
1905
- streamCompleted: { value: boolean },
1906
- continuation = false,
1907
- abortSignal?: AbortSignal
1908
- ) {
1909
- // if not AI SDK SSE format, we need to inject text-start and text-end events ourselves
1910
- this._broadcastTextEvent(
1911
- streamId,
1912
- { type: "text-start", id },
1913
- continuation
1914
- );
1915
-
1916
- // Use a single text part and accumulate into it, so the persisted message
1917
- // has one text part regardless of how many network chunks the response spans.
1918
- const textPart: TextUIPart = { type: "text", text: "", state: "streaming" };
1919
- message.parts.push(textPart);
1920
-
1921
- // Cancel the reader when the abort signal fires
1922
- if (abortSignal && !abortSignal.aborted) {
1923
- abortSignal.addEventListener(
1924
- "abort",
1925
- () => {
1926
- reader.cancel().catch(() => {});
1927
- },
1928
- { once: true }
1929
- );
1930
- }
1931
-
1932
- while (true) {
1933
- if (abortSignal?.aborted) break;
1934
- let readResult: ReadableStreamReadResult<Uint8Array>;
1935
- try {
1936
- readResult = await reader.read();
1937
- } catch {
1938
- // reader.read() throws after cancel() — treat as abort
1939
- break;
1940
- }
1941
- const { done, value } = readResult;
1942
- if (done) {
1943
- textPart.state = "done";
1944
-
1945
- this._broadcastTextEvent(
1946
- streamId,
1947
- { type: "text-end", id },
1948
- continuation
1949
- );
1950
-
1951
- // Mark the stream as completed
1952
- this._completeStream(streamId);
1953
- streamCompleted.value = true;
1954
- // Send final completion signal
1955
- this._broadcastChatMessage({
1956
- body: "",
1957
- done: true,
1958
- id,
1959
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1960
- ...(continuation && { continuation: true })
1961
- });
1962
- break;
1963
- }
1964
-
1965
- const chunk = decoder.decode(value);
1966
-
1967
- // Accumulate into the single text part to preserve exact formatting
1968
- if (chunk.length > 0) {
1969
- textPart.text += chunk;
1970
- this._broadcastTextEvent(
1971
- streamId,
1972
- { type: "text-delta", id, delta: chunk },
1973
- continuation
1974
- );
1975
- }
1976
- }
1977
-
1978
- // If we exited due to abort, send a done signal so clients know the stream ended
1979
- if (!streamCompleted.value) {
1980
- console.warn(
1981
- "[AIChatAgent] Stream was still active when cancel was received. " +
1982
- "Pass options.abortSignal to streamText() in your onChatMessage() " +
1983
- "to cancel the upstream LLM call and avoid wasted work."
1984
- );
1985
- textPart.state = "done";
1986
- this._broadcastTextEvent(
1987
- streamId,
1988
- { type: "text-end", id },
1989
- continuation
1990
- );
1991
- this._completeStream(streamId);
1992
- streamCompleted.value = true;
1993
- this._broadcastChatMessage({
1994
- body: "",
1995
- done: true,
1996
- id,
1997
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1998
- ...(continuation && { continuation: true })
1999
- });
2000
- }
2001
- }
2002
-
2003
- /**
2004
- * Applies a tool approval response from the client, updating the persisted message.
2005
- * This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
2006
- *
2007
- * - approved=true transitions to approval-responded
2008
- * - approved=false transitions to output-denied so convertToModelMessages
2009
- * emits a tool_result for providers (e.g. Anthropic) that require it.
2010
- *
2011
- * @param toolCallId - The tool call ID this approval is for
2012
- * @param approved - Whether the tool execution was approved
2013
- * @returns true if the approval was applied, false if the message was not found
2014
- */
2015
- private async _applyToolApproval(
2016
- toolCallId: string,
2017
- approved: boolean
2018
- ): Promise<boolean> {
2019
- return this._findAndUpdateToolPart(
2020
- toolCallId,
2021
- "_applyToolApproval",
2022
- ["input-available", "approval-requested"],
2023
- (part) => ({
2024
- ...part,
2025
- state: approved ? "approval-responded" : "output-denied",
2026
- // Merge with existing approval data to preserve the id field.
2027
- // convertToModelMessages needs approval.id to produce a valid
2028
- // tool-approval-request content part with approvalId.
2029
- approval: {
2030
- ...(part.approval as Record<string, unknown> | undefined),
2031
- approved
2032
- }
2033
- })
2034
- );
2035
- }
2036
-
2037
- private async _reply(
2038
- id: string,
2039
- response: Response,
2040
- excludeBroadcastIds: string[] = [],
2041
- options: { continuation?: boolean; chatMessageId?: string } = {}
2042
- ) {
2043
- const { continuation = false, chatMessageId } = options;
2044
- // Look up the abort signal for this request so we can cancel the reader
2045
- // loop if the client sends a cancel message. This is a safety net —
2046
- // users should also pass abortSignal to streamText for proper cancellation.
2047
- const abortSignal = chatMessageId
2048
- ? this._chatMessageAbortControllers.get(chatMessageId)?.signal
2049
- : undefined;
2050
-
2051
- return this._tryCatchChat(async () => {
2052
- if (!response.body) {
2053
- // Send empty response if no body
2054
- this._broadcastChatMessage({
2055
- body: "",
2056
- done: true,
2057
- id,
2058
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
2059
- ...(continuation && { continuation: true })
2060
- });
2061
- return;
2062
- }
2063
-
2064
- // Start tracking this stream for resumability
2065
- const streamId = this._startStream(id);
2066
-
2067
- const reader = response.body.getReader();
2068
-
2069
- // Parsing state adapted from:
2070
- // https://github.com/vercel/ai/blob/main/packages/ai/src/ui-message-stream/ui-message-chunks.ts#L295
2071
- const message: ChatMessage = {
2072
- id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`, // default
2073
- role: "assistant",
2074
- parts: []
2075
- };
2076
- // Track the streaming message so tool results can be applied before persistence
2077
- this._streamingMessage = message;
2078
- // Set up completion promise for tool continuation to wait on
2079
- this._streamCompletionPromise = new Promise((resolve) => {
2080
- this._streamCompletionResolve = resolve;
2081
- });
2082
-
2083
- // Determine response format based on content-type
2084
- const contentType = response.headers.get("content-type") || "";
2085
- const isSSE = contentType.includes("text/event-stream"); // AI SDK v5 SSE format
2086
- const streamCompleted = { value: false };
2087
- // Capture before try so it's available after finally.
2088
- // _approvalPersistedMessageId is set inside _streamSSEReply when a
2089
- // tool enters approval-requested state and the message is persisted early.
2090
- let earlyPersistedId: string | null = null;
2091
-
2092
- try {
2093
- if (isSSE) {
2094
- // AI SDK v5 SSE format
2095
- await this._streamSSEReply(
2096
- id,
2097
- streamId,
2098
- reader,
2099
- message,
2100
- streamCompleted,
2101
- continuation,
2102
- abortSignal
2103
- );
2104
- } else {
2105
- await this._sendPlaintextReply(
2106
- id,
2107
- streamId,
2108
- reader,
2109
- message,
2110
- streamCompleted,
2111
- continuation,
2112
- abortSignal
2113
- );
2114
- }
2115
- } catch (error) {
2116
- // Mark stream as error if not already completed
2117
- if (!streamCompleted.value) {
2118
- this._markStreamError(streamId);
2119
- // Notify clients of the error
2120
- this._broadcastChatMessage({
2121
- body: error instanceof Error ? error.message : "Stream error",
2122
- done: true,
2123
- error: true,
2124
- id,
2125
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
2126
- ...(continuation && { continuation: true })
2127
- });
2128
- }
2129
- throw error;
2130
- } finally {
2131
- reader.releaseLock();
2132
-
2133
- // Always clear the streaming message reference and resolve completion
2134
- // promise, even on error. Without this, tool continuations waiting on
2135
- // _streamCompletionPromise would hang forever after a stream error.
2136
- this._streamingMessage = null;
2137
- // Capture and clear early-persist tracking. The persistence block
2138
- // after the finally uses the local to update in place.
2139
- earlyPersistedId = this._approvalPersistedMessageId;
2140
- this._approvalPersistedMessageId = null;
2141
- if (this._streamCompletionResolve) {
2142
- this._streamCompletionResolve();
2143
- this._streamCompletionResolve = null;
2144
- this._streamCompletionPromise = null;
2145
- }
2146
-
2147
- // Framework-level cleanup: always remove abort controller.
2148
- // Only emit observability on success (not on error path).
2149
- if (chatMessageId) {
2150
- this._removeAbortController(chatMessageId);
2151
- if (streamCompleted.value) {
2152
- this.observability?.emit(
2153
- {
2154
- displayMessage: continuation
2155
- ? "Chat message response (tool continuation)"
2156
- : "Chat message response",
2157
- id: chatMessageId,
2158
- payload: {},
2159
- timestamp: Date.now(),
2160
- type: "message:response"
2161
- },
2162
- this.ctx
2163
- );
2164
- }
2165
- }
2166
- }
2167
-
2168
- if (message.parts.length > 0) {
2169
- if (earlyPersistedId) {
2170
- // Message already exists in this.messages from the early persist.
2171
- // Update it in place with the final streaming state.
2172
- // Note: early-persisted messages come from the initial stream
2173
- // (before approval), which is never a continuation. The
2174
- // continuation stream starts fresh after approval, so
2175
- // earlyPersistedId will always be null for continuations.
2176
- const updatedMessages = this.messages.map((msg) =>
2177
- msg.id === earlyPersistedId ? message : msg
2178
- );
2179
- await this.persistMessages(updatedMessages, excludeBroadcastIds);
2180
- } else if (continuation) {
2181
- // Find the last assistant message and append parts to it
2182
- let lastAssistantIdx = -1;
2183
- for (let i = this.messages.length - 1; i >= 0; i--) {
2184
- if (this.messages[i].role === "assistant") {
2185
- lastAssistantIdx = i;
2186
- break;
2187
- }
2188
- }
2189
- if (lastAssistantIdx >= 0) {
2190
- const lastAssistant = this.messages[lastAssistantIdx];
2191
- const mergedMessage: ChatMessage = {
2192
- ...lastAssistant,
2193
- parts: [...lastAssistant.parts, ...message.parts]
2194
- };
2195
- const updatedMessages = [...this.messages];
2196
- updatedMessages[lastAssistantIdx] = mergedMessage;
2197
- await this.persistMessages(updatedMessages, excludeBroadcastIds);
2198
- } else {
2199
- // No assistant message to append to, create new one
2200
- await this.persistMessages(
2201
- [...this.messages, message],
2202
- excludeBroadcastIds
2203
- );
2204
- }
2205
- } else {
2206
- await this.persistMessages(
2207
- [...this.messages, message],
2208
- excludeBroadcastIds
2209
- );
2210
- }
2211
- }
2212
- });
2213
- }
2214
-
2215
- /**
2216
- * For the given message id, look up its associated AbortController
2217
- * If the AbortController does not exist, create and store one in memory
2218
- *
2219
- * returns the AbortSignal associated with the AbortController
2220
- */
2221
- private _getAbortSignal(id: string): AbortSignal | undefined {
2222
- // Defensive check, since we're coercing message types at the moment
2223
- if (typeof id !== "string") {
2224
- return undefined;
2225
- }
2226
-
2227
- if (!this._chatMessageAbortControllers.has(id)) {
2228
- this._chatMessageAbortControllers.set(id, new AbortController());
2229
- }
2230
-
2231
- return this._chatMessageAbortControllers.get(id)?.signal;
2232
- }
2233
-
2234
- /**
2235
- * Remove an abort controller from the cache of pending message responses
2236
- */
2237
- private _removeAbortController(id: string) {
2238
- this._chatMessageAbortControllers.delete(id);
2239
- }
2240
-
2241
- /**
2242
- * Propagate an abort signal for any requests associated with the given message id
2243
- */
2244
- private _cancelChatRequest(id: string) {
2245
- if (this._chatMessageAbortControllers.has(id)) {
2246
- const abortController = this._chatMessageAbortControllers.get(id);
2247
- abortController?.abort();
2248
- }
2249
- }
2250
-
2251
- /**
2252
- * Abort all pending requests and clear the cache of AbortControllers
2253
- */
2254
- private _destroyAbortControllers() {
2255
- for (const controller of this._chatMessageAbortControllers.values()) {
2256
- controller?.abort();
2257
- }
2258
- this._chatMessageAbortControllers.clear();
2259
- }
2260
-
2261
- /**
2262
- * When the DO is destroyed, cancel all pending requests and clean up resources
2263
- */
2264
- async destroy() {
2265
- this._destroyAbortControllers();
2266
- this._resumableStream.destroy();
2267
- await super.destroy();
2268
- }
2269
- }