@cloudflare/ai-chat 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/experimental/forever.d.ts +4 -13
  2. package/dist/experimental/forever.js +1 -46
  3. package/dist/experimental/forever.js.map +1 -1
  4. package/dist/index.d.ts +59 -4
  5. package/dist/index.js +170 -28
  6. package/dist/index.js.map +1 -1
  7. package/dist/{message-builder-Bwc_Umye.js → message-builder-uSvexDl2.js} +17 -4
  8. package/dist/message-builder-uSvexDl2.js.map +1 -0
  9. package/dist/react.js +125 -31
  10. package/dist/react.js.map +1 -1
  11. package/dist/{resumable-stream-DqXxQVjf.d.ts → resumable-stream-DTLAk9XC.d.ts} +25 -2
  12. package/dist/types.d.ts +2 -1
  13. package/dist/types.js.map +1 -1
  14. package/package.json +7 -3
  15. package/CHANGELOG.md +0 -244
  16. package/dist/message-builder-Bwc_Umye.js.map +0 -1
  17. package/e2e/chat.spec.ts +0 -1703
  18. package/e2e/client-tools.spec.ts +0 -504
  19. package/e2e/llm.spec.ts +0 -637
  20. package/e2e/playwright.config.ts +0 -27
  21. package/e2e/worker.ts +0 -174
  22. package/e2e/wrangler.jsonc +0 -23
  23. package/scripts/build.ts +0 -32
  24. package/src/ai-chat-v5-migration.ts +0 -403
  25. package/src/experimental/forever.ts +0 -66
  26. package/src/index.ts +0 -2269
  27. package/src/message-builder.ts +0 -384
  28. package/src/react-tests/setup.ts +0 -3
  29. package/src/react-tests/use-agent-chat.test.tsx +0 -1435
  30. package/src/react-tests/vitest.config.ts +0 -20
  31. package/src/react.tsx +0 -1447
  32. package/src/resumable-stream.ts +0 -441
  33. package/src/tests/cancel-request.test.ts +0 -280
  34. package/src/tests/chat-context.test.ts +0 -85
  35. package/src/tests/chat-persistence.test.ts +0 -426
  36. package/src/tests/clear-history.test.ts +0 -132
  37. package/src/tests/client-tool-duplicate-message.test.ts +0 -1957
  38. package/src/tests/client-tools-broadcast.test.ts +0 -138
  39. package/src/tests/client-tools-continuation.test.ts +0 -314
  40. package/src/tests/client-tools-reconnect.test.ts +0 -143
  41. package/src/tests/cloudflare-test.d.ts +0 -5
  42. package/src/tests/custom-body-continuation.test.ts +0 -309
  43. package/src/tests/custom-body.test.ts +0 -186
  44. package/src/tests/destroy.test.ts +0 -57
  45. package/src/tests/get-messages-endpoint.test.ts +0 -153
  46. package/src/tests/max-persisted-messages.test.ts +0 -201
  47. package/src/tests/merge-server-state.test.ts +0 -343
  48. package/src/tests/message-builder.test.ts +0 -808
  49. package/src/tests/migration.test.ts +0 -282
  50. package/src/tests/non-sse-response.test.ts +0 -186
  51. package/src/tests/onfinish-cleanup.test.ts +0 -362
  52. package/src/tests/plaintext-response.test.ts +0 -87
  53. package/src/tests/request-id.test.ts +0 -312
  54. package/src/tests/resumable-streaming.test.ts +0 -758
  55. package/src/tests/row-size-guard.test.ts +0 -374
  56. package/src/tests/sanitize-messages.test.ts +0 -325
  57. package/src/tests/test-utils.ts +0 -39
  58. package/src/tests/tsconfig.json +0 -10
  59. package/src/tests/validate-messages.test.ts +0 -269
  60. package/src/tests/vitest.config.ts +0 -30
  61. package/src/tests/worker.ts +0 -456
  62. package/src/tests/wrangler.jsonc +0 -50
  63. package/src/types.ts +0 -152
  64. package/src/ws-chat-transport.ts +0 -203
  65. package/tsconfig.json +0 -4
  66. package/vitest.config.ts +0 -7
@@ -1,27 +1,18 @@
1
- import "../resumable-stream-DqXxQVjf.js";
1
+ import "../resumable-stream-DTLAk9XC.js";
2
2
  import { AIChatAgent } from "../index.js";
3
3
  import * as agents from "agents";
4
4
 
5
5
  //#region src/experimental/forever.d.ts
6
6
  type Constructor<T = object> = new (...args: any[]) => T;
