@cloudflare/ai-chat 0.7.2 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -248,6 +248,35 @@ Streams automatically resume on disconnect/reconnect. No configuration needed.
248
248
 
249
249
  When a client disconnects mid-stream, chunks are buffered in SQLite. On reconnect, the client receives all buffered chunks and continues receiving the live stream.
250
250
 
251
+ This handles browser disconnects, navigation, and React cleanup while the Durable Object keeps running. To recover after the Durable Object itself is evicted during a model call, opt in to `chatRecovery`.
252
+
253
+ ## Durable Chat Recovery
254
+
255
+ `AIChatAgent` defaults `chatRecovery` to `false`. Enable it when you want chat turns to survive Worker deploys, Durable Object eviction, or process restarts:
256
+
257
+ ```typescript
258
+ import type {
259
+ ChatRecoveryContext,
260
+ ChatRecoveryOptions
261
+ } from "@cloudflare/ai-chat";
262
+
263
+ export class ChatAgent extends AIChatAgent<Env> {
264
+ override chatRecovery = {
265
+ maxAttempts: 6,
266
+ terminalMessage: "The assistant was interrupted. Please try again."
267
+ };
268
+
269
+ override async onChatRecovery(
270
+ ctx: ChatRecoveryContext
271
+ ): Promise<ChatRecoveryOptions> {
272
+ console.log("Recovering", ctx.incidentId, ctx.recoveryKind);
273
+ return {}; // persist partial output and continue/retry when possible
274
+ }
275
+ }
276
+ ```
277
+
278
+ See [`docs/chat-agents.md`](../../docs/chat-agents.md#stream-recovery) for provider-specific recovery strategies and observability events.
279
+
251
280
  Generic client stream abort/cleanup is local-only by default: the server turn continues and can be resumed later. An explicit `stop()` still cancels the server turn:
252
281
 
253
282
  ```tsx
@@ -431,9 +460,11 @@ Extends `Agent` from the `agents` package.
431
460
  | Property / Method | Type | Description |
432
461
  | ------------------------------------ | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
433
462
  | `messages` | `ChatMessage[]` | Current conversation messages (loaded from SQLite) |
463
+ | `chatRecovery` | `ChatRecoveryConfig` | Opt-in Durable Object eviction recovery for chat turns. Default: `false` |
434
464
  | `maxPersistedMessages` | `number \| undefined` | Max messages to keep in SQLite. Default: unlimited |
435
465
  | `messageConcurrency` | `MessageConcurrency` | Concurrency strategy for `sendMessage()` submits. Default: `"queue"` |
436
466
  | `onChatMessage(onFinish?, options?)` | Override | Handle incoming chat messages. Return a `Response`. `onFinish` is optional. |
467
+ | `onChatRecovery(ctx)` | Override | Customize recovery after a chat turn is interrupted while `chatRecovery` is enabled |
437
468
  | `onChatResponse(result)` | Override | Called after a chat turn completes. `result` has `message`, `requestId`, `status`, `continuation` |
438
469
  | `persistMessages(messages)` | `Promise<void>` | Manually persist messages (usually automatic) |
439
470
  | `saveMessages(messages, options?)` | `Promise<SaveMessagesResult>` | Persist messages and trigger `onChatMessage`. Accepts array or function. `options.signal` cancels the turn externally. |
@@ -472,11 +503,11 @@ React hook for chat interactions. Wraps the AI SDK's `useChat` with WebSocket tr
472
503
 
473
504
  ### Exports
474
505
 
475
- | Import path | What it provides |
476
- | --------------------------- | ------------------------------------------------------------ |
477
- | `@cloudflare/ai-chat` | `AIChatAgent`, `ChatMessage`, `createToolsFromClientSchemas` |
478
- | `@cloudflare/ai-chat/react` | `useAgentChat` |
479
- | `@cloudflare/ai-chat/types` | `MessageType`, `OutgoingMessage`, `IncomingMessage` |
506
+ | Import path | What it provides |
507
+ | --------------------------- | --------------------------------------------------------------------------------------------------------- |
508
+ | `@cloudflare/ai-chat` | `AIChatAgent`, `ChatMessage`, `createToolsFromClientSchemas`, `ChatRecoveryContext`, `ChatRecoveryConfig` |
509
+ | `@cloudflare/ai-chat/react` | `useAgentChat` |
510
+ | `@cloudflare/ai-chat/types` | `MessageType`, `OutgoingMessage`, `IncomingMessage` |
480
511
 
481
512
  ## Examples
482
513
 
@@ -1,9 +1,50 @@
1
+ import { normalizeToolInput } from "agents/chat";
1
2
  //#region src/ai-chat-v5-migration.ts
2
3
  /**
3
4
  * AI SDK v5 Migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages
4
5
  * Using exact types from the official AI SDK documentation
5
6
  */
6
7
  /**
8
+ * Heal tool parts whose persisted `input` is not a provider-acceptable object.
9
+ *
10
+ * The write boundary (`applyChunkToParts`) now coerces malformed input to `{}`,
11
+ * but sessions corrupted before that guard shipped still carry a `null`,
12
+ * `undefined`, `""`, array, or stringified-JSON `input` in storage. Because
13
+ * the Anthropic Messages API rejects a `tool_use` block whose `input` is not an
14
+ * object, such a session 400s on every later turn and stays wedged across
15
+ * reconnects/redeploys/evictions. Repairing on load (where there's no
16
+ * framework-side `convertToModelMessages` to hook) unwedges them without
17
+ * per-DO storage surgery. Only malformed inputs are touched; a healthy message
18
+ * is returned by reference so the persistence cache stays a no-op.
19
+ *
20
+ * An absent `input` key is treated as `undefined` (→ `{}`): a JSON round-trip of
21
+ * `input: undefined` drops the key entirely (e.g. a tool call interrupted at the
22
+ * `tool-input-start` stage), so the missing-key case must coerce too. Mirrors
23
+ * the read-side repair in `@cloudflare/think`.
24
+ */
25
+ function normalizeToolPartInputs(message) {
26
+ const parts = message.parts;
27
+ const isMalformedToolPart = (part) => {
28
+ const record = part;
29
+ const type = typeof record.type === "string" ? record.type : "";
30
+ if (!(type.startsWith("tool-") || type === "dynamic-tool")) return false;
31
+ return normalizeToolInput(record.input).changed;
32
+ };
33
+ if (!parts.some(isMalformedToolPart)) return message;
34
+ const nextParts = parts.map((part) => {
35
+ if (!isMalformedToolPart(part)) return part;
36
+ const record = part;
37
+ return {
38
+ ...record,
39
+ input: normalizeToolInput(record.input).input
40
+ };
41
+ });
42
+ return {
43
+ ...message,
44
+ parts: nextParts
45
+ };
46
+ }
47
+ /**
7
48
  * One-shot deprecation warnings (warns once per key per session).
8
49
  */
9
50
  const _deprecationWarnings = /* @__PURE__ */ new Set();
@@ -49,7 +90,7 @@ function isCorruptArrayMessage(message) {
49
90
  * @returns UIMessage in v5 format
50
91
  */
51
92
  function autoTransformMessage(message, index = 0) {
52
- if (isUIMessage(message)) return message;
93
+ if (isUIMessage(message)) return normalizeToolPartInputs(message);
53
94
  const parts = [];
54
95
  if (message.reasoning) parts.push({
55
96
  type: "reasoning",
@@ -95,11 +136,11 @@ function autoTransformMessage(message, index = 0) {
95
136
  type: "text",
96
137
  text: typeof message === "string" ? message : JSON.stringify(message)
97
138
  });
98
- return {
139
+ return normalizeToolPartInputs({
99
140
  id: message.id || `msg-${index}`,
100
141
  role: message.role === "data" ? "system" : message.role || "user",
101
142
  parts
102
- };
143
+ });
103
144
  }
104
145
  /**
105
146
  * Legacy single message migration for backward compatibility.
@@ -1 +1 @@
1
- {"version":3,"file":"ai-chat-v5-migration.js","names":[],"sources":["../src/ai-chat-v5-migration.ts"],"sourcesContent":["import type { UIMessage } from \"ai\";\n\n/**\n * AI SDK v5 Migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages\n * Using exact types from the official AI SDK documentation\n */\n\n/**\n * One-shot deprecation warnings (warns once per key per session).\n */\nconst _deprecationWarnings = new Set<string>();\nfunction warnDeprecated(id: string, message: string) {\n if (!_deprecationWarnings.has(id)) {\n _deprecationWarnings.add(id);\n console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);\n }\n}\n\n/**\n * AI SDK v5 Message Part types reference (from official AI SDK documentation)\n *\n * The migration logic below transforms legacy messages to match these official AI SDK v5 formats:\n * - TextUIPart: { type: \"text\", text: string, state?: \"streaming\" | \"done\" }\n * - ReasoningUIPart: { type: \"reasoning\", text: string, state?: \"streaming\" | \"done\", providerMetadata?: Record<string, unknown> }\n * - FileUIPart: { type: \"file\", mediaType: string, filename?: string, url: string }\n * - ToolUIPart: { type: `tool-${string}`, toolCallId: string, state: \"input-streaming\" | \"input-available\" | \"output-available\" | \"output-error\", input?: Record<string, unknown>, output?: unknown, errorText?: string, providerExecuted?: boolean }\n */\n\n/**\n * Tool invocation from v4 format\n */\ntype ToolInvocation = {\n toolCallId: string;\n toolName: string;\n args: Record<string, unknown>;\n result?: unknown;\n state: \"partial-call\" | \"call\" | \"result\" | \"error\";\n};\n\n/**\n * Legacy part from v4 format\n */\ntype LegacyPart = {\n type: string;\n text?: string;\n url?: string;\n data?: string;\n mimeType?: string;\n mediaType?: string;\n filename?: string;\n};\n\n/**\n * Legacy message format from AI SDK v4\n */\nexport type LegacyMessage = {\n id?: string;\n role: string;\n content: string;\n reasoning?: string;\n toolInvocations?: ToolInvocation[];\n parts?: LegacyPart[];\n [key: string]: unknown;\n};\n\n/**\n * Corrupt content item\n */\ntype CorruptContentItem = {\n type: string;\n text: string;\n};\n\n/**\n * Corrupted message format - has content as array instead of parts\n */\nexport type CorruptArrayMessage = {\n id?: string;\n role: string;\n content: CorruptContentItem[];\n reasoning?: string;\n toolInvocations?: ToolInvocation[];\n [key: string]: unknown;\n};\n\n/**\n * Union type for messages that could be in any format\n */\nexport type MigratableMessage = LegacyMessage | CorruptArrayMessage | UIMessage;\n\n/**\n * Tool call state mapping for v4 to v5 migration\n */\nconst STATE_MAP = {\n \"partial-call\": \"input-streaming\",\n call: \"input-available\",\n result: \"output-available\",\n error: \"output-error\"\n} as const;\n\n/**\n * Checks if a message is already in the UIMessage format (has parts array)\n */\nexport function isUIMessage(message: unknown): message is UIMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"parts\" in message &&\n Array.isArray((message as { parts: unknown }).parts)\n );\n}\n\n/**\n * Type guard to check if a message is in legacy format (content as string)\n */\nfunction isLegacyMessage(message: unknown): message is LegacyMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"role\" in message &&\n \"content\" in message &&\n typeof (message as { role: unknown }).role === \"string\" &&\n typeof (message as { content: unknown }).content === \"string\"\n );\n}\n\n/**\n * Type guard to check if a message has corrupted array content format\n * Detects: {role: \"user\", content: [{type: \"text\", text: \"...\"}]}\n */\nfunction isCorruptArrayMessage(\n message: unknown\n): message is CorruptArrayMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"role\" in message &&\n \"content\" in message &&\n typeof (message as { role: unknown }).role === \"string\" &&\n Array.isArray((message as { content: unknown }).content) &&\n !(\"parts\" in message) // Ensure it's not already a UIMessage\n );\n}\n\n/**\n * Internal message part type for transformation\n */\ntype TransformMessagePart = {\n type: string;\n text?: string;\n toolCallId?: string;\n state?: string;\n input?: Record<string, unknown>;\n output?: unknown;\n url?: string;\n mediaType?: string;\n errorText?: string;\n filename?: string;\n};\n\n/**\n * Input message that could be in any format - using unknown for flexibility\n */\ntype InputMessage = {\n id?: string;\n role?: string;\n content?: unknown;\n reasoning?: string;\n toolInvocations?: unknown[];\n parts?: unknown[];\n [key: string]: unknown;\n};\n\n/**\n * Automatic message transformer following the blog post pattern\n * Handles comprehensive migration from AI SDK v4 to v5 format\n * @param message - Message in any legacy format\n * @param index - Index for ID generation fallback\n * @returns UIMessage in v5 format\n */\nexport function autoTransformMessage(\n message: UIMessage | InputMessage,\n index = 0\n): UIMessage {\n // Already in v5 format\n if (isUIMessage(message)) {\n return message;\n }\n\n const parts: TransformMessagePart[] = [];\n\n // Handle reasoning transformation\n if (message.reasoning) {\n parts.push({\n type: \"reasoning\",\n text: message.reasoning\n });\n }\n\n // Handle tool invocations transformation\n if (message.toolInvocations && Array.isArray(message.toolInvocations)) {\n message.toolInvocations.forEach((inv: unknown) => {\n if (typeof inv === \"object\" && inv !== null && \"toolName\" in inv) {\n const invObj = inv as ToolInvocation;\n parts.push({\n type: `tool-${invObj.toolName}`,\n toolCallId: invObj.toolCallId,\n state:\n STATE_MAP[invObj.state as keyof typeof STATE_MAP] ||\n \"input-available\",\n input: invObj.args,\n output: invObj.result !== undefined ? invObj.result : null\n });\n }\n });\n }\n\n // Handle file parts transformation\n if (message.parts && Array.isArray(message.parts)) {\n message.parts.forEach((part: unknown) => {\n if (typeof part === \"object\" && part !== null && \"type\" in part) {\n const partObj = part as LegacyPart;\n if (partObj.type === \"file\") {\n parts.push({\n type: \"file\",\n url:\n partObj.url ||\n (partObj.data\n ? `data:${partObj.mimeType || partObj.mediaType};base64,${partObj.data}`\n : undefined),\n mediaType: partObj.mediaType || partObj.mimeType,\n filename: partObj.filename\n });\n }\n }\n });\n }\n\n // Handle corrupt array format: {role: \"user\", content: [{type: \"text\", text: \"...\"}]}\n if (Array.isArray(message.content)) {\n message.content.forEach((item: unknown) => {\n if (typeof item === \"object\" && item !== null && \"text\" in item) {\n const itemObj = item as CorruptContentItem;\n parts.push({\n type: itemObj.type || \"text\",\n text: itemObj.text || \"\"\n });\n }\n });\n }\n\n // Fallback: convert plain content to text part\n if (!parts.length && message.content !== undefined) {\n parts.push({\n type: \"text\",\n text:\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content)\n });\n }\n\n // If still no parts, create a default text part\n if (!parts.length) {\n parts.push({\n type: \"text\",\n text: typeof message === \"string\" ? message : JSON.stringify(message)\n });\n }\n\n return {\n id: message.id || `msg-${index}`,\n role:\n message.role === \"data\"\n ? \"system\"\n : (message.role as \"user\" | \"assistant\" | \"system\") || \"user\",\n parts: parts as UIMessage[\"parts\"]\n };\n}\n\n/**\n * Legacy single message migration for backward compatibility.\n * @deprecated Use `autoTransformMessage` instead. Will be removed in the next major version.\n */\nexport function migrateToUIMessage(message: MigratableMessage): UIMessage {\n warnDeprecated(\n \"migrateToUIMessage\",\n \"migrateToUIMessage() is deprecated. Use autoTransformMessage() instead. It will be removed in the next major version.\"\n );\n return autoTransformMessage(message as InputMessage);\n}\n\n/**\n * Automatic message transformer for arrays following the blog post pattern\n * @param messages - Array of messages in any format\n * @returns Array of UIMessages in v5 format\n */\nexport function autoTransformMessages(messages: unknown[]): UIMessage[] {\n return messages.map((msg, i) => autoTransformMessage(msg as InputMessage, i));\n}\n\n/**\n * Migrates an array of messages to UIMessage format (legacy compatibility).\n * @param messages - Array of messages in old or new format\n * @returns Array of UIMessages in the new format\n * @deprecated Use `autoTransformMessages` instead. Will be removed in the next major version.\n */\nexport function migrateMessagesToUIFormat(\n messages: MigratableMessage[]\n): UIMessage[] {\n warnDeprecated(\n \"migrateMessagesToUIFormat\",\n \"migrateMessagesToUIFormat() is deprecated. Use autoTransformMessages() instead. It will be removed in the next major version.\"\n );\n return autoTransformMessages(messages as InputMessage[]);\n}\n\n/**\n * Checks if any messages in an array need migration.\n * @param messages - Array of messages to check\n * @returns true if any messages are not in proper UIMessage format\n * @deprecated Migration is now automatic via `autoTransformMessages`. Will be removed in the next major version.\n */\nexport function needsMigration(messages: unknown[]): boolean {\n warnDeprecated(\n \"needsMigration\",\n \"needsMigration() is deprecated. Migration is automatic via autoTransformMessages(). It will be removed in the next major version.\"\n );\n return messages.some((message) => {\n // If it's already a UIMessage, no migration needed\n if (isUIMessage(message)) {\n return false;\n }\n\n // Check for corrupt array format specifically\n if (isCorruptArrayMessage(message)) {\n return true;\n }\n\n // Check for legacy string format\n if (isLegacyMessage(message)) {\n return true;\n }\n\n // Any other format needs migration\n return true;\n });\n}\n\n/**\n * Analyzes the corruption types in a message array for debugging.\n * @param messages - Array of messages to analyze\n * @returns Statistics about corruption types found\n * @deprecated Migration is now automatic. Use this only for debugging legacy data. Will be removed in the next major version.\n */\nexport function analyzeCorruption(messages: unknown[]): {\n total: number;\n clean: number;\n legacyString: number;\n corruptArray: number;\n unknown: number;\n examples: {\n legacyString?: unknown;\n corruptArray?: unknown;\n unknown?: unknown;\n };\n} {\n const stats = {\n total: messages.length,\n clean: 0,\n legacyString: 0,\n corruptArray: 0,\n unknown: 0,\n examples: {} as {\n legacyString?: unknown;\n corruptArray?: unknown;\n unknown?: unknown;\n }\n };\n\n for (const message of messages) {\n if (isUIMessage(message)) {\n stats.clean++;\n } else if (isCorruptArrayMessage(message)) {\n stats.corruptArray++;\n if (!stats.examples.corruptArray) {\n stats.examples.corruptArray = message;\n }\n } else if (isLegacyMessage(message)) {\n stats.legacyString++;\n if (!stats.examples.legacyString) {\n stats.examples.legacyString = message;\n }\n } else {\n stats.unknown++;\n if (!stats.examples.unknown) {\n stats.examples.unknown = message;\n }\n }\n }\n\n return stats;\n}\n"],"mappings":";;;;;;;;AAUA,MAAM,uCAAuB,IAAI,IAAY;AAC7C,SAAS,eAAe,IAAY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;;;;;;AAQA,SAAgB,eAAe,UAA8B;CAC3D,eACE,kBACA,mIACF;CACA,OAAO,SAAS,MAAM,YAAY;EAEhC,IAAI,YAAY,OAAO,GACrB,OAAO;EAIT,IAAI,sBAAsB,OAAO,GAC/B,OAAO;EAIT,IAAI,gBAAgB,OAAO,GACzB,OAAO;EAIT,OAAO;CACT,CAAC;AACH;;;;;;;AAQA,SAAgB,kBAAkB,UAWhC;CACA,MAAM,QAAQ;EACZ,OAAO,SAAS;EAChB,OAAO;EACP,cAAc;EACd,cAAc;EACd,SAAS;EACT,UAAU,CAAC;CAKb;CAEA,KAAK,MAAM,WAAW,UACpB,IAAI,YAAY,OAAO,GACrB,MAAM;MACD,IAAI,sBAAsB,OAAO,GAAG;EACzC,MAAM;EACN,IAAI,CAAC,MAAM,SAAS,cAClB,MAAM,SAAS,eAAe;CAElC,OAAO,IAAI,gBAAgB,OAAO,GAAG;EACnC,MAAM;EACN,IAAI,CAAC,MAAM,SAAS,cAClB,MAAM,SAAS,eAAe;CAElC,OAAO;EACL,MAAM;EACN,IAAI,CAAC,MAAM,SAAS,SAClB,MAAM,SAAS,UAAU;CAE7B;CAGF,OAAO;AACT"}
1
+ {"version":3,"file":"ai-chat-v5-migration.js","names":[],"sources":["../src/ai-chat-v5-migration.ts"],"sourcesContent":["import type { UIMessage } from \"ai\";\nimport { normalizeToolInput } from \"agents/chat\";\n\n/**\n * AI SDK v5 Migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages\n * Using exact types from the official AI SDK documentation\n */\n\n/**\n * Heal tool parts whose persisted `input` is not a provider-acceptable object.\n *\n * The write boundary (`applyChunkToParts`) now coerces malformed input to `{}`,\n * but sessions corrupted before that guard shipped still carry a `null`,\n * `undefined`, `\"\"`, array, or stringified-JSON `input` in storage. Because\n * the Anthropic Messages API rejects a `tool_use` block whose `input` is not an\n * object, such a session 400s on every later turn and stays wedged across\n * reconnects/redeploys/evictions. Repairing on load (where there's no\n * framework-side `convertToModelMessages` to hook) unwedges them without\n * per-DO storage surgery. Only malformed inputs are touched; a healthy message\n * is returned by reference so the persistence cache stays a no-op.\n *\n * An absent `input` key is treated as `undefined` (→ `{}`): a JSON round-trip of\n * `input: undefined` drops the key entirely (e.g. a tool call interrupted at the\n * `tool-input-start` stage), so the missing-key case must coerce too. Mirrors\n * the read-side repair in `@cloudflare/think`.\n */\nfunction normalizeToolPartInputs(message: UIMessage): UIMessage {\n const parts = message.parts;\n const isMalformedToolPart = (part: unknown): boolean => {\n const record = part as Record<string, unknown>;\n const type = typeof record.type === \"string\" ? record.type : \"\";\n if (!(type.startsWith(\"tool-\") || type === \"dynamic-tool\")) return false;\n return normalizeToolInput(record.input).changed;\n };\n\n if (!parts.some(isMalformedToolPart)) return message;\n\n const nextParts = parts.map((part) => {\n if (!isMalformedToolPart(part)) return part;\n const record = part as Record<string, unknown>;\n return {\n ...record,\n input: normalizeToolInput(record.input).input\n } as UIMessage[\"parts\"][number];\n });\n return { ...message, parts: nextParts };\n}\n\n/**\n * One-shot deprecation warnings (warns once per key per session).\n */\nconst _deprecationWarnings = new Set<string>();\nfunction warnDeprecated(id: string, message: string) {\n if (!_deprecationWarnings.has(id)) {\n _deprecationWarnings.add(id);\n console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);\n }\n}\n\n/**\n * AI SDK v5 Message Part types reference (from official AI SDK documentation)\n *\n * The migration logic below transforms legacy messages to match these official AI SDK v5 formats:\n * - TextUIPart: { type: \"text\", text: string, state?: \"streaming\" | \"done\" }\n * - ReasoningUIPart: { type: \"reasoning\", text: string, state?: \"streaming\" | \"done\", providerMetadata?: Record<string, unknown> }\n * - FileUIPart: { type: \"file\", mediaType: string, filename?: string, url: string }\n * - ToolUIPart: { type: `tool-${string}`, toolCallId: string, state: \"input-streaming\" | \"input-available\" | \"output-available\" | \"output-error\", input?: Record<string, unknown>, output?: unknown, errorText?: string, providerExecuted?: boolean }\n */\n\n/**\n * Tool invocation from v4 format\n */\ntype ToolInvocation = {\n toolCallId: string;\n toolName: string;\n args: Record<string, unknown>;\n result?: unknown;\n state: \"partial-call\" | \"call\" | \"result\" | \"error\";\n};\n\n/**\n * Legacy part from v4 format\n */\ntype LegacyPart = {\n type: string;\n text?: string;\n url?: string;\n data?: string;\n mimeType?: string;\n mediaType?: string;\n filename?: string;\n};\n\n/**\n * Legacy message format from AI SDK v4\n */\nexport type LegacyMessage = {\n id?: string;\n role: string;\n content: string;\n reasoning?: string;\n toolInvocations?: ToolInvocation[];\n parts?: LegacyPart[];\n [key: string]: unknown;\n};\n\n/**\n * Corrupt content item\n */\ntype CorruptContentItem = {\n type: string;\n text: string;\n};\n\n/**\n * Corrupted message format - has content as array instead of parts\n */\nexport type CorruptArrayMessage = {\n id?: string;\n role: string;\n content: CorruptContentItem[];\n reasoning?: string;\n toolInvocations?: ToolInvocation[];\n [key: string]: unknown;\n};\n\n/**\n * Union type for messages that could be in any format\n */\nexport type MigratableMessage = LegacyMessage | CorruptArrayMessage | UIMessage;\n\n/**\n * Tool call state mapping for v4 to v5 migration\n */\nconst STATE_MAP = {\n \"partial-call\": \"input-streaming\",\n call: \"input-available\",\n result: \"output-available\",\n error: \"output-error\"\n} as const;\n\n/**\n * Checks if a message is already in the UIMessage format (has parts array)\n */\nexport function isUIMessage(message: unknown): message is UIMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"parts\" in message &&\n Array.isArray((message as { parts: unknown }).parts)\n );\n}\n\n/**\n * Type guard to check if a message is in legacy format (content as string)\n */\nfunction isLegacyMessage(message: unknown): message is LegacyMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"role\" in message &&\n \"content\" in message &&\n typeof (message as { role: unknown }).role === \"string\" &&\n typeof (message as { content: unknown }).content === \"string\"\n );\n}\n\n/**\n * Type guard to check if a message has corrupted array content format\n * Detects: {role: \"user\", content: [{type: \"text\", text: \"...\"}]}\n */\nfunction isCorruptArrayMessage(\n message: unknown\n): message is CorruptArrayMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"role\" in message &&\n \"content\" in message &&\n typeof (message as { role: unknown }).role === \"string\" &&\n Array.isArray((message as { content: unknown }).content) &&\n !(\"parts\" in message) // Ensure it's not already a UIMessage\n );\n}\n\n/**\n * Internal message part type for transformation\n */\ntype TransformMessagePart = {\n type: string;\n text?: string;\n toolCallId?: string;\n state?: string;\n input?: Record<string, unknown>;\n output?: unknown;\n url?: string;\n mediaType?: string;\n errorText?: string;\n filename?: string;\n};\n\n/**\n * Input message that could be in any format - using unknown for flexibility\n */\ntype InputMessage = {\n id?: string;\n role?: string;\n content?: unknown;\n reasoning?: string;\n toolInvocations?: unknown[];\n parts?: unknown[];\n [key: string]: unknown;\n};\n\n/**\n * Automatic message transformer following the blog post pattern\n * Handles comprehensive migration from AI SDK v4 to v5 format\n * @param message - Message in any legacy format\n * @param index - Index for ID generation fallback\n * @returns UIMessage in v5 format\n */\nexport function autoTransformMessage(\n message: UIMessage | InputMessage,\n index = 0\n): UIMessage {\n // Already in v5 format\n if (isUIMessage(message)) {\n return normalizeToolPartInputs(message);\n }\n\n const parts: TransformMessagePart[] = [];\n\n // Handle reasoning transformation\n if (message.reasoning) {\n parts.push({\n type: \"reasoning\",\n text: message.reasoning\n });\n }\n\n // Handle tool invocations transformation\n if (message.toolInvocations && Array.isArray(message.toolInvocations)) {\n message.toolInvocations.forEach((inv: unknown) => {\n if (typeof inv === \"object\" && inv !== null && \"toolName\" in inv) {\n const invObj = inv as ToolInvocation;\n parts.push({\n type: `tool-${invObj.toolName}`,\n toolCallId: invObj.toolCallId,\n state:\n STATE_MAP[invObj.state as keyof typeof STATE_MAP] ||\n \"input-available\",\n input: invObj.args,\n output: invObj.result !== undefined ? invObj.result : null\n });\n }\n });\n }\n\n // Handle file parts transformation\n if (message.parts && Array.isArray(message.parts)) {\n message.parts.forEach((part: unknown) => {\n if (typeof part === \"object\" && part !== null && \"type\" in part) {\n const partObj = part as LegacyPart;\n if (partObj.type === \"file\") {\n parts.push({\n type: \"file\",\n url:\n partObj.url ||\n (partObj.data\n ? `data:${partObj.mimeType || partObj.mediaType};base64,${partObj.data}`\n : undefined),\n mediaType: partObj.mediaType || partObj.mimeType,\n filename: partObj.filename\n });\n }\n }\n });\n }\n\n // Handle corrupt array format: {role: \"user\", content: [{type: \"text\", text: \"...\"}]}\n if (Array.isArray(message.content)) {\n message.content.forEach((item: unknown) => {\n if (typeof item === \"object\" && item !== null && \"text\" in item) {\n const itemObj = item as CorruptContentItem;\n parts.push({\n type: itemObj.type || \"text\",\n text: itemObj.text || \"\"\n });\n }\n });\n }\n\n // Fallback: convert plain content to text part\n if (!parts.length && message.content !== undefined) {\n parts.push({\n type: \"text\",\n text:\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content)\n });\n }\n\n // If still no parts, create a default text part\n if (!parts.length) {\n parts.push({\n type: \"text\",\n text: typeof message === \"string\" ? message : JSON.stringify(message)\n });\n }\n\n return normalizeToolPartInputs({\n id: message.id || `msg-${index}`,\n role:\n message.role === \"data\"\n ? \"system\"\n : (message.role as \"user\" | \"assistant\" | \"system\") || \"user\",\n parts: parts as UIMessage[\"parts\"]\n });\n}\n\n/**\n * Legacy single message migration for backward compatibility.\n * @deprecated Use `autoTransformMessage` instead. Will be removed in the next major version.\n */\nexport function migrateToUIMessage(message: MigratableMessage): UIMessage {\n warnDeprecated(\n \"migrateToUIMessage\",\n \"migrateToUIMessage() is deprecated. Use autoTransformMessage() instead. It will be removed in the next major version.\"\n );\n return autoTransformMessage(message as InputMessage);\n}\n\n/**\n * Automatic message transformer for arrays following the blog post pattern\n * @param messages - Array of messages in any format\n * @returns Array of UIMessages in v5 format\n */\nexport function autoTransformMessages(messages: unknown[]): UIMessage[] {\n return messages.map((msg, i) => autoTransformMessage(msg as InputMessage, i));\n}\n\n/**\n * Migrates an array of messages to UIMessage format (legacy compatibility).\n * @param messages - Array of messages in old or new format\n * @returns Array of UIMessages in the new format\n * @deprecated Use `autoTransformMessages` instead. Will be removed in the next major version.\n */\nexport function migrateMessagesToUIFormat(\n messages: MigratableMessage[]\n): UIMessage[] {\n warnDeprecated(\n \"migrateMessagesToUIFormat\",\n \"migrateMessagesToUIFormat() is deprecated. Use autoTransformMessages() instead. It will be removed in the next major version.\"\n );\n return autoTransformMessages(messages as InputMessage[]);\n}\n\n/**\n * Checks if any messages in an array need migration.\n * @param messages - Array of messages to check\n * @returns true if any messages are not in proper UIMessage format\n * @deprecated Migration is now automatic via `autoTransformMessages`. Will be removed in the next major version.\n */\nexport function needsMigration(messages: unknown[]): boolean {\n warnDeprecated(\n \"needsMigration\",\n \"needsMigration() is deprecated. Migration is automatic via autoTransformMessages(). It will be removed in the next major version.\"\n );\n return messages.some((message) => {\n // If it's already a UIMessage, no migration needed\n if (isUIMessage(message)) {\n return false;\n }\n\n // Check for corrupt array format specifically\n if (isCorruptArrayMessage(message)) {\n return true;\n }\n\n // Check for legacy string format\n if (isLegacyMessage(message)) {\n return true;\n }\n\n // Any other format needs migration\n return true;\n });\n}\n\n/**\n * Analyzes the corruption types in a message array for debugging.\n * @param messages - Array of messages to analyze\n * @returns Statistics about corruption types found\n * @deprecated Migration is now automatic. Use this only for debugging legacy data. Will be removed in the next major version.\n */\nexport function analyzeCorruption(messages: unknown[]): {\n total: number;\n clean: number;\n legacyString: number;\n corruptArray: number;\n unknown: number;\n examples: {\n legacyString?: unknown;\n corruptArray?: unknown;\n unknown?: unknown;\n };\n} {\n const stats = {\n total: messages.length,\n clean: 0,\n legacyString: 0,\n corruptArray: 0,\n unknown: 0,\n examples: {} as {\n legacyString?: unknown;\n corruptArray?: unknown;\n unknown?: unknown;\n }\n };\n\n for (const message of messages) {\n if (isUIMessage(message)) {\n stats.clean++;\n } else if (isCorruptArrayMessage(message)) {\n stats.corruptArray++;\n if (!stats.examples.corruptArray) {\n stats.examples.corruptArray = message;\n }\n } else if (isLegacyMessage(message)) {\n stats.legacyString++;\n if (!stats.examples.legacyString) {\n stats.examples.legacyString = message;\n }\n } else {\n stats.unknown++;\n if (!stats.examples.un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AAS,eAAe;CAElC,OAAO,IAAI,gBAAgB,OAAO,GAAG;EACnC,MAAM;EACN,IAAI,CAAC,MAAM,SAAS,cAClB,MAAM,SAAS,eAAe;CAElC,OAAO;EACL,MAAM;EACN,IAAI,CAAC,MAAM,SAAS,SAClB,MAAM,SAAS,UAAU;CAE7B;CAGF,OAAO;AACT"}
package/dist/index.d.ts CHANGED
@@ -6,8 +6,11 @@ import {
6
6
  FiberRecoveryContext
7
7
  } from "agents";
