@cloudflare/ai-chat 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/experimental/forever.d.ts +4 -13
  2. package/dist/experimental/forever.js +1 -46
  3. package/dist/experimental/forever.js.map +1 -1
  4. package/dist/index.d.ts +59 -4
  5. package/dist/index.js +150 -36
  6. package/dist/index.js.map +1 -1
  7. package/dist/{message-builder-Bwc_Umye.js → message-builder-uSvexDl2.js} +17 -4
  8. package/dist/message-builder-uSvexDl2.js.map +1 -0
  9. package/dist/react.js +96 -10
  10. package/dist/react.js.map +1 -1
  11. package/dist/{resumable-stream-DqXxQVjf.d.ts → resumable-stream-DTLAk9XC.d.ts} +25 -2
  12. package/dist/types.d.ts +2 -1
  13. package/dist/types.js.map +1 -1
  14. package/package.json +7 -3
  15. package/CHANGELOG.md +0 -251
  16. package/dist/message-builder-Bwc_Umye.js.map +0 -1
  17. package/e2e/chat.spec.ts +0 -1703
  18. package/e2e/client-tools.spec.ts +0 -504
  19. package/e2e/llm.spec.ts +0 -637
  20. package/e2e/playwright.config.ts +0 -27
  21. package/e2e/worker.ts +0 -174
  22. package/e2e/wrangler.jsonc +0 -23
  23. package/scripts/build.ts +0 -32
  24. package/src/ai-chat-v5-migration.ts +0 -403
  25. package/src/experimental/forever.ts +0 -66
  26. package/src/index.ts +0 -2269
  27. package/src/message-builder.ts +0 -384
  28. package/src/react-tests/setup.ts +0 -3
  29. package/src/react-tests/use-agent-chat.test.tsx +0 -1435
  30. package/src/react-tests/vitest.config.ts +0 -20
  31. package/src/react.tsx +0 -1447
  32. package/src/resumable-stream.ts +0 -441
  33. package/src/tests/cancel-request.test.ts +0 -280
  34. package/src/tests/chat-context.test.ts +0 -85
  35. package/src/tests/chat-persistence.test.ts +0 -426
  36. package/src/tests/clear-history.test.ts +0 -132
  37. package/src/tests/client-tool-duplicate-message.test.ts +0 -1957
  38. package/src/tests/client-tools-broadcast.test.ts +0 -138
  39. package/src/tests/client-tools-continuation.test.ts +0 -314
  40. package/src/tests/client-tools-reconnect.test.ts +0 -143
  41. package/src/tests/cloudflare-test.d.ts +0 -5
  42. package/src/tests/custom-body-continuation.test.ts +0 -309
  43. package/src/tests/custom-body.test.ts +0 -186
  44. package/src/tests/destroy.test.ts +0 -57
  45. package/src/tests/get-messages-endpoint.test.ts +0 -153
  46. package/src/tests/max-persisted-messages.test.ts +0 -201
  47. package/src/tests/merge-server-state.test.ts +0 -343
  48. package/src/tests/message-builder.test.ts +0 -808
  49. package/src/tests/migration.test.ts +0 -282
  50. package/src/tests/non-sse-response.test.ts +0 -186
  51. package/src/tests/onfinish-cleanup.test.ts +0 -362
  52. package/src/tests/plaintext-response.test.ts +0 -87
  53. package/src/tests/request-id.test.ts +0 -312
  54. package/src/tests/resumable-streaming.test.ts +0 -758
  55. package/src/tests/row-size-guard.test.ts +0 -374
  56. package/src/tests/sanitize-messages.test.ts +0 -325
  57. package/src/tests/test-utils.ts +0 -39
  58. package/src/tests/tsconfig.json +0 -10
  59. package/src/tests/validate-messages.test.ts +0 -269
  60. package/src/tests/vitest.config.ts +0 -30
  61. package/src/tests/worker.ts +0 -456
  62. package/src/tests/wrangler.jsonc +0 -50
  63. package/src/tests/ws-transport-abort.test.ts +0 -198
  64. package/src/types.ts +0 -152
  65. package/src/ws-chat-transport.ts +0 -227
  66. package/tsconfig.json +0 -4
  67. package/vitest.config.ts +0 -7
