@cloudflare/ai-chat 0.0.7 → 0.1.0

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 (60) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/README.md +225 -459
  3. package/dist/ai-chat-v5-migration.d.ts +9 -9
  4. package/dist/ai-chat-v5-migration.js +25 -4
  5. package/dist/ai-chat-v5-migration.js.map +1 -1
  6. package/dist/experimental/forever.d.ts +29 -0
  7. package/dist/experimental/forever.js +55 -0
  8. package/dist/experimental/forever.js.map +1 -0
  9. package/dist/index.d.ts +126 -74
  10. package/dist/index.js +753 -632
  11. package/dist/index.js.map +1 -1
  12. package/dist/message-builder-Bwc_Umye.js +231 -0
  13. package/dist/message-builder-Bwc_Umye.js.map +1 -0
  14. package/dist/react.d.ts +27 -9
  15. package/dist/react.js +248 -259
  16. package/dist/react.js.map +1 -1
  17. package/dist/resumable-stream-DqXxQVjf.d.ts +103 -0
  18. package/dist/types.d.ts +16 -4
  19. package/dist/types.js +2 -0
  20. package/dist/types.js.map +1 -1
  21. package/e2e/chat.spec.ts +1703 -0
  22. package/e2e/client-tools.spec.ts +504 -0
  23. package/e2e/llm.spec.ts +637 -0
  24. package/e2e/playwright.config.ts +24 -0
  25. package/e2e/worker.ts +176 -0
  26. package/e2e/wrangler.jsonc +23 -0
  27. package/package.json +12 -5
  28. package/scripts/build.ts +2 -1
  29. package/src/ai-chat-v5-migration.ts +32 -5
  30. package/src/experimental/forever.ts +66 -0
  31. package/src/index.ts +850 -1132
  32. package/src/message-builder.ts +384 -0
  33. package/src/react-tests/use-agent-chat.test.tsx +738 -2
  34. package/src/react.tsx +396 -462
  35. package/src/resumable-stream.ts +441 -0
  36. package/src/tests/chat-context.test.ts +1 -1
  37. package/src/tests/chat-persistence.test.ts +5 -5
  38. package/src/tests/clear-history.test.ts +132 -0
  39. package/src/tests/client-tool-duplicate-message.test.ts +457 -14
  40. package/src/tests/client-tools-broadcast.test.ts +2 -2
  41. package/src/tests/client-tools-continuation.test.ts +314 -0
  42. package/src/tests/client-tools-reconnect.test.ts +143 -0
  43. package/src/tests/custom-body-continuation.test.ts +309 -0
  44. package/src/tests/custom-body.test.ts +186 -0
  45. package/src/tests/destroy.test.ts +57 -0
  46. package/src/tests/get-messages-endpoint.test.ts +79 -0
  47. package/src/tests/max-persisted-messages.test.ts +201 -0
  48. package/src/tests/merge-server-state.test.ts +106 -0
  49. package/src/tests/message-builder.test.ts +808 -0
  50. package/src/tests/migration.test.ts +282 -0
  51. package/src/tests/non-sse-response.test.ts +2 -2
  52. package/src/tests/onfinish-cleanup.test.ts +362 -0
  53. package/src/tests/plaintext-response.test.ts +87 -0
  54. package/src/tests/resumable-streaming.test.ts +220 -14
  55. package/src/tests/row-size-guard.test.ts +374 -0
  56. package/src/tests/sanitize-messages.test.ts +215 -0
  57. package/src/tests/validate-messages.test.ts +269 -0
  58. package/src/tests/worker.ts +85 -23
  59. package/src/types.ts +17 -1
  60. package/src/ws-chat-transport.ts +203 -0
package/src/index.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import type {
2
2
  UIMessage as ChatMessage,
3
- DynamicToolUIPart,
4
3
  JSONSchema7,
5
4
  ProviderMetadata,
6
5
  ReasoningUIPart,
@@ -8,12 +7,12 @@ import type {
8
7
  TextUIPart,
9
8
  Tool,
10
9
  ToolSet,
11
- ToolUIPart,
12
10
  UIMessageChunk
13
11
  } from "ai";
14
12
  import { tool, jsonSchema } from "ai";
15
13
  import {
16
14
  Agent,
15
+ __DO_NOT_USE_WILL_BREAK__agentContext as agentContext,
17
16
  type AgentContext,
18
17
  type Connection,
19
18
  type ConnectionContext,
@@ -26,9 +25,49 @@ import {
26
25
  type OutgoingMessage
27
26
  } from "./types";
28
27
  import { autoTransformMessages } from "./ai-chat-v5-migration";
28
+ import { applyChunkToParts } from "./message-builder";
29
+ import { ResumableStream } from "./resumable-stream";
29
30
  import { nanoid } from "nanoid";
30
31
 
31
- import { agentContext } from "agents/internal_context";
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
+ * One-shot deprecation warnings (warns once per key per session).
63
+ */
64
+ const _deprecationWarnings = new Set<string>();
65
+ function warnDeprecated(id: string, message: string) {
66
+ if (!_deprecationWarnings.has(id)) {
67
+ _deprecationWarnings.add(id);
68
+ console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);
69
+ }
70
+ }
32
71
 
33
72
  /**
34
73
  * Schema for a client-defined tool sent from the browser.
@@ -65,6 +104,19 @@ export type OnChatMessageOptions = {
65
104
  * in `useAgentChat` for client-side execution.
66
105
  */
67
106
  clientTools?: ClientToolSchema[];
107
+ /**
108
+ * Custom body data sent from the client via `prepareSendMessagesRequest`
109
+ * or the AI SDK's `body` option in `sendMessage`.
110
+ *
111
+ * Contains all fields from the request body except `messages` and `clientTools`,
112
+ * which are handled separately.
113
+ *
114
+ * During tool continuations (auto-continue after client tool results), this
115
+ * contains the body from the most recent chat request. The value is persisted
116
+ * to SQLite so it survives Durable Object hibernation. It is cleared when the
117
+ * chat is cleared via `CF_AGENT_CHAT_CLEAR`.
118
+ */
119
+ body?: Record<string, unknown>;
68
120
  };
69
121
 
70
122
  /**
@@ -105,6 +157,11 @@ export type OnChatMessageOptions = {
105
157
  export function createToolsFromClientSchemas(
106
158
  clientTools?: ClientToolSchema[]
107
159
  ): ToolSet {
160
+ warnDeprecated(
161
+ "createToolsFromClientSchemas",
162
+ "createToolsFromClientSchemas() is deprecated. Define tools on the server using tool() from 'ai' and handle client execution via onToolCall in useAgentChat. Will be removed in the next major version."
163
+ );
164
+
108
165
  if (!clientTools || clientTools.length === 0) {
109
166
  return {};
110
167
  }
@@ -132,41 +189,8 @@ export function createToolsFromClientSchemas(
132
189
  );
133
190
  }
134
191
 
135
- /** Number of chunks to buffer before flushing to SQLite */
136
- const CHUNK_BUFFER_SIZE = 10;
137
- /** Maximum buffer size to prevent memory issues on rapid reconnections */
138
- const CHUNK_BUFFER_MAX_SIZE = 100;
139
- /** Maximum age for a "streaming" stream before considering it stale (ms) - 5 minutes */
140
- const STREAM_STALE_THRESHOLD_MS = 5 * 60 * 1000;
141
- /** Default cleanup interval for old streams (ms) - every 10 minutes */
142
- const CLEANUP_INTERVAL_MS = 10 * 60 * 1000;
143
- /** Default age threshold for cleaning up completed streams (ms) - 24 hours */
144
- const CLEANUP_AGE_THRESHOLD_MS = 24 * 60 * 60 * 1000;
145
-
146
192
  const decoder = new TextDecoder();
147
193
 
148
- /**
149
- * Stored stream chunk for resumable streaming
150
- */
151
- type StreamChunk = {
152
- id: string;
153
- stream_id: string;
154
- body: string;
155
- chunk_index: number;
156
- created_at: number;
157
- };
158
-
159
- /**
160
- * Stream metadata for tracking active streams
161
- */
162
- type StreamMetadata = {
163
- id: string;
164
- request_id: string;
165
- status: "streaming" | "completed" | "error";
166
- created_at: number;
167
- completed_at: number | null;
168
- };
169
-
170
194
  /**
171
195
  * Extension of Agent with built-in chat capabilities
172
196
  * @template Env Environment type containing bindings
@@ -182,17 +206,10 @@ export class AIChatAgent<
182
206
  private _chatMessageAbortControllers: Map<string, AbortController>;
183
207
 
184
208
  /**
185
- * Currently active stream ID for resumable streaming.
186
- * Stored in memory for quick access; persisted in stream_metadata table.
187
- * @internal Protected for testing purposes.
188
- */
189
- protected _activeStreamId: string | null = null;
190
-
191
- /**
192
- * Request ID associated with the active stream.
209
+ * Resumable stream manager -- handles chunk buffering, persistence, and replay.
193
210
  * @internal Protected for testing purposes.
194
211
  */
195
- protected _activeRequestId: string | null = null;
212
+ protected _resumableStream!: ResumableStream;
196
213
 
197
214
  /**
198
215
  * The message currently being streamed. Used to apply tool results
@@ -201,6 +218,14 @@ export class AIChatAgent<
201
218
  */
202
219
  private _streamingMessage: ChatMessage | null = null;
203
220
 
221
+ /**
222
+ * Tracks the ID of a streaming message that was persisted early due to
223
+ * a tool entering approval-requested state. When set, stream completion
224
+ * updates the existing persisted message instead of appending a new one.
225
+ * @internal
226
+ */
227
+ private _approvalPersistedMessageId: string | null = null;
228
+
204
229
  /**
205
230
  * Promise that resolves when the current stream completes.
206
231
  * Used to wait for message persistence before continuing after tool results.
@@ -210,38 +235,60 @@ export class AIChatAgent<
210
235
  private _streamCompletionResolve: (() => void) | null = null;
211
236
 
212
237
  /**
213
- * Current chunk index for the active stream
238
+ * Set of connection IDs that are pending stream resume.
239
+ * These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
240
+ * They should be excluded from live stream broadcasts until they ACK.
241
+ * @internal
214
242
  */
215
- private _streamChunkIndex = 0;
243
+ private _pendingResumeConnections: Set<string> = new Set();
216
244
 
217
245
  /**
218
- * Buffer for stream chunks pending write to SQLite.
219
- * Chunks are batched and flushed when buffer reaches CHUNK_BUFFER_SIZE.
246
+ * Client tool schemas from the most recent chat request.
247
+ * Stored so they can be passed to onChatMessage during tool continuations.
248
+ * @internal
220
249
  */
221
- private _chunkBuffer: Array<{
222
- id: string;
223
- streamId: string;
224
- body: string;
225
- index: number;
226
- }> = [];
250
+ private _lastClientTools: ClientToolSchema[] | undefined;
227
251
 
228
252
  /**
229
- * Lock to prevent concurrent flush operations
253
+ * Custom body data from the most recent chat request.
254
+ * Stored so it can be passed to onChatMessage during tool continuations.
255
+ * @internal
230
256
  */
231
- private _isFlushingChunks = false;
257
+ private _lastBody: Record<string, unknown> | undefined;
232
258
 
233
259
  /**
234
- * Timestamp of the last cleanup operation for old streams
260
+ * Cache of last-persisted JSON for each message ID.
261
+ * Used for incremental persistence: skip SQL writes for unchanged messages.
262
+ * Lost on hibernation, repopulated from SQLite on wake.
263
+ * @internal
235
264
  */
