@cloudflare/ai-chat 0.0.8 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +97 -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 +114 -76
  10. package/dist/index.js +745 -629
  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 +244 -258
  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 +13 -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 +831 -1137
  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 +385 -461
  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 +3 -3
  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 +3 -3
  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 +59 -24
  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,7 +7,6 @@ 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";
@@ -27,8 +25,50 @@ import {
27
25
  type OutgoingMessage
28
26
  } from "./types";
29
27
  import { autoTransformMessages } from "./ai-chat-v5-migration";
28
+ import { applyChunkToParts } from "./message-builder";
29
+ import { ResumableStream } from "./resumable-stream";
30
30
  import { nanoid } from "nanoid";
31
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
+ * 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
+ }
71
+
32
72
  /**
33
73
  * Schema for a client-defined tool sent from the browser.
34
74
  * These tools are executed on the client, not the server.
@@ -70,6 +110,11 @@ export type OnChatMessageOptions = {
70
110
  *
71
111
  * Contains all fields from the request body except `messages` and `clientTools`,
72
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`.
73
118
  */
74
119
  body?: Record<string, unknown>;
75
120
  };
@@ -112,6 +157,11 @@ export type OnChatMessageOptions = {
112
157
  export function createToolsFromClientSchemas(
113
158
  clientTools?: ClientToolSchema[]
114
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
+
115
165
  if (!clientTools || clientTools.length === 0) {
116
166
  return {};
117
167
  }
@@ -139,41 +189,8 @@ export function createToolsFromClientSchemas(
139
189
  );
140
190
  }
141
191
 
142
- /** Number of chunks to buffer before flushing to SQLite */
143
- const CHUNK_BUFFER_SIZE = 10;
144
- /** Maximum buffer size to prevent memory issues on rapid reconnections */
145
- const CHUNK_BUFFER_MAX_SIZE = 100;
146
- /** Maximum age for a "streaming" stream before considering it stale (ms) - 5 minutes */
147
- const STREAM_STALE_THRESHOLD_MS = 5 * 60 * 1000;
148
- /** Default cleanup interval for old streams (ms) - every 10 minutes */
149
- const CLEANUP_INTERVAL_MS = 10 * 60 * 1000;
150
- /** Default age threshold for cleaning up completed streams (ms) - 24 hours */
151
- const CLEANUP_AGE_THRESHOLD_MS = 24 * 60 * 60 * 1000;
152
-
153
192
  const decoder = new TextDecoder();
154
193
 
155
- /**
156
- * Stored stream chunk for resumable streaming
157
- */
158
- type StreamChunk = {
159
- id: string;
160
- stream_id: string;
161
- body: string;
162
- chunk_index: number;
163
- created_at: number;
164
- };
165
-
166
- /**
167
- * Stream metadata for tracking active streams
168
- */
169
- type StreamMetadata = {
170
- id: string;
171
- request_id: string;
172
- status: "streaming" | "completed" | "error";
173
- created_at: number;
174
- completed_at: number | null;
175
- };
176
-
177
194
  /**
178
195
  * Extension of Agent with built-in chat capabilities
179
196
  * @template Env Environment type containing bindings
@@ -189,17 +206,10 @@ export class AIChatAgent<
189
206
  private _chatMessageAbortControllers: Map<string, AbortController>;
190
207
 
191
208
  /**
192
- * Currently active stream ID for resumable streaming.
193
- * Stored in memory for quick access; persisted in stream_metadata table.
194
- * @internal Protected for testing purposes.
195
- */
196
- protected _activeStreamId: string | null = null;
197
-
198
- /**
199
- * Request ID associated with the active stream.
209
+ * Resumable stream manager -- handles chunk buffering, persistence, and replay.
200
210
  * @internal Protected for testing purposes.
201
211
  */
202
- protected _activeRequestId: string | null = null;
212
+ protected _resumableStream!: ResumableStream;
203
213
 
204
214
  /**
205
215
  * The message currently being streamed. Used to apply tool results
@@ -208,6 +218,14 @@ export class AIChatAgent<
208
218
  */
209
219
  private _streamingMessage: ChatMessage | null = null;
210
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
+
211
229
  /**
212
230
  * Promise that resolves when the current stream completes.
213
231
  * Used to wait for message persistence before continuing after tool results.
@@ -217,45 +235,60 @@ export class AIChatAgent<
217
235
  private _streamCompletionResolve: (() => void) | null = null;
218
236
 
219
237
  /**
220
- * Current chunk index for the active stream
221
- */
222
- private _streamChunkIndex = 0;
223
-
224
- /**
225
- * Buffer for stream chunks pending write to SQLite.
226
- * Chunks are batched and flushed when buffer reaches CHUNK_BUFFER_SIZE.
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
227
242
  */
228
- private _chunkBuffer: Array<{
229
- id: string;
230
- streamId: string;
231
- body: string;
232
- index: number;
233
- }> = [];
243
+ private _pendingResumeConnections: Set<string> = new Set();
234
244
 
235
245
  /**
236
- * Lock to prevent concurrent flush operations
246
+ * Client tool schemas from the most recent chat request.
247
+ * Stored so they can be passed to onChatMessage during tool continuations.
248
+ * @internal
237
249
  */
238
- private _isFlushingChunks = false;
250
+ private _lastClientTools: ClientToolSchema[] | undefined;
239
251
 
240
252
  /**
241
- * Timestamp of the last cleanup operation for old streams
253
+ * Custom body data from the most recent chat request.
254
+ * Stored so it can be passed to onChatMessage during tool continuations.
255
+ * @internal
242
256
  */
243
- private _lastCleanupTime = 0;
257
+ private _lastBody: Record<string, unknown> | undefined;
244
258
 
245
259
  /**
246
- * Set of connection IDs that are pending stream resume.
247
- * These connections have received CF_AGENT_STREAM_RESUMING but haven't sent ACK yet.
248
- * They should be excluded from live stream broadcasts until they ACK.
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.
249
263
  * @internal
250
264
  */
251
- private _pendingResumeConnections: Set<string> = new Set();
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
+ }
252
274
 
253
275
  /**
254
- * Client tool schemas from the most recent chat request.
255
- * Stored so they can be passed to onChatMessage during tool continuations.
256
- * @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
+ * ```
257
290
  */
258
- private _lastClientTools: ClientToolSchema[] | undefined;
291
+ maxPersistedMessages: number | undefined = undefined;
259
292
 
260
293
  /** Array of chat messages for the current conversation */
261
294
  messages: ChatMessage[];
@@ -268,40 +301,35 @@ export class AIChatAgent<
268
301
  created_at datetime default current_timestamp
269
302
  )`;
270
303
 
271
- // Create tables for automatic resumable streaming
272
- this.sql`create table if not exists cf_ai_chat_stream_chunks (
273
- id text primary key,
274
- stream_id text not null,
275
- body text not null,
276
- chunk_index integer not null,
277
- 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
278
309
  )`;
279
310
 
280
- this.sql`create table if not exists cf_ai_chat_stream_metadata (
281
- id text primary key,
282
- request_id text not null,
283
- status text not null,
284
- created_at integer not null,
285
- completed_at integer
286
- )`;
311
+ // Restore request context from SQLite (survives hibernation)
312
+ this._restoreRequestContext();
287
313
 
288
- this.sql`create index if not exists idx_stream_chunks_stream_id
289
- 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));
290
316
 
291
- // 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.
292
323
  const rawMessages = this._loadMessagesFromDb();
293
324
 
294
325
  // Automatic migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages
295
326
  this.messages = autoTransformMessages(rawMessages);
296
327
 
297
328
  this._chatMessageAbortControllers = new Map();
298
-
299
- // Check for any active streams from a previous session
300
- this._restoreActiveStream();
301
329
  const _onConnect = this.onConnect.bind(this);
