@cloudflare/ai-chat 0.8.1 → 0.8.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License Copyright (c) 2025 Cloudflare, Inc.
2
+
3
+ Permission is hereby granted, free of
4
+ charge, to any person obtaining a copy of this software and associated
5
+ documentation files (the "Software"), to deal in the Software without
6
+ restriction, including without limitation the rights to use, copy, modify, merge,
7
+ publish, distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to the
9
+ following conditions:
10
+
11
+ The above copyright notice and this permission notice
12
+ (including the next paragraph) shall be included in all copies or substantial
13
+ portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
16
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
18
+ EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
19
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -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\";\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.unknown) {\n stats.examples.unknown = message;\n }\n }\n }\n\n return stats;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAS,wBAAwB,SAA+B;CAC9D,MAAM,QAAQ,QAAQ;CACtB,MAAM,uBAAuB,SAA2B;EACtD,MAAM,SAAS;EACf,MAAM,OAAO,OAAO,OAAO,SAAS,WAAW,OAAO,OAAO;EAC7D,IAAI,EAAE,KAAK,WAAW,OAAO,KAAK,SAAS,iBAAiB,OAAO;EACnE,OAAO,mBAAmB,OAAO,KAAK,EAAE;CAC1C;CAEA,IAAI,CAAC,MAAM,KAAK,mBAAmB,GAAG,OAAO;CAE7C,MAAM,YAAY,MAAM,KAAK,SAAS;EACpC,IAAI,CAAC,oBAAoB,IAAI,GAAG,OAAO;EACvC,MAAM,SAAS;EACf,OAAO;GACL,GAAG;GACH,OAAO,mBAAmB,OAAO,KAAK,EAAE;EAC1C;CACF,CAAC;CACD,OAAO;EAAE,GAAG;EAAS,OAAO;CAAU;AACxC;;;;AAKA,MAAM,uCAAuB,IAAI,IAAY;AAC7C,SAAS,eAAe,IAAY,SAAiB;CACnD,IAAI,CAAC,qBAAqB,IAAI,EAAE,GAAG;EACjC,qBAAqB,IAAI,EAAE;EAC3B,QAAQ,KAAK,qCAAqC,SAAS;CAC7D;AACF;;;;AA6EA,MAAM,YAAY;CAChB,gBAAgB;CAChB,MAAM;CACN,QAAQ;CACR,OAAO;AACT;;;;AAKA,SAAgB,YAAY,SAAwC;CAClE,OACE,OAAO,YAAY,YACnB,YAAY,QACZ,WAAW,WACX,MAAM,QAAS,QAA+B,KAAK;AAEvD;;;;AAKA,SAAS,gBAAgB,SAA4C;CACnE,OACE,OAAO,YAAY,YACnB,YAAY,QACZ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U,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.unknown) {\n stats.examples.unknown = message;\n }\n }\n }\n\n return stats;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAS,wBAAwB,SAA+B;CAC9D,MAAM,QAAQ,QAAQ;CACtB,MAAM,uBAAuB,SAA2B;EACtD,MAAM,SAAS;EACf,MAAM,OAAO,OAAO,OAAO,SAAS,WAAW,OAAO,OAAO;EAC7D,IAAI,EAAE,KAAK,WAAW,OAAO,KAAK,SAAS,iBAAiB,OAAO;EACnE,OAAO,mBAAmB,OAAO,KAAK,CAAC,CAAC;CAC1C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AAI,QAAQ,MAAM,OAAO;EACzB,MACE,QAAQ,SAAS,SACb,WACC,QAAQ,QAA4C;EACpD;CACT,CAAC;AACH;;;;;AAMA,SAAgB,mBAAmB,SAAuC;CACxE,eACE,sBACA,uHACF;CACA,OAAO,qBAAqB,OAAuB;AACrD;;;;;;AAOA,SAAgB,sBAAsB,UAAkC;CACtE,OAAO,SAAS,KAAK,KAAK,MAAM,qBAAqB,KAAqB,CAAC,CAAC;AAC9E;;;;;;;AAQA,SAAgB,0BACd,UACa;CACb,eACE,6BACA,+HACF;CACA,OAAO,sBAAsB,QAA0B;AACzD;;;;;;;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"}
package/dist/index.d.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  ChatRecoveryExhaustedContext,
14
14
  ChatRecoveryOptions,
15
15
  ChatRecoveryOptions as ChatRecoveryOptions$1,