8
8
  import {
9
+ ChatRecoveryConfig,
10
+ ChatRecoveryConfig as ChatRecoveryConfig$1,
9
11
  ChatRecoveryContext,
10
12
  ChatRecoveryContext as ChatRecoveryContext$1,
13
+ ChatRecoveryExhaustedContext,
11
14
  ChatRecoveryOptions,
12
15
  ChatRecoveryOptions as ChatRecoveryOptions$1,
13
16
  ChatResponseResult,
@@ -16,6 +19,7 @@ import {
16
19
  ClientToolSchema as ClientToolSchema$1,
17
20
  MessageConcurrency,
18
21
  MessageConcurrency as MessageConcurrency$1,
22
+ ResolvedChatRecoveryConfig,
19
23
  ResumableStream,
20
24
  SaveMessagesOptions,
21
25
  SaveMessagesOptions as SaveMessagesOptions$1,
@@ -29,12 +33,14 @@ import { StreamTextOnFinishCallback, ToolSet, UIMessage } from "ai";
29
33
  type ChatRecoveryRetryData = {
30
34
  targetUserId?: string;
31
35
  originalRequestId?: string;
36
+ incidentId?: string;
32
37
  lastBody?: Record<string, unknown> | null;
33
38
  lastClientTools?: ClientToolSchema$1[] | null;
34
39
  };
35
40
  type ChatRecoveryContinueData = {
36
41
  targetAssistantId?: string;
37
42
  originalRequestId?: string;
43
+ incidentId?: string;
38
44
  lastBody?: Record<string, unknown> | null;
39
45
  lastClientTools?: ClientToolSchema$1[] | null;
40
46
  };
@@ -97,6 +103,7 @@ declare class AIChatAgent<
97
103
  State = unknown,
98
104
  Props extends Record<string, unknown> = Record<string, unknown>
99
105
  > extends Agent<Env, State, Props> {
106
+ private _activeChatRecoveryRootRequestId;
100
107
  /**
101
108
  * Registry of per-request AbortControllers.
102
109
  * Used to propagate cancellation signals for any external calls made by the agent.
@@ -132,6 +139,14 @@ declare class AIChatAgent<
132
139
  * cleared when it settles. Used by waitUntilStable to avoid polling.
133
140
  */
134
141
  private _pendingInteractionPromise;
142
+ /**
143
+ * Serialization tail for client-tool result/approval applies (#1649). Each
144
+ * apply is a read-modify-write of the full message; running siblings from a
145
+ * parallel tool batch concurrently lets last-write-wins clobber the others
146
+ * back to `input-available`. Chaining every apply off this tail makes them
147
+ * commit atomically in arrival order.
148
+ */
149
+ private _interactionApplyTail;
135
150
  /**
136
151
  * Tracks the ID of a streaming message that was persisted early due to
137
152
  * a tool entering approval-requested state. When set, stream completion
@@ -149,7 +164,7 @@ declare class AIChatAgent<
149
164
  * Enables `onChatRecovery` hook and `this.stash()` during streaming.
150
165
  * Set to `true` in subclasses to enable durable streaming.
151
166
  */
152
- chatRecovery: boolean;
167
+ chatRecovery: ChatRecoveryConfig$1;
153
168
  /** First queued overlap message index for merge strategy, keyed by epoch. */
154
169
  private _mergeQueuedUserStartIndexByEpoch;
155
170
  /** Shared admission policy state for overlapping submit-message requests. */
@@ -302,8 +317,17 @@ declare class AIChatAgent<
302
317
  protected _startStream(requestId: string): string;
303
318
  /** @internal Delegate to _resumableStream */
304
319
  protected _completeStream(streamId: string): void;
305
- /** @internal Delegate to _resumableStream */
306
- protected _storeStreamChunk(streamId: string, body: string): void;
320
+ /** @internal Delegate to _resumableStream. Also advances the recovery
321
+ * progress counter at production time (see `_maybeBumpRecoveryProgress`). */
322
+ protected _storeStreamChunk(streamId: string, body: string): Promise<void>;
323
+ /** Advance the recovery-progress counter when a chunk represents genuinely
324
+ * new produced content — a started text/reasoning segment or a settled tool
325
+ * input/output. Bumped at production time (the streaming path), so it
326
+ * reflects real forward progress and is immune to client reconnects /
327
+ * recovery re-persists (which replay or re-materialize stored chunks rather
328
+ * than flow through here). This is what the recovery no-progress window keys
329
+ * off (#1637), and stays compaction-proof (#1628). */
330
+ private _maybeBumpRecoveryProgress;
307
331
  /** @internal Delegate to _resumableStream */
308
332
  protected _flushChunkBuffer(): void;
309
333
  /** @internal Delegate to _resumableStream */
@@ -319,7 +343,7 @@ declare class AIChatAgent<
319
343
  * message parts, then persists the result so it survives further refreshes.
320
344
  * @internal
321
345
  */
322
- protected _persistOrphanedStream(streamId: string): void;
346
+ protected _persistOrphanedStream(streamId: string): Promise<void>;
323
347
  /**
324
348
  * Restore _lastBody and _lastClientTools from SQLite.
325
349
  * Called in the constructor so these values survive DO hibernation.
@@ -424,6 +448,30 @@ declare class AIChatAgent<
424
448
  private _runExclusiveChatTurn;
425
449
  private _enqueueAutoContinuation;
426
450
  private _awaitPendingAutoContinuationPrerequisite;
451
+ /**
452
+ * Block until the latest assistant step's parallel tool batch is fully
453
+ * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
454
+ * in-flight tool-result apply when one exists (so a sibling that lands
455
+ * mid-wait is observed promptly) and polls otherwise. Runs inside the
456
+ * continuation turn, so — unlike `waitUntilStable` — it must not wait on the
457
+ * turn queue (that would deadlock).
458
+ *
459
+ * No concurrent-entry guard is needed (unlike Think's `_continuationBarrier
460
+ * Active`): this runs inside the exclusive continuation turn, and a sibling
461
+ * result arriving while it waits hits the merge branch of
462
+ * `_enqueueAutoContinuation` (it updates `pending.prerequisite`) rather than
463
+ * enqueuing a second turn — so the turn queue serializes barrier waits.
464
+ */
465
+ private _awaitPendingInteractionBarrier;
466
+ /**
467
+ * `true` when the latest assistant message is mid-batch: it carries at least
468
+ * one settled tool result AND at least one tool call/approval still awaiting a
469
+ * client result. That is the #1649 signature — the model fanned out parallel
470
+ * tool calls and only some have been answered. Scoped to the leaf (the step
471
+ * the continuation answers) so an unrelated dangling tool in an earlier
472
+ * message doesn't block a legitimate follow-up continuation.
473
+ */
474
+ private _hasIncompleteToolBatch;
427
475
  private _queueAutoContinuation;
428
476
  /**
429
477
  * @returns Terminal status for the turn.
@@ -538,6 +586,28 @@ declare class AIChatAgent<
538
586
  }
539
587
  ): Promise<AgentToolRunInspection>;
540
588
  cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
589
+ /**
590
+ * Classify any in-flight chat-recovery on this child facet (#1630 / N6). A
591
+ * child facet is dedicated to a single agent-tool run, so any recovery
592
+ * incident is that run's. Incidents in `detected`/`scheduled`/`attempting`
593
+ * mean recovery is still resolving the interrupted turn; `exhausted`/`failed`
594
+ * mean recovery gave up; a completed recovery deletes its incident.
595
+ */
596
+ private _classifyAgentToolChildRecovery;
597
+ /**
598
+ * Reconcile a stale (post-eviction) child run row from the child's own
599
+ * durable recovery (#1630). The child facet self-heals its interrupted turn
600
+ * via `chatRecovery`, but that path never writes the run row, so without this
601
+ * the row strands `running` and the parent can only collect `interrupted`.
602
+ *
603
+ * Persisting the terminal here (rather than only computing it) is intentional:
604
+ * it's a lazy materialization of the run's true terminal that also lets a
605
+ * tailing parent's stream close promptly and makes subsequent inspects cheap.
606
+ * While recovery is still resolving (active stream or in-progress incident)
607
+ * the row is left `running` so the parent's bounded re-attach keeps waiting.
608
+ * Mutates `row` in place when it settles so the caller can report it.
609
+ */
610
+ private _reconcileStaleAgentToolChildRun;
541
611
  inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
542
612
  getAgentToolChunks(
543
613
  runId: string,
@@ -624,6 +694,60 @@ declare class AIChatAgent<
624
694
  * `onFiberRecovered` hook. Maps to `onChatRecovery`.
625
695
  * @internal
626
696
  */
697
+ private _resolveChatRecoveryConfig;
698
+ private _chatRecoveryIncidentId;
699
+ private _chatRecoveryIncidentKey;
700
+ /**
701
+ * Monotonic forward-progress signal for recovery budget resets.
702
+ *
703
+ * This used to count assistant messages in `this.messages`, but that is
704
+ * recomputed from the live, mutable transcript. Compaction collapses older
705
+ * assistant messages into a summary, lowering the count — so a turn that had
706
+ * genuinely advanced could read as "no progress" between attempts and exhaust
707
+ * its budget prematurely (#1628). Instead we read a durably-persisted counter
708
+ * that only ever increments — bumped at production time when new content is
709
+ * streamed (see `_storeStreamChunk` / `_maybeBumpRecoveryProgress`), which is
710
+ * genuine forward progress and is immune to client reconnects / recovery
711
+ * re-persists — so compaction can never lower it and a reconnect can't fake
712
+ * it (#1637).
713
+ */
714
+ private _chatRecoveryProgressMarker;
715
+ /** Advance the durable recovery-progress counter. Called from
716
+ * `_maybeBumpRecoveryProgress` when new content is streamed (real,
717
+ * reconnect-immune forward progress). */
718
+ private _bumpChatRecoveryProgress;
719
+ /** In-memory wall-clock of the last N9 child-stream progress bump (reset per
720
+ * isolate so the first forwarded chunk after a restart always credits). */
721
+ private _lastAgentToolStreamProgressAt;
722
+ /**
723
+ * N9: forwarding a sub-agent's chunks IS forward progress for this parent
724
+ * turn, so credit the parent's recovery progress marker — otherwise a parent
725
+ * whose turn merely `await`s a child banks no progress of its own and its
726
+ * no-progress window exhausts while the child is healthily streaming. Only
727
+ * invoked after a child actually produced output (see
728
+ * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
729
+ * Throttled (and reset per isolate) so we never write storage per token.
730
+ */
731
+ protected _onAgentToolStreamProgress(): Promise<void>;
732
+ /** Whether a reconstructed partial carries any settled (provider-accepted)
733
+ * tool result — the completed, often non-idempotent work that a
734
+ * `{ persist: false }` recovery return would silently discard.
735
+ * `convertToModelMessages` treats `output-available` / `output-error` /
736
+ * `output-denied` (or a part carrying `output`/`result`) as settled. */
737
+ private _partialHasSettledToolResults;
738
+ /** Sweep recovery incidents that have been inactive past the TTL. */
739
+ private _sweepStaleChatRecoveryIncidents;
740
+ private _beginChatRecoveryIncident;
741
+ private _updateChatRecoveryIncident;
742
+ private _exhaustChatRecovery;
743
+ /**
744
+ * Set or clear the live "recovering…" status (#1620). Persists a durable
745
+ * record (so set/clear stay consistent across the isolates a recovery spans)
746
+ * and broadcasts a `CF_AGENT_CHAT_RECOVERING` frame on a genuine transition.
747
+ * NOTE: AIChatAgent does not yet replay this on connect (no idle-connect
748
+ * hydration; tracked in #1645) — this is the live signal only.
749
+ */
750
+ private _setChatRecovering;
627
751
  protected _handleInternalFiberRecovery(
628
752
  ctx: FiberRecoveryContext
629
753
  ): Promise<boolean>;
@@ -646,6 +770,49 @@ declare class AIChatAgent<
646
770
  ): Promise<ChatRecoveryOptions$1 | void>;
647
771
  _chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void>;
648
772
  private _applyRecoveredRequestContext;
773
+ /**
774
+ * Reschedule a recovery callback that timed out waiting for stable state,
775
+ * consuming one attempt. Returns `true` if rescheduled, `false` if the
776
+ * attempt budget is exhausted (caller should then fail terminally).
777
+ */
778
+ private _rescheduleRecoveryAfterStableTimeout;
779
+ /**
780
+ * Resolve the stream id for a recovery turn so the give-up terminalization
781
+ * can surface whatever partial the turn produced. Prefers the durable stream
782
+ * row keyed by the recovery-root request id; falls back to the live active
783
+ * stream. Returns `""` when neither is available.
784
+ */
785
+ private _resolveRecoveryStreamId;
786
+ /**
787
+ * Terminalize a recovery turn that has run out of stable-state-timeout retry
788
+ * budget — or whose incident record has vanished — by routing through the
789
+ * SAME `_exhaustChatRecovery` path as deploy-recovery exhaustion. It fires
790
+ * `onExhausted`, emits `chat:recovery:exhausted`, and delivers the configured
791
+ * `terminalMessage`.
792
+ *
793
+ * This replaces the older give-up that only set the incident to `failed`,
794
+ * which bypassed `_exhaustChatRecovery` entirely — so an app relying on
795
+ * `onExhausted` for the terminal banner regressed to an eternal spinner when
796
+ * recovery gave up under extreme churn. Shared by `_chatRecoveryRetry` and
797
+ * `_chatRecoveryContinue`; mirrors the same helper in `@cloudflare/think`.
798
+ *
799
+ * Exactly-once terminalization here rests SOLELY on the
800
+ * `stored?.status === "exhausted"` re-entry guard below — unlike
801
+ * `@cloudflare/think`, `@cloudflare/ai-chat` has no durable-submission layer
802
+ * to short-circuit a duplicate alarm earlier. The sealed incident is
803
+ * re-persisted even when the record was found missing, so a swept record is
804
+ * re-armed for the guard on the next alarm.
805
+ *
806
+ * Two residual at-least-once edges, both deliberately accepted as "deliver a
807
+ * second banner" ≫ "silently drop the turn":
808
+ * • No `incidentId` at all in the payload (only reachable via a direct/test
809
+ * invocation — every production scheduler carries one): the synthesized
810
+ * incident can't be persisted (no key), so the guard can't arm.
811
+ * • The record is swept AGAIN between two alarms (the guard re-persists on
812
+ * the first, so this needs a second independent sweep) — vanishingly
813
+ * unlikely.
814
+ */
815
+ private _exhaustRecoveryAfterStableTimeout;
649
816
  private _shouldRetryRecoveredPreStreamTurn;
650
817
  _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
651
818
  /**
@@ -777,6 +944,26 @@ declare class AIChatAgent<
777
944
  * SQLite writes plus `MESSAGE_UPDATED` broadcasts.
778
945
  */
779
946
  private static _isToolPartUnchanged;
947
+ /**
948
+ * Serialize a client-tool result/approval apply behind any in-flight apply
949
+ * (#1649, defensive). Each apply is a read-modify-write of the message and
950
+ * parallel tool results arrive as independent WebSocket messages. Today
951
+ * `_findAndUpdateToolPart` performs that read-modify-write synchronously (no
952
+ * await between reading `this.messages` and the SQLite write), so concurrent
953
+ * applies can't actually interleave — unlike Think, ai-chat does not exhibit
954
+ * the #1649 clobber. This queue is a guard so the invariant survives if the
955
+ * apply ever gains an await between read and write (e.g. async storage): each
956
+ * apply commits atomically in arrival order.
957
+ *
958
+ * `_pendingInteractionPromise` is set to the newest link so the barrier's
959
+ * single-slot wake-up observes the latest apply; because the chain is serial,
960
+ * awaiting it transitively waits for every predecessor.
961
+ *
962
+ * @internal
963
+ */
964
+ protected _enqueueInteractionApply(
965
+ apply: () => Promise<boolean>
966
+ ): Promise<boolean>;
780
967
  /**
781
968
  * Applies a tool result to an existing assistant message.
782
969
  * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
@@ -825,12 +1012,15 @@ declare class AIChatAgent<
825
1012
  export {
826
1013
  AIChatAgent,
827
1014
  ChatMessage,
1015
+ type ChatRecoveryConfig,
828
1016
  type ChatRecoveryContext,
1017
+ type ChatRecoveryExhaustedContext,
829
1018
  type ChatRecoveryOptions,
830
1019
  type ChatResponseResult,
831
1020
  type ClientToolSchema,
832
1021
  type MessageConcurrency,
833
1022
  OnChatMessageOptions,
1023
+ type ResolvedChatRecoveryConfig,
834
1024
  type SaveMessagesOptions,
835
1025
  type SaveMessagesResult,
836
1026
  createToolsFromClientSchemas