@@ -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,8 @@ 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]);
427
- this.observability?.emit({
428
- displayMessage: "Chat message request",
429
- id: data.id,
430
- payload: {},
431
- timestamp: Date.now(),
432
- type: "message:request"
433
- }, this.ctx);
476
+ await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
477
+ this._emit("message:request");
434
478
  const chatMessageId = data.id;
435
479
  const abortSignal = this._getAbortSignal(chatMessageId);
436
480
  return this._tryCatchChat(async () => {
@@ -470,6 +514,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
470
514
  this._persistedMessageCache.clear();
471
515
  this.messages = [];
472
516
  this._broadcastChatMessage({ type: MessageType.CF_AGENT_CHAT_CLEAR }, [connection.id]);
517
+ this._emit("message:clear");
473
518
  return;
474
519
  }
475
520
  if (data.type === MessageType.CF_AGENT_CHAT_MESSAGES) {
@@ -479,6 +524,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
479
524
  }
480
525
  if (data.type === MessageType.CF_AGENT_CHAT_REQUEST_CANCEL) {
481
526
  this._cancelChatRequest(data.id);
527
+ this._emit("message:cancel", { requestId: data.id });
482
528
  return;
483
529
  }
484
530
  if (data.type === MessageType.CF_AGENT_STREAM_RESUME_REQUEST) {
@@ -487,7 +533,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
487
533
  }
488
534
  if (data.type === MessageType.CF_AGENT_STREAM_RESUME_ACK) {
489
535
  this._pendingResumeConnections.delete(connection.id);
490
- if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
536
+ if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) {
537
+ const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
538
+ if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
539
+ }
491
540
  return;
492
541
  }
493
542
  if (data.type === MessageType.CF_AGENT_TOOL_RESULT) {
@@ -497,6 +546,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
497
546
  this._persistRequestContext();
498
547
  }
499
548
  const overrideState = state === "output-error" ? "output-error" : void 0;
