@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/dist/index.js CHANGED
@@ -1,11 +1,326 @@
1
1
  import { MessageType } from "./types.js";
2
2
  import { autoTransformMessages } from "./ai-chat-v5-migration.js";
3
+ import { t as applyChunkToParts } from "./message-builder-Bwc_Umye.js";
3
4
  import { jsonSchema, tool } from "ai";
4
- import { Agent } from "agents";
5
+ import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
5
6
  import { nanoid } from "nanoid";
6
- import { agentContext } from "agents/internal_context";
7
7
 
8
+ //#region src/resumable-stream.ts
9
+ /**
10
+ * ResumableStream: Standalone class for buffering, persisting, and replaying
11
+ * stream chunks in SQLite. Extracted from AIChatAgent to separate concerns.
12
+ *
13
+ * Handles:
14
+ * - Chunk buffering (batched writes to SQLite for performance)
15
+ * - Stream lifecycle (start, complete, error)
16
+ * - Chunk replay for reconnecting clients
17
+ * - Stale stream cleanup
18
+ * - Active stream restoration after agent restart
19
+ */
20
+ /** Number of chunks to buffer before flushing to SQLite */
21
+ const CHUNK_BUFFER_SIZE = 10;
22
+ /** Maximum buffer size to prevent memory issues on rapid reconnections */
23
+ const CHUNK_BUFFER_MAX_SIZE = 100;
24
+ /** Maximum age for a "streaming" stream before considering it stale (ms) - 5 minutes */
25
+ const STREAM_STALE_THRESHOLD_MS = 300 * 1e3;
26
+ /** Default cleanup interval for old streams (ms) - every 10 minutes */
27
+ const CLEANUP_INTERVAL_MS = 600 * 1e3;
28
+ /** Default age threshold for cleaning up completed streams (ms) - 24 hours */
29
+ const CLEANUP_AGE_THRESHOLD_MS = 1440 * 60 * 1e3;
30
+ /** Shared encoder for UTF-8 byte length measurement */
31
+ const textEncoder$1 = new TextEncoder();
32
+ var ResumableStream = class ResumableStream {
33
+ constructor(sql) {
34
+ this.sql = sql;
35
+ this._activeStreamId = null;
36
+ this._activeRequestId = null;
37
+ this._streamChunkIndex = 0;
38
+ this._chunkBuffer = [];
39
+ this._isFlushingChunks = false;
40
+ this._lastCleanupTime = 0;
41
+ this.sql`create table if not exists cf_ai_chat_stream_chunks (
42
+ id text primary key,
43
+ stream_id text not null,
44
+ body text not null,
45
+ chunk_index integer not null,
46
+ created_at integer not null
47
+ )`;
48
+ this.sql`create table if not exists cf_ai_chat_stream_metadata (
49
+ id text primary key,
50
+ request_id text not null,
51
+ status text not null,
52
+ created_at integer not null,
53
+ completed_at integer
54
+ )`;
55
+ this.sql`create index if not exists idx_stream_chunks_stream_id
56
+ on cf_ai_chat_stream_chunks(stream_id, chunk_index)`;
57
+ this.restore();
58
+ }
59
+ get activeStreamId() {
60
+ return this._activeStreamId;
61
+ }
62
+ get activeRequestId() {
63
+ return this._activeRequestId;
64
+ }
65
+ hasActiveStream() {
66
+ return this._activeStreamId !== null;
67
+ }
68
+ /**
69
+ * Start tracking a new stream for resumable streaming.
70
+ * Creates metadata entry in SQLite and sets up tracking state.
71
+ * @param requestId - The unique ID of the chat request
72
+ * @returns The generated stream ID
73
+ */
74
+ start(requestId) {
75
+ this.flushBuffer();
76
+ const streamId = nanoid();
77
+ this._activeStreamId = streamId;
78
+ this._activeRequestId = requestId;
79
+ this._streamChunkIndex = 0;
80
+ this.sql`
81
+ insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
82
+ values (${streamId}, ${requestId}, 'streaming', ${Date.now()})
83
+ `;
84
+ return streamId;
85
+ }
86
+ /**
87
+ * Mark a stream as completed and flush any pending chunks.
88
+ * @param streamId - The stream to mark as completed
89
+ */
90
+ complete(streamId) {
91
+ this.flushBuffer();
92
+ this.sql`
93
+ update cf_ai_chat_stream_metadata
94
+ set status = 'completed', completed_at = ${Date.now()}
95
+ where id = ${streamId}
96
+ `;
97
+ this._activeStreamId = null;
98
+ this._activeRequestId = null;
99
+ this._streamChunkIndex = 0;
100
+ this._maybeCleanupOldStreams();
101
+ }
102
+ /**
103
+ * Mark a stream as errored and clean up state.
104
+ * @param streamId - The stream to mark as errored
105
+ */
106
+ markError(streamId) {
107
+ this.flushBuffer();
108
+ this.sql`
109
+ update cf_ai_chat_stream_metadata
110
+ set status = 'error', completed_at = ${Date.now()}
111
+ where id = ${streamId}
112
+ `;
113
+ this._activeStreamId = null;
114
+ this._activeRequestId = null;
115
+ this._streamChunkIndex = 0;
116
+ }
117
+ static {
118
+ this.CHUNK_MAX_BYTES = 18e5;
119
+ }
120
+ /**
121
+ * Buffer a stream chunk for batch write to SQLite.
122
+ * Chunks exceeding the row size limit are skipped to prevent crashes.
123
+ * The chunk is still broadcast to live clients (caller handles that),
124
+ * but will be missing from replay on reconnection.
125
+ * @param streamId - The stream this chunk belongs to
126
+ * @param body - The serialized chunk body
127
+ */
128
+ storeChunk(streamId, body) {
129
+ const bodyBytes = textEncoder$1.encode(body).byteLength;
130
+ if (bodyBytes > ResumableStream.CHUNK_MAX_BYTES) {
131
+ console.warn(`[ResumableStream] Skipping oversized chunk (${bodyBytes} bytes) to prevent SQLite row limit crash. Live clients still receive it.`);
132
+ return;
133
+ }
134
+ if (this._chunkBuffer.length >= CHUNK_BUFFER_MAX_SIZE) this.flushBuffer();
135
+ this._chunkBuffer.push({
136
+ id: nanoid(),
137
+ streamId,
138
+ body,
139
+ index: this._streamChunkIndex
140
+ });
141
+ this._streamChunkIndex++;
142
+ if (this._chunkBuffer.length >= CHUNK_BUFFER_SIZE) this.flushBuffer();
143
+ }
144
+ /**
145
+ * Flush buffered chunks to SQLite in a single batch.
146
+ * Uses a lock to prevent concurrent flush operations.
147
+ */
148
+ flushBuffer() {
149
+ if (this._isFlushingChunks || this._chunkBuffer.length === 0) return;
150
+ this._isFlushingChunks = true;
151
+ try {
152
+ const chunks = this._chunkBuffer;
153
+ this._chunkBuffer = [];
154
+ const now = Date.now();
155
+ for (const chunk of chunks) this.sql`
156
+ insert into cf_ai_chat_stream_chunks (id, stream_id, body, chunk_index, created_at)
157
+ values (${chunk.id}, ${chunk.streamId}, ${chunk.body}, ${chunk.index}, ${now})
158
+ `;
159
+ } finally {
160
+ this._isFlushingChunks = false;
161
+ }
162
+ }
163
+ /**
164
+ * Send stored stream chunks to a connection for replay.
165
+ * Chunks are marked with replay: true so the client can batch-apply them.
166
+ * @param connection - The WebSocket connection
167
+ * @param requestId - The original request ID
168
+ */
169
+ replayChunks(connection, requestId) {
170
+ const streamId = this._activeStreamId;
171
+ if (!streamId) return;
172
+ this.flushBuffer();
173
+ const chunks = this.sql`
174
+ select * from cf_ai_chat_stream_chunks
175
+ where stream_id = ${streamId}
176
+ order by chunk_index asc
177
+ `;
178
+ for (const chunk of chunks || []) connection.send(JSON.stringify({
179
+ body: chunk.body,
180
+ done: false,
181
+ id: requestId,
182
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
183
+ replay: true
184
+ }));
185
+ if (this._activeStreamId !== streamId) connection.send(JSON.stringify({
186
+ body: "",
187
+ done: true,
188
+ id: requestId,
189
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
190
+ replay: true
191
+ }));
192
+ }
193
+ /**
194
+ * Restore active stream state if the agent was restarted during streaming.
195
+ * Validates stream freshness to avoid sending stale resume notifications.
196
+ */
197
+ restore() {
198
+ const activeStreams = this.sql`
199
+ select * from cf_ai_chat_stream_metadata
200
+ where status = 'streaming'
201
+ order by created_at desc
202
+ limit 1
203
+ `;
204
+ if (activeStreams && activeStreams.length > 0) {
205
+ const stream = activeStreams[0];
206
+ const streamAge = Date.now() - stream.created_at;
207
+ if (streamAge > STREAM_STALE_THRESHOLD_MS) {
208
+ this.sql`delete from cf_ai_chat_stream_chunks where stream_id = ${stream.id}`;
209
+ this.sql`delete from cf_ai_chat_stream_metadata where id = ${stream.id}`;
210
+ console.warn(`[ResumableStream] Deleted stale stream ${stream.id} (age: ${Math.round(streamAge / 1e3)}s)`);
211
+ return;
212
+ }
213
+ this._activeStreamId = stream.id;
214
+ this._activeRequestId = stream.request_id;
215
+ const lastChunk = this.sql`
216
+ select max(chunk_index) as max_index
217
+ from cf_ai_chat_stream_chunks
218
+ where stream_id = ${this._activeStreamId}
219
+ `;
220
+ this._streamChunkIndex = lastChunk && lastChunk[0]?.max_index != null ? lastChunk[0].max_index + 1 : 0;
221
+ }
222
+ }
223
+ /**
224
+ * Clear all stream data (called on chat history clear).
225
+ */
226
+ clearAll() {
227
+ this._chunkBuffer = [];
228
+ this.sql`delete from cf_ai_chat_stream_chunks`;
229
+ this.sql`delete from cf_ai_chat_stream_metadata`;
230
+ this._activeStreamId = null;
231
+ this._activeRequestId = null;
232
+ this._streamChunkIndex = 0;
233
+ }
234
+ /**
235
+ * Drop all stream tables (called on destroy).
236
+ */
237
+ destroy() {
238
+ this.flushBuffer();
239
+ this.sql`drop table if exists cf_ai_chat_stream_chunks`;
240
+ this.sql`drop table if exists cf_ai_chat_stream_metadata`;
241
+ this._activeStreamId = null;
242
+ this._activeRequestId = null;
243
+ }
244
+ _maybeCleanupOldStreams() {
245
+ const now = Date.now();
246
+ if (now - this._lastCleanupTime < CLEANUP_INTERVAL_MS) return;
247
+ this._lastCleanupTime = now;
248
+ const cutoff = now - CLEANUP_AGE_THRESHOLD_MS;
249
+ this.sql`
250
+ delete from cf_ai_chat_stream_chunks
251
+ where stream_id in (
252
+ select id from cf_ai_chat_stream_metadata
253
+ where status in ('completed', 'error') and completed_at < ${cutoff}
254
+ )
255
+ `;
256
+ this.sql`
257
+ delete from cf_ai_chat_stream_metadata
258
+ where status in ('completed', 'error') and completed_at < ${cutoff}
259
+ `;
260
+ }
261
+ /** @internal For testing only */
262
+ getStreamChunks(streamId) {
263
+ return this.sql`
264
+ select body, chunk_index from cf_ai_chat_stream_chunks
265
+ where stream_id = ${streamId}
266
+ order by chunk_index asc
267
+ ` || [];
268
+ }
269
+ /** @internal For testing only */
270
+ getStreamMetadata(streamId) {
271
+ const result = this.sql`
272
+ select status, request_id from cf_ai_chat_stream_metadata
273
+ where id = ${streamId}
274
+ `;
275
+ return result && result.length > 0 ? result[0] : null;
276
+ }
277
+ /** @internal For testing only */
278
+ getAllStreamMetadata() {
279
+ return this.sql`select id, status, request_id, created_at from cf_ai_chat_stream_metadata` || [];
280
+ }
281
+ /** @internal For testing only */
282
+ insertStaleStream(streamId, requestId, ageMs) {
283
+ const createdAt = Date.now() - ageMs;
284
+ this.sql`
285
+ insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
286
+ values (${streamId}, ${requestId}, 'streaming', ${createdAt})
287
+ `;
288
+ }
289
+ };
290
+
291
+ //#endregion
8
292
  //#region src/index.ts