7
- type AIChatAgentLike = Constructor<Pick<AIChatAgent, "scheduleEvery" | "cancelSchedule">>;
7
+ type AIChatAgentLike = Constructor<Pick<AIChatAgent, "scheduleEvery" | "cancelSchedule" | "keepAlive" | "keepAliveWhile">>;
8
8
  declare function withDurableChat<TBase extends AIChatAgentLike>(Base: TBase): {
9
9
  new (...args: any[]): {
10
- /**
11
- * No-op heartbeat callback. The schedule itself keeps the DO alive;
12
- * the callback doesn't need to do anything.
13
- * @internal
14
- */
15
- _cf_streamKeepAlive(): void;
16
- /**
17
- * Keep the DO alive during streaming.
18
- * Returns a disposer that cancels the heartbeat schedule.
19
- */
20
- keepAlive(): Promise<() => void>;
21
10
  scheduleEvery: <T = string>(intervalSeconds: number, callback: keyof AIChatAgent<Cloudflare.Env, unknown>, payload?: T | undefined, options?: {
22
11
  retry?: agents.RetryOptions;
23
12
  }) => Promise<agents.Schedule<T>>;
24
13
  cancelSchedule: (id: string) => Promise<boolean>;
14
+ keepAlive: () => Promise<() => void>;
15
+ keepAliveWhile: <T>(fn: () => Promise<T>) => Promise<T>;
25
16
  };
26
17
  } & TBase;
27
18
  //#endregion
@@ -1,52 +1,7 @@
1
- import { keepAlive } from "agents/experimental/forever";
2
-
3
1
  //#region src/experimental/forever.ts
4
- /**
5
- * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
6
- * !! WARNING: EXPERIMENTAL — DO NOT USE IN PRODUCTION !!
7
- * !! !!
8
- * !! This API is under active development and WILL break between !!
9
- * !! releases. Method names, types, behavior, and the mixin signature !!
10
- * !! are all subject to change without notice. !!
11
- * !! !!
12
- * !! If you use this, pin your @cloudflare/ai-chat version and expect !!
13
- * !! to rewrite your code when upgrading. !!
14
- * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
15
- *
16
- * Experimental mixin for durable chat streaming.
17
- *
18
- * Usage:
19
- * import { AIChatAgent } from "@cloudflare/ai-chat";
20
- * import { withDurableChat } from "@cloudflare/ai-chat/experimental/forever";
21
- *
22
- * class MyAgent extends withDurableChat(AIChatAgent)<Env, State> {
23
- * async onChatMessage(onFinish, options) { ... }
24
- * }
25
- *
26
- * This mixin adds:
27
- * - keepAlive during streaming — DO stays alive while LLM generates
28
- * - (planned) getPartialStreamText() — extract partial response from chunks
29
- * - (planned) onStreamInterrupted() — hook for recovery after eviction
30
- *
31
- * @experimental This API is not yet stable and may change.
32
- */
33
2
  console.warn("[@cloudflare/ai-chat/experimental/forever] WARNING: You are using an experimental API that WILL break between releases. Do not use in production.");
34
3
  function withDurableChat(Base) {
35
- class DurableChatAgent extends Base {
36
- /**
37
- * No-op heartbeat callback. The schedule itself keeps the DO alive;
38
- * the callback doesn't need to do anything.
39
- * @internal
40
- */
41
- _cf_streamKeepAlive() {}
42
- /**
43
- * Keep the DO alive during streaming.
44
- * Returns a disposer that cancels the heartbeat schedule.
45
- */
46
- async keepAlive() {
47
- return keepAlive(this, "_cf_streamKeepAlive");
48
- }
49
- }
4
+ class DurableChatAgent extends Base {}
50
5
  return DurableChatAgent;
51
6
  }
52
7
 