236
- private _lastCleanupTime = 0;
265
+ private _persistedMessageCache: Map<string, string> = new Map();
266
+
267
+ /** Maximum serialized message size before compaction (bytes). 1.8MB with headroom below SQLite's 2MB limit. */
268
+ private static ROW_MAX_BYTES = 1_800_000;
269
+
270
+ /** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
271
+ private static _byteLength(s: string): number {
272
+ return textEncoder.encode(s).byteLength;
273
+ }
237
274
 
238
275
  /**
239
- * Set of connection IDs that are pending stream resume.
240
- * These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
241
- * They should be excluded from live stream broadcasts until they ACK.
242
- * @internal
276
+ * Maximum number of messages to keep in SQLite storage.
277
+ * When the conversation exceeds this limit, oldest messages are deleted
278
+ * after each persist. Set to `undefined` (default) for no limit.
279
+ *
280
+ * This controls storage only — it does not affect what's sent to the LLM.
281
+ * Use `pruneMessages()` from the AI SDK in your `onChatMessage` to control
282
+ * LLM context separately.
283
+ *
284
+ * @example
285
+ * ```typescript
286
+ * class MyAgent extends AIChatAgent<Env> {
287
+ * maxPersistedMessages = 100; // Keep last 100 messages in storage
288
+ * }
289
+ * ```
243
290
  */
244
- private _pendingResumeConnections: Set<string> = new Set();
291
+ maxPersistedMessages: number | undefined = undefined;
245
292
 
246
293
  /** Array of chat messages for the current conversation */
247
294
  messages: ChatMessage[];
@@ -254,40 +301,35 @@ export class AIChatAgent<
254
301
  created_at datetime default current_timestamp