293
+ /** Shared encoder for UTF-8 byte length measurement */
294
+ const textEncoder = new TextEncoder();
295
+ /**
296
+ * Validates that a parsed message has the minimum required structure.
297
+ * Returns false for messages that would cause runtime errors downstream
298
+ * (e.g. in convertToModelMessages or the UI layer).
299
+ *
300
+ * Checks:
301
+ * - `id` is a non-empty string
302
+ * - `role` is one of the valid roles
303
+ * - `parts` is an array (may be empty — the AI SDK enforces nonempty
304
+ * on incoming messages, but we are lenient on persisted data)
305
+ */
306
+ function isValidMessageStructure(msg) {
307
+ if (typeof msg !== "object" || msg === null) return false;
308
+ const m = msg;
309
+ if (typeof m.id !== "string" || m.id.length === 0) return false;
310
+ if (m.role !== "user" && m.role !== "assistant" && m.role !== "system") return false;
311
+ if (!Array.isArray(m.parts)) return false;
312
+ return true;
313
+ }
314
+ /**
315
+ * One-shot deprecation warnings (warns once per key per session).
316
+ */
317
+ const _deprecationWarnings = /* @__PURE__ */ new Set();
318
+ function warnDeprecated(id, message) {
319
+ if (!_deprecationWarnings.has(id)) {
320
+ _deprecationWarnings.add(id);
321
+ console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);
322
+ }
323
+ }
9
324
  /**
10
325
  * Converts client tool schemas to AI SDK tool format.
11
326
  *
@@ -42,6 +357,7 @@ import { agentContext } from "agents/internal_context";
42
357
  * ```
43
358
  */
44
359
  function createToolsFromClientSchemas(clientTools) {
360
+ warnDeprecated("createToolsFromClientSchemas", "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.");
45
361
  if (!clientTools || clientTools.length === 0) return {};
46
362
  const seenNames = /* @__PURE__ */ new Set();
47
363
  for (const t of clientTools) {
@@ -53,61 +369,44 @@ function createToolsFromClientSchemas(clientTools) {
53
369
  inputSchema: jsonSchema(t.parameters ?? { type: "object" })
54
370
  })]));
55
371
  }
56
- /** Number of chunks to buffer before flushing to SQLite */
57
- const CHUNK_BUFFER_SIZE = 10;
58
- /** Maximum buffer size to prevent memory issues on rapid reconnections */
59
- const CHUNK_BUFFER_MAX_SIZE = 100;
60
- /** Maximum age for a "streaming" stream before considering it stale (ms) - 5 minutes */
61
- const STREAM_STALE_THRESHOLD_MS = 300 * 1e3;
62
- /** Default cleanup interval for old streams (ms) - every 10 minutes */
63
- const CLEANUP_INTERVAL_MS = 600 * 1e3;
64
- /** Default age threshold for cleaning up completed streams (ms) - 24 hours */
65
- const CLEANUP_AGE_THRESHOLD_MS = 1440 * 60 * 1e3;
66
372
  const decoder = new TextDecoder();
67
373
  /**
68
374
  * Extension of Agent with built-in chat capabilities
69
375
  * @template Env Environment type containing bindings
70
376
  */