@@ -1 +1 @@
1
- {"version":3,"file":"forever.js","names":[],"sources":["../../src/experimental/forever.ts"],"sourcesContent":["/**\n * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n * !! WARNING: EXPERIMENTAL — DO NOT USE IN PRODUCTION !!\n * !! !!\n * !! This API is under active development and WILL break between !!\n * !! releases. Method names, types, behavior, and the mixin signature !!\n * !! are all subject to change without notice. !!\n * !! !!\n * !! If you use this, pin your @cloudflare/ai-chat version and expect !!\n * !! to rewrite your code when upgrading. !!\n * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n *\n * Experimental mixin for durable chat streaming.\n *\n * Usage:\n * import { AIChatAgent } from \"@cloudflare/ai-chat\";\n * import { withDurableChat } from \"@cloudflare/ai-chat/experimental/forever\";\n *\n * class MyAgent extends withDurableChat(AIChatAgent)<Env, State> {\n * async onChatMessage(onFinish, options) { ... }\n * }\n *\n * This mixin adds:\n * - keepAlive during streaming — DO stays alive while LLM generates\n * - (planned) getPartialStreamText() — extract partial response from chunks\n * - (planned) onStreamInterrupted() — hook for recovery after eviction\n *\n * @experimental This API is not yet stable and may change.\n */\nimport { keepAlive } from \"agents/experimental/forever\";\nimport type { AIChatAgent } from \"../index\";\n\nconsole.warn(\n \"[@cloudflare/ai-chat/experimental/forever] WARNING: You are using an experimental API that WILL break between releases. Do not use in production.\"\n);\n\n// ── Mixin ─────────────────────────────────────────────────────────────\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any -- mixin constructor constraint\ntype Constructor<T = object> = new (...args: any[]) => T;\n\ntype AIChatAgentLike = Constructor<\n Pick<AIChatAgent, \"scheduleEvery\" | \"cancelSchedule\">\n>;\n\nexport function withDurableChat<TBase extends AIChatAgentLike>(Base: TBase) {\n class DurableChatAgent extends Base {\n /**\n * No-op heartbeat callback. The schedule itself keeps the DO alive;\n * the callback doesn't need to do anything.\n * @internal\n */\n // oxlint-disable-next-line @typescript-eslint/no-empty-function\n _cf_streamKeepAlive() {}\n\n /**\n * Keep the DO alive during streaming.\n * Returns a disposer that cancels the heartbeat schedule.\n */\n async keepAlive(): Promise<() => void> {\n return keepAlive(this, \"_cf_streamKeepAlive\");\n }\n }\n\n return DurableChatAgent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,QAAQ,KACN,oJACD;AAWD,SAAgB,gBAA+C,MAAa;CAC1E,MAAM,yBAAyB,KAAK;;;;;;EAOlC,sBAAsB;;;;;EAMtB,MAAM,YAAiC;AACrC,UAAO,UAAU,MAAM,sBAAsB;;;AAIjD,QAAO"}
1
+ {"version":3,"file":"forever.js","names":[],"sources":["../../src/experimental/forever.ts"],"sourcesContent":["/**\n * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n * !! WARNING: EXPERIMENTAL — DO NOT USE IN PRODUCTION !!\n * !! !!\n * !! This API is under active development and WILL break between !!\n * !! releases. Method names, types, behavior, and the mixin signature !!\n * !! are all subject to change without notice. !!\n * !! !!\n * !! If you use this, pin your @cloudflare/ai-chat version and expect !!\n * !! to rewrite your code when upgrading. !!\n * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n *\n * Experimental mixin for durable chat streaming.\n *\n * Usage:\n * import { AIChatAgent } from \"@cloudflare/ai-chat\";\n * import { withDurableChat } from \"@cloudflare/ai-chat/experimental/forever\";\n *\n * class MyAgent extends withDurableChat(AIChatAgent)<Env, State> {\n * async onChatMessage(onFinish, options) { ... }\n * }\n *\n * This mixin adds:\n * - keepAlive during streaming — DO stays alive while LLM generates\n * - (planned) getPartialStreamText() — extract partial response from chunks\n * - (planned) onStreamInterrupted() — hook for recovery after eviction\n *\n * @experimental This API is not yet stable and may change.\n */\nimport type { AIChatAgent } from \"../index\";\n\nconsole.warn(\n \"[@cloudflare/ai-chat/experimental/forever] WARNING: You are using an experimental API that WILL break between releases. Do not use in production.\"\n);\n\n// ── Mixin ─────────────────────────────────────────────────────────────\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any -- mixin constructor constraint\ntype Constructor<T = object> = new (...args: any[]) => T;\n\ntype AIChatAgentLike = Constructor<\n Pick<\n AIChatAgent,\n \"scheduleEvery\" | \"cancelSchedule\" | \"keepAlive\" | \"keepAliveWhile\"\n >\n>;\n\nexport function withDurableChat<TBase extends AIChatAgentLike>(Base: TBase) {\n class DurableChatAgent extends Base {\n // keepAlive() is inherited from Agent via AIChatAgent.\n // No override needed — the base implementation handles everything.\n }\n\n return DurableChatAgent;\n}\n"],"mappings":";AA+BA,QAAQ,KACN,oJACD;AAcD,SAAgB,gBAA+C,MAAa;CAC1E,MAAM,yBAAyB,KAAK;AAKpC,QAAO"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as ResumableStream } from "./resumable-stream-DqXxQVjf.js";
1
+ import { t as ResumableStream } from "./resumable-stream-DTLAk9XC.js";
2
2
  import {
3
3
  JSONSchema7,
4
4
  StreamTextOnFinishCallback,
@@ -181,6 +181,38 @@ declare class AIChatAgent<
181
181
  * ```
182
182
  */
183
183
  maxPersistedMessages: number | undefined;
184
+ /**
185
+ * When enabled, waits for all MCP server connections to be ready before
186
+ * calling `onChatMessage`. This prevents the race condition where
187
+ * `getAITools()` returns an incomplete set because connections are still
188
+ * restoring after Durable Object hibernation.
189
+ *
190
+ * - `false` (default) — non-blocking; `onChatMessage` runs immediately.
191
+ * - `true` — waits indefinitely for all connections to settle.
192
+ * - `{ timeout: number }` — waits up to `timeout` milliseconds.
193
+ *
194
+ * For lower-level control, call `this.mcp.waitForConnections()` directly
195
+ * inside your `onChatMessage` instead.
196
+ *
197
+ * @example
198
+ * ```typescript
199
+ * class MyAgent extends AIChatAgent<Env> {
200
+ * waitForMcpConnections = true;
201
+ * }
202
+ * ```
203
+ *
204
+ * @example
205
+ * ```typescript
206
+ * class MyAgent extends AIChatAgent<Env> {
207
+ * waitForMcpConnections = { timeout: 10_000 };
208
+ * }
209
+ * ```
210
+ */
211
+ waitForMcpConnections:
212
+ | boolean
213
+ | {
214
+ timeout: number;
215
+ };
184
216
  /** Array of chat messages for the current conversation */
185
217
  messages: UIMessage[];
186
218
  constructor(ctx: AgentContext, env: Env);
@@ -206,6 +238,16 @@ declare class AIChatAgent<
206
238
  protected _restoreActiveStream(): void;
207
239
  /** @internal Delegate to _resumableStream */
208
240
  protected _markStreamError(streamId: string): void;
241
+ /**
242
+ * Reconstruct and persist a partial assistant message from an orphaned
243
+ * stream's stored chunks. Called when the DO wakes from hibernation and
244
+ * discovers an active stream with no live LLM reader.
245
+ *
246
+ * Replays each chunk body through `applyChunkToParts` to rebuild the
247
+ * message parts, then persists the result so it survives further refreshes.
248
+ * @internal
249
+ */
250
+ private _persistOrphanedStream;
209
251
  /**
210
252
  * Restore _lastBody and _lastClientTools from SQLite.
211
253
  * Called in the constructor so these values survive DO hibernation.
@@ -247,7 +289,10 @@ declare class AIChatAgent<
247
289
  saveMessages(messages: UIMessage[]): Promise<void>;
248
290
  persistMessages(
249
291
  messages: UIMessage[],
250
- excludeBroadcastIds?: string[]
292
+ excludeBroadcastIds?: string[],
293
+ /** @internal */ options?: {
294
+ _deleteStaleRows?: boolean;
295
+ }
251
296
  ): Promise<void>;
252
297
  /**
253
298
  * Merges incoming messages with existing server state.
@@ -264,8 +309,18 @@ declare class AIChatAgent<
264
309
  * The client can keep a different local ID for an assistant message than the one
265
310
  * persisted on the server (e.g. optimistic/local IDs). When that full history is
266
311
  * sent back, persisting by ID alone creates duplicate assistant rows. To prevent
267
- * this, we reuse the server ID for assistant messages that match by content and
268
- * order, while leaving tool-call messages to _resolveMessageForToolMerge.
312
+ * this, we reuse the server ID for assistant messages that match by content,
313
+ * while leaving tool-call messages to _resolveMessageForToolMerge.
314
+ *
315
+ * Uses a two-pass approach:
316
+ * - Pass 1: resolve all exact-ID matches, claiming server indices.
317
+ * - Pass 2: content-based matching for remaining non-tool assistant messages,
318
+ * scanning only unclaimed server indices left-to-right.
319
+ *
320
+ * The two-pass design prevents exact-ID matches from advancing a cursor past
321
+ * server messages that a later incoming message needs for content matching.
322
+ * This fixes mismatches when two assistant messages have identical text
323
+ * (e.g. "Sure", "I understand") — see #1008.
269
324
  */
270
325
  private _reconcileAssistantIdsWithServerState;
271
326
  private _hasToolCallPart;
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
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
+ import { t as applyChunkToParts } from "./message-builder-uSvexDl2.js";
4
4
  import { jsonSchema, tool } from "ai";
5
5
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
6
6
  import { nanoid } from "nanoid";
@@ -35,6 +35,7 @@ var ResumableStream = class ResumableStream {
35
35
  this._activeStreamId = null;
36
36
  this._activeRequestId = null;
37
37
  this._streamChunkIndex = 0;
38
+ this._isLive = false;
38
39
  this._chunkBuffer = [];
39
40
  this._isFlushingChunks = false;
40
41
  this._lastCleanupTime = 0;
@@ -66,6 +67,13 @@ var ResumableStream = class ResumableStream {
66
67
  return this._activeStreamId !== null;
67
68
  }
68
69
  /**
70
+ * Whether the active stream has a live LLM reader (started in this
71
+ * instance) vs being restored from SQLite after hibernation (orphaned).
72
+ */
73
+ get isLive() {
74
+ return this._isLive;
75
+ }
76
+ /**
69
77
  * Start tracking a new stream for resumable streaming.
70
78
  * Creates metadata entry in SQLite and sets up tracking state.
71
79
  * @param requestId - The unique ID of the chat request
@@ -77,6 +85,7 @@ var ResumableStream = class ResumableStream {
77
85
  this._activeStreamId = streamId;
78
86
  this._activeRequestId = requestId;
79
87
  this._streamChunkIndex = 0;
88
+ this._isLive = true;
80
89
  this.sql`
81
90
  insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
82
91
  values (${streamId}, ${requestId}, 'streaming', ${Date.now()})
@@ -97,6 +106,7 @@ var ResumableStream = class ResumableStream {
97
106
  this._activeStreamId = null;
98
107
  this._activeRequestId = null;
99
108
  this._streamChunkIndex = 0;
109
+ this._isLive = false;
100
110
  this._maybeCleanupOldStreams();
101
111
  }
102
112
  /**
@@ -113,6 +123,7 @@ var ResumableStream = class ResumableStream {
113
123
  this._activeStreamId = null;
114
124
  this._activeRequestId = null;
115
125
  this._streamChunkIndex = 0;
126
+ this._isLive = false;
116
127
  }
117
128
  static {
118
129
  this.CHUNK_MAX_BYTES = 18e5;
@@ -163,12 +174,23 @@ var ResumableStream = class ResumableStream {
163
174
  /**
164
175
  * Send stored stream chunks to a connection for replay.
165
176
  * Chunks are marked with replay: true so the client can batch-apply them.
177
+ *
178
+ * Three outcomes:
179
+ * - **Live stream**: sends chunks + `replayComplete` — client flushes and
180
+ * continues receiving live chunks from the LLM reader.
181
+ * - **Orphaned stream** (restored from SQLite after hibernation, no reader):
182
+ * sends chunks + `done` and completes the stream. The caller should
183
+ * reconstruct and persist the partial message from the stored chunks.
184
+ * - **Completed during replay** (defensive): sends chunks + `done`.
185
+ *
166
186
  * @param connection - The WebSocket connection
167
187
  * @param requestId - The original request ID
188
+ * @returns The stream ID if the stream was orphaned and finalized, null otherwise.
189
+ * When non-null the caller should reconstruct the message from chunks.
168
190
  */
169
191
  replayChunks(connection, requestId) {
170
192
  const streamId = this._activeStreamId;
171
- if (!streamId) return;
193
+ if (!streamId) return null;
172
194
  this.flushBuffer();
173
195
  const chunks = this.sql`
174
196
  select * from cf_ai_chat_stream_chunks
@@ -182,13 +204,36 @@ var ResumableStream = class ResumableStream {
182
204
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
183
205
  replay: true
184
206
  }));
185
- if (this._activeStreamId !== streamId) connection.send(JSON.stringify({
207
+ if (this._activeStreamId !== streamId) {
208
+ connection.send(JSON.stringify({
209
+ body: "",
210
+ done: true,
211
+ id: requestId,
212
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
213
+ replay: true
214
+ }));
215
+ return null;
216
+ }
217
+ if (!this._isLive) {
218
+ connection.send(JSON.stringify({
219
+ body: "",
220
+ done: true,
221
+ id: requestId,
222
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
223
+ replay: true
224
+ }));
225
+ this.complete(streamId);
226
+ return streamId;
227
+ }
228
+ connection.send(JSON.stringify({
186
229
  body: "",
187
- done: true,
230
+ done: false,
188
231
  id: requestId,
189
232
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
190
- replay: true
233
+ replay: true,
234
+ replayComplete: true
191
235
  }));
236
+ return null;
192
237
  }
193
238
  /**
194
239
  * Restore active stream state if the agent was restarted during streaming.
@@ -368,6 +413,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
368
413
  this._pendingResumeConnections = /* @__PURE__ */ new Set();
369
414
  this._persistedMessageCache = /* @__PURE__ */ new Map();
370
415
  this.maxPersistedMessages = void 0;
416
+ this.waitForMcpConnections = { timeout: 1e4 };
371
417
  this.sql`create table if not exists cf_ai_chat_agent_messages (
372
418
  id text primary key,
373
419
  message text not null,
@@ -402,6 +448,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
402
448
  return _onMessage(connection, message);
403
449
  }
404
450
  if (data.type === MessageType.CF_AGENT_USE_CHAT_REQUEST && data.init.method === "POST") {
451
+ if (this.waitForMcpConnections) {
452
+ const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : void 0;
453
+ await this.mcp.waitForConnections(timeout != null ? { timeout } : void 0);
454
+ }
405
455
  const { body } = data.init;
406
456
  if (!body) {
407
457
  console.warn("[AIChatAgent] Received chat request with empty body, ignoring");
@@ -414,7 +464,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
414
464
  console.warn("[AIChatAgent] Received chat request with invalid JSON body, ignoring");
415
465
  return;
416
466
  }
417
- const { messages, clientTools, ...customBody } = parsed;
467
+ const { messages, clientTools, trigger: _trigger, ...customBody } = parsed;
418
468
  this._lastClientTools = clientTools?.length ? clientTools : void 0;
419
469
  this._lastBody = Object.keys(customBody).length > 0 ? customBody : void 0;
420
470
  this._persistRequestContext();
@@ -423,14 +473,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
423
473
  messages: transformedMessages,
424
474
  type: MessageType.CF_AGENT_CHAT_MESSAGES
425
475
  }, [connection.id]);
426
- await this.persistMessages(transformedMessages, [connection.id]);
476
+ await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
427
477
  this.observability?.emit({
428
- displayMessage: "Chat message request",
429
- id: data.id,
430
478
  payload: {},
431
479
  timestamp: Date.now(),
432
480
  type: "message:request"
433
- }, this.ctx);
481
+ });
434
482
  const chatMessageId = data.id;