16
+ ChatRecoveryProgressContext,
16
17
  ChatResponseResult,
17
18
  ChatResponseResult as ChatResponseResult$1,
18
19
  ClientToolSchema,
@@ -163,6 +164,12 @@ declare class AIChatAgent<
163
164
  * When true, chat turns are wrapped in `runFiber` for durable execution.
164
165
  * Enables `onChatRecovery` hook and `this.stash()` during streaming.
165
166
  * Set to `true` in subclasses to enable durable streaming.
167
+ *
168
+ * Assign this as a class field or in the constructor — NOT in `onStart()`.
169
+ * On every wake the SDK evaluates recovery budgets (and may seal an
170
+ * interrupted turn, firing `onExhausted`) before `onStart()` runs, so a config
171
+ * set in `onStart()` is applied too late and the built-in defaults are used
172
+ * for the recovery that matters. See {@link ChatRecoveryConfig}.
166
173
  */
167
174
  chatRecovery: ChatRecoveryConfig$1;
168
175
  /** First queued overlap message index for merge strategy, keyed by epoch. */
@@ -438,9 +445,42 @@ declare class AIChatAgent<
438
445
  * concurrency state — use {@link resetTurnState} for the full
439
446
  * teardown that runs on `chat-clear`.
440
447
  */
441
- protected abortAllRequests(): void;
448
+ protected abortAllRequests(reason?: unknown): void;
442
449
  private _awaitWithDeadline;
443
450
  private _messageHasPendingInteraction;
451
+ /**
452
+ * `true` when the turn is parked on a pending interaction that the CLIENT can
453
+ * still resolve after a restart — an `approval-requested` part, or an
454
+ * `input-available` part for a CLIENT tool (no server `execute`) whose
455
+ * `tool-result` the SPA replays over the WebSocket on reconnect.
456
+ *
457
+ * This is intentionally NARROWER than `hasPendingInteraction()` (which
458
+ * `waitUntilStable` uses): a SERVER tool's `input-available` orphan is
459
+ * excluded, because its `execute()` promise died with the evicted isolate and
460
+ * nothing will ever post its result — so it must NOT be treated as a healthy
461
+ * "waiting on the human" wait. Used to make a HITL turn budget-free during
462
+ * recovery so a slow human can't trip the no-progress / attempt / stable-
463
+ * timeout budgets; see `_beginChatRecoveryIncident` and
464
+ * `_parkRecoveryForPendingInteraction`. Mirrors `@cloudflare/think`'s
465
+ * `hasPendingInteraction`, which is already client-only by construction.
466
+ */
467
+ protected hasPendingClientInteraction(): boolean;
468
+ private _messageAwaitsClientInteraction;
469
+ /**
470
+ * Whether a part is still awaiting a CLIENT interaction that can genuinely
471
+ * arrive after a restart: an `approval-requested` part (a reconnecting client
472
+ * replays the approval) or an `input-available` part for a CLIENT tool (the
473
+ * SPA replays the `tool-result`). A SERVER tool's `input-available` is NOT
474
+ * pending — its `execute()` died with the isolate. Mirrors `@cloudflare/think`.
475
+ */
476
+ private _partAwaitsClientInteraction;
477
+ /** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */
478
+ private _toolPartName;
479
+ /**
480
+ * Names of the CLIENT-resolvable tools (the client-provided schemas from the
481
+ * last request, which have no server `execute`). Mirrors `@cloudflare/think`.
482
+ */
483
+ private _clientResolvableToolNames;
444
484
  /**
445
485
  * Run a chat turn exclusively so `_reply()` never overlaps with another
446
486
  * streaming turn.
@@ -608,6 +648,22 @@ declare class AIChatAgent<
608
648
  * Mutates `row` in place when it settles so the caller can report it.
609
649
  */
610
650
  private _reconcileStaleAgentToolChildRun;