302
330
  this.onConnect = async (connection: Connection, ctx: ConnectionContext) => {
303
331
  // Notify client about active streams that can be resumed
304
- if (this._activeStreamId) {
332
+ if (this._resumableStream.hasActiveStream()) {
305
333
  this._notifyStreamResuming(connection);
306
334
  }
307
335
  // Call consumer's onConnect
@@ -341,15 +369,34 @@ export class AIChatAgent<
341
369
  data.init.method === "POST"
342
370
  ) {
343
371
  const { body } = data.init;
344
- const parsed = JSON.parse(body as string);
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
+
345
389
  const { messages, clientTools, ...customBody } = parsed as {
346
390
  messages: ChatMessage[];
347
391
  clientTools?: ClientToolSchema[];
348
392
  [key: string]: unknown;
349
393
  };
350
394
 
351
- // Store client tools for use during tool continuations
395
+ // Store client tools and body for use during tool continuations
352
396
  this._lastClientTools = clientTools?.length ? clientTools : undefined;
397
+ this._lastBody =
398
+ Object.keys(customBody).length > 0 ? customBody : undefined;
399
+ this._persistRequestContext();
353
400
 
354
401
  // Automatically transform any incoming messages
355
402
  const transformedMessages = autoTransformMessages(messages);
@@ -386,31 +433,20 @@ export class AIChatAgent<
386
433
  async () => {
387
434
  const response = await this.onChatMessage(
388
435
  async (_finishResult) => {
389
- this._removeAbortController(chatMessageId);
390
-
391
- this.observability?.emit(
392
- {
393
- displayMessage: "Chat message response",
394
- id: data.id,
395
- payload: {},
396
- timestamp: Date.now(),
397
- type: "message:response"
398
- },
399
- this.ctx
400
- );
436
+ // User-provided hook. Cleanup is now handled by _reply,
437
+ // so this is optional for the user to pass to streamText.
401
438
  },
402
439
  {
403
440
  abortSignal,
404
441
  clientTools,
405
- body:
406
- Object.keys(customBody).length > 0
407
- ? customBody
408
- : undefined
442
+ body: this._lastBody
409
443
  }
410
444
  );
411
445
 
412
446
  if (response) {
413
- await this._reply(data.id, response, [connection.id]);
447
+ await this._reply(data.id, response, [connection.id], {
448
+ chatMessageId
449
+ });
414
450
  } else {
415
451
  console.warn(
416
452
  `[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`
@@ -434,13 +470,12 @@ export class AIChatAgent<
434
470
  if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
435
471
  this._destroyAbortControllers();
436
472
  this.sql`delete from cf_ai_chat_agent_messages`;
437
- this.sql`delete from cf_ai_chat_stream_chunks`;
438
- this.sql`delete from cf_ai_chat_stream_metadata`;
439
- this._activeStreamId = null;
440
- this._activeRequestId = null;
441
- this._streamChunkIndex = 0;
473
+ this._resumableStream.clearAll();
442
474
  this._pendingResumeConnections.clear();
443
475
  this._lastClientTools = undefined;
476
+ this._lastBody = undefined;
477
+ this._persistRequestContext();
478
+ this._persistedMessageCache.clear();
444
479
  this.messages = [];
445
480
  this._broadcastChatMessage(
446
481
  { type: MessageType.CF_AGENT_CHAT_CLEAR },
@@ -462,19 +497,28 @@ export class AIChatAgent<
462
497
  return;
463
498
  }
464
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
+
465
511
  // Handle stream resume acknowledgment
466
512
  if (data.type === MessageType.CF_AGENT_STREAM_RESUME_ACK) {
467
513
  this._pendingResumeConnections.delete(connection.id);
468
514
 
469
515
  if (
470
- this._activeStreamId &&
471
- this._activeRequestId &&
472
- this._activeRequestId === data.id
516
+ this._resumableStream.hasActiveStream() &&
517
+ this._resumableStream.activeRequestId === data.id
473
518
  ) {
474
- this._sendStreamChunks(
519
+ this._resumableStream.replayChunks(
475
520
  connection,
476
- this._activeStreamId,
477
- this._activeRequestId
521
+ this._resumableStream.activeRequestId
478
522
  );
479
523
  }
480
524
  return;
@@ -482,7 +526,14 @@ export class AIChatAgent<
482
526
 
483
527
  // Handle client-side tool result
484
528
  if (data.type === MessageType.CF_AGENT_TOOL_RESULT) {
485
- 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
+ }
486
537
 
487
538
  // Apply the tool result
488
539
  this._applyToolResult(toolCallId, toolName, output).then(
@@ -497,16 +548,91 @@ export class AIChatAgent<
497
548
  if (this._streamCompletionPromise) {
498
549
  await this._streamCompletionPromise;
499
550
  } else {
500
- // 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).
501
555
  await new Promise((resolve) => setTimeout(resolve, 500));
502
556
  }
503
557
  };
504
558
 
505
- 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(() => {
506
632
  const continuationId = nanoid();
507
633
  const abortSignal = this._getAbortSignal(continuationId);
508
634
 
509
- this._tryCatchChat(async () => {
635
+ return this._tryCatchChat(async () => {
510
636
  return agentContext.run(
511
637
  {
512
638
  agent: this,
@@ -516,54 +642,32 @@ export class AIChatAgent<
516
642
  },
517
643
  async () => {
518
644
  const response = await this.onChatMessage(
519
- async (_finishResult) => {
520
- this._removeAbortController(continuationId);
521
-
522
- this.observability?.emit(
523
- {
524
- displayMessage:
525
- "Chat message response (tool continuation)",
526
- id: continuationId,
527
- payload: {},
528
- timestamp: Date.now(),
529
- type: "message:response"
530
- },
531
- this.ctx
532
- );
533
- },
645
+ async (_finishResult) => {},
534
646
  {
535
647
  abortSignal,
536
- clientTools: this._lastClientTools
648
+ clientTools: this._lastClientTools,
649
+ body: this._lastBody
537
650
  }
538
651
  );
539
652
 
540
653
  if (response) {
541
- // Pass continuation flag to merge parts into last assistant message
542
- // Note: We pass an empty excludeBroadcastIds array because the sender
543
- // NEEDS to receive the continuation stream. Unlike regular chat requests
544
- // where aiFetch handles the response, tool continuations have no listener
545
- // waiting - the client relies on the broadcast.
546
- await this._reply(
547
- continuationId,
548
- response,
549
- [], // Don't exclude sender - they need the continuation
550
- { continuation: true }
551
- );
654
+ await this._reply(continuationId, response, [], {
655
+ continuation: true,
656
+ chatMessageId: continuationId
657
+ });
552
658
  }
553
659
  }
554
660
  );
555
661
  });
662
+ })
663
+ .catch((error) => {
664
+ console.error(
665
+ "[AIChatAgent] Tool approval continuation failed:",
666
+ error
667
+ );
556
668
  });
557
- }
558
669
  }
559
- );
560
- return;
561
- }
562
-
563
- // Handle client-side tool approval response
564
- if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
565
- const { toolCallId, approved } = data;
566
- this._applyToolApproval(toolCallId, approved);
670
+ });
567
671
  return;
568
672
  }
569
673
  }
@@ -573,60 +677,13 @@ export class AIChatAgent<
573
677
  };
574
678
  }
575
679
 