435
483
  const abortSignal = this._getAbortSignal(chatMessageId);
436
484
  return this._tryCatchChat(async () => {
@@ -470,6 +518,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
470
518
  this._persistedMessageCache.clear();
471
519
  this.messages = [];
472
520
  this._broadcastChatMessage({ type: MessageType.CF_AGENT_CHAT_CLEAR }, [connection.id]);
521
+ this.observability?.emit({
522
+ type: "message:clear",
523
+ payload: {},
524
+ timestamp: Date.now()
525
+ });
473
526
  return;
474
527
  }
475
528
  if (data.type === MessageType.CF_AGENT_CHAT_MESSAGES) {
@@ -479,6 +532,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
479
532
  }
480
533
  if (data.type === MessageType.CF_AGENT_CHAT_REQUEST_CANCEL) {
481
534
  this._cancelChatRequest(data.id);
535
+ this.observability?.emit({
536
+ type: "message:cancel",
537
+ payload: { requestId: data.id },
538
+ timestamp: Date.now()
539
+ });
482
540
  return;
483
541
  }
484
542
  if (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {
@@ -487,7 +545,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
487
545
  }
488
546
  if (data.type === MessageType.CF_AGENT_STREAM_RESUME_ACK) {
489
547
  this._pendingResumeConnections.delete(connection.id);
490
- if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
548
+ if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) {
549
+ const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
550
+ if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
551
+ }
491
552
  return;
492
553
  }
493
554
  if (data.type === MessageType.CF_AGENT_TOOL_RESULT) {
@@ -497,6 +558,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
497
558
  this._persistRequestContext();
498
559
  }
499
560
  const overrideState = state === "output-error" ? "output-error" : void 0;
561
+ this.observability?.emit({
562
+ type: "tool:result",
563
+ payload: {
564
+ toolCallId,
565
+ toolName
566
+ },
567
+ timestamp: Date.now()
568
+ });
500
569
  this._applyToolResult(toolCallId, toolName, output, overrideState, errorText).then((applied) => {
501
570
  if (applied && autoContinue) {
502
571
  const waitForStream = async () => {
@@ -534,6 +603,14 @@ var AIChatAgent = class AIChatAgent extends Agent {
534
603
  }
535
604
  if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
536
605
  const { toolCallId, approved, autoContinue } = data;
606
+ this.observability?.emit({
607
+ type: "tool:approval",
608
+ payload: {
609
+ toolCallId,
610
+ approved
611
+ },
612
+ timestamp: Date.now()
613
+ });
537
614
  this._applyToolApproval(toolCallId, approved).then((applied) => {
538
615
  if (applied && autoContinue) {
539
616
  const waitForStream = async () => {
@@ -627,6 +704,38 @@ var AIChatAgent = class AIChatAgent extends Agent {
627
704
  this._resumableStream.markError(streamId);
628
705
  }
629
706
  /**
707
+ * Reconstruct and persist a partial assistant message from an orphaned
708
+ * stream's stored chunks. Called when the DO wakes from hibernation and
709
+ * discovers an active stream with no live LLM reader.
710
+ *
711
+ * Replays each chunk body through `applyChunkToParts` to rebuild the
712
+ * message parts, then persists the result so it survives further refreshes.
713
+ * @internal
714
+ */
715
+ _persistOrphanedStream(streamId) {
716
+ const chunks = this._resumableStream.getStreamChunks(streamId);
717
+ if (!chunks.length) return;
718
+ const message = {
719
+ id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
720
+ role: "assistant",
721
+ parts: []
722
+ };
723
+ for (const chunk of chunks) try {
724
+ const data = JSON.parse(chunk.body);
725
+ if (data.type === "start" && data.messageId != null) message.id = data.messageId;
726
+ if ((data.type === "start" || data.type === "finish" || data.type === "message-metadata") && data.messageMetadata != null) message.metadata = message.metadata ? {
727
+ ...message.metadata,
728
+ ...data.messageMetadata
729
+ } : data.messageMetadata;
730
+ applyChunkToParts(message.parts, data);
731
+ } catch {}
732
+ if (message.parts.length > 0) {
733
+ const existingIdx = this.messages.findIndex((m) => m.id === message.id);
734
+ const updatedMessages = existingIdx >= 0 ? this.messages.map((m, i) => i === existingIdx ? message : m) : [...this.messages, message];
735
+ this.persistMessages(updatedMessages);
736
+ }
737
+ }
738
+ /**
630
739
  * Restore _lastBody and _lastClientTools from SQLite.
631
740
  * Called in the constructor so these values survive DO hibernation.
632
741
  * @internal
@@ -733,7 +842,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
733
842
  if (response) this._reply(requestId, response);
734
843
  });
735
844
  }
736
- async persistMessages(messages, excludeBroadcastIds = []) {
845
+ async persistMessages(messages, excludeBroadcastIds = [], options) {
737
846
  const mergedMessages = this._mergeIncomingWithServerState(messages);
738
847
  for (const message of mergedMessages) {
739
848
  const sanitizedMessage = this._sanitizeMessageForPersistence(message);
@@ -748,6 +857,21 @@ var AIChatAgent = class AIChatAgent extends Agent {
748
857
  `;
749
858
  this._persistedMessageCache.set(safe.id, json);
750
859
  }
860
+ if (options?._deleteStaleRows) {
861
+ const serverIds = new Set(this.messages.map((m) => m.id));
862
+ if (mergedMessages.every((m) => serverIds.has(m.id))) {
863
+ const keepIds = new Set(mergedMessages.map((m) => m.id));
864
+ const allDbRows = this.sql`
865
+ select id from cf_ai_chat_agent_messages
866
+ ` || [];
867
+ for (const row of allDbRows) if (!keepIds.has(row.id)) {
868
+ this.sql`
869
+ delete from cf_ai_chat_agent_messages where id = ${row.id}
870
+ `;
871
+ this._persistedMessageCache.delete(row.id);
872
+ }
873
+ }
874
+ }
751
875
  if (this.maxPersistedMessages != null) this._enforceMaxPersistedMessages();
752
876
  this.messages = autoTransformMessages(this._loadMessagesFromDb());
753
877
  this._broadcastChatMessage({
@@ -773,7 +897,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
773
897
  if (msg.role !== "assistant") return msg;
774
898
  let hasChanges = false;
775
899
  const updatedParts = msg.parts.map((part) => {
776
- if ("toolCallId" in part && "state" in part && part.state === "input-available" && serverToolOutputs.has(part.toolCallId)) {
900
+ if ("toolCallId" in part && "state" in part && (part.state === "input-available" || part.state === "approval-requested" || part.state === "approval-responded") && serverToolOutputs.has(part.toolCallId)) {
777
901
  hasChanges = true;
778
902
  return {
779
903
  ...part,
@@ -796,26 +920,41 @@ var AIChatAgent = class AIChatAgent extends Agent {
796
920
  * The client can keep a different local ID for an assistant message than the one
797
921
  * persisted on the server (e.g. optimistic/local IDs). When that full history is
798
922
  * sent back, persisting by ID alone creates duplicate assistant rows. To prevent
799
- * this, we reuse the server ID for assistant messages that match by content and
800
- * order, while leaving tool-call messages to _resolveMessageForToolMerge.
923
+ * this, we reuse the server ID for assistant messages that match by content,
924
+ * while leaving tool-call messages to _resolveMessageForToolMerge.
925
+ *
926
+ * Uses a two-pass approach:
927
+ * - Pass 1: resolve all exact-ID matches, claiming server indices.
928
+ * - Pass 2: content-based matching for remaining non-tool assistant messages,
929
+ * scanning only unclaimed server indices left-to-right.
930
+ *
931
+ * The two-pass design prevents exact-ID matches from advancing a cursor past
932
+ * server messages that a later incoming message needs for content matching.
933
+ * This fixes mismatches when two assistant messages have identical text
934
+ * (e.g. "Sure", "I understand") — see #1008.
801
935
  */
802
936
  _reconcileAssistantIdsWithServerState(incomingMessages) {
803
937
  if (this.messages.length === 0) return incomingMessages;
804
- let serverCursor = 0;
805
- return incomingMessages.map((incomingMessage) => {
806
- const exactMatchIndex = this.messages.findIndex((serverMessage, index) => index >= serverCursor && serverMessage.id === incomingMessage.id);
807
- if (exactMatchIndex !== -1) {
808
- serverCursor = exactMatchIndex + 1;
809
- return incomingMessage;
938
+ const claimedServerIndices = /* @__PURE__ */ new Set();
939
+ const exactMatchMap = /* @__PURE__ */ new Map();
940
+ for (let i = 0; i < incomingMessages.length; i++) {
941
+ const serverIdx = this.messages.findIndex((sm, si) => !claimedServerIndices.has(si) && sm.id === incomingMessages[i].id);
942
+ if (serverIdx !== -1) {
943
+ claimedServerIndices.add(serverIdx);
944
+ exactMatchMap.set(i, serverIdx);
810
945
  }
946
+ }
947
+ return incomingMessages.map((incomingMessage, incomingIdx) => {
948
+ if (exactMatchMap.has(incomingIdx)) return incomingMessage;
811
949
  if (incomingMessage.role !== "assistant" || this._hasToolCallPart(incomingMessage)) return incomingMessage;
812
950
  const incomingKey = this._assistantMessageContentKey(incomingMessage);
813
951
  if (!incomingKey) return incomingMessage;
814
- for (let i = serverCursor; i < this.messages.length; i++) {
952
+ for (let i = 0; i < this.messages.length; i++) {
953
+ if (claimedServerIndices.has(i)) continue;
815
954
  const serverMessage = this.messages[i];
816
955
  if (serverMessage.role !== "assistant" || this._hasToolCallPart(serverMessage)) continue;
817
956
  if (this._assistantMessageContentKey(serverMessage) === incomingKey) {
818
- serverCursor = i + 1;
957
+ claimedServerIndices.add(i);
819
958
  return {
820
959
  ...incomingMessage,
821
960
  id: serverMessage.id
@@ -1372,7 +1511,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1372
1511
  async _reply(id, response, excludeBroadcastIds = [], options = {}) {
1373
1512
  const { continuation = false, chatMessageId } = options;
1374
1513
  const abortSignal = chatMessageId ? this._chatMessageAbortControllers.get(chatMessageId)?.signal : void 0;
1375
- return this._tryCatchChat(async () => {
1514
+ return this.keepAliveWhile(() => this._tryCatchChat(async () => {
1376
1515
  if (!response.body) {
1377
1516
  this._broadcastChatMessage({
1378
1517
  body: "",
@@ -1411,6 +1550,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
1411
1550
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1412
1551
  ...continuation && { continuation: true }
1413
1552
  });
1553
+ this.observability?.emit({
1554
+ type: "message:error",
1555
+ payload: { error: error instanceof Error ? error.message : String(error) },
1556
+ timestamp: Date.now()
1557
+ });
1414
1558
  }
1415
1559
  throw error;
1416
1560
  } finally {
@@ -1426,12 +1570,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
1426
1570
  if (chatMessageId) {
1427
1571
  this._removeAbortController(chatMessageId);
1428
1572
  if (streamCompleted.value) this.observability?.emit({
1429
- displayMessage: continuation ? "Chat message response (tool continuation)" : "Chat message response",
1430
- id: chatMessageId,
1431
1573
  payload: {},
1432
1574
  timestamp: Date.now(),
1433
1575
  type: "message:response"
1434
- }, this.ctx);
1576
+ });
1435
1577
  }
1436
1578
  }
1437
1579
  if (message.parts.length > 0) if (earlyPersistedId) {
@@ -1454,7 +1596,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1454
1596
  await this.persistMessages(updatedMessages, excludeBroadcastIds);
1455
1597
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
1456
1598
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
1457
- });
1599
+ }));
1458
1600
  }
1459
1601
  /**
1460
1602
  * For the given message id, look up its associated AbortController