651
+ /**
652
+ * Eagerly terminalize this child facet's OWN agent-tool run row(s) once a
653
+ * recovered turn has settled. A recovered turn re-runs via either
654
+ * `_chatRecoveryContinue` → `continueLastTurn` or, for a pre-stream eviction,
655
+ * `_chatRecoveryRetry` → `_retryLastUserTurn` — neither flows through
656
+ * `startAgentToolRun`'s finalizer, so without this the row strands `running`
657
+ * and its tailers stay open until a parent inspect lazily reconciles it —
658
+ * forcing a re-attached parent to wait out a full no-progress window before
659
+ * collecting an already-finished result (#1630 follow-up). Reconciling here
660
+ * closes the tail promptly so the parent collects the terminal immediately.
661
+ * No-op on non-child facets (their `cf_ai_chat_agent_tool_runs` table is
662
+ * empty) and on rows whose in-memory run is still live; the underlying
663
+ * reconcile leaves a row `running` while its recovery is still in progress.
664
+ * Mirrors `@cloudflare/think`.
665
+ */
666
+ private _reconcileOwnStaleAgentToolChildRuns;
611
667
  inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
612
668
  getAgentToolChunks(
613
669
  runId: string,
@@ -776,6 +832,33 @@ declare class AIChatAgent<
776
832
  * attempt budget is exhausted (caller should then fail terminally).
777
833
  */
778
834
  private _rescheduleRecoveryAfterStableTimeout;
835
+ /**
836
+ * Park a recovery continuation that timed out waiting for stable state
837
+ * because the turn is holding a pending CLIENT interaction (an
838
+ * `input-available` client-tool part or an `approval-requested` part — see
839
+ * `hasPendingClientInteraction`). Such a turn is WAITING ON THE HUMAN, not
840
+ * stuck: the client replays the interrupted tool-result / approval after
841
+ * reconnect, which drives a fresh continuation independently of the recovery
842
+ * retry loop. Burning the attempt budget on that wait (each `waitUntilStable`
843
+ * times out because the human hasn't answered) would seal a perfectly healthy
844
+ * turn on `stable_timeout` — the symptom behind HITL "session recovery errors"
845
+ * under deploy churn.
846
+ *
847
+ * So instead of rescheduling or exhausting, we stop the loop and mark the
848
+ * incident `skipped` (reason `awaiting_client_interaction`). That retains the
849
+ * incident record (a later genuine interruption re-evaluates it) while
850
+ * resolving the live "recovering…" indicator via `_updateChatRecoveryIncident`
851
+ * so the client sees the parked tool-call UI rather than an eternal spinner.
852
+ * A client that never returns is reclaimed by the incident TTL sweep and DO
853
+ * idle-eviction. SERVER-tool orphans are excluded by `hasPendingClientInteraction`
854
+ * (their `execute` died with the isolate), so they still reschedule / exhaust
855
+ * via the normal path. Mirrors the same helper in `@cloudflare/think`.
856
+ *
857
+ * Returns `true` when the recovery was parked (caller must return), `false`
858
+ * when there is no pending client interaction (caller proceeds to the normal
859
+ * reschedule / exhaustion path).
860
+ */
861
+ private _parkRecoveryForPendingInteraction;
779
862
  /**
780
863
  * Resolve the stream id for a recovery turn so the give-up terminalization
781
864
  * can surface whatever partial the turn produced. Prefers the durable stream
@@ -889,6 +972,13 @@ declare class AIChatAgent<
889
972
  private static _shouldPreserveProviderToolPayload;
890
973
  private static _getToolNameFromPart;
891
974
  private static _isOpaqueReplayFieldKey;
975
+ /**
976
+ * Delete the given message rows from SQLite in batched `IN (...)` queries
977
+ * and evict them from the persistence cache. Batches stay within the SQLite
978
+ * 100 bound-parameter limit. No-op for an empty list.
979
+ * @internal
980
+ */
981
+ private _deleteMessagesByIds;
892
982
  /**
893
983
  * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
894
984
  * Called after each persist to keep storage bounded.
@@ -1016,6 +1106,7 @@ export {
1016
1106
  type ChatRecoveryContext,
1017
1107
  type ChatRecoveryExhaustedContext,
1018
1108
  type ChatRecoveryOptions,
1109
+ type ChatRecoveryProgressContext,
1019
1110
  type ChatResponseResult,
1020
1111
  type ClientToolSchema,
1021
1112
  type MessageConcurrency,
package/dist/index.js CHANGED
@@ -1,21 +1,23 @@
1
1
  import "./types.js";
2
2
  import { autoTransformMessages } from "./ai-chat-v5-migration.js";
3
3
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
4
- import { AbortRegistry, ContinuationState, ROW_MAX_BYTES, ResumableStream, SubmitConcurrencyController, TurnQueue, applyChunkToParts, byteLength, createChatFiberSnapshot, createToolsFromClientSchemas, isReplayChunk, reconcileMessages, resolveToolMergeId, sanitizeMessage, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
4
+ import { AbortRegistry, ContinuationState, MAX_BOUND_PARAMS, ROW_MAX_BYTES, ResumableStream, SubmitConcurrencyController, TurnQueue, applyChunkToParts, buildInClauseStrings, byteLength, createChatFiberSnapshot, createToolsFromClientSchemas, isReplayChunk, reconcileMessages, resolveToolMergeId, sanitizeMessage, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
5
5
  import { nanoid } from "nanoid";
6
6
  //#region src/index.ts
7
7
  const CHAT_RECOVERY_INCIDENT_KEY_PREFIX = "cf:chat-recovery:incident:";
8
8
  const CHAT_RECOVERY_PROGRESS_KEY = "cf:chat-recovery:progress";
9
9
  const DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS = 10;
10
+ const DEFAULT_CHAT_RECOVERY_MAX_WORK = Number.POSITIVE_INFINITY;
10
11
  const DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS = 1e4;
11
12
  const AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS = 6e4;
12
13
  const CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;
13
14
  const DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE = "The assistant was interrupted and could not recover. Please try again.";
14
15
  const CHAT_RECOVERING_KEY = "cf:chat:recovering";
15
16
  const CHAT_RECOVERY_INCIDENT_TTL_MS = 3600 * 1e3;
16
- const CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS = 300 * 1e3;
17
+ const KV_DELETE_MAX_KEYS = 128;
18
+ const DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 300 * 1e3;
17
19
  const CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1e3;
18
- const CHAT_RECOVERY_MAX_WINDOW_MS = 900 * 1e3;
20
+ const CHAT_RECOVERING_FLAG_TTL_MS = 900 * 1e3;
19
21
  const AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5e3;
20
22
  function sendIfOpen(connection, message) {
21
23
  try {
@@ -835,8 +837,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
835
837
  * concurrency state — use {@link resetTurnState} for the full
836
838
  * teardown that runs on `chat-clear`.
837
839
  */
838
- abortAllRequests() {
839
- this._abortRegistry.destroyAll();
840
+ abortAllRequests(reason) {
841
+ this._abortRegistry.destroyAll(reason);
840
842
  }
841
843
  async _awaitWithDeadline(promise, deadline) {
842
844
  if (deadline == null) return promise;
@@ -852,6 +854,61 @@ var AIChatAgent = class AIChatAgent extends Agent {
852
854
  return message.parts.some((part) => "state" in part && (part.state === "input-available" || part.state === "approval-requested"));
853
855
  }
854
856
  /**
857
+ * `true` when the turn is parked on a pending interaction that the CLIENT can
858
+ * still resolve after a restart — an `approval-requested` part, or an
859
+ * `input-available` part for a CLIENT tool (no server `execute`) whose
860
+ * `tool-result` the SPA replays over the WebSocket on reconnect.
861
+ *
862
+ * This is intentionally NARROWER than `hasPendingInteraction()` (which
863
+ * `waitUntilStable` uses): a SERVER tool's `input-available` orphan is
864
+ * excluded, because its `execute()` promise died with the evicted isolate and
865
+ * nothing will ever post its result — so it must NOT be treated as a healthy
866
+ * "waiting on the human" wait. Used to make a HITL turn budget-free during
867
+ * recovery so a slow human can't trip the no-progress / attempt / stable-
868
+ * timeout budgets; see `_beginChatRecoveryIncident` and
869
+ * `_parkRecoveryForPendingInteraction`. Mirrors `@cloudflare/think`'s
870
+ * `hasPendingInteraction`, which is already client-only by construction.
871
+ */
872
+ hasPendingClientInteraction() {
873
+ const clientResolvable = this._clientResolvableToolNames();
874
+ if (this._streamingMessage && this._messageAwaitsClientInteraction(this._streamingMessage, clientResolvable)) return true;
875
+ return this.messages.some((message) => message.role === "assistant" && this._messageAwaitsClientInteraction(message, clientResolvable));
876
+ }
877
+ _messageAwaitsClientInteraction(message, clientResolvable) {
878
+ return message.parts.some((part) => this._partAwaitsClientInteraction(part, clientResolvable));
879
+ }
880
+ /**
881
+ * Whether a part is still awaiting a CLIENT interaction that can genuinely
882
+ * arrive after a restart: an `approval-requested` part (a reconnecting client
883
+ * replays the approval) or an `input-available` part for a CLIENT tool (the
884
+ * SPA replays the `tool-result`). A SERVER tool's `input-available` is NOT
885
+ * pending — its `execute()` died with the isolate. Mirrors `@cloudflare/think`.
886
+ */
887
+ _partAwaitsClientInteraction(part, clientResolvable) {
888
+ if (!("state" in part)) return false;
889
+ const record = part;
890
+ const state = record.state;
891
+ if (state === "approval-requested") return true;
892
+ if (state !== "input-available") return false;
893
+ const toolName = this._toolPartName(record);
894
+ return toolName != null && clientResolvable.has(toolName);
895
+ }
896
+ /** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */
897
+ _toolPartName(record) {
898
+ const type = typeof record.type === "string" ? record.type : "";
899
+ if (type === "dynamic-tool") return typeof record.toolName === "string" ? record.toolName : void 0;
900
+ if (type.startsWith("tool-")) return type.slice(5);
901
+ }
902
+ /**
903
+ * Names of the CLIENT-resolvable tools (the client-provided schemas from the
904
+ * last request, which have no server `execute`). Mirrors `@cloudflare/think`.
905
+ */
906
+ _clientResolvableToolNames() {
907
+ const names = /* @__PURE__ */ new Set();
908
+ for (const tool of this._lastClientTools ?? []) if (tool?.name) names.add(tool.name);
909
+ return names;
910
+ }
911
+ /**
855
912
  * Run a chat turn exclusively so `_reply()` never overlaps with another
856
913
  * streaming turn.
857
914
  */
@@ -1313,6 +1370,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1313
1370
  }
1314
1371
  async cancelAgentToolRun(runId, reason) {
1315
1372
  this._agentToolAbortControllers.get(runId)?.abort(reason);
1373
+ this.abortAllRequests(reason);
1316
1374
  this.sql`
1317
1375
  update cf_ai_chat_agent_tool_runs
1318
1376
  set status = 'aborted', completed_at = coalesce(completed_at, ${Date.now()})
@@ -1391,6 +1449,40 @@ var AIChatAgent = class AIChatAgent extends Agent {
1391
1449
  this._closeAgentToolTailers(runId);
1392
1450
  }
1393
1451
  }
1452
+ /**
1453
+ * Eagerly terminalize this child facet's OWN agent-tool run row(s) once a
1454
+ * recovered turn has settled. A recovered turn re-runs via either
1455
+ * `_chatRecoveryContinue` → `continueLastTurn` or, for a pre-stream eviction,
1456
+ * `_chatRecoveryRetry` → `_retryLastUserTurn` — neither flows through
1457
+ * `startAgentToolRun`'s finalizer, so without this the row strands `running`
1458
+ * and its tailers stay open until a parent inspect lazily reconciles it —
1459
+ * forcing a re-attached parent to wait out a full no-progress window before
1460
+ * collecting an already-finished result (#1630 follow-up). Reconciling here
1461
+ * closes the tail promptly so the parent collects the terminal immediately.
1462
+ * No-op on non-child facets (their `cf_ai_chat_agent_tool_runs` table is
1463
+ * empty) and on rows whose in-memory run is still live; the underlying
1464
+ * reconcile leaves a row `running` while its recovery is still in progress.
1465
+ * Mirrors `@cloudflare/think`.
1466
+ */
1467
+ async _reconcileOwnStaleAgentToolChildRuns() {
1468
+ let rows;
1469
+ try {
1470
+ rows = this.sql`
1471
+ select run_id from cf_ai_chat_agent_tool_runs
1472
+ where status = 'running'
1473
+ `;
1474
+ } catch {
1475
+ return;
1476
+ }
1477
+ for (const { run_id } of rows) {
1478
+ if (this._agentToolAbortControllers.has(run_id)) continue;
1479
+ const row = this._getAgentToolRunRow(run_id);
1480
+ if (!row || row.status !== "running") continue;
1481
+ try {
1482
+ await this._reconcileStaleAgentToolChildRun(run_id, row);
1483
+ } catch {}
1484
+ }
1485
+ }
1394
1486
  async inspectAgentToolRun(runId) {
1395
1487
  const row = this._getAgentToolRunRow(runId);
1396
1488
  if (!row) return null;
@@ -1486,14 +1578,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1486
1578
  _getAgentToolStoredChunks(requestId, afterSequence = -1) {
1487
1579
  const streamId = this._getAgentToolStreamId(requestId);
1488
1580
  if (!streamId) return [];
1489
- return this.sql`
1490
- select body, chunk_index
1491
- from cf_ai_chat_stream_chunks
1492
- where stream_id = ${streamId} and chunk_index > ${afterSequence}
1493
- order by chunk_index asc
1494
- `.map((row) => ({
1495
- sequence: row.chunk_index,
1496
- body: row.body
1581
+ return this._resumableStream.getStreamChunks(streamId).filter((chunk) => chunk.chunk_index > afterSequence).map((chunk) => ({
1582
+ sequence: chunk.chunk_index,
1583
+ body: chunk.body
1497
1584
  }));
1498
1585
  }
1499
1586
  _getAgentToolMessagesAfterStart(runId) {
@@ -1702,6 +1789,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1702
1789
  maxAttempts: Math.max(1, Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)),
1703
1790
  stableTimeoutMs: Math.max(0, Math.floor(custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS)),
1704
1791
  terminalMessage: custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,
1792
+ noProgressTimeoutMs: Math.max(0, Math.floor(custom?.noProgressTimeoutMs ?? DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS)),
1793
+ maxRecoveryWork: typeof custom?.maxRecoveryWork === "number" && custom.maxRecoveryWork >= 0 ? custom.maxRecoveryWork : DEFAULT_CHAT_RECOVERY_MAX_WORK,
1794
+ ...custom?.shouldKeepRecovering ? { shouldKeepRecovering: custom.shouldKeepRecovering } : {},
1705
1795
  ...custom?.onExhausted ? { onExhausted: custom.onExhausted } : {}
1706
1796
  };
1707
1797
  }
@@ -1770,7 +1860,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1770
1860
  const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
1771
1861
  const staleKeys = [];
1772
1862
  for (const [key, incident] of entries) if (now - (incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0) > CHAT_RECOVERY_INCIDENT_TTL_MS) staleKeys.push(key);
1773
- for (const key of staleKeys) await this.ctx.storage.delete(key);
1863
+ for (let i = 0; i < staleKeys.length; i += KV_DELETE_MAX_KEYS) await this.ctx.storage.delete(staleKeys.slice(i, i + KV_DELETE_MAX_KEYS));
1774
1864
  }
1775
1865
  async _beginChatRecoveryIncident(input) {
1776
1866
  const config = this._resolveChatRecoveryConfig();
@@ -1782,12 +1872,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
1782
1872
  const prevProgress = existing?.progress ?? 0;
1783
1873
  const currentProgress = await this._chatRecoveryProgressMarker();
1784
1874
  const madeProgress = existing != null && currentProgress > prevProgress;
1785
- const lastProgressAt = madeProgress ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
1786
- const noProgressExceeded = existing != null && now - lastProgressAt > CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS;
1787
- const incidentAgeExceeded = existing != null && now - existing.firstSeenAt > CHAT_RECOVERY_MAX_WINDOW_MS;
1875
+ const awaitingClientInteraction = this.hasPendingClientInteraction();
1876
+ const lastProgressAt = madeProgress || awaitingClientInteraction ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
1877
+ const noProgressExceeded = existing != null && !awaitingClientInteraction && now - lastProgressAt > config.noProgressTimeoutMs;
1878
+ const workBaseline = existing?.workBaseline ?? currentProgress;
1879
+ const progress = Math.max(prevProgress, currentProgress);
1880
+ const work = progress - workBaseline;
1881
+ const workBudgetExceeded = existing != null && Number.isFinite(config.maxRecoveryWork) && work > config.maxRecoveryWork;
1788
1882
  const debounced = existing != null && !madeProgress && now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;
1789
1883
  const attempt = madeProgress ? 1 : debounced ? existing?.attempt ?? 1 : (existing?.attempt ?? 0) + 1;
1790
- const exhausted = noProgressExceeded || incidentAgeExceeded || attempt > config.maxAttempts;
1884
+ let abortedByCaller = false;
1885
+ if (existing != null && !awaitingClientInteraction && config.shouldKeepRecovering && !noProgressExceeded && !workBudgetExceeded && attempt <= config.maxAttempts) try {
1886
+ abortedByCaller = await config.shouldKeepRecovering({
1887
+ incidentId,
1888
+ requestId: input.requestId,
1889
+ recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,
1890
+ attempt,
1891
+ maxAttempts: config.maxAttempts,
1892
+ recoveryKind: input.recoveryKind,
1893
+ work,
1894
+ ageMs: now - (existing.firstSeenAt ?? now)
1895
+ }) === false;
1896
+ } catch (error) {
1897
+ console.error("[AIChatAgent] chatRecovery shouldKeepRecovering hook threw", error);
1898
+ }
1899
+ const exhausted = !awaitingClientInteraction && (noProgressExceeded || workBudgetExceeded || abortedByCaller || attempt > config.maxAttempts);
1791
1900
  const incident = {
1792
1901
  incidentId,
1793
1902
  requestId: input.requestId,
@@ -1799,8 +1908,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1799
1908
  firstSeenAt: existing?.firstSeenAt ?? now,
1800
1909
  lastAttemptAt: now,
1801
1910
  lastProgressAt,
1802
- progress: Math.max(prevProgress, currentProgress),
1803
- ...exhausted ? { reason: incidentAgeExceeded ? "max_recovery_window_exceeded" : noProgressExceeded ? "no_progress_timeout" : "max_attempts_exceeded" } : {}
1911
+ progress,
1912
+ workBaseline,
1913
+ ...exhausted ? { reason: workBudgetExceeded ? "work_budget_exceeded" : noProgressExceeded ? "no_progress_timeout" : abortedByCaller ? "recovery_aborted" : "max_attempts_exceeded" } : {}
1804
1914
  };
1805
1915
  await this.ctx.storage.put(key, incident);
1806
1916
  if (!existing) this._emit("chat:recovery:detected", {
@@ -1888,7 +1998,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1888
1998
  */
1889
1999
  async _setChatRecovering(active, requestId) {
1890
2000
  const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
1891
- const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS;
2001
+ const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERING_FLAG_TTL_MS;
1892
2002
  if (active) {
1893
2003
  if (activeExisting) return;
1894
2004
  await this.ctx.storage.put(CHAT_RECOVERING_KEY, {
@@ -2024,6 +2134,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2024
2134
  try {
2025
2135
  const recoveryConfig = this._resolveChatRecoveryConfig();
2026
2136
  if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
2137
+ if (await this._parkRecoveryForPendingInteraction(data)) return;
2027
2138
  console.warn("[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state");
2028
2139
  if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryContinue", data, recoveryConfig.maxAttempts)) return;
2029
2140
  await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryContinue", data);
@@ -2039,6 +2150,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2039
2150
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2040
2151
  } finally {
2041
2152
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
2153
+ await this._reconcileOwnStaleAgentToolChildRuns();
2042
2154
  }
2043
2155
  }
2044
2156
  _applyRecoveredRequestContext(data) {
@@ -2069,6 +2181,37 @@ var AIChatAgent = class AIChatAgent extends Agent {
2069
2181
  return true;
2070
2182
  }
2071
2183
  /**
2184
+ * Park a recovery continuation that timed out waiting for stable state
2185
+ * because the turn is holding a pending CLIENT interaction (an
2186
+ * `input-available` client-tool part or an `approval-requested` part — see
2187
+ * `hasPendingClientInteraction`). Such a turn is WAITING ON THE HUMAN, not
2188
+ * stuck: the client replays the interrupted tool-result / approval after
2189
+ * reconnect, which drives a fresh continuation independently of the recovery
2190
+ * retry loop. Burning the attempt budget on that wait (each `waitUntilStable`
2191
+ * times out because the human hasn't answered) would seal a perfectly healthy
2192
+ * turn on `stable_timeout` — the symptom behind HITL "session recovery errors"
2193
+ * under deploy churn.
2194
+ *
2195
+ * So instead of rescheduling or exhausting, we stop the loop and mark the
2196
+ * incident `skipped` (reason `awaiting_client_interaction`). That retains the
2197
+ * incident record (a later genuine interruption re-evaluates it) while
2198
+ * resolving the live "recovering…" indicator via `_updateChatRecoveryIncident`
2199
+ * so the client sees the parked tool-call UI rather than an eternal spinner.
2200
+ * A client that never returns is reclaimed by the incident TTL sweep and DO
2201
+ * idle-eviction. SERVER-tool orphans are excluded by `hasPendingClientInteraction`
2202
+ * (their `execute` died with the isolate), so they still reschedule / exhaust
2203
+ * via the normal path. Mirrors the same helper in `@cloudflare/think`.
2204
+ *
2205
+ * Returns `true` when the recovery was parked (caller must return), `false`
2206
+ * when there is no pending client interaction (caller proceeds to the normal
2207
+ * reschedule / exhaustion path).
2208
+ */
2209
+ async _parkRecoveryForPendingInteraction(data) {
2210
+ if (!this.hasPendingClientInteraction()) return false;
2211
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "awaiting_client_interaction");
2212
+ return true;
2213
+ }
2214
+ /**
2072
2215
  * Resolve the stream id for a recovery turn so the give-up terminalization
2073
2216
  * can surface whatever partial the turn produced. Prefers the durable stream
2074
2217
  * row keyed by the recovery-root request id; falls back to the live active
@@ -2151,6 +2294,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2151
2294
  try {
2152
2295
  const recoveryConfig = this._resolveChatRecoveryConfig();
2153
2296
  if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
2297
+ if (await this._parkRecoveryForPendingInteraction(data)) return;
2154
2298
  console.warn("[AIChatAgent] _chatRecoveryRetry timed out waiting for stable state");
2155
2299
  if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryRetry", data, recoveryConfig.maxAttempts)) return;
2156
2300
  await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryRetry", data);
@@ -2170,6 +2314,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2170
2314
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2171
2315
  } finally {
2172
2316
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
2317
+ await this._reconcileOwnStaleAgentToolChildRuns();
2173
2318
  }
2174
2319
  }
2175
2320
  /**
@@ -2204,15 +2349,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2204
2349
  const serverIds = new Set(this.messages.map((m) => m.id));
2205
2350
  if (mergedMessages.every((m) => serverIds.has(m.id))) {
2206
2351
  const keepIds = new Set(mergedMessages.map((m) => m.id));
2207
- const allDbRows = this.sql`
2352
+ const staleIds = (this.sql`
2208
2353
  select id from cf_ai_chat_agent_messages
2209
- ` || [];
2210
- for (const row of allDbRows) if (!keepIds.has(row.id)) {
2211
- this.sql`
2212
- delete from cf_ai_chat_agent_messages where id = ${row.id}
2213
- `;
2214
- this._persistedMessageCache.delete(row.id);
2215
- }
2354
+ ` || []).map((row) => row.id).filter((id) => !keepIds.has(id));
2355
+ this._deleteMessagesByIds(staleIds);
2216
2356
  }
2217
2357
  }
2218
2358
  if (this.maxPersistedMessages != null) this._enforceMaxPersistedMessages();
@@ -2344,6 +2484,20 @@ var AIChatAgent = class AIChatAgent extends Agent {
2344
2484
  return key.startsWith(PROVIDER_TOOL_OPAQUE_STRING_KEY_PREFIX);
2345
2485
  }
2346
2486
  /**
2487
+ * Delete the given message rows from SQLite in batched `IN (...)` queries
2488
+ * and evict them from the persistence cache. Batches stay within the SQLite
2489
+ * 100 bound-parameter limit. No-op for an empty list.
2490
+ * @internal
2491
+ */
2492
+ _deleteMessagesByIds(ids) {
2493
+ for (let i = 0; i < ids.length; i += MAX_BOUND_PARAMS) {
2494
+ const batch = ids.slice(i, i + MAX_BOUND_PARAMS);
2495
+ const strings = buildInClauseStrings("delete from cf_ai_chat_agent_messages where id in ", batch.length);
2496
+ this.sql(strings, ...batch);
2497
+ for (const id of batch) this._persistedMessageCache.delete(id);
2498
+ }
2499
+ }
2500
+ /**
2347
2501
  * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
2348
2502
  * Called after each persist to keep storage bounded.
2349
2503
  */
@@ -2359,10 +2513,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2359
2513
  order by created_at asc
2360
2514
  limit ${excess}
2361
2515
  `;
2362
- if (toDelete && toDelete.length > 0) for (const row of toDelete) {
2363
- this.sql`delete from cf_ai_chat_agent_messages where id = ${row.id}`;
2364
- this._persistedMessageCache.delete(row.id);
2365
- }
2516
+ if (toDelete && toDelete.length > 0) this._deleteMessagesByIds(toDelete.map((row) => row.id));
2366
2517
  }
2367
2518
  /**
2368
2519
  * Enforces SQLite row size limits by compacting tool outputs and text parts