71
- var AIChatAgent = class extends Agent {
377
+ var AIChatAgent = class AIChatAgent extends Agent {
378
+ static {
379
+ this.ROW_MAX_BYTES = 18e5;
380
+ }
381
+ /** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
382
+ static _byteLength(s) {
383
+ return textEncoder.encode(s).byteLength;
384
+ }
72
385
  constructor(ctx, env) {
73
386
  super(ctx, env);
74
- this._activeStreamId = null;
75
- this._activeRequestId = null;
76
387
  this._streamingMessage = null;
388
+ this._approvalPersistedMessageId = null;
77
389
  this._streamCompletionPromise = null;
78
390
  this._streamCompletionResolve = null;
79
- this._streamChunkIndex = 0;
80
- this._chunkBuffer = [];
81
- this._isFlushingChunks = false;
82
- this._lastCleanupTime = 0;
83
391
  this._pendingResumeConnections = /* @__PURE__ */ new Set();
392
+ this._persistedMessageCache = /* @__PURE__ */ new Map();
393
+ this.maxPersistedMessages = void 0;
84
394
  this.sql`create table if not exists cf_ai_chat_agent_messages (
85
395
  id text primary key,
86
396
  message text not null,
87
397
  created_at datetime default current_timestamp
88
398
  )`;
89
- this.sql`create table if not exists cf_ai_chat_stream_chunks (
90
- id text primary key,
91
- stream_id text not null,
92
- body text not null,
93
- chunk_index integer not null,
94
- created_at integer not null
95
- )`;
96
- this.sql`create table if not exists cf_ai_chat_stream_metadata (
97
- id text primary key,
98
- request_id text not null,
99
- status text not null,
100
- created_at integer not null,
101
- completed_at integer
399
+ this.sql`create table if not exists cf_ai_chat_request_context (
400
+ key text primary key,
401
+ value text not null
102
402
  )`;
103
- this.sql`create index if not exists idx_stream_chunks_stream_id
104
- on cf_ai_chat_stream_chunks(stream_id, chunk_index)`;
403
+ this._restoreRequestContext();
404
+ this._resumableStream = new ResumableStream(this.sql.bind(this));
105
405
  this.messages = autoTransformMessages(this._loadMessagesFromDb());
106
406
  this._chatMessageAbortControllers = /* @__PURE__ */ new Map();
107
- this._restoreActiveStream();
108
407
  const _onConnect = this.onConnect.bind(this);
109
408
  this.onConnect = async (connection, ctx) => {
110
- if (this._activeStreamId) this._notifyStreamResuming(connection);
409
+ if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
111
410
  return _onConnect(connection, ctx);
112
411
  };
113
412
  const _onClose = this.onClose.bind(this);
@@ -126,7 +425,21 @@ var AIChatAgent = class extends Agent {
126
425
  }
127
426
  if (data.type === MessageType.CF_AGENT_USE_CHAT_REQUEST && data.init.method === "POST") {
128
427
  const { body } = data.init;
129
- const { messages, clientTools } = JSON.parse(body);
428
+ if (!body) {
429
+ console.warn("[AIChatAgent] Received chat request with empty body, ignoring");
430
+ return;
431
+ }
432
+ let parsed;
433
+ try {
434
+ parsed = JSON.parse(body);
435
+ } catch (_parseError) {
436
+ console.warn("[AIChatAgent] Received chat request with invalid JSON body, ignoring");
437
+ return;
438
+ }
439
+ const { messages, clientTools, ...customBody } = parsed;
440
+ this._lastClientTools = clientTools?.length ? clientTools : void 0;
441
+ this._lastBody = Object.keys(customBody).length > 0 ? customBody : void 0;
442
+ this._persistRequestContext();
130
443
  const transformedMessages = autoTransformMessages(messages);
131
444
  this._broadcastChatMessage({
132
445
  messages: transformedMessages,
@@ -143,26 +456,18 @@ var AIChatAgent = class extends Agent {
143
456
  const chatMessageId = data.id;
144
457
  const abortSignal = this._getAbortSignal(chatMessageId);
145
458
  return this._tryCatchChat(async () => {
146
- return agentContext.run({
459
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
147
460
  agent: this,
148
461
  connection,
149
462
  request: void 0,
150
463
  email: void 0
151
464
  }, async () => {
152
- const response = await this.onChatMessage(async (_finishResult) => {
153
- this._removeAbortController(chatMessageId);
154
- this.observability?.emit({
155
- displayMessage: "Chat message response",
156
- id: data.id,
157
- payload: {},
158
- timestamp: Date.now(),
159
- type: "message:response"
160
- }, this.ctx);
161
- }, {
465
+ const response = await this.onChatMessage(async (_finishResult) => {}, {
162
466
  abortSignal,
163
- clientTools
467
+ clientTools,
468
+ body: this._lastBody
164
469
  });
165
- if (response) await this._reply(data.id, response, [connection.id]);
470
+ if (response) await this._reply(data.id, response, [connection.id], { chatMessageId });
166
471
  else {
167
472
  console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
168
473
  this._broadcastChatMessage({
@@ -178,12 +483,12 @@ var AIChatAgent = class extends Agent {
178
483
  if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
179
484
  this._destroyAbortControllers();
180
485
  this.sql`delete from cf_ai_chat_agent_messages`;
181
- this.sql`delete from cf_ai_chat_stream_chunks`;
182
- this.sql`delete from cf_ai_chat_stream_metadata`;
183
- this._activeStreamId = null;
184
- this._activeRequestId = null;
185
- this._streamChunkIndex = 0;
486
+ this._resumableStream.clearAll();
186
487
  this._pendingResumeConnections.clear();
488
+ this._lastClientTools = void 0;
489
+ this._lastBody = void 0;
490
+ this._persistRequestContext();
491
+ this._persistedMessageCache.clear();
187
492
  this.messages = [];
188
493
  this._broadcastChatMessage({ type: MessageType.CF_AGENT_CHAT_CLEAR }, [connection.id]);
189
494
  return;
@@ -197,13 +502,21 @@ var AIChatAgent = class extends Agent {
197
502
  this._cancelChatRequest(data.id);
198
503
  return;
199
504
  }
505
+ if (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {
506
+ if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
507
+ return;
508
+ }
200
509
  if (data.type === MessageType.CF_AGENT_STREAM_RESUME_ACK) {
201
510
  this._pendingResumeConnections.delete(connection.id);
202
- if (this._activeStreamId && this._activeRequestId && this._activeRequestId === data.id) this._sendStreamChunks(connection, this._activeStreamId, this._activeRequestId);
511
+ if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
203
512
  return;
204
513
  }
205
514
  if (data.type === MessageType.CF_AGENT_TOOL_RESULT) {
206
- const { toolCallId, toolName, output, autoContinue } = data;
515
+ const { toolCallId, toolName, output, autoContinue, clientTools } = data;
516
+ if (clientTools?.length) {
517
+ this._lastClientTools = clientTools;
518
+ this._persistRequestContext();
519
+ }
207
520
  this._applyToolResult(toolCallId, toolName, output).then((applied) => {
208
521
  if (applied && autoContinue) {
209
522
  const waitForStream = async () => {
@@ -213,206 +526,147 @@ var AIChatAgent = class extends Agent {
213
526
  waitForStream().then(() => {
214
527
  const continuationId = nanoid();
215
528
  const abortSignal = this._getAbortSignal(continuationId);
216
- this._tryCatchChat(async () => {
217
- return agentContext.run({
529
+ return this._tryCatchChat(async () => {
530
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
218
531
  agent: this,
219
532
  connection,
220
533
  request: void 0,
221
534
  email: void 0
222
535
  }, async () => {
223
- const response = await this.onChatMessage(async (_finishResult) => {
224
- this._removeAbortController(continuationId);
225
- this.observability?.emit({
226
- displayMessage: "Chat message response (tool continuation)",
227
- id: continuationId,
228
- payload: {},
229
- timestamp: Date.now(),
230
- type: "message:response"
231
- }, this.ctx);
232
- }, { abortSignal });
233
- if (response) await this._reply(continuationId, response, [], { continuation: true });
536
+ const response = await this.onChatMessage(async (_finishResult) => {}, {
537
+ abortSignal,
538
+ clientTools: clientTools ?? this._lastClientTools,
539
+ body: this._lastBody
540
+ });
541
+ if (response) await this._reply(continuationId, response, [], {
542
+ continuation: true,
543
+ chatMessageId: continuationId
544
+ });
234
545
  });
235
546
  });
547
+ }).catch((error) => {
548
+ console.error("[AIChatAgent] Tool continuation failed:", error);
236
549
  });
237
550
  }
238
551
  });
239
552
  return;
240
553
  }
241
554
  if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
242
- const { toolCallId, approved } = data;
243
- this._applyToolApproval(toolCallId, approved);
244
- return;
245
- }
246
- }
247
- return _onMessage(connection, message);
248
- };
249
- }
250
- /**
251
- * Restore active stream state if the agent was restarted during streaming.
252
- * Called during construction to recover any interrupted streams.
253
- * Validates stream freshness to avoid sending stale resume notifications.
254
- * @internal Protected for testing purposes.
255
- */
256
- _restoreActiveStream() {
257
- const activeStreams = this.sql`
258
- select * from cf_ai_chat_stream_metadata
259
- where status = 'streaming'
260
- order by created_at desc
261
- limit 1
262
- `;
263
- if (activeStreams && activeStreams.length > 0) {
264
- const stream = activeStreams[0];
265
- const streamAge = Date.now() - stream.created_at;
266
- if (streamAge > STREAM_STALE_THRESHOLD_MS) {
267
- this.sql`delete from cf_ai_chat_stream_chunks where stream_id = ${stream.id}`;
268
- this.sql`delete from cf_ai_chat_stream_metadata where id = ${stream.id}`;
269
- console.warn(`[AIChatAgent] Deleted stale stream ${stream.id} (age: ${Math.round(streamAge / 1e3)}s)`);
270
- return;
271
- }
272
- this._activeStreamId = stream.id;
273
- this._activeRequestId = stream.request_id;
274
- const lastChunk = this.sql`
275
- select max(chunk_index) as max_index
276
- from cf_ai_chat_stream_chunks
277
- where stream_id = ${this._activeStreamId}
278
- `;
279
- this._streamChunkIndex = lastChunk && lastChunk[0]?.max_index != null ? lastChunk[0].max_index + 1 : 0;
280
- }
281
- }
282
- /**
283
- * Notify a connection about an active stream that can be resumed.
284
- * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
285
- * Uses in-memory state for request ID - no extra DB lookup needed.
286
- * @param connection - The WebSocket connection to notify
287
- */
288
- _notifyStreamResuming(connection) {
289
- if (!this._activeStreamId || !this._activeRequestId) return;
290
- this._pendingResumeConnections.add(connection.id);
291
- connection.send(JSON.stringify({
292
- type: MessageType.CF_AGENT_STREAM_RESUMING,
293
- id: this._activeRequestId
294
- }));
295
- }
296
- /**
297
- * Send stream chunks to a connection after receiving ACK.
298
- * @param connection - The WebSocket connection
299
- * @param streamId - The stream to replay
300
- * @param requestId - The original request ID
301
- */
302
- _sendStreamChunks(connection, streamId, requestId) {
303
- this._flushChunkBuffer();
304
- const chunks = this.sql`
305
- select * from cf_ai_chat_stream_chunks
306
- where stream_id = ${streamId}
307
- order by chunk_index asc
308
- `;
309
- for (const chunk of chunks || []) connection.send(JSON.stringify({
310
- body: chunk.body,
311
- done: false,
312
- id: requestId,
313
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
314
- }));
315
- if (this._activeStreamId !== streamId) connection.send(JSON.stringify({
316
- body: "",
317
- done: true,
318
- id: requestId,
319
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
320
- }));
321
- }
322
- /**
323
- * Buffer a stream chunk for batch write to SQLite.
324
- * @param streamId - The stream this chunk belongs to
325
- * @param body - The serialized chunk body
326
- * @internal Protected for testing purposes.
327
- */
328
- _storeStreamChunk(streamId, body) {
329
- if (this._chunkBuffer.length >= CHUNK_BUFFER_MAX_SIZE) this._flushChunkBuffer();
330
- this._chunkBuffer.push({
331
- id: nanoid(),
332
- streamId,
333
- body,
334
- index: this._streamChunkIndex
335
- });
336
- this._streamChunkIndex++;
337
- if (this._chunkBuffer.length >= CHUNK_BUFFER_SIZE) this._flushChunkBuffer();
338
- }
339
- /**
340
- * Flush buffered chunks to SQLite in a single batch.
341
- * Uses a lock to prevent concurrent flush operations.
342
- * @internal Protected for testing purposes.
343
- */
344
- _flushChunkBuffer() {
345
- if (this._isFlushingChunks || this._chunkBuffer.length === 0) return;
346
- this._isFlushingChunks = true;
347
- try {
348
- const chunks = this._chunkBuffer;
349
- this._chunkBuffer = [];
350
- const now = Date.now();
351
- for (const chunk of chunks) this.sql`
352
- insert into cf_ai_chat_stream_chunks (id, stream_id, body, chunk_index, created_at)
353
- values (${chunk.id}, ${chunk.streamId}, ${chunk.body}, ${chunk.index}, ${now})
354
- `;
355
- } finally {
356
- this._isFlushingChunks = false;
357
- }
358
- }
359
- /**
360
- * Start tracking a new stream for resumable streaming.
361
- * Creates metadata entry in SQLite and sets up tracking state.
362
- * @param requestId - The unique ID of the chat request
363
- * @returns The generated stream ID
364
- * @internal Protected for testing purposes.
365
- */
366
- _startStream(requestId) {
367
- this._flushChunkBuffer();
368
- const streamId = nanoid();
369
- this._activeStreamId = streamId;
370
- this._activeRequestId = requestId;
371
- this._streamChunkIndex = 0;
372
- this.sql`
373
- insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
374
- values (${streamId}, ${requestId}, 'streaming', ${Date.now()})
375
- `;
376
- return streamId;
555
+ const { toolCallId, approved, autoContinue } = data;
556
+ this._applyToolApproval(toolCallId, approved).then((applied) => {
557
+ if (applied && approved && autoContinue) {
558
+ const waitForStream = async () => {
559
+ if (this._streamCompletionPromise) await this._streamCompletionPromise;
560
+ else await new Promise((resolve) => setTimeout(resolve, 500));
561
+ };
562
+ waitForStream().then(() => {
563
+ const continuationId = nanoid();
564
+ const abortSignal = this._getAbortSignal(continuationId);
565
+ return this._tryCatchChat(async () => {
566
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
567
+ agent: this,
568
+ connection,
569
+ request: void 0,
570
+ email: void 0
571
+ }, async () => {
572
+ const response = await this.onChatMessage(async (_finishResult) => {}, {
573
+ abortSignal,
574
+ clientTools: this._lastClientTools,
575
+ body: this._lastBody
576
+ });
577
+ if (response) await this._reply(continuationId, response, [], {
578
+ continuation: true,
579
+ chatMessageId: continuationId
580
+ });
581
+ });
582
+ });
583
+ }).catch((error) => {
584
+ console.error("[AIChatAgent] Tool approval continuation failed:", error);
585
+ });
586
+ }
587
+ });
588
+ return;
589
+ }
590
+ }
591
+ return _onMessage(connection, message);
592
+ };
377
593
  }
378
594
  /**
379
- * Mark a stream as completed and flush any pending chunks.
380
- * @param streamId - The stream to mark as completed
381
- * @internal Protected for testing purposes.
595
+ * Notify a connection about an active stream that can be resumed.
596
+ * The client should respond with CF_AGENT_STREAM_RESUME_ACK to receive chunks.
597
+ * @param connection - The WebSocket connection to notify
382
598
  */
599
+ _notifyStreamResuming(connection) {
600
+ if (!this._resumableStream.hasActiveStream()) return;
601
+ this._pendingResumeConnections.add(connection.id);
602
+ connection.send(JSON.stringify({
603
+ type: MessageType.CF_AGENT_STREAM_RESUMING,
604
+ id: this._resumableStream.activeRequestId
605
+ }));
606
+ }
607
+ /** @internal Delegate to _resumableStream */
608
+ get _activeStreamId() {
609
+ return this._resumableStream?.activeStreamId ?? null;
610
+ }
611
+ /** @internal Delegate to _resumableStream */
612
+ get _activeRequestId() {
613
+ return this._resumableStream?.activeRequestId ?? null;
614
+ }
615
+ /** @internal Delegate to _resumableStream */
616
+ _startStream(requestId) {
617
+ return this._resumableStream.start(requestId);
618
+ }
619
+ /** @internal Delegate to _resumableStream */
383
620
  _completeStream(streamId) {
384
- this._flushChunkBuffer();
385
- this.sql`
386
- update cf_ai_chat_stream_metadata
387
- set status = 'completed', completed_at = ${Date.now()}
388
- where id = ${streamId}
389
- `;
390
- this._activeStreamId = null;
391
- this._activeRequestId = null;
392
- this._streamChunkIndex = 0;
621
+ this._resumableStream.complete(streamId);
393
622
  this._pendingResumeConnections.clear();
394
- this._maybeCleanupOldStreams();
623
+ }
624
+ /** @internal Delegate to _resumableStream */
625
+ _storeStreamChunk(streamId, body) {
626
+ this._resumableStream.storeChunk(streamId, body);
627
+ }
628
+ /** @internal Delegate to _resumableStream */
629
+ _flushChunkBuffer() {
630
+ this._resumableStream.flushBuffer();
631
+ }
632
+ /** @internal Delegate to _resumableStream */
633
+ _restoreActiveStream() {
634
+ this._resumableStream.restore();
635
+ }
636
+ /** @internal Delegate to _resumableStream */
637
+ _markStreamError(streamId) {
638
+ this._resumableStream.markError(streamId);
395
639
  }
396
640
  /**
397
- * Clean up old completed streams if enough time has passed since last cleanup.
398
- * This prevents database growth while avoiding cleanup overhead on every stream completion.
641
+ * Restore _lastBody and _lastClientTools from SQLite.
642
+ * Called in the constructor so these values survive DO hibernation.
643
+ * @internal
399
644
  */
400
- _maybeCleanupOldStreams() {
401
- const now = Date.now();
402
- if (now - this._lastCleanupTime < CLEANUP_INTERVAL_MS) return;
403
- this._lastCleanupTime = now;
404
- const cutoff = now - CLEANUP_AGE_THRESHOLD_MS;
405
- this.sql`
406
- delete from cf_ai_chat_stream_chunks
407
- where stream_id in (
408
- select id from cf_ai_chat_stream_metadata
409
- where status = 'completed' and completed_at < ${cutoff}
410
- )
411
- `;
412
- this.sql`
413
- delete from cf_ai_chat_stream_metadata
414
- where status = 'completed' and completed_at < ${cutoff}
415
- `;
645
+ _restoreRequestContext() {
646
+ const rows = this.sql`
647
+ select key, value from cf_ai_chat_request_context
648
+ ` || [];
649
+ for (const row of rows) try {
650
+ if (row.key === "lastBody") this._lastBody = JSON.parse(row.value);
651
+ else if (row.key === "lastClientTools") this._lastClientTools = JSON.parse(row.value);
652
+ } catch {}
653
+ }
654
+ /**
655
+ * Persist _lastBody and _lastClientTools to SQLite so they survive hibernation.
656
+ * Uses upsert (INSERT OR REPLACE) so repeated calls are safe.
657
+ * @internal
658
+ */
659
+ _persistRequestContext() {
660
+ if (this._lastBody) this.sql`
661
+ insert or replace into cf_ai_chat_request_context (key, value)
662
+ values ('lastBody', ${JSON.stringify(this._lastBody)})
663
+ `;
664
+ else this.sql`delete from cf_ai_chat_request_context where key = 'lastBody'`;
665
+ if (this._lastClientTools) this.sql`
666
+ insert or replace into cf_ai_chat_request_context (key, value)
667
+ values ('lastClientTools', ${JSON.stringify(this._lastClientTools)})
668
+ `;
669
+ else this.sql`delete from cf_ai_chat_request_context where key = 'lastClientTools'`;
416
670
  }
417
671
  _broadcastChatMessage(message, exclude) {
418
672
  const allExclusions = [...exclude || [], ...this._pendingResumeConnections];
@@ -438,9 +692,18 @@ var AIChatAgent = class extends Agent {
438
692
  });
439
693
  }
440
694
  _loadMessagesFromDb() {
441
- return (this.sql`select * from cf_ai_chat_agent_messages order by created_at` || []).map((row) => {
695
+ const rows = this.sql`select * from cf_ai_chat_agent_messages order by created_at` || [];
696
+ this._persistedMessageCache.clear();
697
+ return rows.map((row) => {
442
698
  try {
443
- return JSON.parse(row.message);
699
+ const messageStr = row.message;
700
+ const parsed = JSON.parse(messageStr);
701
+ if (!isValidMessageStructure(parsed)) {
702
+ console.warn(`[AIChatAgent] Skipping invalid message ${row.id}: missing or malformed id, role, or parts`);
703
+ return null;
704
+ }
705
+ this._persistedMessageCache.set(parsed.id, messageStr);
706
+ return parsed;
444
707
  } catch (error) {
445
708
  console.error(`Failed to parse message ${row.id}:`, error);
446
709
  return null;
@@ -470,7 +733,7 @@ var AIChatAgent = class extends Agent {
470
733
  * @returns Response to send to the client or undefined
471
734
  */
472
735
  async onChatMessage(onFinish, options) {
473
- throw new Error("recieved a chat message, override onChatMessage and return a Response to send to the client");
736
+ throw new Error("received a chat message, override onChatMessage and return a Response to send to the client");
474
737
  }
475
738
  /**
476
739
  * Save messages on the server side
@@ -487,13 +750,18 @@ var AIChatAgent = class extends Agent {
487
750
  const mergedMessages = this._mergeIncomingWithServerState(messages);
488
751
  for (const message of mergedMessages) {
489
752
  const sanitizedMessage = this._sanitizeMessageForPersistence(message);
490
- const messageToSave = this._resolveMessageForToolMerge(sanitizedMessage);
753
+ const resolved = this._resolveMessageForToolMerge(sanitizedMessage);
754
+ const safe = this._enforceRowSizeLimit(resolved);
755
+ const json = JSON.stringify(safe);
756
+ if (this._persistedMessageCache.get(safe.id) === json) continue;
491
757
  this.sql`
492
758
  insert into cf_ai_chat_agent_messages (id, message)
493
- values (${messageToSave.id}, ${JSON.stringify(messageToSave)})
759
+ values (${safe.id}, ${json})
494
760
  on conflict(id) do update set message = excluded.message
495
761
  `;
762
+ this._persistedMessageCache.set(safe.id, json);
496
763
  }
764
+ if (this.maxPersistedMessages != null) this._enforceMaxPersistedMessages();
497
765
  this.messages = autoTransformMessages(this._loadMessagesFromDb());
498
766
  this._broadcastChatMessage({
499
767
  messages: mergedMessages,
@@ -631,17 +899,129 @@ var AIChatAgent = class extends Agent {
631
899
  return restPart;
632
900
  }
633
901
  /**
634
- * Applies a tool result to an existing assistant message.
635
- * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
636
- * The server is the source of truth, so we update the message here and broadcast
637
- * the update to all clients.
902
+ * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
903
+ * Called after each persist to keep storage bounded.
904
+ */
905
+ _enforceMaxPersistedMessages() {
906
+ if (this.maxPersistedMessages == null) return;
907
+ const count = this.sql`
908
+ select count(*) as cnt from cf_ai_chat_agent_messages
909
+ `?.[0]?.cnt ?? 0;
910
+ if (count <= this.maxPersistedMessages) return;
911
+ const excess = count - this.maxPersistedMessages;
912
+ const toDelete = this.sql`
913
+ select id from cf_ai_chat_agent_messages
914
+ order by created_at asc
915
+ limit ${excess}
916
+ `;
917
+ if (toDelete && toDelete.length > 0) for (const row of toDelete) {
918
+ this.sql`delete from cf_ai_chat_agent_messages where id = ${row.id}`;
919
+ this._persistedMessageCache.delete(row.id);
920
+ }
921
+ }
922
+ /**
923
+ * Enforces SQLite row size limits by compacting tool outputs and text parts
924
+ * when a serialized message exceeds the safety threshold (1.8MB).
638
925
  *
639
- * @param toolCallId - The tool call ID this result is for
640
- * @param toolName - The name of the tool
641
- * @param output - The output from the tool execution
642
- * @returns true if the result was applied, false if the message was not found
926
+ * Only fires in pathological cases (extremely large tool outputs or text).
927
+ * Returns the message unchanged if it fits within limits.
928
+ *
929
+ * Compaction strategy:
930
+ * 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
931
+ * 2. If still too big, truncate text parts from oldest to newest
932
+ * 3. Add metadata so clients can detect compaction
933
+ *
934
+ * @param message - The message to check
935
+ * @returns The message, compacted if necessary
643
936
  */
644
- async _applyToolResult(toolCallId, _toolName, output) {
937
+ _enforceRowSizeLimit(message) {
938
+ let json = JSON.stringify(message);
939
+ let size = AIChatAgent._byteLength(json);
940
+ if (size <= AIChatAgent.ROW_MAX_BYTES) return message;
941
+ if (message.role !== "assistant") {
942
+ console.warn(`[AIChatAgent] Non-assistant message ${message.id} is ${size} bytes, exceeds row limit. Truncating text parts.`);
943
+ return this._truncateTextParts(message);
944
+ }
945
+ console.warn(`[AIChatAgent] Message ${message.id} is ${size} bytes, compacting tool outputs to fit SQLite row limit`);
946
+ const compactedToolCallIds = [];
947
+ const compactedParts = message.parts.map((part) => {
948
+ if ("output" in part && "toolCallId" in part && "state" in part && part.state === "output-available") {
949
+ const outputJson = JSON.stringify(part.output);
950
+ if (outputJson.length > 1e3) {
951
+ compactedToolCallIds.push(part.toolCallId);
952
+ return {
953
+ ...part,
954
+ output: `This tool output was too large to persist in storage (${outputJson.length} bytes). If the user asks about this data, suggest re-running the tool. Preview: ${outputJson.slice(0, 500)}...`
955
+ };
956
+ }
957
+ }
958
+ return part;
959
+ });
960
+ let result = {
961
+ ...message,
962
+ parts: compactedParts
963
+ };
964
+ if (compactedToolCallIds.length > 0) result.metadata = {
965
+ ...result.metadata ?? {},
966
+ compactedToolOutputs: compactedToolCallIds
967
+ };
968
+ json = JSON.stringify(result);
969
+ size = AIChatAgent._byteLength(json);
970
+ if (size <= AIChatAgent.ROW_MAX_BYTES) return result;
971
+ console.warn(`[AIChatAgent] Message ${message.id} still ${size} bytes after tool compaction, truncating text parts`);
972
+ return this._truncateTextParts(result);
973
+ }
974
+ /**
975
+ * Truncates text parts in a message to fit within the row size limit.
976
+ * Truncates from the first text part forward, keeping the last text part
977
+ * as intact as possible (it is usually the most relevant).
978
+ */
979
+ _truncateTextParts(message) {
980
+ const compactedTextPartIndices = [];
981
+ const parts = [...message.parts];
982
+ for (let i = 0; i < parts.length; i++) {
983
+ const part = parts[i];
984
+ if (part.type === "text" && "text" in part) {
985
+ const text = part.text;
986
+ if (text.length > 1e3) {
987
+ compactedTextPartIndices.push(i);
988
+ parts[i] = {
989
+ ...part,
990
+ text: `[Text truncated for storage (${text.length} chars). First 500 chars: ${text.slice(0, 500)}...]`
991
+ };
992
+ const candidate = {
993
+ ...message,
994
+ parts
995
+ };
996
+ if (AIChatAgent._byteLength(JSON.stringify(candidate)) <= AIChatAgent.ROW_MAX_BYTES) break;
997
+ }
998
+ }
999
+ }
1000
+ const result = {
1001
+ ...message,
1002
+ parts
1003
+ };
1004
+ if (compactedTextPartIndices.length > 0) result.metadata = {
1005
+ ...result.metadata ?? {},
1006
+ compactedTextParts: compactedTextPartIndices
1007
+ };
1008
+ return result;
1009
+ }
1010
+ /**
1011
+ * Shared helper for finding a tool part by toolCallId and applying an update.
1012
+ * Handles both streaming (in-memory) and persisted (SQLite) messages.
1013
+ *
1014
+ * Checks _streamingMessage first (tool results/approvals can arrive while
1015
+ * the AI is still streaming), then retries persisted messages with backoff
1016
+ * in case streaming completes between attempts.
1017
+ *
1018
+ * @param toolCallId - The tool call ID to find
1019
+ * @param callerName - Name for log messages (e.g. "_applyToolResult")
1020
+ * @param matchStates - Which tool part states to match
1021
+ * @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
1022
+ * @returns true if the update was applied, false if not found or state didn't match
1023
+ */
1024
+ async _findAndUpdateToolPart(toolCallId, callerName, matchStates, applyUpdate) {
645
1025
  let message;
646
1026
  if (this._streamingMessage) {
647
1027
  for (const part of this._streamingMessage.parts) if ("toolCallId" in part && part.toolCallId === toolCallId) {
@@ -655,27 +1035,23 @@ var AIChatAgent = class extends Agent {
655
1035
  await new Promise((resolve) => setTimeout(resolve, 100));
656
1036
  }
657
1037
  if (!message) {
658
- console.warn(`[AIChatAgent] _applyToolResult: Could not find message with toolCallId ${toolCallId} after retries`);
1038
+ console.warn(`[AIChatAgent] ${callerName}: Could not find message with toolCallId ${toolCallId} after retries`);
659
1039
  return false;
660
1040
  }
661
1041
  const isStreamingMessage = message === this._streamingMessage;
662
1042
  let updated = false;
663
1043
  if (isStreamingMessage) {
664
- for (const part of message.parts) if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && part.state === "input-available") {
665
- part.state = "output-available";
666
- part.output = output;
1044
+ for (const part of message.parts) if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && matchStates.includes(part.state)) {
1045
+ const applied = applyUpdate(part);
1046
+ Object.assign(part, applied);
667
1047
  updated = true;
668
1048
  break;
669
1049
  }
670
1050
  } else {
671
1051
  const updatedParts = message.parts.map((part) => {
672
- if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && part.state === "input-available") {
1052
+ if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && matchStates.includes(part.state)) {
673
1053
  updated = true;
674
- return {
675
- ...part,
676
- state: "output-available",
677
- output
678
- };
1054
+ return applyUpdate(part);
679
1055
  }
680
1056
  return part;
681
1057
  });
@@ -684,19 +1060,26 @@ var AIChatAgent = class extends Agent {
684
1060
  ...message,
685
1061
  parts: updatedParts
686
1062
  });
1063
+ const safe = this._enforceRowSizeLimit(updatedMessage);
1064
+ const json = JSON.stringify(safe);
687
1065
  this.sql`
688
1066
  update cf_ai_chat_agent_messages
689
- set message = ${JSON.stringify(updatedMessage)}
1067
+ set message = ${json}
690
1068
  where id = ${message.id}
691
1069
  `;
1070
+ this._persistedMessageCache.set(message.id, json);
692
1071
  this.messages = autoTransformMessages(this._loadMessagesFromDb());
693
1072
  }
694
1073
  }
695
1074
  if (!updated) {
696
- console.warn(`[AIChatAgent] _applyToolResult: Tool part with toolCallId ${toolCallId} not in input-available state`);
1075
+ console.warn(`[AIChatAgent] ${callerName}: Tool part with toolCallId ${toolCallId} not in expected state (expected: ${matchStates.join("|")})`);
697
1076
  return false;
698
1077
  }
699
- if (!isStreamingMessage) {
1078
+ if (isStreamingMessage) this._broadcastChatMessage({
1079
+ type: MessageType.CF_AGENT_MESSAGE_UPDATED,
1080
+ message
1081
+ });
1082
+ else {
700
1083
  const broadcastMessage = this._findMessageByToolCallId(toolCallId);
701
1084
  if (broadcastMessage) this._broadcastChatMessage({
702
1085
  type: MessageType.CF_AGENT_MESSAGE_UPDATED,
@@ -705,11 +1088,26 @@ var AIChatAgent = class extends Agent {
705
1088
  }
706
1089
  return true;
707
1090
  }
1091
+ /**
1092
+ * Applies a tool result to an existing assistant message.
1093
+ * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
1094
+ * The server is the source of truth, so we update the message here and broadcast
1095
+ * the update to all clients.
1096
+ *
1097
+ * @param toolCallId - The tool call ID this result is for
1098
+ * @param _toolName - The name of the tool (unused, kept for API compat)
1099
+ * @param output - The output from the tool execution
1100
+ * @returns true if the result was applied, false if the message was not found
1101
+ */
1102
+ async _applyToolResult(toolCallId, _toolName, output) {
1103
+ return this._findAndUpdateToolPart(toolCallId, "_applyToolResult", ["input-available"], (part) => ({
1104
+ ...part,
1105
+ state: "output-available",
1106
+ output,
1107
+ preliminary: false
1108
+ }));
1109
+ }
708
1110
  async _streamSSEReply(id, streamId, reader, message, streamCompleted, continuation = false) {
709
- let activeTextParts = {};
710
- let activeReasoningParts = {};
711
- const partialToolCalls = {};
712
- const { getToolName, isToolUIPart, parsePartialJson } = await import("ai");
713
1111
  streamCompleted.value = false;
714
1112
  while (true) {
715
1113
  const { done, value } = await reader.read();
@@ -728,225 +1126,60 @@ var AIChatAgent = class extends Agent {
728
1126
  const lines = decoder.decode(value).split("\n");
729
1127
  for (const line of lines) if (line.startsWith("data: ") && line !== "data: [DONE]") try {
730
1128
  const data = JSON.parse(line.slice(6));
731
- switch (data.type) {
732
- case "text-start": {
733
- const textPart = {
734
- type: "text",
735
- text: "",
736
- providerMetadata: data.providerMetadata,
737
- state: "streaming"
738
- };
739
- activeTextParts[data.id] = textPart;
740
- message.parts.push(textPart);
741
- break;
742
- }
743
- case "text-delta": {
744
- const textPart = activeTextParts[data.id];
745
- textPart.text += data.delta;
746
- textPart.providerMetadata = data.providerMetadata ?? textPart.providerMetadata;
747
- break;
748
- }
749
- case "text-end": {
750
- const textPart = activeTextParts[data.id];
751
- textPart.state = "done";
752
- textPart.providerMetadata = data.providerMetadata ?? textPart.providerMetadata;
753
- delete activeTextParts[data.id];
754
- break;
755
- }
756
- case "reasoning-start": {
757
- const reasoningPart = {
758
- type: "reasoning",
759
- text: "",
760
- providerMetadata: data.providerMetadata,
761
- state: "streaming"
762
- };
763
- activeReasoningParts[data.id] = reasoningPart;
764
- message.parts.push(reasoningPart);
765
- break;
766
- }
767
- case "reasoning-delta": {
768
- const reasoningPart = activeReasoningParts[data.id];
769
- reasoningPart.text += data.delta;
770
- reasoningPart.providerMetadata = data.providerMetadata ?? reasoningPart.providerMetadata;
771
- break;
772
- }
773
- case "reasoning-end": {
774
- const reasoningPart = activeReasoningParts[data.id];
775
- reasoningPart.providerMetadata = data.providerMetadata ?? reasoningPart.providerMetadata;
776
- reasoningPart.state = "done";
777
- delete activeReasoningParts[data.id];
778
- break;
779
- }
780
- case "file":
781
- message.parts.push({
782
- type: "file",
783
- mediaType: data.mediaType,
784
- url: data.url
785
- });
786
- break;
787
- case "source-url":
788
- message.parts.push({
789
- type: "source-url",
790
- sourceId: data.sourceId,
791
- url: data.url,
792
- title: data.title,
793
- providerMetadata: data.providerMetadata
794
- });
795
- break;
796
- case "source-document":
797
- message.parts.push({
798
- type: "source-document",
799
- sourceId: data.sourceId,
800
- mediaType: data.mediaType,
801
- title: data.title,
802
- filename: data.filename,
803
- providerMetadata: data.providerMetadata
804
- });
805
- break;
806
- case "tool-input-start": {
807
- const toolInvocations = message.parts.filter(isToolUIPart);
808
- partialToolCalls[data.toolCallId] = {
809
- text: "",
810
- toolName: data.toolName,
811
- index: toolInvocations.length,
812
- dynamic: data.dynamic
813
- };
814
- if (data.dynamic) this.updateDynamicToolPart(message, {
815
- toolCallId: data.toolCallId,
816
- toolName: data.toolName,
817
- state: "input-streaming",
818
- input: void 0
819
- });
820
- else await this.updateToolPart(message, {
821
- toolCallId: data.toolCallId,
822
- toolName: data.toolName,
823
- state: "input-streaming",
824
- input: void 0
825
- });
826
- break;
827
- }
828
- case "tool-input-delta": {
829
- const partialToolCall = partialToolCalls[data.toolCallId];
830
- partialToolCall.text += data.inputTextDelta;
831
- const partialArgs = (await parsePartialJson(partialToolCall.text)).value;
832
- if (partialToolCall.dynamic) this.updateDynamicToolPart(message, {
833
- toolCallId: data.toolCallId,
834
- toolName: partialToolCall.toolName,
835
- state: "input-streaming",
836
- input: partialArgs
837
- });
838
- else await this.updateToolPart(message, {
839
- toolCallId: data.toolCallId,
840
- toolName: partialToolCall.toolName,
841
- state: "input-streaming",
842
- input: partialArgs
843
- });
844
- break;
845
- }
846
- case "tool-input-available":
847
- if (data.dynamic) this.updateDynamicToolPart(message, {
848
- toolCallId: data.toolCallId,
849
- toolName: data.toolName,
850
- state: "input-available",
851
- input: data.input,
852
- providerMetadata: data.providerMetadata
853
- });
854
- else await this.updateToolPart(message, {
855
- toolCallId: data.toolCallId,
856
- toolName: data.toolName,
857
- state: "input-available",
858
- input: data.input,
859
- providerExecuted: data.providerExecuted,
860
- providerMetadata: data.providerMetadata
861
- });
862
- break;
863
- case "tool-input-error":
864
- if (data.dynamic) this.updateDynamicToolPart(message, {
865
- toolCallId: data.toolCallId,
866
- toolName: data.toolName,
867
- state: "output-error",
868
- input: data.input,
869
- errorText: data.errorText,
870
- providerMetadata: data.providerMetadata
871
- });
872
- else await this.updateToolPart(message, {
873
- toolCallId: data.toolCallId,
874
- toolName: data.toolName,
875
- state: "output-error",
876
- input: void 0,
877
- rawInput: data.input,
878
- errorText: data.errorText,
879
- providerExecuted: data.providerExecuted,
880
- providerMetadata: data.providerMetadata
881
- });
882
- break;
883
- case "tool-output-available":
884
- if (data.dynamic) {
885
- const toolInvocation = message.parts.filter((part) => part.type === "dynamic-tool").find((invocation) => invocation.toolCallId === data.toolCallId);
886
- if (!toolInvocation) throw new Error("Tool invocation not found");
887
- this.updateDynamicToolPart(message, {
888
- toolCallId: data.toolCallId,
889
- toolName: toolInvocation.toolName,
890
- state: "output-available",
891
- input: toolInvocation.input,
892
- output: data.output,
893
- preliminary: data.preliminary
894
- });
895
- } else {
896
- const toolInvocation = message.parts.filter(isToolUIPart).find((invocation) => invocation.toolCallId === data.toolCallId);
897
- if (!toolInvocation) throw new Error("Tool invocation not found");
898
- await this.updateToolPart(message, {
899
- toolCallId: data.toolCallId,
900
- toolName: getToolName(toolInvocation),
901
- state: "output-available",
902
- input: toolInvocation.input,
903
- output: data.output,
904
- providerExecuted: data.providerExecuted,
905
- preliminary: data.preliminary
906
- });
907
- }
908
- break;
909
- case "tool-output-error":
910
- if (data.dynamic) {
911
- const toolInvocation = message.parts.filter((part) => part.type === "dynamic-tool").find((invocation) => invocation.toolCallId === data.toolCallId);
912
- if (!toolInvocation) throw new Error("Tool invocation not found");
913
- this.updateDynamicToolPart(message, {
914
- toolCallId: data.toolCallId,
915
- toolName: toolInvocation.toolName,
916
- state: "output-error",
917
- input: toolInvocation.input,
918
- errorText: data.errorText
919
- });
920
- } else {
921
- const toolInvocation = message.parts.filter(isToolUIPart).find((invocation) => invocation.toolCallId === data.toolCallId);
922
- if (!toolInvocation) throw new Error("Tool invocation not found");
923
- await this.updateToolPart(message, {
924
- toolCallId: data.toolCallId,
925
- toolName: getToolName(toolInvocation),
926
- state: "output-error",
927
- input: toolInvocation.input,
928
- rawInput: "rawInput" in toolInvocation ? toolInvocation.rawInput : void 0,
929
- errorText: data.errorText
930
- });
931
- }
932
- break;
933
- case "start-step":
934
- message.parts.push({ type: "step-start" });
935
- break;
936
- case "finish-step":
937
- activeTextParts = {};
938
- activeReasoningParts = {};
939
- break;
1129
+ const handled = applyChunkToParts(message.parts, data);
1130
+ if (data.type === "tool-approval-request" && this._streamingMessage) {
1131
+ const snapshot = {
1132
+ ...this._streamingMessage,
1133
+ parts: [...this._streamingMessage.parts]
1134
+ };
1135
+ const sanitized = this._sanitizeMessageForPersistence(snapshot);
1136
+ const json = JSON.stringify(sanitized);
1137
+ this.sql`
1138
+ INSERT INTO cf_ai_chat_agent_messages (id, message)
1139
+ VALUES (${sanitized.id}, ${json})
1140
+ ON CONFLICT(id) DO UPDATE SET message = excluded.message
1141
+ `;
1142
+ this._approvalPersistedMessageId = sanitized.id;
1143
+ }
1144
+ if ((data.type === "tool-output-available" || data.type === "tool-output-error") && data.toolCallId) {
1145
+ if (!message.parts.some((p) => "toolCallId" in p && p.toolCallId === data.toolCallId)) if (data.type === "tool-output-available") this._findAndUpdateToolPart(data.toolCallId, "_streamSSEReply", [
1146
+ "input-available",
1147
+ "input-streaming",
1148
+ "approval-responded",
1149
+ "approval-requested"
1150
+ ], (part) => ({
1151
+ ...part,
1152
+ state: "output-available",
1153
+ output: data.output,
1154
+ ...data.preliminary !== void 0 && { preliminary: data.preliminary }
1155
+ }));
1156
+ else this._findAndUpdateToolPart(data.toolCallId, "_streamSSEReply", [
1157
+ "input-available",
1158
+ "input-streaming",
1159
+ "approval-responded",
1160
+ "approval-requested"
1161
+ ], (part) => ({
1162
+ ...part,
1163
+ state: "output-error",
1164
+ errorText: data.errorText
1165
+ }));
1166
+ }
1167
+ if (!handled) switch (data.type) {
940
1168
  case "start":
941
1169
  if (data.messageId != null) message.id = data.messageId;
942
- await this.updateMessageMetadata(message, data.messageMetadata);
1170
+ if (data.messageMetadata != null) message.metadata = message.metadata ? {
1171
+ ...message.metadata,
1172
+ ...data.messageMetadata
1173
+ } : data.messageMetadata;
943
1174
  break;
944
1175
  case "finish":
945
- await this.updateMessageMetadata(message, data.messageMetadata);
946
- break;
947
1176
  case "message-metadata":
948
- await this.updateMessageMetadata(message, data.messageMetadata);
1177
+ if (data.messageMetadata != null) message.metadata = message.metadata ? {
1178
+ ...message.metadata,
1179
+ ...data.messageMetadata
1180
+ } : data.messageMetadata;
949
1181
  break;
1182
+ case "finish-step": break;
950
1183
  case "error":
951
1184
  this._broadcastChatMessage({
952
1185
  error: true,
@@ -983,9 +1216,16 @@ var AIChatAgent = class extends Agent {
983
1216
  type: "text-start",
984
1217
  id
985
1218
  }, continuation);
1219
+ const textPart = {
1220
+ type: "text",
1221
+ text: "",
1222
+ state: "streaming"
1223
+ };
1224
+ message.parts.push(textPart);
986
1225
  while (true) {
987
1226
  const { done, value } = await reader.read();
988
1227
  if (done) {
1228
+ textPart.state = "done";
989
1229
  this._broadcastTextEvent(streamId, {
990
1230
  type: "text-end",
991
1231
  id
@@ -1003,10 +1243,7 @@ var AIChatAgent = class extends Agent {
1003
1243
  }
1004
1244
  const chunk = decoder.decode(value);
1005
1245
  if (chunk.length > 0) {
1006
- message.parts.push({
1007
- type: "text",
1008
- text: chunk
1009
- });
1246
+ textPart.text += chunk;
1010
1247
  this._broadcastTextEvent(streamId, {
1011
1248
  type: "text-delta",
1012
1249
  id,
@@ -1015,64 +1252,6 @@ var AIChatAgent = class extends Agent {
1015
1252
  }
1016
1253
  }
1017
1254
  }
1018
- updateDynamicToolPart(message, options) {
1019
- const part = message.parts.find((part) => part.type === "dynamic-tool" && part.toolCallId === options.toolCallId);
1020
- const anyOptions = options;
1021
- const anyPart = part;
1022
- if (part != null) {
1023
- part.state = options.state;
1024
- anyPart.toolName = options.toolName;
1025
- anyPart.input = anyOptions.input;
1026
- anyPart.output = anyOptions.output;
1027
- anyPart.errorText = anyOptions.errorText;
1028
- anyPart.rawInput = anyOptions.rawInput ?? anyPart.rawInput;
1029
- anyPart.preliminary = anyOptions.preliminary;
1030
- if (anyOptions.providerMetadata != null && part.state === "input-available") part.callProviderMetadata = anyOptions.providerMetadata;
1031
- } else message.parts.push({
1032
- type: "dynamic-tool",
1033
- toolName: options.toolName,
1034
- toolCallId: options.toolCallId,
1035
- state: options.state,
1036
- input: anyOptions.input,
1037
- output: anyOptions.output,
1038
- errorText: anyOptions.errorText,
1039
- preliminary: anyOptions.preliminary,
1040
- ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
1041
- });
1042
- }
1043
- async updateToolPart(message, options) {
1044
- const { isToolUIPart } = await import("ai");
1045
- const part = message.parts.find((part) => isToolUIPart(part) && part.toolCallId === options.toolCallId);
1046
- const anyOptions = options;
1047
- const anyPart = part;
1048
- if (part != null) {
1049
- part.state = options.state;
1050
- anyPart.input = anyOptions.input;
1051
- anyPart.output = anyOptions.output;
1052
- anyPart.errorText = anyOptions.errorText;
1053
- anyPart.rawInput = anyOptions.rawInput;
1054
- anyPart.preliminary = anyOptions.preliminary;
1055
- anyPart.providerExecuted = anyOptions.providerExecuted ?? part.providerExecuted;
1056
- if (anyOptions.providerMetadata != null && part.state === "input-available") part.callProviderMetadata = anyOptions.providerMetadata;
1057
- } else message.parts.push({
1058
- type: `tool-${options.toolName}`,
1059
- toolCallId: options.toolCallId,
1060
- state: options.state,
1061
- input: anyOptions.input,
1062
- output: anyOptions.output,
1063
- rawInput: anyOptions.rawInput,
1064
- errorText: anyOptions.errorText,
1065
- providerExecuted: anyOptions.providerExecuted,
1066
- preliminary: anyOptions.preliminary,
1067
- ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
1068
- });
1069
- }
1070
- async updateMessageMetadata(message, metadata) {
1071
- if (metadata != null) message.metadata = message.metadata != null ? {
1072
- ...message.metadata,
1073
- ...metadata
1074
- } : metadata;
1075
- }
1076
1255
  /**
1077
1256
  * Applies a tool approval response from the client, updating the persisted message.
1078
1257
  * This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
@@ -1083,71 +1262,17 @@ var AIChatAgent = class extends Agent {
1083
1262
  * @returns true if the approval was applied, false if the message was not found
1084
1263
  */
1085
1264
  async _applyToolApproval(toolCallId, approved) {
1086
- let message;
1087
- if (this._streamingMessage) {
1088
- for (const part of this._streamingMessage.parts) if ("toolCallId" in part && part.toolCallId === toolCallId) {
1089
- message = this._streamingMessage;
1090
- break;
1091
- }
1092
- }
1093
- if (!message) for (let attempt = 0; attempt < 10; attempt++) {
1094
- message = this._findMessageByToolCallId(toolCallId);
1095
- if (message) break;
1096
- await new Promise((resolve) => setTimeout(resolve, 100));
1097
- }
1098
- if (!message) {
1099
- console.warn(`[AIChatAgent] _applyToolApproval: Could not find message with toolCallId ${toolCallId} after retries`);
1100
- return false;
1101
- }
1102
- const isStreamingMessage = message === this._streamingMessage;
1103
- let updated = false;
1104
- if (isStreamingMessage) {
1105
- for (const part of message.parts) if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && (part.state === "input-available" || part.state === "approval-requested")) {
1106
- part.state = "approval-responded";
1107
- part.approval = { approved };
1108
- updated = true;
1109
- break;
1110
- }
1111
- } else {
1112
- const updatedParts = message.parts.map((part) => {
1113
- if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && (part.state === "input-available" || part.state === "approval-requested")) {
1114
- updated = true;
1115
- return {
1116
- ...part,
1117
- state: "approval-responded",
1118
- approval: { approved }
1119
- };
1120
- }
1121
- return part;
1122
- });
1123
- if (updated) {
1124
- const updatedMessage = this._sanitizeMessageForPersistence({
1125
- ...message,
1126
- parts: updatedParts
1127
- });
1128
- this.sql`
1129
- update cf_ai_chat_agent_messages
1130
- set message = ${JSON.stringify(updatedMessage)}
1131
- where id = ${message.id}
1132
- `;
1133
- this.messages = autoTransformMessages(this._loadMessagesFromDb());
1265
+ return this._findAndUpdateToolPart(toolCallId, "_applyToolApproval", ["input-available", "approval-requested"], (part) => ({
1266
+ ...part,
1267
+ state: "approval-responded",
1268
+ approval: {
1269
+ ...part.approval,
1270
+ approved
1134
1271
  }
1135
- }
1136
- if (!updated) {
1137
- console.warn(`[AIChatAgent] _applyToolApproval: Tool part with toolCallId ${toolCallId} not in input-available or approval-requested state`);
1138
- return false;
1139
- }
1140
- if (!isStreamingMessage) {
1141
- const broadcastMessage = this._findMessageByToolCallId(toolCallId);
1142
- if (broadcastMessage) this._broadcastChatMessage({
1143
- type: MessageType.CF_AGENT_MESSAGE_UPDATED,
1144
- message: broadcastMessage
1145
- });
1146
- }
1147
- return true;
1272
+ }));
1148
1273
  }
1149
1274
  async _reply(id, response, excludeBroadcastIds = [], options = {}) {
1150
- const { continuation = false } = options;
1275
+ const { continuation = false, chatMessageId } = options;
1151
1276
  return this._tryCatchChat(async () => {
1152
1277
  if (!response.body) {
1153
1278
  this._broadcastChatMessage({
@@ -1172,6 +1297,7 @@ var AIChatAgent = class extends Agent {
1172
1297
  });
1173
1298
  const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
1174
1299
  const streamCompleted = { value: false };
1300
+ let earlyPersistedId = null;
1175
1301
  try {
1176
1302
  if (isSSE) await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation);
1177
1303
  else await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation);
@@ -1190,8 +1316,29 @@ var AIChatAgent = class extends Agent {
1190
1316
  throw error;
1191
1317
  } finally {
1192
1318
  reader.releaseLock();
1319
+ this._streamingMessage = null;
1320
+ earlyPersistedId = this._approvalPersistedMessageId;
1321
+ this._approvalPersistedMessageId = null;
1322
+ if (this._streamCompletionResolve) {
1323
+ this._streamCompletionResolve();
1324
+ this._streamCompletionResolve = null;
1325
+ this._streamCompletionPromise = null;
1326
+ }
1327
+ if (chatMessageId) {
1328
+ this._removeAbortController(chatMessageId);
1329
+ if (streamCompleted.value) this.observability?.emit({
1330
+ displayMessage: continuation ? "Chat message response (tool continuation)" : "Chat message response",
1331
+ id: chatMessageId,
1332
+ payload: {},
1333
+ timestamp: Date.now(),
1334
+ type: "message:response"
1335
+ }, this.ctx);
1336
+ }
1193
1337
  }
1194
- if (message.parts.length > 0) if (continuation) {
1338
+ if (message.parts.length > 0) if (earlyPersistedId) {
1339
+ const updatedMessages = this.messages.map((msg) => msg.id === earlyPersistedId ? message : msg);
1340
+ await this.persistMessages(updatedMessages, excludeBroadcastIds);
1341
+ } else if (continuation) {
1195
1342
  let lastAssistantIdx = -1;
1196
1343
  for (let i = this.messages.length - 1; i >= 0; i--) if (this.messages[i].role === "assistant") {
1197
1344
  lastAssistantIdx = i;
@@ -1208,31 +1355,9 @@ var AIChatAgent = class extends Agent {
1208
1355
  await this.persistMessages(updatedMessages, excludeBroadcastIds);
1209
1356
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
1210
1357
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
1211
- this._streamingMessage = null;
1212
- if (this._streamCompletionResolve) {
1213
- this._streamCompletionResolve();
1214
- this._streamCompletionResolve = null;
1215
- this._streamCompletionPromise = null;
1216
- }
1217
1358
  });
1218
1359
  }
1219
1360
  /**
1220
- * Mark a stream as errored and clean up state.
1221
- * @param streamId - The stream to mark as errored
1222
- * @internal Protected for testing purposes.
1223
- */
1224
- _markStreamError(streamId) {
1225
- this._flushChunkBuffer();
1226
- this.sql`
1227
- update cf_ai_chat_stream_metadata
1228
- set status = 'error', completed_at = ${Date.now()}
1229
- where id = ${streamId}
1230
- `;
1231
- this._activeStreamId = null;
1232
- this._activeRequestId = null;
1233
- this._streamChunkIndex = 0;
1234
- }
1235
- /**
1236
1361
  * For the given message id, look up its associated AbortController
1237
1362
  * If the AbortController does not exist, create and store one in memory
1238
1363
  *
@@ -1267,11 +1392,7 @@ var AIChatAgent = class extends Agent {
1267
1392
  */
1268
1393
  async destroy() {
1269
1394
  this._destroyAbortControllers();
1270
- this._flushChunkBuffer();
1271
- this.sql`drop table if exists cf_ai_chat_stream_chunks`;
1272
- this.sql`drop table if exists cf_ai_chat_stream_metadata`;
1273
- this._activeStreamId = null;
1274
- this._activeRequestId = null;
1395
+ this._resumableStream.destroy();
1275
1396
  await super.destroy();
1276
1397
  }
1277
1398
  };