576
- /**
577
- * Restore active stream state if the agent was restarted during streaming.
578
- * Called during construction to recover any interrupted streams.
579
- * Validates stream freshness to avoid sending stale resume notifications.
580
- * @internal Protected for testing purposes.
581
- */
582
- protected _restoreActiveStream() {
583
- const activeStreams = this.sql<StreamMetadata>`
584
- select * from cf_ai_chat_stream_metadata
585
- where status = 'streaming'
586
- order by created_at desc
587
- limit 1
588
- `;
589
-
590
- if (activeStreams && activeStreams.length > 0) {
591
- const stream = activeStreams[0];
592
- const streamAge = Date.now() - stream.created_at;
593
-
594
- // Check if stream is stale; delete to free storage
595
- if (streamAge > STREAM_STALE_THRESHOLD_MS) {
596
- this
597
- .sql`delete from cf_ai_chat_stream_chunks where stream_id = ${stream.id}`;
598
- this
599
- .sql`delete from cf_ai_chat_stream_metadata where id = ${stream.id}`;
600
- console.warn(
601
- `[AIChatAgent] Deleted stale stream ${stream.id} (age: ${Math.round(streamAge / 1000)}s)`
602
- );
603
- return;
604
- }
605
-
606
- this._activeStreamId = stream.id;
607
- this._activeRequestId = stream.request_id;
608
-
609
- // Get the last chunk index
610
- const lastChunk = this.sql<{ max_index: number }>`
611
- select max(chunk_index) as max_index
612
- from cf_ai_chat_stream_chunks
613
- where stream_id = ${this._activeStreamId}
614
- `;
615
- this._streamChunkIndex =
616
- lastChunk && lastChunk[0]?.max_index != null
617
- ? lastChunk[0].max_index + 1
618
- : 0;
619
- }
620
- }
621
-
622
680
  /**
623
681
  * Notify a connection about an active stream that can be resumed.
624
682
  * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
625
- * Uses in-memory state for request ID - no extra DB lookup needed.
626
683
  * @param connection - The WebSocket connection to notify
627
684
  */