549
+ this._emit("tool:result", {
550
+ toolCallId,
551
+ toolName
552
+ });
500
553
  this._applyToolResult(toolCallId, toolName, output, overrideState, errorText).then((applied) => {
501
554
  if (applied && autoContinue) {
502
555
  const waitForStream = async () => {
@@ -534,6 +587,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
534
587
  }
535
588
  if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
536
589
  const { toolCallId, approved, autoContinue } = data;
590
+ this._emit("tool:approval", {
591
+ toolCallId,
592
+ approved
593
+ });
537
594
  this._applyToolApproval(toolCallId, approved).then((applied) => {
538
595
  if (applied && autoContinue) {
539
596
  const waitForStream = async () => {
@@ -627,6 +684,38 @@ var AIChatAgent = class AIChatAgent extends Agent {
627
684
  this._resumableStream.markError(streamId);
628
685
  }
629
686
  /**
687
+ * Reconstruct and persist a partial assistant message from an orphaned
688
+ * stream's stored chunks. Called when the DO wakes from hibernation and
689
+ * discovers an active stream with no live LLM reader.
690
+ *
691
+ * Replays each chunk body through `applyChunkToParts` to rebuild the
692
+ * message parts, then persists the result so it survives further refreshes.
693
+ * @internal
694
+ */
695
+ _persistOrphanedStream(streamId) {
696
+ const chunks = this._resumableStream.getStreamChunks(streamId);
697
+ if (!chunks.length) return;
698
+ const message = {
699
+ id: `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
700
+ role: "assistant",
701
+ parts: []
702
+ };
703
+ for (const chunk of chunks) try {
704
+ const data = JSON.parse(chunk.body);
705
+ if (data.type === "start" && data.messageId != null) message.id = data.messageId;
706
+ if ((data.type === "start" || data.type === "finish" || data.type === "message-metadata") && data.messageMetadata != null) message.metadata = message.metadata ? {
707
+ ...message.metadata,
708
+ ...data.messageMetadata
709
+ } : data.messageMetadata;
710
+ applyChunkToParts(message.parts, data);
711
+ } catch {}
712
+ if (message.parts.length > 0) {
713
+ const existingIdx = this.messages.findIndex((m) => m.id === message.id);
714
+ const updatedMessages = existingIdx >= 0 ? this.messages.map((m, i) => i === existingIdx ? message : m) : [...this.messages, message];
715
+ this.persistMessages(updatedMessages);
716
+ }
717
+ }
718
+ /**
630
719
  * Restore _lastBody and _lastClientTools from SQLite.
631
720
  * Called in the constructor so these values survive DO hibernation.
632
721
  * @internal
@@ -733,7 +822,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
733
822
  if (response) this._reply(requestId, response);
734
823
  });
735
824
  }
736
- async persistMessages(messages, excludeBroadcastIds = []) {
825
+ async persistMessages(messages, excludeBroadcastIds = [], options) {
737
826
  const mergedMessages = this._mergeIncomingWithServerState(messages);
738
827
  for (const message of mergedMessages) {
739
828
  const sanitizedMessage = this._sanitizeMessageForPersistence(message);
@@ -748,6 +837,21 @@ var AIChatAgent = class AIChatAgent extends Agent {
748
837
  `;
749
838
  this._persistedMessageCache.set(safe.id, json);
750
839
  }
840
+ if (options?._deleteStaleRows) {
841
+ const serverIds = new Set(this.messages.map((m) => m.id));
842
+ if (mergedMessages.every((m) => serverIds.has(m.id))) {
843
+ const keepIds = new Set(mergedMessages.map((m) => m.id));
844
+ const allDbRows = this.sql`
845
+ select id from cf_ai_chat_agent_messages
846
+ ` || [];
847
+ for (const row of allDbRows) if (!keepIds.has(row.id)) {
848
+ this.sql`
849
+ delete from cf_ai_chat_agent_messages where id = ${row.id}
850
+ `;
851
+ this._persistedMessageCache.delete(row.id);
852
+ }
853
+ }
854
+ }
751
855
  if (this.maxPersistedMessages != null) this._enforceMaxPersistedMessages();
752
856
  this.messages = autoTransformMessages(this._loadMessagesFromDb());
753
857
  this._broadcastChatMessage({
@@ -773,7 +877,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
773
877
  if (msg.role !== "assistant") return msg;
774
878
  let hasChanges = false;
775
879
  const updatedParts = msg.parts.map((part) => {
776
- if ("toolCallId" in part && "state" in part && part.state === "input-available" && serverToolOutputs.has(part.toolCallId)) {
880
+ if ("toolCallId" in part && "state" in part && (part.state === "input-available" || part.state === "approval-requested" || part.state === "approval-responded") && serverToolOutputs.has(part.toolCallId)) {
777
881
  hasChanges = true;
778
882
  return {
779
883
  ...part,
@@ -796,26 +900,41 @@ var AIChatAgent = class AIChatAgent extends Agent {
796
900
  * The client can keep a different local ID for an assistant message than the one
797
901
  * persisted on the server (e.g. optimistic/local IDs). When that full history is
798
902
  * 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.
903
+ * this, we reuse the server ID for assistant messages that match by content,
904
+ * while leaving tool-call messages to _resolveMessageForToolMerge.
905
+ *
906
+ * Uses a two-pass approach:
907
+ * - Pass 1: resolve all exact-ID matches, claiming server indices.
908
+ * - Pass 2: content-based matching for remaining non-tool assistant messages,
909
+ * scanning only unclaimed server indices left-to-right.
910
+ *
911
+ * The two-pass design prevents exact-ID matches from advancing a cursor past
912
+ * server messages that a later incoming message needs for content matching.
913
+ * This fixes mismatches when two assistant messages have identical text
914
+ * (e.g. "Sure", "I understand") — see #1008.
801
915
  */
802
916
  _reconcileAssistantIdsWithServerState(incomingMessages) {
803
917
  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;
918
+ const claimedServerIndices = /* @__PURE__ */ new Set();
919
+ const exactMatchMap = /* @__PURE__ */ new Map();
920
+ for (let i = 0; i < incomingMessages.length; i++) {
921
+ const serverIdx = this.messages.findIndex((sm, si) => !claimedServerIndices.has(si) && sm.id === incomingMessages[i].id);
922
+ if (serverIdx !== -1) {
923
+ claimedServerIndices.add(serverIdx);
924
+ exactMatchMap.set(i, serverIdx);
810
925
  }
926
+ }
927
+ return incomingMessages.map((incomingMessage, incomingIdx) => {
928
+ if (exactMatchMap.has(incomingIdx)) return incomingMessage;
811
929
  if (incomingMessage.role !== "assistant" || this._hasToolCallPart(incomingMessage)) return incomingMessage;
812
930
  const incomingKey = this._assistantMessageContentKey(incomingMessage);
813
931
  if (!incomingKey) return incomingMessage;
814
- for (let i = serverCursor; i < this.messages.length; i++) {
932
+ for (let i = 0; i < this.messages.length; i++) {
933
+ if (claimedServerIndices.has(i)) continue;
815
934
  const serverMessage = this.messages[i];
816
935
  if (serverMessage.role !== "assistant" || this._hasToolCallPart(serverMessage)) continue;
817
936
  if (this._assistantMessageContentKey(serverMessage) === incomingKey) {
818
- serverCursor = i + 1;
937
+ claimedServerIndices.add(i);
819
938
  return {
820
939
  ...incomingMessage,
821
940
  id: serverMessage.id
@@ -1372,7 +1491,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1372
1491
  async _reply(id, response, excludeBroadcastIds = [], options = {}) {
1373
1492
  const { continuation = false, chatMessageId } = options;
1374
1493
  const abortSignal = chatMessageId ? this._chatMessageAbortControllers.get(chatMessageId)?.signal : void 0;
1375
- return this._tryCatchChat(async () => {
1494
+ return this.keepAliveWhile(() => this._tryCatchChat(async () => {
1376
1495
  if (!response.body) {
1377
1496
  this._broadcastChatMessage({
1378
1497
  body: "",
@@ -1411,6 +1530,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1411
1530
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1412
1531
  ...continuation && { continuation: true }
1413
1532
  });
1533
+ this._emit("message:error", { error: error instanceof Error ? error.message : String(error) });
1414
1534
  }
1415
1535
  throw error;
1416
1536
  } finally {
@@ -1425,13 +1545,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1425
1545
  }
1426
1546
  if (chatMessageId) {
1427
1547
  this._removeAbortController(chatMessageId);
1428
- if (streamCompleted.value) this.observability?.emit({
1429
- displayMessage: continuation ? "Chat message response (tool continuation)" : "Chat message response",
1430
- id: chatMessageId,
1431
- payload: {},
1432
- timestamp: Date.now(),
1433
- type: "message:response"
1434
- }, this.ctx);
1548
+ if (streamCompleted.value) this._emit("message:response");
1435
1549
  }
1436
1550
  }
1437
1551
  if (message.parts.length > 0) if (earlyPersistedId) {
@@ -1454,7 +1568,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1454
1568
  await this.persistMessages(updatedMessages, excludeBroadcastIds);
1455
1569
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
1456
1570
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
1457
- });
1571
+ }));
1458
1572
  }
1459
1573
  /**
1460
1574
  * For the given message id, look up its associated AbortController