255
302
  )`;
256
303
 
257
- // Create tables for automatic resumable streaming
258
- this.sql`create table if not exists cf_ai_chat_stream_chunks (
259
- id text primary key,
260
- stream_id text not null,
261
- body text not null,
262
- chunk_index integer not null,
263
- created_at integer not null
304
+ // Key-value table for request context that must survive hibernation
305
+ // (e.g., custom body fields, client tools from the last chat request).
306
+ this.sql`create table if not exists cf_ai_chat_request_context (
307
+ key text primary key,
308
+ value text not null
264
309
  )`;
265
310
 
266
- this.sql`create table if not exists cf_ai_chat_stream_metadata (
267
- id text primary key,
268
- request_id text not null,
269
- status text not null,
270
- created_at integer not null,
271
- completed_at integer
272
- )`;
311
+ // Restore request context from SQLite (survives hibernation)
312
+ this._restoreRequestContext();
273
313
 
274
- this.sql`create index if not exists idx_stream_chunks_stream_id
275
- on cf_ai_chat_stream_chunks(stream_id, chunk_index)`;
314
+ // Initialize resumable stream manager (creates its own tables + restores state)
315
+ this._resumableStream = new ResumableStream(this.sql.bind(this));
276
316
 
277
- // Load messages and automatically transform them to v5 format
317
+ // Load messages and automatically transform them to v5 format.
318
+ // Note: _loadMessagesFromDb() runs structural validation which requires
319
+ // `parts` to be an array. Legacy v4 messages (with `content` instead of
320
+ // `parts`) would fail this check — but that's fine because autoTransformMessages
321
+ // already migrated them on a previous load, and persistMessages wrote them back.
322
+ // Any message still without `parts` at this point is genuinely corrupt.
278
323
  const rawMessages = this._loadMessagesFromDb();
279
324
 
280
325
  // Automatic migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages
281
326
  this.messages = autoTransformMessages(rawMessages);
282
327
 
283
328
  this._chatMessageAbortControllers = new Map();
284
-
285
- // Check for any active streams from a previous session
286
- this._restoreActiveStream();
287
329
  const _onConnect = this.onConnect.bind(this);
288
330
  this.onConnect = async (connection: Connection, ctx: ConnectionContext) => {
289
331
  // Notify client about active streams that can be resumed
290
- if (this._activeStreamId) {
332
+ if (this._resumableStream.hasActiveStream()) {
291
333
  this._notifyStreamResuming(connection);
292
334
  }
293
335
  // Call consumer's onConnect
@@ -327,12 +369,35 @@ export class AIChatAgent<
327
369
  data.init.method === "POST"
328
370
  ) {
329
371
  const { body } = data.init;
330
- const parsed = JSON.parse(body as string);
331
- const { messages, clientTools } = parsed as {
372
+ if (!body) {
373
+ console.warn(
374
+ "[AIChatAgent] Received chat request with empty body, ignoring"
375
+ );
376
+ return;
377
+ }
378
+
379
+ let parsed: Record<string, unknown>;
380
+ try {
381
+ parsed = JSON.parse(body as string);
382
+ } catch (_parseError) {
383
+ console.warn(
384
+ "[AIChatAgent] Received chat request with invalid JSON body, ignoring"
385
+ );
386
+ return;
387
+ }
388
+
389
+ const { messages, clientTools, ...customBody } = parsed as {
332
390
  messages: ChatMessage[];
333
391
  clientTools?: ClientToolSchema[];
392
+ [key: string]: unknown;
334
393
  };
335
394
 
395
+ // Store client tools and body for use during tool continuations
396
+ this._lastClientTools = clientTools?.length ? clientTools : undefined;
397
+ this._lastBody =
398
+ Object.keys(customBody).length > 0 ? customBody : undefined;
399
+ this._persistRequestContext();
400
+
336
401
  // Automatically transform any incoming messages
337
402
  const transformedMessages = autoTransformMessages(messages);
338
403
 
@@ -368,27 +433,20 @@ export class AIChatAgent<
368
433
  async () => {
369
434
  const response = await this.onChatMessage(
370
435
  async (_finishResult) => {
371
- this._removeAbortController(chatMessageId);
372
-
373
- this.observability?.emit(
374
- {
375
- displayMessage: "Chat message response",
376
- id: data.id,
377
- payload: {},
378
- timestamp: Date.now(),
379
- type: "message:response"
380
- },
381
- this.ctx
382
- );
436
+ // User-provided hook. Cleanup is now handled by _reply,
437
+ // so this is optional for the user to pass to streamText.
383
438
  },
384
439
  {
385
440
  abortSignal,
386
- clientTools
441
+ clientTools,
442
+ body: this._lastBody
387
443
  }
388
444
  );
389
445
 
390
446
  if (response) {
391
- await this._reply(data.id, response, [connection.id]);
447
+ await this._reply(data.id, response, [connection.id], {
448
+ chatMessageId
449
+ });
392
450
  } else {
393
451
  console.warn(
394
452
  `[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`
@@ -412,12 +470,12 @@ export class AIChatAgent<
412
470
  if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
413
471
  this._destroyAbortControllers();
414
472
  this.sql`delete from cf_ai_chat_agent_messages`;
415
- this.sql`delete from cf_ai_chat_stream_chunks`;
416
- this.sql`delete from cf_ai_chat_stream_metadata`;
417
- this._activeStreamId = null;
418
- this._activeRequestId = null;
419
- this._streamChunkIndex = 0;
473
+ this._resumableStream.clearAll();
420
474
  this._pendingResumeConnections.clear();
475
+ this._lastClientTools = undefined;
476
+ this._lastBody = undefined;
477
+ this._persistRequestContext();
478
+ this._persistedMessageCache.clear();
421
479
  this.messages = [];
422
480
  this._broadcastChatMessage(
423
481
  { type: MessageType.CF_AGENT_CHAT_CLEAR },
@@ -439,19 +497,28 @@ export class AIChatAgent<
439
497
  return;
440
498
  }
441
499
 
500
+ // Handle client-initiated stream resume request.
501
+ // The client sends this after its message handler is registered,
502
+ // avoiding the race condition where CF_AGENT_STREAM_RESUMING sent
503
+ // in onConnect arrives before the client's handler is ready.
504
+ if (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {
505
+ if (this._resumableStream.hasActiveStream()) {
506
+ this._notifyStreamResuming(connection);
507
+ }
508
+ return;
509
+ }
510
+
442
511
  // Handle stream resume acknowledgment
443
512
  if (data.type === MessageType.CF_AGENT_STREAM_RESUME_ACK) {
444
513
  this._pendingResumeConnections.delete(connection.id);
445
514
 
446
515
  if (
447
- this._activeStreamId &&
448
- this._activeRequestId &&
449
- this._activeRequestId === data.id
516
+ this._resumableStream.hasActiveStream() &&
517
+ this._resumableStream.activeRequestId === data.id
450
518
  ) {
451
- this._sendStreamChunks(
519
+ this._resumableStream.replayChunks(
452
520
  connection,
453
- this._activeStreamId,
454
- this._activeRequestId
521
+ this._resumableStream.activeRequestId
455
522
  );
456
523
  }
457
524
  return;
@@ -459,7 +526,14 @@ export class AIChatAgent<
459
526
 
460
527
  // Handle client-side tool result
461
528
  if (data.type === MessageType.CF_AGENT_TOOL_RESULT) {
462
- const { toolCallId, toolName, output, autoContinue } = data;
529
+ const { toolCallId, toolName, output, autoContinue, 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
+ }
463
537
 
464
538
  // Apply the tool result
465
539
  this._applyToolResult(toolCallId, toolName, output).then(
@@ -474,16 +548,91 @@ export class AIChatAgent<
474
548
  if (this._streamCompletionPromise) {
475
549
  await this._streamCompletionPromise;
476
550
  } else {
477
- // If no promise, wait a bit for the stream to finish
551
+ // TODO: The completion promise can be null if the stream finished
552
+ // before the tool result arrived (race between stream end and tool
553
+ // apply). The 500ms fallback is a pragmatic workaround — consider
554
+ // a more deterministic signal (e.g. always setting the promise).
478
555
  await new Promise((resolve) => setTimeout(resolve, 500));
479
556
  }
480
557
  };
481
558
 
482
- waitForStream().then(() => {
559
+ waitForStream()
560
+ .then(() => {
561
+ const continuationId = nanoid();
562
+ const abortSignal = this._getAbortSignal(continuationId);
563
+
564
+ return this._tryCatchChat(async () => {
565
+ return agentContext.run(
566
+ {
567
+ agent: this,
568
+ connection,
569
+ request: undefined,
570
+ email: undefined
571
+ },
572
+ async () => {
573
+ const response = await this.onChatMessage(
574
+ async (_finishResult) => {
575
+ // User-provided hook. Cleanup handled by _reply.
576
+ },
577
+ {
578
+ abortSignal,
579
+ clientTools: clientTools ?? this._lastClientTools,
580
+ body: this._lastBody
581
+ }
582
+ );
583
+
584
+ if (response) {
585
+ // Pass continuation flag to merge parts into last assistant message
586
+ // Note: We pass an empty excludeBroadcastIds array because the sender
587
+ // NEEDS to receive the continuation stream. Unlike regular chat requests
588
+ // where aiFetch handles the response, tool continuations have no listener
589
+ // waiting - the client relies on the broadcast.
590
+ await this._reply(
591
+ continuationId,
592
+ response,
593
+ [], // Don't exclude sender - they need the continuation
594
+ {
595
+ continuation: true,
596
+ chatMessageId: continuationId
597
+ }
598
+ );
599
+ }
600
+ }
601
+ );
602
+ });
603
+ })
604
+ .catch((error) => {
605
+ console.error(
606
+ "[AIChatAgent] Tool continuation failed:",
607
+ error
608
+ );
609
+ });
610
+ }
611
+ }
612
+ );
613
+ return;
614
+ }
615
+
616
+ // Handle client-side tool approval response
617
+ if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
618
+ const { toolCallId, approved, autoContinue } = data;
619
+ this._applyToolApproval(toolCallId, approved).then((applied) => {
620
+ // Only auto-continue if approved AND client requested it
621
+ if (applied && approved && autoContinue) {
622
+ const waitForStream = async () => {
623
+ if (this._streamCompletionPromise) {
624
+ await this._streamCompletionPromise;
625
+ } else {
626
+ await new Promise((resolve) => setTimeout(resolve, 500));
627
+ }
628
+ };
629
+
630
+ waitForStream()
631
+ .then(() => {
483
632
  const continuationId = nanoid();
484
633
  const abortSignal = this._getAbortSignal(continuationId);
485
634
 
486
- this._tryCatchChat(async () => {
635
+ return this._tryCatchChat(async () => {
487
636
  return agentContext.run(
488
637
  {
489
638
  agent: this,
@@ -493,53 +642,32 @@ export class AIChatAgent<
493
642
  },
494
643
  async () => {
495
644
  const response = await this.onChatMessage(
496
- async (_finishResult) => {
497
- this._removeAbortController(continuationId);
498
-
499
- this.observability?.emit(
500
- {
501
- displayMessage:
502
- "Chat message response (tool continuation)",
503
- id: continuationId,
504
- payload: {},
505
- timestamp: Date.now(),
506
- type: "message:response"
507
- },
508
- this.ctx
509
- );
510
- },
645
+ async (_finishResult) => {},
511
646
  {
512
- abortSignal
647
+ abortSignal,
648
+ clientTools: this._lastClientTools,
649
+ body: this._lastBody
513
650
  }
514
651
  );
515
652
 
516
653
  if (response) {
517
- // Pass continuation flag to merge parts into last assistant message
518
- // Note: We pass an empty excludeBroadcastIds array because the sender
519
- // NEEDS to receive the continuation stream. Unlike regular chat requests
520
- // where aiFetch handles the response, tool continuations have no listener
521
- // waiting - the client relies on the broadcast.
522
- await this._reply(
523
- continuationId,
524
- response,
525
- [], // Don't exclude sender - they need the continuation
526
- { continuation: true }
527
- );
654
+ await this._reply(continuationId, response, [], {
655
+ continuation: true,
656
+ chatMessageId: continuationId
657
+ });
528
658
  }
529
659
  }
530
660
  );
531
661
  });
662
+ })
663
+ .catch((error) => {
664
+ console.error(
665
+ "[AIChatAgent] Tool approval continuation failed:",
666
+ error
667
+ );
532
668
  });
533
- }
534
669
  }
535
- );
536
- return;
537
- }
538
-
539
- // Handle client-side tool approval response
540
- if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
541
- const { toolCallId, approved } = data;
542
- this._applyToolApproval(toolCallId, approved);
670
+ });
543
671
  return;
544
672
  }
545
673
  }
@@ -549,60 +677,13 @@ export class AIChatAgent<
549
677
  };
550
678
  }
551
679
 
552
- /**
553
- * Restore active stream state if the agent was restarted during streaming.
554
- * Called during construction to recover any interrupted streams.
555
- * Validates stream freshness to avoid sending stale resume notifications.
556
- * @internal Protected for testing purposes.
557
- */
558
- protected _restoreActiveStream() {
559
- const activeStreams = this.sql<StreamMetadata>`
560
- select * from cf_ai_chat_stream_metadata
561
- where status = 'streaming'
562
- order by created_at desc
563
- limit 1
564
- `;
565
-
566
- if (activeStreams && activeStreams.length > 0) {
567
- const stream = activeStreams[0];
568
- const streamAge = Date.now() - stream.created_at;
569
-
570
- // Check if stream is stale; delete to free storage
571
- if (streamAge > STREAM_STALE_THRESHOLD_MS) {
572
- this
573
- .sql`delete from cf_ai_chat_stream_chunks where stream_id = ${stream.id}`;
574
- this
575
- .sql`delete from cf_ai_chat_stream_metadata where id = ${stream.id}`;
576
- console.warn(
577
- `[AIChatAgent] Deleted stale stream ${stream.id} (age: ${Math.round(streamAge / 1000)}s)`
578
- );
579
- return;
580
- }
581
-
582
- this._activeStreamId = stream.id;
583
- this._activeRequestId = stream.request_id;
584
-
585
- // Get the last chunk index
586
- const lastChunk = this.sql<{ max_index: number }>`
587
- select max(chunk_index) as max_index
588
- from cf_ai_chat_stream_chunks
589
- where stream_id = ${this._activeStreamId}
590
- `;
591
- this._streamChunkIndex =
592
- lastChunk && lastChunk[0]?.max_index != null
593
- ? lastChunk[0].max_index + 1
594
- : 0;
595
- }
596
- }
597
-
598
680
  /**
599
681
  * Notify a connection about an active stream that can be resumed.
600
682
  * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
601
- * Uses in-memory state for request ID - no extra DB lookup needed.
602
683
  * @param connection - The WebSocket connection to notify
603
684
  */
604
685
  private _notifyStreamResuming(connection: Connection) {
605
- if (!this._activeStreamId || !this._activeRequestId) {
686
+ if (!this._resumableStream.hasActiveStream()) {
606
687
  return;
607
688
  }
608
689
 
@@ -614,184 +695,105 @@ export class AIChatAgent<
614
695
  connection.send(
615
696
  JSON.stringify({
616
697
  type: MessageType.CF_AGENT_STREAM_RESUMING,
617
- id: this._activeRequestId
698
+ id: this._resumableStream.activeRequestId
618
699
  })
619
700
  );
620
701
  }
621
702
 
622
- /**
623
- * Send stream chunks to a connection after receiving ACK.
624
- * @param connection - The WebSocket connection
625
- * @param streamId - The stream to replay
626
- * @param requestId - The original request ID
627
- */
628
- private _sendStreamChunks(
629
- connection: Connection,
630
- streamId: string,
631
- requestId: string
632
- ) {
633
- // Flush any pending chunks first to ensure we have the latest
634
- this._flushChunkBuffer();
635
-
636
- const chunks = this.sql<StreamChunk>`
637
- select * from cf_ai_chat_stream_chunks
638
- where stream_id = ${streamId}
639
- order by chunk_index asc
640
- `;
703
+ // ── Delegate methods for backward compatibility with tests ─────────
704
+ // These protected methods delegate to _resumableStream so existing
705
+ // test workers that call them directly continue to work.
641
706
 
642
- // Send all stored chunks
643
- for (const chunk of chunks || []) {
644
- connection.send(
645
- JSON.stringify({
646
- body: chunk.body,
647
- done: false,
648
- id: requestId,
649
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
650
- })
651
- );
652
- }
707
+ /** @internal Delegate to _resumableStream */
708
+ protected get _activeStreamId(): string | null {
709
+ return this._resumableStream?.activeStreamId ?? null;
710
+ }
653
711
 
654
- // If the stream is no longer active (completed), send done signal
655
- // We track active state in memory, no need to query DB
656
- if (this._activeStreamId !== streamId) {
657
- connection.send(
658
- JSON.stringify({
659
- body: "",
660
- done: true,
661
- id: requestId,
662
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
663
- })
664
- );
665
- }
712
+ /** @internal Delegate to _resumableStream */
713
+ protected get _activeRequestId(): string | null {
714
+ return this._resumableStream?.activeRequestId ?? null;
666
715
  }
667
716
 
668
- /**
669
- * Buffer a stream chunk for batch write to SQLite.
670
- * @param streamId - The stream this chunk belongs to
671
- * @param body - The serialized chunk body
672
- * @internal Protected for testing purposes.
673
- */
674
- protected _storeStreamChunk(streamId: string, body: string) {
675
- // Force flush if buffer is at max to prevent memory issues
676
- if (this._chunkBuffer.length >= CHUNK_BUFFER_MAX_SIZE) {
677
- this._flushChunkBuffer();
678
- }
717
+ /** @internal Delegate to _resumableStream */
718
+ protected _startStream(requestId: string): string {
719
+ return this._resumableStream.start(requestId);
720
+ }
679
721
 
680
- this._chunkBuffer.push({
681
- id: nanoid(),
682
- streamId,
683
- body,
684
- index: this._streamChunkIndex
685
- });
686
- this._streamChunkIndex++;
722
+ /** @internal Delegate to _resumableStream */
723
+ protected _completeStream(streamId: string) {
724
+ this._resumableStream.complete(streamId);
725
+ this._pendingResumeConnections.clear();
726
+ }
687
727
 
688
- // Flush when buffer reaches threshold
689
- if (this._chunkBuffer.length >= CHUNK_BUFFER_SIZE) {
690
- this._flushChunkBuffer();
691
- }
728
+ /** @internal Delegate to _resumableStream */
729
+ protected _storeStreamChunk(streamId: string, body: string) {
730
+ this._resumableStream.storeChunk(streamId, body);
692
731
  }
693
732
 
694
- /**
695
- * Flush buffered chunks to SQLite in a single batch.
696
- * Uses a lock to prevent concurrent flush operations.
697
- * @internal Protected for testing purposes.
698
- */
733
+ /** @internal Delegate to _resumableStream */
699
734
  protected _flushChunkBuffer() {
700
- // Prevent concurrent flushes
701
- if (this._isFlushingChunks || this._chunkBuffer.length === 0) {
702
- return;
703
- }
704
-
705
- this._isFlushingChunks = true;
706
- try {
707
- const chunks = this._chunkBuffer;
708
- this._chunkBuffer = [];
709
-
710
- // Batch insert all chunks
711
- const now = Date.now();
712
- for (const chunk of chunks) {
713
- this.sql`
714
- insert into cf_ai_chat_stream_chunks (id, stream_id, body, chunk_index, created_at)
715
- values (${chunk.id}, ${chunk.streamId}, ${chunk.body}, ${chunk.index}, ${now})
716
- `;
717
- }
718
- } finally {
719
- this._isFlushingChunks = false;
720
- }
735
+ this._resumableStream.flushBuffer();
721
736
  }
722
737
 
723
- /**
724
- * Start tracking a new stream for resumable streaming.
725
- * Creates metadata entry in SQLite and sets up tracking state.
726
- * @param requestId - The unique ID of the chat request
727
- * @returns The generated stream ID
728
- * @internal Protected for testing purposes.
729
- */
730
- protected _startStream(requestId: string): string {
731
- // Flush any pending chunks from previous streams to prevent mixing
732
- this._flushChunkBuffer();
733
-
734
- const streamId = nanoid();
735
- this._activeStreamId = streamId;
736
- this._activeRequestId = requestId;
737
- this._streamChunkIndex = 0;
738
-
739
- this.sql`
740
- insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
741
- values (${streamId}, ${requestId}, 'streaming', ${Date.now()})
742
- `;
738
+ /** @internal Delegate to _resumableStream */
739
+ protected _restoreActiveStream() {
740
+ this._resumableStream.restore();
741
+ }
743
742
 
744
- return streamId;
743
+ /** @internal Delegate to _resumableStream */
744
+ protected _markStreamError(streamId: string) {
745
+ this._resumableStream.markError(streamId);
745
746
  }
746
747
 
747
748
  /**
748
- * Mark a stream as completed and flush any pending chunks.
749
- * @param streamId - The stream to mark as completed
750
- * @internal Protected for testing purposes.
749
+ * Restore _lastBody and _lastClientTools from SQLite.
750
+ * Called in the constructor so these values survive DO hibernation.
751
+ * @internal
751
752
  */
752
- protected _completeStream(streamId: string) {
753
- // Flush any pending chunks before completing
754
- this._flushChunkBuffer();
755
-
756
- this.sql`
757
- update cf_ai_chat_stream_metadata
758
- set status = 'completed', completed_at = ${Date.now()}
759
- where id = ${streamId}
760
- `;
761
- this._activeStreamId = null;
762
- this._activeRequestId = null;
763
- this._streamChunkIndex = 0;
764
-
765
- // Clear pending resume connections - no active stream to resume
766
- this._pendingResumeConnections.clear();
753
+ private _restoreRequestContext() {
754
+ const rows =
755
+ this.sql<{ key: string; value: string }>`
756
+ select key, value from cf_ai_chat_request_context
757
+ ` || [];
767
758
 
768
- // Periodically clean up old streams (not on every completion)
769
- this._maybeCleanupOldStreams();
759
+ for (const row of rows) {
760
+ try {
761
+ if (row.key === "lastBody") {
762
+ this._lastBody = JSON.parse(row.value);
763
+ } else if (row.key === "lastClientTools") {
764
+ this._lastClientTools = JSON.parse(row.value);
765
+ }
766
+ } catch {
767
+ // Corrupted row — ignore and let the next request overwrite it
768
+ }
769
+ }
770
770
  }
771
771
 
772
772
  /**
773
- * Clean up old completed streams if enough time has passed since last cleanup.
774
- * This prevents database growth while avoiding cleanup overhead on every stream completion.
773
+ * Persist _lastBody and _lastClientTools to SQLite so they survive hibernation.
774
+ * Uses upsert (INSERT OR REPLACE) so repeated calls are safe.
775
+ * @internal
775
776
  */
776
- private _maybeCleanupOldStreams() {
777
- const now = Date.now();
778
- if (now - this._lastCleanupTime < CLEANUP_INTERVAL_MS) {
779
- return;
777
+ private _persistRequestContext() {
778
+ // Persist or delete body
779
+ if (this._lastBody) {
780
+ this.sql`
781
+ insert or replace into cf_ai_chat_request_context (key, value)
782
+ values ('lastBody', ${JSON.stringify(this._lastBody)})
783
+ `;
784
+ } else {
785
+ this.sql`delete from cf_ai_chat_request_context where key = 'lastBody'`;
786
+ }
787
+ // Persist or delete client tools
788
+ if (this._lastClientTools) {
789
+ this.sql`
790
+ insert or replace into cf_ai_chat_request_context (key, value)
791
+ values ('lastClientTools', ${JSON.stringify(this._lastClientTools)})
792
+ `;
793
+ } else {
794
+ this
795
+ .sql`delete from cf_ai_chat_request_context where key = 'lastClientTools'`;
780
796
  }
781
- this._lastCleanupTime = now;
782
-
783
- const cutoff = now - CLEANUP_AGE_THRESHOLD_MS;
784
- this.sql`
785
- delete from cf_ai_chat_stream_chunks
786
- where stream_id in (
787
- select id from cf_ai_chat_stream_metadata
788
- where status = 'completed' and completed_at < ${cutoff}
789
- )
790
- `;
791
- this.sql`
792
- delete from cf_ai_chat_stream_metadata
793
- where status = 'completed' and completed_at < ${cutoff}
794
- `;
795
797
  }
796
798
 
797
799
  private _broadcastChatMessage(message: OutgoingMessage, exclude?: string[]) {
@@ -836,10 +838,31 @@ export class AIChatAgent<
836
838
  const rows =
837
839
  this.sql`select * from cf_ai_chat_agent_messages order by created_at` ||
838
840
  [];
841
+
842
+ // Populate the persistence cache from DB so incremental persistence
843
+ // can skip SQL writes for messages already stored.
844
+ this._persistedMessageCache.clear();
845
+
839
846
  return rows
840
847
  .map((row) => {
841
848
  try {
842
- return JSON.parse(row.message as string);
849
+ const messageStr = row.message as string;
850
+ const parsed = JSON.parse(messageStr) as ChatMessage;
851
+
852
+ // Structural validation: ensure required fields exist and have
853
+ // the correct types. This catches corrupted rows, manual tampering,
854
+ // or schema drift from older versions without crashing the agent.
855
+ if (!isValidMessageStructure(parsed)) {
856
+ console.warn(
857
+ `[AIChatAgent] Skipping invalid message ${row.id}: ` +
858
+ "missing or malformed id, role, or parts"
859
+ );
860
+ return null;
861
+ }
862
+
863
+ // Cache the raw JSON keyed by message ID
864
+ this._persistedMessageCache.set(parsed.id, messageStr);
865
+ return parsed;
843
866
  } catch (error) {
844
867
  console.error(`Failed to parse message ${row.id}:`, error);
845
868
  return null;
@@ -882,7 +905,7 @@ export class AIChatAgent<
882
905
  options?: OnChatMessageOptions
883
906
  ): Promise<Response | undefined> {
884
907
  throw new Error(
885
- "recieved a chat message, override onChatMessage and return a Response to send to the client"
908
+ "received a chat message, override onChatMessage and return a Response to send to the client"
886
909
  );
887
910
  }
888
911
 
@@ -907,18 +930,30 @@ export class AIChatAgent<
907
930
  // tool outputs, but the server has them via _applyToolResult.
908
931
  const mergedMessages = this._mergeIncomingWithServerState(messages);
909
932
 
910
- // Persist the merged messages
933
+ // Persist only new or changed messages (incremental persistence).
934
+ // Compares serialized JSON against a cache of last-persisted versions.
911
935
  for (const message of mergedMessages) {
912
- // Strip OpenAI item IDs to prevent "Duplicate item found" errors
913
- // when using the OpenAI Responses API. These IDs are assigned by OpenAI
914
- // and if sent back in subsequent requests, cause duplicate detection.
915
936
  const sanitizedMessage = this._sanitizeMessageForPersistence(message);
916
- const messageToSave = this._resolveMessageForToolMerge(sanitizedMessage);
937
+ const resolved = this._resolveMessageForToolMerge(sanitizedMessage);
938
+ const safe = this._enforceRowSizeLimit(resolved);
939
+ const json = JSON.stringify(safe);
940
+
941
+ // Skip SQL write if the message is identical to what's already persisted
942
+ if (this._persistedMessageCache.get(safe.id) === json) {
943
+ continue;
944
+ }
945
+
917
946
  this.sql`
918
947
  insert into cf_ai_chat_agent_messages (id, message)
919
- values (${messageToSave.id}, ${JSON.stringify(messageToSave)})
948
+ values (${safe.id}, ${json})
920
949
  on conflict(id) do update set message = excluded.message
921
950
  `;
951
+ this._persistedMessageCache.set(safe.id, json);
952
+ }
953
+
954
+ // Enforce maxPersistedMessages: delete oldest messages if over the limit
955
+ if (this.maxPersistedMessages != null) {
956
+ this._enforceMaxPersistedMessages();
922
957
  }
923
958
 
924
959
  // refresh in-memory messages
@@ -1179,111 +1214,262 @@ export class AIChatAgent<
1179
1214
  }
1180
1215
 
1181
1216
  /**
1182
- * Applies a tool result to an existing assistant message.
1183
- * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
1184
- * The server is the source of truth, so we update the message here and broadcast
1185
- * the update to all clients.
1186
- *
1187
- * @param toolCallId - The tool call ID this result is for
1188
- * @param toolName - The name of the tool
1189
- * @param output - The output from the tool execution
1190
- * @returns true if the result was applied, false if the message was not found
1217
+ * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
1218
+ * Called after each persist to keep storage bounded.
1191
1219
  */
1192
- private async _applyToolResult(
1193
- toolCallId: string,
1194
- _toolName: string,
1195
- output: unknown
1196
- ): Promise<boolean> {
1197
- // Find the message with this tool call
1198
- // First check the currently streaming message
1199
- let message: ChatMessage | undefined;
1220
+ private _enforceMaxPersistedMessages() {
1221
+ if (this.maxPersistedMessages == null) return;
1200
1222
 
1201
- // Check streaming message first
1202
- if (this._streamingMessage) {
1203
- for (const part of this._streamingMessage.parts) {
1204
- if ("toolCallId" in part && part.toolCallId === toolCallId) {
1205
- message = this._streamingMessage;
1206
- break;
1207
- }
1208
- }
1209
- }
1223
+ const countResult = this.sql<{ cnt: number }>`
1224
+ select count(*) as cnt from cf_ai_chat_agent_messages
1225
+ `;
1226
+ const count = countResult?.[0]?.cnt ?? 0;
1210
1227
 
1211
- // If not found in streaming message, retry persisted messages
1212
- if (!message) {
1213
- for (let attempt = 0; attempt < 10; attempt++) {
1214
- message = this._findMessageByToolCallId(toolCallId);
1215
- if (message) break;
1216
- // Wait 100ms before retrying
1217
- await new Promise((resolve) => setTimeout(resolve, 100));
1228
+ if (count <= this.maxPersistedMessages) return;
1229
+
1230
+ const excess = count - this.maxPersistedMessages;
1231
+
1232
+ // Delete the oldest messages (by created_at)
1233
+ // Also remove them from the persistence cache
1234
+ const toDelete = this.sql<{ id: string }>`
1235
+ select id from cf_ai_chat_agent_messages
1236
+ order by created_at asc
1237
+ limit ${excess}
1238
+ `;
1239
+
1240
+ if (toDelete && toDelete.length > 0) {
1241
+ for (const row of toDelete) {
1242
+ this.sql`delete from cf_ai_chat_agent_messages where id = ${row.id}`;
1243
+ this._persistedMessageCache.delete(row.id);
1218
1244
  }
1219
1245
  }
1246
+ }
1220
1247
 
1221
- if (!message) {
1222
- // The tool result will be included when
1223
- // the client sends the follow-up message via sendMessage().
1248
+ /**
1249
+ * Enforces SQLite row size limits by compacting tool outputs and text parts
1250
+ * when a serialized message exceeds the safety threshold (1.8MB).
1251
+ *
1252
+ * Only fires in pathological cases (extremely large tool outputs or text).
1253
+ * Returns the message unchanged if it fits within limits.
1254
+ *
1255
+ * Compaction strategy:
1256
+ * 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
1257
+ * 2. If still too big, truncate text parts from oldest to newest
1258
+ * 3. Add metadata so clients can detect compaction
1259
+ *
1260
+ * @param message - The message to check
1261
+ * @returns The message, compacted if necessary
1262
+ */
1263
+ private _enforceRowSizeLimit(message: ChatMessage): ChatMessage {
1264
+ let json = JSON.stringify(message);
1265
+ let size = AIChatAgent._byteLength(json);
1266
+ if (size <= AIChatAgent.ROW_MAX_BYTES) return message;
1267
+
1268
+ if (message.role !== "assistant") {
1269
+ // Non-assistant messages (user/system) are harder to compact safely.
1270
+ // Truncate the entire message JSON as a last resort.
1224
1271
  console.warn(
1225
- `[AIChatAgent] _applyToolResult: Could not find message with toolCallId ${toolCallId} after retries`
1272
+ `[AIChatAgent] Non-assistant message ${message.id} is ${size} bytes, ` +
1273
+ `exceeds row limit. Truncating text parts.`
1226
1274
  );
1227
- return false;
1275
+ return this._truncateTextParts(message);
1228
1276
  }
1229
1277
 
1230
- // Check if this is the streaming message (not yet persisted)
1231
- const isStreamingMessage = message === this._streamingMessage;
1278
+ console.warn(
1279
+ `[AIChatAgent] Message ${message.id} is ${size} bytes, ` +
1280
+ `compacting tool outputs to fit SQLite row limit`
1281
+ );
1232
1282
 
1233
- // Update the tool part with the output
1234
- let updated = false;
1235
- if (isStreamingMessage) {
1236
- // Update in place - the message will be persisted when streaming completes
1283
+ // Pass 1: compact tool outputs
1284
+ const compactedToolCallIds: string[] = [];
1285
+ const compactedParts = message.parts.map((part) => {
1286
+ if (
1287
+ "output" in part &&
1288
+ "toolCallId" in part &&
1289
+ "state" in part &&
1290
+ part.state === "output-available"
1291
+ ) {
1292
+ const outputJson = JSON.stringify((part as { output: unknown }).output);
1293
+ if (outputJson.length > 1000) {
1294
+ compactedToolCallIds.push(part.toolCallId as string);
1295
+ return {
1296
+ ...part,
1297
+ output:
1298
+ "This tool output was too large to persist in storage " +
1299
+ `(${outputJson.length} bytes). ` +
1300
+ "If the user asks about this data, suggest re-running the tool. " +
1301
+ `Preview: ${outputJson.slice(0, 500)}...`
1302
+ };
1303
+ }
1304
+ }
1305
+ return part;
1306
+ }) as ChatMessage["parts"];
1307
+
1308
+ let result: ChatMessage = {
1309
+ ...message,
1310
+ parts: compactedParts
1311
+ };
1312
+
1313
+ if (compactedToolCallIds.length > 0) {
1314
+ result.metadata = {
1315
+ ...(result.metadata ?? {}),
1316
+ compactedToolOutputs: compactedToolCallIds
1317
+ };
1318
+ }
1319
+
1320
+ // Check if tool compaction was enough
1321
+ json = JSON.stringify(result);
1322
+ size = AIChatAgent._byteLength(json);
1323
+ if (size <= AIChatAgent.ROW_MAX_BYTES) return result;
1324
+
1325
+ // Pass 2: truncate text parts
1326
+ console.warn(
1327
+ `[AIChatAgent] Message ${message.id} still ${size} bytes after tool compaction, truncating text parts`
1328
+ );
1329
+ return this._truncateTextParts(result);
1330
+ }
1331
+
1332
+ /**
1333
+ * Truncates text parts in a message to fit within the row size limit.
1334
+ * Truncates from the first text part forward, keeping the last text part
1335
+ * as intact as possible (it is usually the most relevant).
1336
+ */
1337
+ private _truncateTextParts(message: ChatMessage): ChatMessage {
1338
+ const compactedTextPartIndices: number[] = [];
1339
+ const parts = [...message.parts];
1340
+
1341
+ // Truncate text parts from oldest to newest until we fit
1342
+ for (let i = 0; i < parts.length; i++) {
1343
+ const part = parts[i];
1344
+ if (part.type === "text" && "text" in part) {
1345
+ const text = (part as { text: string }).text;
1346
+ if (text.length > 1000) {
1347
+ compactedTextPartIndices.push(i);
1348
+ parts[i] = {
1349
+ ...part,
1350
+ text:
1351
+ `[Text truncated for storage (${text.length} chars). ` +
1352
+ `First 500 chars: ${text.slice(0, 500)}...]`
1353
+ } as ChatMessage["parts"][number];
1354
+
1355
+ // Check if we fit now
1356
+ const candidate = { ...message, parts };
1357
+ if (
1358
+ AIChatAgent._byteLength(JSON.stringify(candidate)) <=
1359
+ AIChatAgent.ROW_MAX_BYTES
1360
+ ) {
1361
+ break;
1362
+ }
1363
+ }
1364
+ }
1365
+ }
1366
+
1367
+ const result: ChatMessage = { ...message, parts };
1368
+ if (compactedTextPartIndices.length > 0) {
1369
+ result.metadata = {
1370
+ ...(result.metadata ?? {}),
1371
+ compactedTextParts: compactedTextPartIndices
1372
+ };
1373
+ }
1374
+ return result;
1375
+ }
1376
+
1377
+ /**
1378
+ * Shared helper for finding a tool part by toolCallId and applying an update.
1379
+ * Handles both streaming (in-memory) and persisted (SQLite) messages.
1380
+ *
1381
+ * Checks _streamingMessage first (tool results/approvals can arrive while
1382
+ * the AI is still streaming), then retries persisted messages with backoff
1383
+ * in case streaming completes between attempts.
1384
+ *
1385
+ * @param toolCallId - The tool call ID to find
1386
+ * @param callerName - Name for log messages (e.g. "_applyToolResult")
1387
+ * @param matchStates - Which tool part states to match
1388
+ * @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
1389
+ * @returns true if the update was applied, false if not found or state didn't match
1390
+ */
1391
+ private async _findAndUpdateToolPart(
1392
+ toolCallId: string,
1393
+ callerName: string,
1394
+ matchStates: string[],
1395
+ applyUpdate: (part: Record<string, unknown>) => Record<string, unknown>
1396
+ ): Promise<boolean> {
1397
+ // Find the message containing this tool call.
1398
+ // Check streaming message first (in-memory, not yet persisted), then
1399
+ // retry persisted messages with backoff.
1400
+ let message: ChatMessage | undefined;
1401
+
1402
+ if (this._streamingMessage) {
1403
+ for (const part of this._streamingMessage.parts) {
1404
+ if ("toolCallId" in part && part.toolCallId === toolCallId) {
1405
+ message = this._streamingMessage;
1406
+ break;
1407
+ }
1408
+ }
1409
+ }
1410
+
1411
+ if (!message) {
1412
+ for (let attempt = 0; attempt < 10; attempt++) {
1413
+ message = this._findMessageByToolCallId(toolCallId);
1414
+ if (message) break;
1415
+ await new Promise((resolve) => setTimeout(resolve, 100));
1416
+ }
1417
+ }
1418
+
1419
+ if (!message) {
1420
+ console.warn(
1421
+ `[AIChatAgent] ${callerName}: Could not find message with toolCallId ${toolCallId} after retries`
1422
+ );
1423
+ return false;
1424
+ }
1425
+
1426
+ const isStreamingMessage = message === this._streamingMessage;
1427
+ let updated = false;
1428
+
1429
+ if (isStreamingMessage) {
1430
+ // Update in place -- the message will be persisted when streaming completes
1237
1431
  for (const part of message.parts) {
1238
1432
  if (
1239
1433
  "toolCallId" in part &&
1240
1434
  part.toolCallId === toolCallId &&
1241
1435
  "state" in part &&
1242
- part.state === "input-available"
1436
+ matchStates.includes(part.state as string)
1243
1437
  ) {
1244
- (part as { state: string; output?: unknown }).state =
1245
- "output-available";
1246
- (part as { state: string; output?: unknown }).output = output;
1438
+ const applied = applyUpdate(part as Record<string, unknown>);
1439
+ Object.assign(part, applied);
1247
1440
  updated = true;
1248
1441
  break;
1249
1442
  }
1250
1443
  }
1251
1444
  } else {
1252
- // For persisted messages, create updated parts
1445
+ // For persisted messages, create updated parts immutably
1253
1446
  const updatedParts = message.parts.map((part) => {
1254
1447
  if (
1255
1448
  "toolCallId" in part &&
1256
1449
  part.toolCallId === toolCallId &&
1257
1450
  "state" in part &&
1258
- part.state === "input-available"
1451
+ matchStates.includes(part.state as string)
1259
1452
  ) {
1260
1453
  updated = true;
1261
- return {
1262
- ...part,
1263
- state: "output-available" as const,
1264
- output
1265
- };
1454
+ return applyUpdate(part as Record<string, unknown>);
1266
1455
  }
1267
1456
  return part;
1268
1457
  }) as ChatMessage["parts"];
1269
1458
 
1270
1459
  if (updated) {
1271
- // Create the updated message and strip OpenAI item IDs
1272
1460
  const updatedMessage: ChatMessage = this._sanitizeMessageForPersistence(
1273
- {
1274
- ...message,
1275
- parts: updatedParts
1276
- }
1461
+ { ...message, parts: updatedParts }
1277
1462
  );
1463
+ const safe = this._enforceRowSizeLimit(updatedMessage);
1464
+ const json = JSON.stringify(safe);
1278
1465
 
1279
- // Persist the updated message
1280
1466
  this.sql`
1281
1467
  update cf_ai_chat_agent_messages
1282
- set message = ${JSON.stringify(updatedMessage)}
1468
+ set message = ${json}
1283
1469
  where id = ${message.id}
1284
1470
  `;
1471
+ this._persistedMessageCache.set(message.id, json);
1285
1472
 
1286
- // Reload messages to update in-memory state
1287
1473
  const persisted = this._loadMessagesFromDb();
1288
1474
  this.messages = autoTransformMessages(persisted);
1289
1475
  }
@@ -1291,15 +1477,21 @@ export class AIChatAgent<
1291
1477
 
1292
1478
  if (!updated) {
1293
1479
  console.warn(
1294
- `[AIChatAgent] _applyToolResult: Tool part with toolCallId ${toolCallId} not in input-available state`
1480
+ `[AIChatAgent] ${callerName}: Tool part with toolCallId ${toolCallId} not in expected state (expected: ${matchStates.join("|")})`
1295
1481
  );
1296
1482
  return false;
1297
1483
  }
1298
1484
 
1299
- // Broadcast the update to all clients (only for persisted messages)
1300
- // For streaming messages, the update will be included when persisted
1301
- if (!isStreamingMessage) {
1302
- // Re-fetch the message for broadcast since we modified it
1485
+ // Broadcast the update to all clients.
1486
+ // For persisted messages, re-fetch the latest state from this.messages.
1487
+ // For streaming messages, broadcast the in-memory snapshot so clients
1488
+ // get immediate confirmation that the tool result/approval was applied.
1489
+ if (isStreamingMessage) {
1490
+ this._broadcastChatMessage({
1491
+ type: MessageType.CF_AGENT_MESSAGE_UPDATED,
1492
+ message
1493
+ });
1494
+ } else {
1303
1495
  const broadcastMessage = this._findMessageByToolCallId(toolCallId);
1304
1496
  if (broadcastMessage) {
1305
1497
  this._broadcastChatMessage({
@@ -1309,13 +1501,38 @@ export class AIChatAgent<
1309
1501
  }
1310
1502
  }
1311
1503
 
1312
- // Note: We don't automatically continue the conversation here.
1313
- // The client is responsible for sending a follow-up request if needed.
1314
- // This avoids re-entering onChatMessage with unexpected state.
1315
-
1316
1504
  return true;
1317
1505
  }
1318
1506
 
1507
+ /**
1508
+ * Applies a tool result to an existing assistant message.
1509
+ * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
1510
+ * The server is the source of truth, so we update the message here and broadcast
1511
+ * the update to all clients.
1512
+ *
1513
+ * @param toolCallId - The tool call ID this result is for
1514
+ * @param _toolName - The name of the tool (unused, kept for API compat)
1515
+ * @param output - The output from the tool execution
1516
+ * @returns true if the result was applied, false if the message was not found
1517
+ */
1518
+ private async _applyToolResult(
1519
+ toolCallId: string,
1520
+ _toolName: string,
1521
+ output: unknown
1522
+ ): Promise<boolean> {
1523
+ return this._findAndUpdateToolPart(
1524
+ toolCallId,
1525
+ "_applyToolResult",
1526
+ ["input-available"],
1527
+ (part) => ({
1528
+ ...part,
1529
+ state: "output-available",
1530
+ output,
1531
+ preliminary: false
1532
+ })
1533
+ );
1534
+ }
1535
+
1319
1536
  private async _streamSSEReply(
1320
1537
  id: string,
1321
1538
  streamId: string,
@@ -1324,29 +1541,12 @@ export class AIChatAgent<
1324
1541
  streamCompleted: { value: boolean },
1325
1542
  continuation = false
1326
1543
  ) {
1327
- let activeTextParts: Record<string, TextUIPart> = {};
1328
- let activeReasoningParts: Record<string, ReasoningUIPart> = {};
1329
- const partialToolCalls: Record<
1330
- string,
1331
- { text: string; index: number; toolName: string; dynamic?: boolean }
1332
- > = {};
1333
-
1334
- /* Lazy loading ai sdk, because putting it in module scope is
1335
- * causing issues with startup time.
1336
- * The only place it's used is in _reply, which only matters after
1337
- * a chat message is received.
1338
- * So it's safe to delay loading it until a chat message is received.
1339
- */
1340
- const { getToolName, isToolUIPart, parsePartialJson } = await import("ai");
1341
-
1342
1544
  streamCompleted.value = false;
1343
1545
  while (true) {
1344
1546
  const { done, value } = await reader.read();
1345
1547
  if (done) {
1346
- // Mark the stream as completed
1347
1548
  this._completeStream(streamId);
1348
1549
  streamCompleted.value = true;
1349
- // Send final completion signal
1350
1550
  this._broadcastChatMessage({
1351
1551
  body: "",
1352
1552
  done: true,
@@ -1358,370 +1558,144 @@ export class AIChatAgent<
1358
1558
  }
1359
1559
 
1360
1560
  const chunk = decoder.decode(value);
1361
-
1362
- // After streaming is complete, persist the complete assistant's response
1363
-
1364
- // Parse AI SDK v5 SSE format and extract text deltas
1365
1561
  const lines = chunk.split("\n");
1562
+
1366
1563
  for (const line of lines) {
1367
1564
  if (line.startsWith("data: ") && line !== "data: [DONE]") {
1368
1565
  try {
1369
- const data: UIMessageChunk = JSON.parse(line.slice(6)); // Remove 'data: ' prefix
1370
- switch (data.type) {
1371
- case "text-start": {
1372
- const textPart: TextUIPart = {
1373
- type: "text",
1374
- text: "",
1375
- providerMetadata: data.providerMetadata,
1376
- state: "streaming"
1377
- };
1378
- activeTextParts[data.id] = textPart;
1379
- message.parts.push(textPart);
1380
- break;
1381
- }
1382
-
1383
- case "text-delta": {
1384
- const textPart = activeTextParts[data.id];
1385
- textPart.text += data.delta;
1386
- textPart.providerMetadata =
1387
- data.providerMetadata ?? textPart.providerMetadata;
1388
- break;
1389
- }
1390
-
1391
- case "text-end": {
1392
- const textPart = activeTextParts[data.id];
1393
- textPart.state = "done";
1394
- textPart.providerMetadata =
1395
- data.providerMetadata ?? textPart.providerMetadata;
1396
- delete activeTextParts[data.id];
1397
- break;
1398
- }
1399
-
1400
- case "reasoning-start": {
1401
- const reasoningPart: ReasoningUIPart = {
1402
- type: "reasoning",
1403
- text: "",
1404
- providerMetadata: data.providerMetadata,
1405
- state: "streaming"
1406
- };
1407
- activeReasoningParts[data.id] = reasoningPart;
1408
- message.parts.push(reasoningPart);
1409
- break;
1410
- }
1411
-
1412
- case "reasoning-delta": {
1413
- const reasoningPart = activeReasoningParts[data.id];
1414
- reasoningPart.text += data.delta;
1415
- reasoningPart.providerMetadata =
1416
- data.providerMetadata ?? reasoningPart.providerMetadata;
1417
- break;
1418
- }
1419
-
1420
- case "reasoning-end": {
1421
- const reasoningPart = activeReasoningParts[data.id];
1422
- reasoningPart.providerMetadata =
1423
- data.providerMetadata ?? reasoningPart.providerMetadata;
1424
- reasoningPart.state = "done";
1425
- delete activeReasoningParts[data.id];
1426
-
1427
- break;
1428
- }
1429
-
1430
- case "file": {
1431
- message.parts.push({
1432
- type: "file",
1433
- mediaType: data.mediaType,
1434
- url: data.url
1435
- });
1436
-
1437
- break;
1438
- }
1439
-
1440
- case "source-url": {
1441
- message.parts.push({
1442
- type: "source-url",
1443
- sourceId: data.sourceId,
1444
- url: data.url,
1445
- title: data.title,
1446
- providerMetadata: data.providerMetadata
1447
- });
1448
-
1449
- break;
1450
- }
1451
-
1452
- case "source-document": {
1453
- message.parts.push({
1454
- type: "source-document",
1455
- sourceId: data.sourceId,
1456
- mediaType: data.mediaType,
1457
- title: data.title,
1458
- filename: data.filename,
1459
- providerMetadata: data.providerMetadata
1460
- });
1461
-
1462
- break;
1463
- }
1464
-
1465
- case "tool-input-start": {
1466
- const toolInvocations = message.parts.filter(isToolUIPart);
1467
-
1468
- // add the partial tool call to the map
1469
- partialToolCalls[data.toolCallId] = {
1470
- text: "",
1471
- toolName: data.toolName,
1472
- index: toolInvocations.length,
1473
- dynamic: data.dynamic
1474
- };
1566
+ const data: UIMessageChunk = JSON.parse(line.slice(6));
1567
+
1568
+ // Delegate message building to the shared parser.
1569
+ // It handles: text, reasoning, file, source, tool lifecycle,
1570
+ // step boundaries — all the part types needed for UIMessage.
1571
+ const handled = applyChunkToParts(message.parts, data);
1572
+
1573
+ // When a tool enters approval-requested state, the stream is
1574
+ // paused waiting for user approval. Persist the streaming message
1575
+ // immediately so the approval UI survives page refresh. Without
1576
+ // this, a refresh would reload from SQLite where the tool part
1577
+ // is still in input-available state, showing "Running..." instead
1578
+ // of the Approve/Reject buttons.
1579
+ if (
1580
+ data.type === "tool-approval-request" &&
1581
+ this._streamingMessage
1582
+ ) {
1583
+ // Persist directly to SQLite without broadcasting.
1584
+ // The client already has this data from the SSE stream —
1585
+ // broadcasting would cause the approval UI to render twice.
1586
+ // We only need the SQL write so the state survives page refresh.
1587
+ const snapshot: ChatMessage = {
1588
+ ...this._streamingMessage,
1589
+ parts: [...this._streamingMessage.parts]
1590
+ };
1591
+ const sanitized = this._sanitizeMessageForPersistence(snapshot);
1592
+ const json = JSON.stringify(sanitized);
1593
+ this.sql`
1594
+ INSERT INTO cf_ai_chat_agent_messages (id, message)
1595
+ VALUES (${sanitized.id}, ${json})
1596
+ ON CONFLICT(id) DO UPDATE SET message = excluded.message
1597
+ `;
1598
+ // Track that we persisted early so stream completion can update
1599
+ // in place rather than appending a duplicate.
1600
+ this._approvalPersistedMessageId = sanitized.id;
1601
+ }
1475
1602
 
1476
- if (data.dynamic) {
1477
- this.updateDynamicToolPart(message, {
1478
- toolCallId: data.toolCallId,
1479
- toolName: data.toolName,
1480
- state: "input-streaming",
1481
- input: undefined
1482
- });
1603
+ // Cross-message tool output fallback:
1604
+ // When a tool with needsApproval is approved, the continuation
1605
+ // stream emits tool-output-available/tool-output-error for a
1606
+ // tool call that lives in a *previous* assistant message.
1607
+ // applyChunkToParts only searches the current message's parts,
1608
+ // so the update is silently skipped. Fall back to searching
1609
+ // this.messages and update the persisted message directly.
1610
+ // Note: checked independently of `handled` — applyChunkToParts
1611
+ // returns true for recognized chunk types even when it cannot
1612
+ // find the target part, so `handled` is not a reliable signal.
1613
+ if (
1614
+ (data.type === "tool-output-available" ||
1615
+ data.type === "tool-output-error") &&
1616
+ data.toolCallId
1617
+ ) {
1618
+ const foundInCurrentMessage = message.parts.some(
1619
+ (p) => "toolCallId" in p && p.toolCallId === data.toolCallId
1620
+ );
1621
+ if (!foundInCurrentMessage) {
1622
+ if (data.type === "tool-output-available") {
1623
+ this._findAndUpdateToolPart(
1624
+ data.toolCallId,
1625
+ "_streamSSEReply",
1626
+ [
1627
+ "input-available",
1628
+ "input-streaming",
1629
+ "approval-responded",
1630
+ "approval-requested"
1631
+ ],
1632
+ (part) => ({
1633
+ ...part,
1634
+ state: "output-available",
1635
+ output: data.output,
1636
+ ...(data.preliminary !== undefined && {
1637
+ preliminary: data.preliminary
1638
+ })
1639
+ })
1640
+ );
1483
1641
  } else {
1484
- await this.updateToolPart(message, {
1485
- toolCallId: data.toolCallId,
1486
- toolName: data.toolName,
1487
- state: "input-streaming",
1488
- input: undefined
1489
- });
1642
+ this._findAndUpdateToolPart(
1643
+ data.toolCallId,
1644
+ "_streamSSEReply",
1645
+ [
1646
+ "input-available",
1647
+ "input-streaming",
1648
+ "approval-responded",
1649
+ "approval-requested"
1650
+ ],
1651
+ (part) => ({
1652
+ ...part,
1653
+ state: "output-error",
1654
+ errorText: data.errorText
1655
+ })
1656
+ );
1490
1657
  }
1491
-
1492
- break;
1493
1658
  }
1659
+ }
1494
1660
 
1495
- case "tool-input-delta": {
1496
- const partialToolCall = partialToolCalls[data.toolCallId];
1497
-
1498
- partialToolCall.text += data.inputTextDelta;
1499
-
1500
- const partialArgsResult = await parsePartialJson(
1501
- partialToolCall.text
1502
- );
1503
- const partialArgs = (
1504
- partialArgsResult as { value: Record<string, unknown> }
1505
- ).value;
1506
-
1507
- if (partialToolCall.dynamic) {
1508
- this.updateDynamicToolPart(message, {
1509
- toolCallId: data.toolCallId,
1510
- toolName: partialToolCall.toolName,
1511
- state: "input-streaming",
1512
- input: partialArgs
1513
- });
1514
- } else {
1515
- await this.updateToolPart(message, {
1516
- toolCallId: data.toolCallId,
1517
- toolName: partialToolCall.toolName,
1518
- state: "input-streaming",
1519
- input: partialArgs
1520
- });
1661
+ // Handle server-specific chunk types not covered by the shared parser
1662
+ if (!handled) {
1663
+ switch (data.type) {
1664
+ case "start": {
1665
+ if (data.messageId != null) {
1666
+ message.id = data.messageId;
1667
+ }
1668
+ if (data.messageMetadata != null) {
1669
+ message.metadata = message.metadata
1670
+ ? { ...message.metadata, ...data.messageMetadata }
1671
+ : data.messageMetadata;
1672
+ }
1673
+ break;
1521
1674
  }
1522
-
1523
- break;
1524
- }
1525
-
1526
- case "tool-input-available": {
1527
- if (data.dynamic) {
1528
- this.updateDynamicToolPart(message, {
1529
- toolCallId: data.toolCallId,
1530
- toolName: data.toolName,
1531
- state: "input-available",
1532
- input: data.input,
1533
- providerMetadata: data.providerMetadata
1534
- });
1535
- } else {
1536
- await this.updateToolPart(message, {
1537
- toolCallId: data.toolCallId,
1538
- toolName: data.toolName,
1539
- state: "input-available",
1540
- input: data.input,
1541
- providerExecuted: data.providerExecuted,
1542
- providerMetadata: data.providerMetadata
1543
- });
1675
+ case "finish":
1676
+ case "message-metadata": {
1677
+ if (data.messageMetadata != null) {
1678
+ message.metadata = message.metadata
1679
+ ? { ...message.metadata, ...data.messageMetadata }
1680
+ : data.messageMetadata;
1681
+ }
1682
+ break;
1544
1683
  }
1545
-
1546
- // TODO: Do we want to expose onToolCall?
1547
-
1548
- // invoke the onToolCall callback if it exists. This is blocking.
1549
- // In the future we should make this non-blocking, which
1550
- // requires additional state management for error handling etc.
1551
- // Skip calling onToolCall for provider-executed tools since they are already executed
1552
- // if (onToolCall && !data.providerExecuted) {
1553
- // await onToolCall({
1554
- // toolCall: data
1555
- // });
1556
- // }
1557
- break;
1558
- }
1559
-
1560
- case "tool-input-error": {
1561
- if (data.dynamic) {
1562
- this.updateDynamicToolPart(message, {
1563
- toolCallId: data.toolCallId,
1564
- toolName: data.toolName,
1565
- state: "output-error",
1566
- input: data.input,
1567
- errorText: data.errorText,
1568
- providerMetadata: data.providerMetadata
1569
- });
1570
- } else {
1571
- await this.updateToolPart(message, {
1572
- toolCallId: data.toolCallId,
1573
- toolName: data.toolName,
1574
- state: "output-error",
1575
- input: undefined,
1576
- rawInput: data.input,
1577
- errorText: data.errorText,
1578
- providerExecuted: data.providerExecuted,
1579
- providerMetadata: data.providerMetadata
1580
- });
1684
+ case "finish-step": {
1685
+ // No-op for message building (shared parser handles step-start)
1686
+ break;
1581
1687
  }
1582
-
1583
- break;
1584
- }
1585
-
1586
- case "tool-output-available": {
1587
- if (data.dynamic) {
1588
- const toolInvocations = message.parts.filter(
1589
- (part) => part.type === "dynamic-tool"
1590
- ) as DynamicToolUIPart[];
1591
-
1592
- const toolInvocation = toolInvocations.find(
1593
- (invocation) => invocation.toolCallId === data.toolCallId
1594
- );
1595
-
1596
- if (!toolInvocation)
1597
- throw new Error("Tool invocation not found");
1598
-
1599
- this.updateDynamicToolPart(message, {
1600
- toolCallId: data.toolCallId,
1601
- toolName: toolInvocation.toolName,
1602
- state: "output-available",
1603
- input: toolInvocation.input,
1604
- output: data.output,
1605
- preliminary: data.preliminary
1606
- });
1607
- } else {
1608
- const toolInvocations = message.parts.filter(
1609
- isToolUIPart
1610
- ) as ToolUIPart[];
1611
-
1612
- const toolInvocation = toolInvocations.find(
1613
- (invocation) => invocation.toolCallId === data.toolCallId
1614
- );
1615
-
1616
- if (!toolInvocation)
1617
- throw new Error("Tool invocation not found");
1618
-
1619
- await this.updateToolPart(message, {
1620
- toolCallId: data.toolCallId,
1621
- toolName: getToolName(toolInvocation),
1622
- state: "output-available",
1623
- input: toolInvocation.input,
1624
- output: data.output,
1625
- providerExecuted: data.providerExecuted,
1626
- preliminary: data.preliminary
1688
+ case "error": {
1689
+ this._broadcastChatMessage({
1690
+ error: true,
1691
+ body: data.errorText ?? JSON.stringify(data),
1692
+ done: false,
1693
+ id,
1694
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
1627
1695
  });
1696
+ break;
1628
1697
  }
1629
-
1630
- break;
1631
1698
  }
1632
-
1633
- case "tool-output-error": {
1634
- if (data.dynamic) {
1635
- const toolInvocations = message.parts.filter(
1636
- (part) => part.type === "dynamic-tool"
1637
- ) as DynamicToolUIPart[];
1638
-
1639
- const toolInvocation = toolInvocations.find(
1640
- (invocation) => invocation.toolCallId === data.toolCallId
1641
- );
1642
-
1643
- if (!toolInvocation)
1644
- throw new Error("Tool invocation not found");
1645
-
1646
- this.updateDynamicToolPart(message, {
1647
- toolCallId: data.toolCallId,
1648
- toolName: toolInvocation.toolName,
1649
- state: "output-error",
1650
- input: toolInvocation.input,
1651
- errorText: data.errorText
1652
- });
1653
- } else {
1654
- const toolInvocations = message.parts.filter(
1655
- isToolUIPart
1656
- ) as ToolUIPart[];
1657
-
1658
- const toolInvocation = toolInvocations.find(
1659
- (invocation) => invocation.toolCallId === data.toolCallId
1660
- );
1661
-
1662
- if (!toolInvocation)
1663
- throw new Error("Tool invocation not found");
1664
- await this.updateToolPart(message, {
1665
- toolCallId: data.toolCallId,
1666
- toolName: getToolName(toolInvocation),
1667
- state: "output-error",
1668
- input: toolInvocation.input,
1669
- rawInput:
1670
- "rawInput" in toolInvocation
1671
- ? toolInvocation.rawInput
1672
- : undefined,
1673
- errorText: data.errorText
1674
- });
1675
- }
1676
-
1677
- break;
1678
- }
1679
-
1680
- case "start-step": {
1681
- // add a step boundary part to the message
1682
- message.parts.push({ type: "step-start" });
1683
- break;
1684
- }
1685
-
1686
- case "finish-step": {
1687
- // reset the current text and reasoning parts
1688
- activeTextParts = {};
1689
- activeReasoningParts = {};
1690
- break;
1691
- }
1692
-
1693
- case "start": {
1694
- if (data.messageId != null) {
1695
- message.id = data.messageId;
1696
- }
1697
-
1698
- await this.updateMessageMetadata(message, data.messageMetadata);
1699
-
1700
- break;
1701
- }
1702
-
1703
- case "finish": {
1704
- await this.updateMessageMetadata(message, data.messageMetadata);
1705
- break;
1706
- }
1707
-
1708
- case "message-metadata": {
1709
- await this.updateMessageMetadata(message, data.messageMetadata);
1710
- break;
1711
- }
1712
-
1713
- case "error": {
1714
- this._broadcastChatMessage({
1715
- error: true,
1716
- body: data.errorText ?? JSON.stringify(data),
1717
- done: false,
1718
- id,
1719
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
1720
- });
1721
-
1722
- break;
1723
- }
1724
- // Do we want to handle data parts?
1725
1699
  }
1726
1700
 
1727
1701
  // Convert internal AI SDK stream events to valid UIMessageStreamPart format.
@@ -1741,11 +1715,9 @@ export class AIChatAgent<
1741
1715
  };
1742
1716
  }
1743
1717
 
1744
- // Store chunk for replay on reconnection
1718
+ // Store chunk for replay and broadcast to clients
1745
1719
  const chunkBody = JSON.stringify(eventToSend);
1746
1720
  this._storeStreamChunk(streamId, chunkBody);
1747
-
1748
- // Forward the converted event to the client
1749
1721
  this._broadcastChatMessage({
1750
1722
  body: chunkBody,
1751
1723
  done: false,
@@ -1777,9 +1749,16 @@ export class AIChatAgent<
1777
1749
  continuation
1778
1750
  );
1779
1751
 
1752
+ // Use a single text part and accumulate into it, so the persisted message
1753
+ // has one text part regardless of how many network chunks the response spans.
1754
+ const textPart: TextUIPart = { type: "text", text: "", state: "streaming" };
1755
+ message.parts.push(textPart);
1756
+
1780
1757
  while (true) {
1781
1758
  const { done, value } = await reader.read();
1782
1759
  if (done) {
1760
+ textPart.state = "done";
1761
+
1783
1762
  this._broadcastTextEvent(
1784
1763
  streamId,
1785
1764
  { type: "text-end", id },
@@ -1802,9 +1781,9 @@ export class AIChatAgent<
1802
1781
 
1803
1782
  const chunk = decoder.decode(value);
1804
1783
 
1805
- // Treat the entire chunk as a text delta to preserve exact formatting
1784
+ // Accumulate into the single text part to preserve exact formatting
1806
1785
  if (chunk.length > 0) {
1807
- message.parts.push({ type: "text", text: chunk });
1786
+ textPart.text += chunk;
1808
1787
  this._broadcastTextEvent(
1809
1788
  streamId,
1810
1789
  { type: "text-delta", id, delta: chunk },
@@ -1814,171 +1793,6 @@ export class AIChatAgent<
1814
1793
  }
1815
1794
  }
1816
1795
 
1817
- private updateDynamicToolPart(
1818
- message: ChatMessage,
1819
- options: {
1820
- toolName: string;
1821
- toolCallId: string;
1822
- providerExecuted?: boolean;
1823
- } & (
1824
- | {
1825
- state: "input-streaming";
1826
- input: unknown;
1827
- }
1828
- | {
1829
- state: "input-available";
1830
- input: unknown;
1831
- providerMetadata?: ProviderMetadata;
1832
- }
1833
- | {
1834
- state: "output-available";
1835
- input: unknown;
1836
- output: unknown;
1837
- preliminary: boolean | undefined;
1838
- }
1839
- | {
1840
- state: "output-error";
1841
- input: unknown;
1842
- errorText: string;
1843
- providerMetadata?: ProviderMetadata;
1844
- }
1845
- )
1846
- ) {
1847
- const part = message.parts.find(
1848
- (part) =>
1849
- part.type === "dynamic-tool" && part.toolCallId === options.toolCallId
1850
- ) as DynamicToolUIPart | undefined;
1851
-
1852
- const anyOptions = options as Record<string, unknown>;
1853
- const anyPart = part as Record<string, unknown>;
1854
-
1855
- if (part != null) {
1856
- part.state = options.state;
1857
- anyPart.toolName = options.toolName;
1858
- anyPart.input = anyOptions.input;
1859
- anyPart.output = anyOptions.output;
1860
- anyPart.errorText = anyOptions.errorText;
1861
- anyPart.rawInput = anyOptions.rawInput ?? anyPart.rawInput;
1862
- anyPart.preliminary = anyOptions.preliminary;
1863
-
1864
- if (
1865
- anyOptions.providerMetadata != null &&
1866
- part.state === "input-available"
1867
- ) {
1868
- part.callProviderMetadata =
1869
- anyOptions.providerMetadata as ProviderMetadata;
1870
- }
1871
- } else {
1872
- message.parts.push({
1873
- type: "dynamic-tool",
1874
- toolName: options.toolName,
1875
- toolCallId: options.toolCallId,
1876
- state: options.state,
1877
- input: anyOptions.input,
1878
- output: anyOptions.output,
1879
- errorText: anyOptions.errorText,
1880
- preliminary: anyOptions.preliminary,
1881
- ...(anyOptions.providerMetadata != null
1882
- ? { callProviderMetadata: anyOptions.providerMetadata }
1883
- : {})
1884
- } as DynamicToolUIPart);
1885
- }
1886
- }
1887
-
1888
- private async updateToolPart(
1889
- message: ChatMessage,
1890
- options: {
1891
- toolName: string;
1892
- toolCallId: string;
1893
- providerExecuted?: boolean;
1894
- } & (
1895
- | {
1896
- state: "input-streaming";
1897
- input: unknown;
1898
- providerExecuted?: boolean;
1899
- }
1900
- | {
1901
- state: "input-available";
1902
- input: unknown;
1903
- providerExecuted?: boolean;
1904
- providerMetadata?: ProviderMetadata;
1905
- }
1906
- | {
1907
- state: "output-available";
1908
- input: unknown;
1909
- output: unknown;
1910
- providerExecuted?: boolean;
1911
- preliminary?: boolean;
1912
- }
1913
- | {
1914
- state: "output-error";
1915
- input: unknown;
1916
- rawInput?: unknown;
1917
- errorText: string;
1918
- providerExecuted?: boolean;
1919
- providerMetadata?: ProviderMetadata;
1920
- }
1921
- )
1922
- ) {
1923
- const { isToolUIPart } = await import("ai");
1924
-
1925
- const part = message.parts.find(
1926
- (part) =>
1927
- isToolUIPart(part) &&
1928
- (part as ToolUIPart).toolCallId === options.toolCallId
1929
- ) as ToolUIPart | undefined;
1930
-
1931
- const anyOptions = options as Record<string, unknown>;
1932
- const anyPart = part as Record<string, unknown>;
1933
-
1934
- if (part != null) {
1935
- part.state = options.state;
1936
- anyPart.input = anyOptions.input;
1937
- anyPart.output = anyOptions.output;
1938
- anyPart.errorText = anyOptions.errorText;
1939
- anyPart.rawInput = anyOptions.rawInput;
1940
- anyPart.preliminary = anyOptions.preliminary;
1941
-
1942
- // once providerExecuted is set, it stays for streaming
1943
- anyPart.providerExecuted =
1944
- anyOptions.providerExecuted ?? part.providerExecuted;
1945
-
1946
- if (
1947
- anyOptions.providerMetadata != null &&
1948
- part.state === "input-available"
1949
- ) {
1950
- part.callProviderMetadata =
1951
- anyOptions.providerMetadata as ProviderMetadata;
1952
- }
1953
- } else {
1954
- message.parts.push({
1955
- type: `tool-${options.toolName}`,
1956
- toolCallId: options.toolCallId,
1957
- state: options.state,
1958
- input: anyOptions.input,
1959
- output: anyOptions.output,
1960
- rawInput: anyOptions.rawInput,
1961
- errorText: anyOptions.errorText,
1962
- providerExecuted: anyOptions.providerExecuted,
1963
- preliminary: anyOptions.preliminary,
1964
- ...(anyOptions.providerMetadata != null
1965
- ? { callProviderMetadata: anyOptions.providerMetadata }
1966
- : {})
1967
- } as ToolUIPart);
1968
- }
1969
- }
1970
-
1971
- private async updateMessageMetadata(message: ChatMessage, metadata: unknown) {
1972
- if (metadata != null) {
1973
- const mergedMetadata =
1974
- message.metadata != null
1975
- ? { ...message.metadata, ...metadata } // TODO: do proper merging
1976
- : metadata;
1977
-
1978
- message.metadata = mergedMetadata;
1979
- }
1980
- }
1981
-
1982
1796
  /**
1983
1797
  * Applies a tool approval response from the client, updating the persisted message.
1984
1798
  * This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
@@ -1992,138 +1806,31 @@ export class AIChatAgent<
1992
1806
  toolCallId: string,
1993
1807
  approved: boolean
1994
1808
  ): Promise<boolean> {
1995
- // Find the message with this tool call.
1996
- // We check two locations:
1997
- // 1. _streamingMessage: in-memory message being actively built during AI response
1998
- // (not yet persisted to SQLite or available in this.messages)
1999
- // 2. this.messages: persisted messages loaded from SQLite database
2000
- //
2001
- // The user can approve before streaming finishes (e.g., approval UI appears
2002
- // while AI is still generating text), so we must check _streamingMessage first.
2003
-
2004
- let message: ChatMessage | undefined;
2005
-
2006
- // Check streaming message first (in-memory, not yet persisted)
2007
- if (this._streamingMessage) {
2008
- for (const part of this._streamingMessage.parts) {
2009
- if ("toolCallId" in part && part.toolCallId === toolCallId) {
2010
- message = this._streamingMessage;
2011
- break;
2012
- }
2013
- }
2014
- }
2015
-
2016
- // If not found in streaming message, check persisted messages (in SQLite).
2017
- // Retry with backoff in case streaming completes and persists between attempts.
2018
- if (!message) {
2019
- for (let attempt = 0; attempt < 10; attempt++) {
2020
- message = this._findMessageByToolCallId(toolCallId);
2021
- if (message) break;
2022
- await new Promise((resolve) => setTimeout(resolve, 100));
2023
- }
2024
- }
2025
-
2026
- if (!message) {
2027
- console.warn(
2028
- `[AIChatAgent] _applyToolApproval: Could not find message with toolCallId ${toolCallId} after retries`
2029
- );
2030
- return false;
2031
- }
2032
-
2033
- // Check if this is the streaming message (not yet persisted)
2034
- const isStreamingMessage = message === this._streamingMessage;
2035
-
2036
- // Update the tool part with the approval
2037
- let updated = false;
2038
- if (isStreamingMessage) {
2039
- // Update in place - the message will be persisted when streaming completes
2040
- for (const part of message.parts) {
2041
- if (
2042
- "toolCallId" in part &&
2043
- part.toolCallId === toolCallId &&
2044
- "state" in part &&
2045
- (part.state === "input-available" ||
2046
- part.state === "approval-requested")
2047
- ) {
2048
- (part as { state: string; approval?: { approved: boolean } }).state =
2049
- "approval-responded";
2050
- (
2051
- part as { state: string; approval?: { approved: boolean } }
2052
- ).approval = { approved };
2053
- updated = true;
2054
- break;
1809
+ return this._findAndUpdateToolPart(
1810
+ toolCallId,
1811
+ "_applyToolApproval",
1812
+ ["input-available", "approval-requested"],
1813
+ (part) => ({
1814
+ ...part,
1815
+ state: "approval-responded",
1816
+ // Merge with existing approval data to preserve the id field.
1817
+ // convertToModelMessages needs approval.id to produce a valid
1818
+ // tool-approval-request content part with approvalId.
1819
+ approval: {
1820
+ ...(part.approval as Record<string, unknown> | undefined),
1821
+ approved
2055
1822
  }
2056
- }
2057
- } else {
2058
- // For persisted messages, create updated parts
2059
- const updatedParts = message.parts.map((part) => {
2060
- if (
2061
- "toolCallId" in part &&
2062
- part.toolCallId === toolCallId &&
2063
- "state" in part &&
2064
- (part.state === "input-available" ||
2065
- part.state === "approval-requested")
2066
- ) {
2067
- updated = true;
2068
- return {
2069
- ...part,
2070
- state: "approval-responded" as const,
2071
- approval: { approved }
2072
- };
2073
- }
2074
- return part;
2075
- }) as ChatMessage["parts"];
2076
-
2077
- if (updated) {
2078
- // Create the updated message and strip OpenAI item IDs
2079
- const updatedMessage: ChatMessage = this._sanitizeMessageForPersistence(
2080
- {
2081
- ...message,
2082
- parts: updatedParts
2083
- }
2084
- );
2085
-
2086
- // Persist the updated message
2087
- this.sql`
2088
- update cf_ai_chat_agent_messages
2089
- set message = ${JSON.stringify(updatedMessage)}
2090
- where id = ${message.id}
2091
- `;
2092
-
2093
- // Reload messages to update in-memory state
2094
- const persisted = this._loadMessagesFromDb();
2095
- this.messages = autoTransformMessages(persisted);
2096
- }
2097
- }
2098
-
2099
- if (!updated) {
2100
- console.warn(
2101
- `[AIChatAgent] _applyToolApproval: Tool part with toolCallId ${toolCallId} not in input-available or approval-requested state`
2102
- );
2103
- return false;
2104
- }
2105
-
2106
- // Broadcast the update to all clients (only for persisted messages)
2107
- if (!isStreamingMessage) {
2108
- const broadcastMessage = this._findMessageByToolCallId(toolCallId);
2109
- if (broadcastMessage) {
2110
- this._broadcastChatMessage({
2111
- type: MessageType.CF_AGENT_MESSAGE_UPDATED,
2112
- message: broadcastMessage
2113
- });
2114
- }
2115
- }
2116
-
2117
- return true;
1823
+ })
1824
+ );
2118
1825
  }
2119
1826
 
2120
1827
  private async _reply(
2121
1828
  id: string,
2122
1829
  response: Response,
2123
1830
  excludeBroadcastIds: string[] = [],
2124
- options: { continuation?: boolean } = {}
1831
+ options: { continuation?: boolean; chatMessageId?: string } = {}
2125
1832
  ) {
2126
- const { continuation = false } = options;
1833
+ const { continuation = false, chatMessageId } = options;
2127
1834
 
2128
1835
  return this._tryCatchChat(async () => {
2129
1836
  if (!response.body) {
@@ -2161,6 +1868,10 @@ export class AIChatAgent<
2161
1868
  const contentType = response.headers.get("content-type") || "";
2162
1869
  const isSSE = contentType.includes("text/event-stream"); // AI SDK v5 SSE format
2163
1870
  const streamCompleted = { value: false };
1871
+ // Capture before try so it's available after finally.
1872
+ // _approvalPersistedMessageId is set inside _streamSSEReply when a
1873
+ // tool enters approval-requested state and the message is persisted early.
1874
+ let earlyPersistedId: string | null = null;
2164
1875
 
2165
1876
  try {
2166
1877
  if (isSSE) {
@@ -2200,10 +1911,55 @@ export class AIChatAgent<
2200
1911
  throw error;
2201
1912
  } finally {
2202
1913
  reader.releaseLock();
1914
+
1915
+ // Always clear the streaming message reference and resolve completion
1916
+ // promise, even on error. Without this, tool continuations waiting on
1917
+ // _streamCompletionPromise would hang forever after a stream error.
1918
+ this._streamingMessage = null;
1919
+ // Capture and clear early-persist tracking. The persistence block
1920
+ // after the finally uses the local to update in place.
1921
+ earlyPersistedId = this._approvalPersistedMessageId;
1922
+ this._approvalPersistedMessageId = null;
1923
+ if (this._streamCompletionResolve) {
1924
+ this._streamCompletionResolve();
1925
+ this._streamCompletionResolve = null;
1926
+ this._streamCompletionPromise = null;
1927
+ }
1928
+
1929
+ // Framework-level cleanup: always remove abort controller.
1930
+ // Only emit observability on success (not on error path).
1931
+ if (chatMessageId) {
1932
+ this._removeAbortController(chatMessageId);
1933
+ if (streamCompleted.value) {
1934
+ this.observability?.emit(
1935
+ {
1936
+ displayMessage: continuation
1937
+ ? "Chat message response (tool continuation)"
1938
+ : "Chat message response",
1939
+ id: chatMessageId,
1940
+ payload: {},
1941
+ timestamp: Date.now(),
1942
+ type: "message:response"
1943
+ },
1944
+ this.ctx
1945
+ );
1946
+ }
1947
+ }
2203
1948
  }
2204
1949
 
2205
1950
  if (message.parts.length > 0) {
2206
- if (continuation) {
1951
+ if (earlyPersistedId) {
1952
+ // Message already exists in this.messages from the early persist.
1953
+ // Update it in place with the final streaming state.
1954
+ // Note: early-persisted messages come from the initial stream
1955
+ // (before approval), which is never a continuation. The
1956
+ // continuation stream starts fresh after approval, so
1957
+ // earlyPersistedId will always be null for continuations.
1958
+ const updatedMessages = this.messages.map((msg) =>
1959
+ msg.id === earlyPersistedId ? message : msg
1960
+ );
1961
+ await this.persistMessages(updatedMessages, excludeBroadcastIds);
1962
+ } else if (continuation) {
2207
1963
  // Find the last assistant message and append parts to it
2208
1964
  let lastAssistantIdx = -1;
2209
1965
  for (let i = this.messages.length - 1; i >= 0; i--) {
@@ -2235,36 +1991,9 @@ export class AIChatAgent<
2235
1991
  );
2236
1992
  }
2237
1993
  }
2238
-
2239
- // Clear the streaming message reference and resolve completion promise
2240
- this._streamingMessage = null;
2241
- if (this._streamCompletionResolve) {
2242
- this._streamCompletionResolve();
2243
- this._streamCompletionResolve = null;
2244
- this._streamCompletionPromise = null;
2245
- }
2246
1994
  });
2247
1995
  }
2248
1996
 
2249
- /**
2250
- * Mark a stream as errored and clean up state.
2251
- * @param streamId - The stream to mark as errored
2252
- * @internal Protected for testing purposes.
2253
- */
2254
- protected _markStreamError(streamId: string) {
2255
- // Flush any pending chunks before marking error
2256
- this._flushChunkBuffer();
2257
-
2258
- this.sql`
2259
- update cf_ai_chat_stream_metadata
2260
- set status = 'error', completed_at = ${Date.now()}
2261
- where id = ${streamId}
2262
- `;
2263
- this._activeStreamId = null;
2264
- this._activeRequestId = null;
2265
- this._streamChunkIndex = 0;
2266
- }
2267
-
2268
1997
  /**
2269
1998
  * For the given message id, look up its associated AbortController
2270
1999
  * If the AbortController does not exist, create and store one in memory
@@ -2316,18 +2045,7 @@ export class AIChatAgent<
2316
2045
  */
2317
2046
  async destroy() {
2318
2047
  this._destroyAbortControllers();
2319
-
2320
- // Flush any remaining chunks before cleanup
2321
- this._flushChunkBuffer();
2322
-
2323
- // Clean up stream tables
2324
- this.sql`drop table if exists cf_ai_chat_stream_chunks`;
2325
- this.sql`drop table if exists cf_ai_chat_stream_metadata`;
2326
-
2327
- // Clear active stream state
2328
- this._activeStreamId = null;
2329
- this._activeRequestId = null;
2330
-
2048
+ this._resumableStream.destroy();
2331
2049
  await super.destroy();
2332
2050
  }
2333
2051
  }