628
685
  private _notifyStreamResuming(connection: Connection) {
629
- if (!this._activeStreamId || !this._activeRequestId) {
686
+ if (!this._resumableStream.hasActiveStream()) {
630
687
  return;
631
688
  }
632
689
 
@@ -638,184 +695,105 @@ export class AIChatAgent<
638
695
  connection.send(
639
696
  JSON.stringify({
640
697
  type: MessageType.CF_AGENT_STREAM_RESUMING,
641
- id: this._activeRequestId
698
+ id: this._resumableStream.activeRequestId
642
699
  })
643
700
  );
644
701
  }
645
702
 
646
- /**
647
- * Send stream chunks to a connection after receiving ACK.
648
- * @param connection - The WebSocket connection
649
- * @param streamId - The stream to replay
650
- * @param requestId - The original request ID
651
- */
652
- private _sendStreamChunks(
653
- connection: Connection,
654
- streamId: string,
655
- requestId: string
656
- ) {
657
- // Flush any pending chunks first to ensure we have the latest
658
- this._flushChunkBuffer();
659
-
660
- const chunks = this.sql<StreamChunk>`
661
- select * from cf_ai_chat_stream_chunks
662
- where stream_id = ${streamId}
663
- order by chunk_index asc
664
- `;
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.
665
706
 
666
- // Send all stored chunks
667
- for (const chunk of chunks || []) {
668
- connection.send(
669
- JSON.stringify({
670
- body: chunk.body,
671
- done: false,
672
- id: requestId,
673
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
674
- })
675
- );
676
- }
707
+ /** @internal Delegate to _resumableStream */
708
+ protected get _activeStreamId(): string | null {
709
+ return this._resumableStream?.activeStreamId ?? null;
710
+ }
677
711
 
678
- // If the stream is no longer active (completed), send done signal
679
- // We track active state in memory, no need to query DB
680
- if (this._activeStreamId !== streamId) {
681
- connection.send(
682
- JSON.stringify({
683
- body: "",
684
- done: true,
685
- id: requestId,
686
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
687
- })
688
- );
689
- }
712
+ /** @internal Delegate to _resumableStream */
713
+ protected get _activeRequestId(): string | null {
714
+ return this._resumableStream?.activeRequestId ?? null;
690
715
  }
691
716
 
692
- /**
693
- * Buffer a stream chunk for batch write to SQLite.
694
- * @param streamId - The stream this chunk belongs to
695
- * @param body - The serialized chunk body
696
- * @internal Protected for testing purposes.
697
- */
698
- protected _storeStreamChunk(streamId: string, body: string) {
699
- // Force flush if buffer is at max to prevent memory issues
700
- if (this._chunkBuffer.length >= CHUNK_BUFFER_MAX_SIZE) {
701
- this._flushChunkBuffer();
702
- }
717
+ /** @internal Delegate to _resumableStream */
718
+ protected _startStream(requestId: string): string {
719
+ return this._resumableStream.start(requestId);
720
+ }
703
721
 
704
- this._chunkBuffer.push({
705
- id: nanoid(),
706
- streamId,
707
- body,
708
- index: this._streamChunkIndex
709
- });
710
- this._streamChunkIndex++;
722
+ /** @internal Delegate to _resumableStream */
723
+ protected _completeStream(streamId: string) {
724
+ this._resumableStream.complete(streamId);
725
+ this._pendingResumeConnections.clear();
726
+ }
711
727
 
712
- // Flush when buffer reaches threshold
713
- if (this._chunkBuffer.length >= CHUNK_BUFFER_SIZE) {
714
- this._flushChunkBuffer();
715
- }
728
+ /** @internal Delegate to _resumableStream */
729
+ protected _storeStreamChunk(streamId: string, body: string) {
730
+ this._resumableStream.storeChunk(streamId, body);
716
731
  }
717
732
 
718
- /**
719
- * Flush buffered chunks to SQLite in a single batch.
720
- * Uses a lock to prevent concurrent flush operations.
721
- * @internal Protected for testing purposes.
722
- */
733
+ /** @internal Delegate to _resumableStream */
723
734
  protected _flushChunkBuffer() {
724
- // Prevent concurrent flushes
725
- if (this._isFlushingChunks || this._chunkBuffer.length === 0) {
726
- return;
727
- }
728
-
729
- this._isFlushingChunks = true;
730
- try {
731
- const chunks = this._chunkBuffer;
732
- this._chunkBuffer = [];
733
-
734
- // Batch insert all chunks
735
- const now = Date.now();
736
- for (const chunk of chunks) {
737
- this.sql`
738
- insert into cf_ai_chat_stream_chunks (id, stream_id, body, chunk_index, created_at)
739
- values (${chunk.id}, ${chunk.streamId}, ${chunk.body}, ${chunk.index}, ${now})
740
- `;
741
- }
742
- } finally {
743
- this._isFlushingChunks = false;
744
- }
735
+ this._resumableStream.flushBuffer();
745
736
  }
746
737
 
747
- /**
748
- * Start tracking a new stream for resumable streaming.
749
- * Creates metadata entry in SQLite and sets up tracking state.
750
- * @param requestId - The unique ID of the chat request
751
- * @returns The generated stream ID
752
- * @internal Protected for testing purposes.
753
- */
754
- protected _startStream(requestId: string): string {
755
- // Flush any pending chunks from previous streams to prevent mixing
756
- this._flushChunkBuffer();
757
-
758
- const streamId = nanoid();
759
- this._activeStreamId = streamId;
760
- this._activeRequestId = requestId;
761
- this._streamChunkIndex = 0;
762
-
763
- this.sql`
764
- insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
765
- values (${streamId}, ${requestId}, 'streaming', ${Date.now()})
766
- `;
738
+ /** @internal Delegate to _resumableStream */
739
+ protected _restoreActiveStream() {
740
+ this._resumableStream.restore();
741
+ }
767
742
 
768
- return streamId;
743
+ /** @internal Delegate to _resumableStream */
744
+ protected _markStreamError(streamId: string) {
745
+ this._resumableStream.markError(streamId);
769
746
  }
770
747
 
771
748
  /**
772
- * Mark a stream as completed and flush any pending chunks.
773
- * @param streamId - The stream to mark as completed
774
- * @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
775
752
  */
776
- protected _completeStream(streamId: string) {
777
- // Flush any pending chunks before completing
778
- this._flushChunkBuffer();
779
-
780
- this.sql`
781
- update cf_ai_chat_stream_metadata
782
- set status = 'completed', completed_at = ${Date.now()}
783
- where id = ${streamId}
784
- `;
785
- this._activeStreamId = null;
786
- this._activeRequestId = null;
787
- this._streamChunkIndex = 0;
788
-
789
- // Clear pending resume connections - no active stream to resume
790
- 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
+ ` || [];
791
758
 
792
- // Periodically clean up old streams (not on every completion)
793
- 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
+ }
794
770
  }
795
771
 
796
772
  /**
797
- * Clean up old completed streams if enough time has passed since last cleanup.
798
- * 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
799
776
  */
800
- private _maybeCleanupOldStreams() {
801
- const now = Date.now();
802
- if (now - this._lastCleanupTime < CLEANUP_INTERVAL_MS) {
803
- 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'`;
804
796
  }
805
- this._lastCleanupTime = now;
806
-
807
- const cutoff = now - CLEANUP_AGE_THRESHOLD_MS;
808
- this.sql`
809
- delete from cf_ai_chat_stream_chunks
810
- where stream_id in (
811
- select id from cf_ai_chat_stream_metadata
812
- where status = 'completed' and completed_at < ${cutoff}
813
- )
814
- `;
815
- this.sql`
816
- delete from cf_ai_chat_stream_metadata
817
- where status = 'completed' and completed_at < ${cutoff}
818
- `;
819
797
  }
820
798
 
821
799
  private _broadcastChatMessage(message: OutgoingMessage, exclude?: string[]) {
@@ -860,10 +838,31 @@ export class AIChatAgent<
860
838
  const rows =
861
839
  this.sql`select * from cf_ai_chat_agent_messages order by created_at` ||
862
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
+
863
846
  return rows
864
847
  .map((row) => {
865
848
  try {
866
- 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;
867
866
  } catch (error) {
868
867
  console.error(`Failed to parse message ${row.id}:`, error);
869
868
  return null;
@@ -906,7 +905,7 @@ export class AIChatAgent<
906
905
  options?: OnChatMessageOptions
907
906
  ): Promise<Response | undefined> {
908
907
  throw new Error(
909
- "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"
910
909
  );
911
910
  }
912
911
 
@@ -931,18 +930,30 @@ export class AIChatAgent<
931
930
  // tool outputs, but the server has them via _applyToolResult.
932
931
  const mergedMessages = this._mergeIncomingWithServerState(messages);
933
932
 
934
- // Persist the merged messages
933
+ // Persist only new or changed messages (incremental persistence).
934
+ // Compares serialized JSON against a cache of last-persisted versions.
935
935
  for (const message of mergedMessages) {
936
- // Strip OpenAI item IDs to prevent "Duplicate item found" errors
937
- // when using the OpenAI Responses API. These IDs are assigned by OpenAI
938
- // and if sent back in subsequent requests, cause duplicate detection.
939
936
  const sanitizedMessage = this._sanitizeMessageForPersistence(message);
940
- 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
+
941
946
  this.sql`
942
947
  insert into cf_ai_chat_agent_messages (id, message)
943
- values (${messageToSave.id}, ${JSON.stringify(messageToSave)})
948
+ values (${safe.id}, ${json})
944
949
  on conflict(id) do update set message = excluded.message
945
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();
946
957
  }
947
958
 
948
959
  // refresh in-memory messages
@@ -1203,111 +1214,262 @@ export class AIChatAgent<
1203
1214
  }
1204
1215
 
1205
1216
  /**
1206
- * Applies a tool result to an existing assistant message.
1207
- * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
1208
- * The server is the source of truth, so we update the message here and broadcast
1209
- * the update to all clients.
1210
- *
1211
- * @param toolCallId - The tool call ID this result is for
1212
- * @param toolName - The name of the tool
1213
- * @param output - The output from the tool execution
1214
- * @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.
1215
1219
  */
1216
- private async _applyToolResult(
1217
- toolCallId: string,
1218
- _toolName: string,
1219
- output: unknown
1220
- ): Promise<boolean> {
1221
- // Find the message with this tool call
1222
- // First check the currently streaming message
1223
- let message: ChatMessage | undefined;
1220
+ private _enforceMaxPersistedMessages() {
1221
+ if (this.maxPersistedMessages == null) return;
1224
1222
 
1225
- // Check streaming message first
1226
- if (this._streamingMessage) {
1227
- for (const part of this._streamingMessage.parts) {
1228
- if ("toolCallId" in part && part.toolCallId === toolCallId) {
1229
- message = this._streamingMessage;
1230
- break;
1231
- }
1232
- }
1233
- }
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;
1234
1227
 
1235
- // If not found in streaming message, retry persisted messages
1236
- if (!message) {
1237
- for (let attempt = 0; attempt < 10; attempt++) {
1238
- message = this._findMessageByToolCallId(toolCallId);
1239
- if (message) break;
1240
- // Wait 100ms before retrying
1241
- 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);
1242
1244
  }
1243
1245
  }
1246
+ }
1244
1247
 
1245
- if (!message) {
1246
- // The tool result will be included when
1247
- // 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.
1248
1271
  console.warn(
1249
- `[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.`
1274
+ );
1275
+ return this._truncateTextParts(message);
1276
+ }
1277
+
1278
+ console.warn(
1279
+ `[AIChatAgent] Message ${message.id} is ${size} bytes, ` +
1280
+ `compacting tool outputs to fit SQLite row limit`
1281
+ );
1282
+
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`
1250
1422
  );
1251
1423
  return false;
1252
1424
  }
1253
1425
 
1254
- // Check if this is the streaming message (not yet persisted)
1255
1426
  const isStreamingMessage = message === this._streamingMessage;
1256
-
1257
- // Update the tool part with the output
1258
1427
  let updated = false;
1428
+
1259
1429
  if (isStreamingMessage) {
1260
- // Update in place - the message will be persisted when streaming completes
1430
+ // Update in place -- the message will be persisted when streaming completes
1261
1431
  for (const part of message.parts) {
1262
1432
  if (
1263
1433
  "toolCallId" in part &&
1264
1434
  part.toolCallId === toolCallId &&
1265
1435
  "state" in part &&
1266
- part.state === "input-available"
1436
+ matchStates.includes(part.state as string)
1267
1437
  ) {
1268
- (part as { state: string; output?: unknown }).state =
1269
- "output-available";
1270
- (part as { state: string; output?: unknown }).output = output;
1438
+ const applied = applyUpdate(part as Record<string, unknown>);
1439
+ Object.assign(part, applied);
1271
1440
  updated = true;
1272
1441
  break;
1273
1442
  }
1274
1443
  }
1275
1444
  } else {
1276
- // For persisted messages, create updated parts
1445
+ // For persisted messages, create updated parts immutably
1277
1446
  const updatedParts = message.parts.map((part) => {
1278
1447
  if (
1279
1448
  "toolCallId" in part &&
1280
1449
  part.toolCallId === toolCallId &&
1281
1450
  "state" in part &&
1282
- part.state === "input-available"
1451
+ matchStates.includes(part.state as string)
1283
1452
  ) {
1284
1453
  updated = true;
1285
- return {
1286
- ...part,
1287
- state: "output-available" as const,
1288
- output
1289
- };
1454
+ return applyUpdate(part as Record<string, unknown>);
1290
1455
  }
1291
1456
  return part;
1292
1457
  }) as ChatMessage["parts"];
1293
1458
 
1294
1459
  if (updated) {
1295
- // Create the updated message and strip OpenAI item IDs
1296
1460
  const updatedMessage: ChatMessage = this._sanitizeMessageForPersistence(
1297
- {
1298
- ...message,
1299
- parts: updatedParts
1300
- }
1461
+ { ...message, parts: updatedParts }
1301
1462
  );
1463
+ const safe = this._enforceRowSizeLimit(updatedMessage);
1464
+ const json = JSON.stringify(safe);
1302
1465
 
1303
- // Persist the updated message
1304
1466
  this.sql`
1305
1467
  update cf_ai_chat_agent_messages
1306
- set message = ${JSON.stringify(updatedMessage)}
1468
+ set message = ${json}
1307
1469
  where id = ${message.id}
1308
1470
  `;
1471
+ this._persistedMessageCache.set(message.id, json);
1309
1472
 
1310
- // Reload messages to update in-memory state
1311
1473
  const persisted = this._loadMessagesFromDb();
1312
1474
  this.messages = autoTransformMessages(persisted);
1313
1475
  }
@@ -1315,15 +1477,21 @@ export class AIChatAgent<
1315
1477
 
1316
1478
  if (!updated) {
1317
1479
  console.warn(
1318
- `[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("|")})`
1319
1481
  );
1320
1482
  return false;
1321
1483
  }
1322
1484
 
1323
- // Broadcast the update to all clients (only for persisted messages)
1324
- // For streaming messages, the update will be included when persisted
1325
- if (!isStreamingMessage) {
1326
- // 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 {
1327
1495
  const broadcastMessage = this._findMessageByToolCallId(toolCallId);
1328
1496
  if (broadcastMessage) {
1329
1497
  this._broadcastChatMessage({
@@ -1333,13 +1501,38 @@ export class AIChatAgent<
1333
1501
  }
1334
1502
  }
1335
1503
 
1336
- // Note: We don't automatically continue the conversation here.
1337
- // The client is responsible for sending a follow-up request if needed.
1338
- // This avoids re-entering onChatMessage with unexpected state.
1339
-
1340
1504
  return true;
1341
1505
  }
1342
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
+
1343
1536
  private async _streamSSEReply(
1344
1537
  id: string,
1345
1538
  streamId: string,
@@ -1348,29 +1541,12 @@ export class AIChatAgent<
1348
1541
  streamCompleted: { value: boolean },
1349
1542
  continuation = false
1350
1543
  ) {
1351
- let activeTextParts: Record<string, TextUIPart> = {};
1352
- let activeReasoningParts: Record<string, ReasoningUIPart> = {};
1353
- const partialToolCalls: Record<
1354
- string,
1355
- { text: string; index: number; toolName: string; dynamic?: boolean }
1356
- > = {};
1357
-
1358
- /* Lazy loading ai sdk, because putting it in module scope is
1359
- * causing issues with startup time.
1360
- * The only place it's used is in _reply, which only matters after
1361
- * a chat message is received.
1362
- * So it's safe to delay loading it until a chat message is received.
1363
- */
1364
- const { getToolName, isToolUIPart, parsePartialJson } = await import("ai");
1365
-
1366
1544
  streamCompleted.value = false;
1367
1545
  while (true) {
1368
1546
  const { done, value } = await reader.read();
1369
1547
  if (done) {
1370
- // Mark the stream as completed
1371
1548
  this._completeStream(streamId);
1372
1549
  streamCompleted.value = true;
1373
- // Send final completion signal
1374
1550
  this._broadcastChatMessage({
1375
1551
  body: "",
1376
1552
  done: true,
@@ -1382,370 +1558,144 @@ export class AIChatAgent<
1382
1558
  }
1383
1559
 
1384
1560
  const chunk = decoder.decode(value);
1385
-
1386
- // After streaming is complete, persist the complete assistant's response
1387
-
1388
- // Parse AI SDK v5 SSE format and extract text deltas
1389
1561
  const lines = chunk.split("\n");
1562
+
1390
1563
  for (const line of lines) {
1391
1564
  if (line.startsWith("data: ") && line !== "data: [DONE]") {
1392
1565
  try {
1393
- const data: UIMessageChunk = JSON.parse(line.slice(6)); // Remove 'data: ' prefix
1394
- switch (data.type) {
1395
- case "text-start": {
1396
- const textPart: TextUIPart = {
1397
- type: "text",
1398
- text: "",
1399
- providerMetadata: data.providerMetadata,
1400
- state: "streaming"
1401
- };
1402
- activeTextParts[data.id] = textPart;
1403
- message.parts.push(textPart);
1404
- break;
1405
- }
1406
-
1407
- case "text-delta": {
1408
- const textPart = activeTextParts[data.id];
1409
- textPart.text += data.delta;
1410
- textPart.providerMetadata =
1411
- data.providerMetadata ?? textPart.providerMetadata;
1412
- break;
1413
- }
1414
-
1415
- case "text-end": {
1416
- const textPart = activeTextParts[data.id];
1417
- textPart.state = "done";
1418
- textPart.providerMetadata =
1419
- data.providerMetadata ?? textPart.providerMetadata;
1420
- delete activeTextParts[data.id];
1421
- break;
1422
- }
1423
-
1424
- case "reasoning-start": {
1425
- const reasoningPart: ReasoningUIPart = {
1426
- type: "reasoning",
1427
- text: "",
1428
- providerMetadata: data.providerMetadata,
1429
- state: "streaming"
1430
- };
1431
- activeReasoningParts[data.id] = reasoningPart;
1432
- message.parts.push(reasoningPart);
1433
- break;
1434
- }
1435
-
1436
- case "reasoning-delta": {
1437
- const reasoningPart = activeReasoningParts[data.id];
1438
- reasoningPart.text += data.delta;
1439
- reasoningPart.providerMetadata =
1440
- data.providerMetadata ?? reasoningPart.providerMetadata;
1441
- break;
1442
- }
1443
-
1444
- case "reasoning-end": {
1445
- const reasoningPart = activeReasoningParts[data.id];
1446
- reasoningPart.providerMetadata =
1447
- data.providerMetadata ?? reasoningPart.providerMetadata;
1448
- reasoningPart.state = "done";
1449
- delete activeReasoningParts[data.id];
1450
-
1451
- break;
1452
- }
1453
-
1454
- case "file": {
1455
- message.parts.push({
1456
- type: "file",
1457
- mediaType: data.mediaType,
1458
- url: data.url
1459
- });
1460
-
1461
- break;
1462
- }
1463
-
1464
- case "source-url": {
1465
- message.parts.push({
1466
- type: "source-url",
1467
- sourceId: data.sourceId,
1468
- url: data.url,
1469
- title: data.title,
1470
- providerMetadata: data.providerMetadata
1471
- });
1472
-
1473
- break;
1474
- }
1475
-
1476
- case "source-document": {
1477
- message.parts.push({
1478
- type: "source-document",
1479
- sourceId: data.sourceId,
1480
- mediaType: data.mediaType,
1481
- title: data.title,
1482
- filename: data.filename,
1483
- providerMetadata: data.providerMetadata
1484
- });
1485
-
1486
- break;
1487
- }
1488
-
1489
- case "tool-input-start": {
1490
- const toolInvocations = message.parts.filter(isToolUIPart);
1491
-
1492
- // add the partial tool call to the map
1493
- partialToolCalls[data.toolCallId] = {
1494
- text: "",
1495
- toolName: data.toolName,
1496
- index: toolInvocations.length,
1497
- dynamic: data.dynamic
1498
- };
1499
-
1500
- if (data.dynamic) {
1501
- this.updateDynamicToolPart(message, {
1502
- toolCallId: data.toolCallId,
1503
- toolName: data.toolName,
1504
- state: "input-streaming",
1505
- input: undefined
1506
- });
1507
- } else {
1508
- await this.updateToolPart(message, {
1509
- toolCallId: data.toolCallId,
1510
- toolName: data.toolName,
1511
- state: "input-streaming",
1512
- input: undefined
1513
- });
1514
- }
1515
-
1516
- break;
1517
- }
1518
-
1519
- case "tool-input-delta": {
1520
- const partialToolCall = partialToolCalls[data.toolCallId];
1521
-
1522
- partialToolCall.text += data.inputTextDelta;
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
+ }
1523
1602
 
1524
- const partialArgsResult = await parsePartialJson(
1525
- partialToolCall.text
1526
- );
1527
- const partialArgs = (
1528
- partialArgsResult as { value: Record<string, unknown> }
1529
- ).value;
1530
-
1531
- if (partialToolCall.dynamic) {
1532
- this.updateDynamicToolPart(message, {
1533
- toolCallId: data.toolCallId,
1534
- toolName: partialToolCall.toolName,
1535
- state: "input-streaming",
1536
- input: partialArgs
1537
- });
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
+ );
1538
1641
  } else {
1539
- await this.updateToolPart(message, {
1540
- toolCallId: data.toolCallId,
1541
- toolName: partialToolCall.toolName,
1542
- state: "input-streaming",
1543
- input: partialArgs
1544
- });
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
+ );
1545
1657
  }
1546
-
1547
- break;
1548
1658
  }
1659
+ }
1549
1660
 
1550
- case "tool-input-available": {
1551
- if (data.dynamic) {
1552
- this.updateDynamicToolPart(message, {
1553
- toolCallId: data.toolCallId,
1554
- toolName: data.toolName,
1555
- state: "input-available",
1556
- input: data.input,
1557
- providerMetadata: data.providerMetadata
1558
- });
1559
- } else {
1560
- await this.updateToolPart(message, {
1561
- toolCallId: data.toolCallId,
1562
- toolName: data.toolName,
1563
- state: "input-available",
1564
- input: data.input,
1565
- providerExecuted: data.providerExecuted,
1566
- providerMetadata: data.providerMetadata
1567
- });
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;
1568
1674
  }
1569
-
1570
- // TODO: Do we want to expose onToolCall?
1571
-
1572
- // invoke the onToolCall callback if it exists. This is blocking.
1573
- // In the future we should make this non-blocking, which
1574
- // requires additional state management for error handling etc.
1575
- // Skip calling onToolCall for provider-executed tools since they are already executed
1576
- // if (onToolCall && !data.providerExecuted) {
1577
- // await onToolCall({
1578
- // toolCall: data
1579
- // });
1580
- // }
1581
- break;
1582
- }
1583
-
1584
- case "tool-input-error": {
1585
- if (data.dynamic) {
1586
- this.updateDynamicToolPart(message, {
1587
- toolCallId: data.toolCallId,
1588
- toolName: data.toolName,
1589
- state: "output-error",
1590
- input: data.input,
1591
- errorText: data.errorText,
1592
- providerMetadata: data.providerMetadata
1593
- });
1594
- } else {
1595
- await this.updateToolPart(message, {
1596
- toolCallId: data.toolCallId,
1597
- toolName: data.toolName,
1598
- state: "output-error",
1599
- input: undefined,
1600
- rawInput: data.input,
1601
- errorText: data.errorText,
1602
- providerExecuted: data.providerExecuted,
1603
- providerMetadata: data.providerMetadata
1604
- });
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;
1605
1683
  }
1606
-
1607
- break;
1608
- }
1609
-
1610
- case "tool-output-available": {
1611
- if (data.dynamic) {
1612
- const toolInvocations = message.parts.filter(
1613
- (part) => part.type === "dynamic-tool"
1614
- ) as DynamicToolUIPart[];
1615
-
1616
- const toolInvocation = toolInvocations.find(
1617
- (invocation) => invocation.toolCallId === data.toolCallId
1618
- );
1619
-
1620
- if (!toolInvocation)
1621
- throw new Error("Tool invocation not found");
1622
-
1623
- this.updateDynamicToolPart(message, {
1624
- toolCallId: data.toolCallId,
1625
- toolName: toolInvocation.toolName,
1626
- state: "output-available",
1627
- input: toolInvocation.input,
1628
- output: data.output,
1629
- preliminary: data.preliminary
1630
- });
1631
- } else {
1632
- const toolInvocations = message.parts.filter(
1633
- isToolUIPart
1634
- ) as ToolUIPart[];
1635
-
1636
- const toolInvocation = toolInvocations.find(
1637
- (invocation) => invocation.toolCallId === data.toolCallId
1638
- );
1639
-
1640
- if (!toolInvocation)
1641
- throw new Error("Tool invocation not found");
1642
-
1643
- await this.updateToolPart(message, {
1644
- toolCallId: data.toolCallId,
1645
- toolName: getToolName(toolInvocation),
1646
- state: "output-available",
1647
- input: toolInvocation.input,
1648
- output: data.output,
1649
- providerExecuted: data.providerExecuted,
1650
- preliminary: data.preliminary
1651
- });
1684
+ case "finish-step": {
1685
+ // No-op for message building (shared parser handles step-start)
1686
+ break;
1652
1687
  }
1653
-
1654
- break;
1655
- }
1656
-
1657
- case "tool-output-error": {
1658
- if (data.dynamic) {
1659
- const toolInvocations = message.parts.filter(
1660
- (part) => part.type === "dynamic-tool"
1661
- ) as DynamicToolUIPart[];
1662
-
1663
- const toolInvocation = toolInvocations.find(
1664
- (invocation) => invocation.toolCallId === data.toolCallId
1665
- );
1666
-
1667
- if (!toolInvocation)
1668
- throw new Error("Tool invocation not found");
1669
-
1670
- this.updateDynamicToolPart(message, {
1671
- toolCallId: data.toolCallId,
1672
- toolName: toolInvocation.toolName,
1673
- state: "output-error",
1674
- input: toolInvocation.input,
1675
- errorText: data.errorText
1676
- });
1677
- } else {
1678
- const toolInvocations = message.parts.filter(
1679
- isToolUIPart
1680
- ) as ToolUIPart[];
1681
-
1682
- const toolInvocation = toolInvocations.find(
1683
- (invocation) => invocation.toolCallId === data.toolCallId
1684
- );
1685
-
1686
- if (!toolInvocation)
1687
- throw new Error("Tool invocation not found");
1688
- await this.updateToolPart(message, {
1689
- toolCallId: data.toolCallId,
1690
- toolName: getToolName(toolInvocation),
1691
- state: "output-error",
1692
- input: toolInvocation.input,
1693
- rawInput:
1694
- "rawInput" in toolInvocation
1695
- ? toolInvocation.rawInput
1696
- : undefined,
1697
- errorText: data.errorText
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
1698
1695
  });
1696
+ break;
1699
1697
  }
1700
-
1701
- break;
1702
- }
1703
-
1704
- case "start-step": {
1705
- // add a step boundary part to the message
1706
- message.parts.push({ type: "step-start" });
1707
- break;
1708
1698
  }
1709
-
1710
- case "finish-step": {
1711
- // reset the current text and reasoning parts
1712
- activeTextParts = {};
1713
- activeReasoningParts = {};
1714
- break;
1715
- }
1716
-
1717
- case "start": {
1718
- if (data.messageId != null) {
1719
- message.id = data.messageId;
1720
- }
1721
-
1722
- await this.updateMessageMetadata(message, data.messageMetadata);
1723
-
1724
- break;
1725
- }
1726
-
1727
- case "finish": {
1728
- await this.updateMessageMetadata(message, data.messageMetadata);
1729
- break;
1730
- }
1731
-
1732
- case "message-metadata": {
1733
- await this.updateMessageMetadata(message, data.messageMetadata);
1734
- break;
1735
- }
1736
-
1737
- case "error": {
1738
- this._broadcastChatMessage({
1739
- error: true,
1740
- body: data.errorText ?? JSON.stringify(data),
1741
- done: false,
1742
- id,
1743
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
1744
- });
1745
-
1746
- break;
1747
- }
1748
- // Do we want to handle data parts?
1749
1699
  }
1750
1700
 
1751
1701
  // Convert internal AI SDK stream events to valid UIMessageStreamPart format.
@@ -1765,11 +1715,9 @@ export class AIChatAgent<
1765
1715
  };
1766
1716
  }
1767
1717
 
1768
- // Store chunk for replay on reconnection
1718
+ // Store chunk for replay and broadcast to clients
1769
1719
  const chunkBody = JSON.stringify(eventToSend);
1770
1720
  this._storeStreamChunk(streamId, chunkBody);
1771
-
1772
- // Forward the converted event to the client
1773
1721
  this._broadcastChatMessage({
1774
1722
  body: chunkBody,
1775
1723
  done: false,
@@ -1801,9 +1749,16 @@ export class AIChatAgent<
1801
1749
  continuation
1802
1750
  );
1803
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
+
1804
1757
  while (true) {
1805
1758
  const { done, value } = await reader.read();
1806
1759
  if (done) {
1760
+ textPart.state = "done";
1761
+
1807
1762
  this._broadcastTextEvent(
1808
1763
  streamId,
1809
1764
  { type: "text-end", id },
@@ -1826,9 +1781,9 @@ export class AIChatAgent<
1826
1781
 
1827
1782
  const chunk = decoder.decode(value);
1828
1783
 
1829
- // Treat the entire chunk as a text delta to preserve exact formatting
1784
+ // Accumulate into the single text part to preserve exact formatting
1830
1785
  if (chunk.length > 0) {
1831
- message.parts.push({ type: "text", text: chunk });
1786
+ textPart.text += chunk;
1832
1787
  this._broadcastTextEvent(
1833
1788
  streamId,
1834
1789
  { type: "text-delta", id, delta: chunk },
@@ -1838,171 +1793,6 @@ export class AIChatAgent<
1838
1793
  }
1839
1794
  }
1840
1795
 
1841
- private updateDynamicToolPart(
1842
- message: ChatMessage,
1843
- options: {
1844
- toolName: string;
1845
- toolCallId: string;
1846
- providerExecuted?: boolean;
1847
- } & (
1848
- | {
1849
- state: "input-streaming";
1850
- input: unknown;
1851
- }
1852
- | {
1853
- state: "input-available";
1854
- input: unknown;
1855
- providerMetadata?: ProviderMetadata;
1856
- }
1857
- | {
1858
- state: "output-available";
1859
- input: unknown;
1860
- output: unknown;
1861
- preliminary: boolean | undefined;
1862
- }
1863
- | {
1864
- state: "output-error";
1865
- input: unknown;
1866
- errorText: string;
1867
- providerMetadata?: ProviderMetadata;
1868
- }
1869
- )
1870
- ) {
1871
- const part = message.parts.find(
1872
- (part) =>
1873
- part.type === "dynamic-tool" && part.toolCallId === options.toolCallId
1874
- ) as DynamicToolUIPart | undefined;
1875
-
1876
- const anyOptions = options as Record<string, unknown>;
1877
- const anyPart = part as Record<string, unknown>;
1878
-
1879
- if (part != null) {
1880
- part.state = options.state;
1881
- anyPart.toolName = options.toolName;
1882
- anyPart.input = anyOptions.input;
1883
- anyPart.output = anyOptions.output;
1884
- anyPart.errorText = anyOptions.errorText;
1885
- anyPart.rawInput = anyOptions.rawInput ?? anyPart.rawInput;
1886
- anyPart.preliminary = anyOptions.preliminary;
1887
-
1888
- if (
1889
- anyOptions.providerMetadata != null &&
1890
- part.state === "input-available"
1891
- ) {
1892
- part.callProviderMetadata =
1893
- anyOptions.providerMetadata as ProviderMetadata;
1894
- }
1895
- } else {
1896
- message.parts.push({
1897
- type: "dynamic-tool",
1898
- toolName: options.toolName,
1899
- toolCallId: options.toolCallId,
1900
- state: options.state,
1901
- input: anyOptions.input,
1902
- output: anyOptions.output,
1903
- errorText: anyOptions.errorText,
1904
- preliminary: anyOptions.preliminary,
1905
- ...(anyOptions.providerMetadata != null
1906
- ? { callProviderMetadata: anyOptions.providerMetadata }
1907
- : {})
1908
- } as DynamicToolUIPart);
1909
- }
1910
- }
1911
-
1912
- private async updateToolPart(
1913
- message: ChatMessage,
1914
- options: {
1915
- toolName: string;
1916
- toolCallId: string;
1917
- providerExecuted?: boolean;
1918
- } & (
1919
- | {
1920
- state: "input-streaming";
1921
- input: unknown;
1922
- providerExecuted?: boolean;
1923
- }
1924
- | {
1925
- state: "input-available";
1926
- input: unknown;
1927
- providerExecuted?: boolean;
1928
- providerMetadata?: ProviderMetadata;
1929
- }
1930
- | {
1931
- state: "output-available";
1932
- input: unknown;
1933
- output: unknown;
1934
- providerExecuted?: boolean;
1935
- preliminary?: boolean;
1936
- }
1937
- | {
1938
- state: "output-error";
1939
- input: unknown;
1940
- rawInput?: unknown;
1941
- errorText: string;
1942
- providerExecuted?: boolean;
1943
- providerMetadata?: ProviderMetadata;
1944
- }
1945
- )
1946
- ) {
1947
- const { isToolUIPart } = await import("ai");
1948
-
1949
- const part = message.parts.find(
1950
- (part) =>
1951
- isToolUIPart(part) &&
1952
- (part as ToolUIPart).toolCallId === options.toolCallId
1953
- ) as ToolUIPart | undefined;
1954
-
1955
- const anyOptions = options as Record<string, unknown>;
1956
- const anyPart = part as Record<string, unknown>;
1957
-
1958
- if (part != null) {
1959
- part.state = options.state;
1960
- anyPart.input = anyOptions.input;
1961
- anyPart.output = anyOptions.output;
1962
- anyPart.errorText = anyOptions.errorText;
1963
- anyPart.rawInput = anyOptions.rawInput;
1964
- anyPart.preliminary = anyOptions.preliminary;
1965
-
1966
- // once providerExecuted is set, it stays for streaming
1967
- anyPart.providerExecuted =
1968
- anyOptions.providerExecuted ?? part.providerExecuted;
1969
-
1970
- if (
1971
- anyOptions.providerMetadata != null &&
1972
- part.state === "input-available"
1973
- ) {
1974
- part.callProviderMetadata =
1975
- anyOptions.providerMetadata as ProviderMetadata;
1976
- }
1977
- } else {
1978
- message.parts.push({
1979
- type: `tool-${options.toolName}`,
1980
- toolCallId: options.toolCallId,
1981
- state: options.state,
1982
- input: anyOptions.input,
1983
- output: anyOptions.output,
1984
- rawInput: anyOptions.rawInput,
1985
- errorText: anyOptions.errorText,
1986
- providerExecuted: anyOptions.providerExecuted,
1987
- preliminary: anyOptions.preliminary,
1988
- ...(anyOptions.providerMetadata != null
1989
- ? { callProviderMetadata: anyOptions.providerMetadata }
1990
- : {})
1991
- } as ToolUIPart);
1992
- }
1993
- }
1994
-
1995
- private async updateMessageMetadata(message: ChatMessage, metadata: unknown) {
1996
- if (metadata != null) {
1997
- const mergedMetadata =
1998
- message.metadata != null
1999
- ? { ...message.metadata, ...metadata } // TODO: do proper merging
2000
- : metadata;
2001
-
2002
- message.metadata = mergedMetadata;
2003
- }
2004
- }
2005
-
2006
1796
  /**
2007
1797
  * Applies a tool approval response from the client, updating the persisted message.
2008
1798
  * This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
@@ -2016,138 +1806,31 @@ export class AIChatAgent<
2016
1806
  toolCallId: string,
2017
1807
  approved: boolean
2018
1808
  ): Promise<boolean> {
2019
- // Find the message with this tool call.
2020
- // We check two locations:
2021
- // 1. _streamingMessage: in-memory message being actively built during AI response
2022
- // (not yet persisted to SQLite or available in this.messages)
2023
- // 2. this.messages: persisted messages loaded from SQLite database
2024
- //
2025
- // The user can approve before streaming finishes (e.g., approval UI appears
2026
- // while AI is still generating text), so we must check _streamingMessage first.
2027
-
2028
- let message: ChatMessage | undefined;
2029
-
2030
- // Check streaming message first (in-memory, not yet persisted)
2031
- if (this._streamingMessage) {
2032
- for (const part of this._streamingMessage.parts) {
2033
- if ("toolCallId" in part && part.toolCallId === toolCallId) {
2034
- message = this._streamingMessage;
2035
- break;
2036
- }
2037
- }
2038
- }
2039
-
2040
- // If not found in streaming message, check persisted messages (in SQLite).
2041
- // Retry with backoff in case streaming completes and persists between attempts.
2042
- if (!message) {
2043
- for (let attempt = 0; attempt < 10; attempt++) {
2044
- message = this._findMessageByToolCallId(toolCallId);
2045
- if (message) break;
2046
- await new Promise((resolve) => setTimeout(resolve, 100));
2047
- }
2048
- }
2049
-
2050
- if (!message) {
2051
- console.warn(
2052
- `[AIChatAgent] _applyToolApproval: Could not find message with toolCallId ${toolCallId} after retries`
2053
- );
2054
- return false;
2055
- }
2056
-
2057
- // Check if this is the streaming message (not yet persisted)
2058
- const isStreamingMessage = message === this._streamingMessage;
2059
-
2060
- // Update the tool part with the approval
2061
- let updated = false;
2062
- if (isStreamingMessage) {
2063
- // Update in place - the message will be persisted when streaming completes
2064
- for (const part of message.parts) {
2065
- if (
2066
- "toolCallId" in part &&
2067
- part.toolCallId === toolCallId &&
2068
- "state" in part &&
2069
- (part.state === "input-available" ||
2070
- part.state === "approval-requested")
2071
- ) {
2072
- (part as { state: string; approval?: { approved: boolean } }).state =
2073
- "approval-responded";
2074
- (
2075
- part as { state: string; approval?: { approved: boolean } }
2076
- ).approval = { approved };
2077
- updated = true;
2078
- 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
2079
1822
  }
2080
- }
2081
- } else {
2082
- // For persisted messages, create updated parts
2083
- const updatedParts = message.parts.map((part) => {
2084
- if (
2085
- "toolCallId" in part &&
2086
- part.toolCallId === toolCallId &&
2087
- "state" in part &&
2088
- (part.state === "input-available" ||
2089
- part.state === "approval-requested")
2090
- ) {
2091
- updated = true;
2092
- return {
2093
- ...part,
2094
- state: "approval-responded" as const,
2095
- approval: { approved }
2096
- };
2097
- }
2098
- return part;
2099
- }) as ChatMessage["parts"];
2100
-
2101
- if (updated) {
2102
- // Create the updated message and strip OpenAI item IDs
2103
- const updatedMessage: ChatMessage = this._sanitizeMessageForPersistence(
2104
- {
2105
- ...message,
2106
- parts: updatedParts
2107
- }
2108
- );
2109
-
2110
- // Persist the updated message
2111
- this.sql`
2112
- update cf_ai_chat_agent_messages
2113
- set message = ${JSON.stringify(updatedMessage)}
2114
- where id = ${message.id}
2115
- `;
2116
-
2117
- // Reload messages to update in-memory state
2118
- const persisted = this._loadMessagesFromDb();
2119
- this.messages = autoTransformMessages(persisted);
2120
- }
2121
- }
2122
-
2123
- if (!updated) {
2124
- console.warn(
2125
- `[AIChatAgent] _applyToolApproval: Tool part with toolCallId ${toolCallId} not in input-available or approval-requested state`
2126
- );
2127
- return false;
2128
- }
2129
-
2130
- // Broadcast the update to all clients (only for persisted messages)
2131
- if (!isStreamingMessage) {
2132
- const broadcastMessage = this._findMessageByToolCallId(toolCallId);
2133
- if (broadcastMessage) {
2134
- this._broadcastChatMessage({
2135
- type: MessageType.CF_AGENT_MESSAGE_UPDATED,
2136
- message: broadcastMessage
2137
- });
2138
- }
2139
- }
2140
-
2141
- return true;
1823
+ })
1824
+ );
2142
1825
  }
2143
1826
 
2144
1827
  private async _reply(
2145
1828
  id: string,
2146
1829
  response: Response,
2147
1830
  excludeBroadcastIds: string[] = [],
2148
- options: { continuation?: boolean } = {}
1831
+ options: { continuation?: boolean; chatMessageId?: string } = {}
2149
1832
  ) {
2150
- const { continuation = false } = options;
1833
+ const { continuation = false, chatMessageId } = options;
2151
1834
 
2152
1835
  return this._tryCatchChat(async () => {
2153
1836
  if (!response.body) {
@@ -2185,6 +1868,10 @@ export class AIChatAgent<
2185
1868
  const contentType = response.headers.get("content-type") || "";
2186
1869
  const isSSE = contentType.includes("text/event-stream"); // AI SDK v5 SSE format
2187
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;
2188
1875
 
2189
1876
  try {
2190
1877
  if (isSSE) {
@@ -2224,10 +1911,55 @@ export class AIChatAgent<
2224
1911
  throw error;
2225
1912
  } finally {
2226
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
+ }
2227
1948
  }
2228
1949
 
2229
1950
  if (message.parts.length > 0) {
2230
- 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) {
2231
1963
  // Find the last assistant message and append parts to it
2232
1964
  let lastAssistantIdx = -1;
2233
1965
  for (let i = this.messages.length - 1; i >= 0; i--) {
@@ -2259,36 +1991,9 @@ export class AIChatAgent<
2259
1991
  );
2260
1992
  }
2261
1993
  }
2262
-
2263
- // Clear the streaming message reference and resolve completion promise
2264
- this._streamingMessage = null;
2265
- if (this._streamCompletionResolve) {
2266
- this._streamCompletionResolve();
2267
- this._streamCompletionResolve = null;
2268
- this._streamCompletionPromise = null;
2269
- }
2270
1994
  });
2271
1995
  }
2272
1996
 
2273
- /**
2274
- * Mark a stream as errored and clean up state.
2275
- * @param streamId - The stream to mark as errored
2276
- * @internal Protected for testing purposes.
2277
- */
2278
- protected _markStreamError(streamId: string) {
2279
- // Flush any pending chunks before marking error
2280
- this._flushChunkBuffer();
2281
-
2282
- this.sql`
2283
- update cf_ai_chat_stream_metadata
2284
- set status = 'error', completed_at = ${Date.now()}
2285
- where id = ${streamId}
2286
- `;
2287
- this._activeStreamId = null;
2288
- this._activeRequestId = null;
2289
- this._streamChunkIndex = 0;
2290
- }
2291
-
2292
1997
  /**
2293
1998
  * For the given message id, look up its associated AbortController
2294
1999
  * If the AbortController does not exist, create and store one in memory
@@ -2340,18 +2045,7 @@ export class AIChatAgent<
2340
2045
  */
2341
2046
  async destroy() {
2342
2047
  this._destroyAbortControllers();
2343
-
2344
- // Flush any remaining chunks before cleanup
2345
- this._flushChunkBuffer();
2346
-
2347
- // Clean up stream tables
2348
- this.sql`drop table if exists cf_ai_chat_stream_chunks`;
2349
- this.sql`drop table if exists cf_ai_chat_stream_metadata`;
2350
-
2351
- // Clear active stream state
2352
- this._activeStreamId = null;
2353
- this._activeRequestId = null;
2354
-
2048
+ this._resumableStream.destroy();
2355
2049
  await super.destroy();
2356
2050
  }
2357
2051
  }