@cloudflare/ai-chat 0.8.1 → 0.8.2

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.
@@ -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;EA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B,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"}
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;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,CAAC,CAAC;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,UAAU,WACV,aAAa,WACb,OAAQ,QA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AAW,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
@@ -1016,6 +1099,7 @@ export {
1016
1099
  type ChatRecoveryContext,
1017
1100
  type ChatRecoveryExhaustedContext,
1018
1101
  type ChatRecoveryOptions,
1102
+ type ChatRecoveryProgressContext,
1019
1103
  type ChatResponseResult,
1020
1104
  type ClientToolSchema,
1021
1105
  type MessageConcurrency,
package/dist/index.js CHANGED
@@ -7,15 +7,16 @@ import { nanoid } from "nanoid";
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 DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 300 * 1e3;
17
18
  const CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1e3;
18
- const CHAT_RECOVERY_MAX_WINDOW_MS = 900 * 1e3;
19
+ const CHAT_RECOVERING_FLAG_TTL_MS = 900 * 1e3;
19
20
  const AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5e3;
20
21
  function sendIfOpen(connection, message) {
21
22
  try {
@@ -835,8 +836,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
835
836
  * concurrency state — use {@link resetTurnState} for the full
836
837
  * teardown that runs on `chat-clear`.
837
838
  */
838
- abortAllRequests() {
839
- this._abortRegistry.destroyAll();
839
+ abortAllRequests(reason) {
840
+ this._abortRegistry.destroyAll(reason);
840
841
  }
841
842
  async _awaitWithDeadline(promise, deadline) {
842
843
  if (deadline == null) return promise;
@@ -852,6 +853,61 @@ var AIChatAgent = class AIChatAgent extends Agent {
852
853
  return message.parts.some((part) => "state" in part && (part.state === "input-available" || part.state === "approval-requested"));
853
854
  }
854
855
  /**
856
+ * `true` when the turn is parked on a pending interaction that the CLIENT can
857
+ * still resolve after a restart — an `approval-requested` part, or an
858
+ * `input-available` part for a CLIENT tool (no server `execute`) whose
859
+ * `tool-result` the SPA replays over the WebSocket on reconnect.
860
+ *
861
+ * This is intentionally NARROWER than `hasPendingInteraction()` (which
862
+ * `waitUntilStable` uses): a SERVER tool's `input-available` orphan is
863
+ * excluded, because its `execute()` promise died with the evicted isolate and
864
+ * nothing will ever post its result — so it must NOT be treated as a healthy
865
+ * "waiting on the human" wait. Used to make a HITL turn budget-free during
866
+ * recovery so a slow human can't trip the no-progress / attempt / stable-
867
+ * timeout budgets; see `_beginChatRecoveryIncident` and
868
+ * `_parkRecoveryForPendingInteraction`. Mirrors `@cloudflare/think`'s
869
+ * `hasPendingInteraction`, which is already client-only by construction.
870
+ */
871
+ hasPendingClientInteraction() {
872
+ const clientResolvable = this._clientResolvableToolNames();
873
+ if (this._streamingMessage && this._messageAwaitsClientInteraction(this._streamingMessage, clientResolvable)) return true;
874
+ return this.messages.some((message) => message.role === "assistant" && this._messageAwaitsClientInteraction(message, clientResolvable));
875
+ }
876
+ _messageAwaitsClientInteraction(message, clientResolvable) {
877
+ return message.parts.some((part) => this._partAwaitsClientInteraction(part, clientResolvable));
878
+ }
879
+ /**
880
+ * Whether a part is still awaiting a CLIENT interaction that can genuinely
881
+ * arrive after a restart: an `approval-requested` part (a reconnecting client
882
+ * replays the approval) or an `input-available` part for a CLIENT tool (the
883
+ * SPA replays the `tool-result`). A SERVER tool's `input-available` is NOT
884
+ * pending — its `execute()` died with the isolate. Mirrors `@cloudflare/think`.
885
+ */
886
+ _partAwaitsClientInteraction(part, clientResolvable) {
887
+ if (!("state" in part)) return false;
888
+ const record = part;
889
+ const state = record.state;
890
+ if (state === "approval-requested") return true;
891
+ if (state !== "input-available") return false;
892
+ const toolName = this._toolPartName(record);
893
+ return toolName != null && clientResolvable.has(toolName);
894
+ }
895
+ /** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */
896
+ _toolPartName(record) {
897
+ const type = typeof record.type === "string" ? record.type : "";
898
+ if (type === "dynamic-tool") return typeof record.toolName === "string" ? record.toolName : void 0;
899
+ if (type.startsWith("tool-")) return type.slice(5);
900
+ }
901
+ /**
902
+ * Names of the CLIENT-resolvable tools (the client-provided schemas from the
903
+ * last request, which have no server `execute`). Mirrors `@cloudflare/think`.
904
+ */
905
+ _clientResolvableToolNames() {
906
+ const names = /* @__PURE__ */ new Set();
907
+ for (const tool of this._lastClientTools ?? []) if (tool?.name) names.add(tool.name);
908
+ return names;
909
+ }
910
+ /**
855
911
  * Run a chat turn exclusively so `_reply()` never overlaps with another
856
912
  * streaming turn.
857
913
  */
@@ -1313,6 +1369,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1313
1369
  }
1314
1370
  async cancelAgentToolRun(runId, reason) {
1315
1371
  this._agentToolAbortControllers.get(runId)?.abort(reason);
1372
+ this.abortAllRequests(reason);
1316
1373
  this.sql`
1317
1374
  update cf_ai_chat_agent_tool_runs
1318
1375
  set status = 'aborted', completed_at = coalesce(completed_at, ${Date.now()})
@@ -1391,6 +1448,40 @@ var AIChatAgent = class AIChatAgent extends Agent {
1391
1448
  this._closeAgentToolTailers(runId);
1392
1449
  }
1393
1450
  }
1451
+ /**
1452
+ * Eagerly terminalize this child facet's OWN agent-tool run row(s) once a
1453
+ * recovered turn has settled. A recovered turn re-runs via either
1454
+ * `_chatRecoveryContinue` → `continueLastTurn` or, for a pre-stream eviction,
1455
+ * `_chatRecoveryRetry` → `_retryLastUserTurn` — neither flows through
1456
+ * `startAgentToolRun`'s finalizer, so without this the row strands `running`
1457
+ * and its tailers stay open until a parent inspect lazily reconciles it —
1458
+ * forcing a re-attached parent to wait out a full no-progress window before
1459
+ * collecting an already-finished result (#1630 follow-up). Reconciling here
1460
+ * closes the tail promptly so the parent collects the terminal immediately.
1461
+ * No-op on non-child facets (their `cf_ai_chat_agent_tool_runs` table is
1462
+ * empty) and on rows whose in-memory run is still live; the underlying
1463
+ * reconcile leaves a row `running` while its recovery is still in progress.
1464
+ * Mirrors `@cloudflare/think`.
1465
+ */
1466
+ async _reconcileOwnStaleAgentToolChildRuns() {
1467
+ let rows;
1468
+ try {
1469
+ rows = this.sql`
1470
+ select run_id from cf_ai_chat_agent_tool_runs
1471
+ where status = 'running'
1472
+ `;
1473
+ } catch {
1474
+ return;
1475
+ }
1476
+ for (const { run_id } of rows) {
1477
+ if (this._agentToolAbortControllers.has(run_id)) continue;
1478
+ const row = this._getAgentToolRunRow(run_id);
1479
+ if (!row || row.status !== "running") continue;
1480
+ try {
1481
+ await this._reconcileStaleAgentToolChildRun(run_id, row);
1482
+ } catch {}
1483
+ }
1484
+ }
1394
1485
  async inspectAgentToolRun(runId) {
1395
1486
  const row = this._getAgentToolRunRow(runId);
1396
1487
  if (!row) return null;
@@ -1702,6 +1793,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1702
1793
  maxAttempts: Math.max(1, Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)),
1703
1794
  stableTimeoutMs: Math.max(0, Math.floor(custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS)),
1704
1795
  terminalMessage: custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,
1796
+ noProgressTimeoutMs: Math.max(0, Math.floor(custom?.noProgressTimeoutMs ?? DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS)),
1797
+ maxRecoveryWork: typeof custom?.maxRecoveryWork === "number" && custom.maxRecoveryWork >= 0 ? custom.maxRecoveryWork : DEFAULT_CHAT_RECOVERY_MAX_WORK,
1798
+ ...custom?.shouldKeepRecovering ? { shouldKeepRecovering: custom.shouldKeepRecovering } : {},
1705
1799
  ...custom?.onExhausted ? { onExhausted: custom.onExhausted } : {}
1706
1800
  };
1707
1801
  }
@@ -1782,12 +1876,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
1782
1876
  const prevProgress = existing?.progress ?? 0;
1783
1877
  const currentProgress = await this._chatRecoveryProgressMarker();
1784
1878
  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;
1879
+ const awaitingClientInteraction = this.hasPendingClientInteraction();
1880
+ const lastProgressAt = madeProgress || awaitingClientInteraction ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
1881
+ const noProgressExceeded = existing != null && !awaitingClientInteraction && now - lastProgressAt > config.noProgressTimeoutMs;
1882
+ const workBaseline = existing?.workBaseline ?? currentProgress;
1883
+ const progress = Math.max(prevProgress, currentProgress);
1884
+ const work = progress - workBaseline;
1885
+ const workBudgetExceeded = existing != null && Number.isFinite(config.maxRecoveryWork) && work > config.maxRecoveryWork;
1788
1886
  const debounced = existing != null && !madeProgress && now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;
1789
1887
  const attempt = madeProgress ? 1 : debounced ? existing?.attempt ?? 1 : (existing?.attempt ?? 0) + 1;
1790
- const exhausted = noProgressExceeded || incidentAgeExceeded || attempt > config.maxAttempts;
1888
+ let abortedByCaller = false;
1889
+ if (existing != null && !awaitingClientInteraction && config.shouldKeepRecovering && !noProgressExceeded && !workBudgetExceeded && attempt <= config.maxAttempts) try {
1890
+ abortedByCaller = await config.shouldKeepRecovering({
1891
+ incidentId,
1892
+ requestId: input.requestId,
1893
+ recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,
1894
+ attempt,
1895
+ maxAttempts: config.maxAttempts,
1896
+ recoveryKind: input.recoveryKind,
1897
+ work,
1898
+ ageMs: now - (existing.firstSeenAt ?? now)
1899
+ }) === false;
1900
+ } catch (error) {
1901
+ console.error("[AIChatAgent] chatRecovery shouldKeepRecovering hook threw", error);
1902
+ }
1903
+ const exhausted = !awaitingClientInteraction && (noProgressExceeded || workBudgetExceeded || abortedByCaller || attempt > config.maxAttempts);
1791
1904
  const incident = {
1792
1905
  incidentId,
1793
1906
  requestId: input.requestId,
@@ -1799,8 +1912,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1799
1912
  firstSeenAt: existing?.firstSeenAt ?? now,
1800
1913
  lastAttemptAt: now,
1801
1914
  lastProgressAt,
1802
- progress: Math.max(prevProgress, currentProgress),
1803
- ...exhausted ? { reason: incidentAgeExceeded ? "max_recovery_window_exceeded" : noProgressExceeded ? "no_progress_timeout" : "max_attempts_exceeded" } : {}
1915
+ progress,
1916
+ workBaseline,
1917
+ ...exhausted ? { reason: workBudgetExceeded ? "work_budget_exceeded" : noProgressExceeded ? "no_progress_timeout" : abortedByCaller ? "recovery_aborted" : "max_attempts_exceeded" } : {}
1804
1918
  };
1805
1919
  await this.ctx.storage.put(key, incident);
1806
1920
  if (!existing) this._emit("chat:recovery:detected", {
@@ -1888,7 +2002,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1888
2002
  */
1889
2003
  async _setChatRecovering(active, requestId) {
1890
2004
  const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
1891
- const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS;
2005
+ const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERING_FLAG_TTL_MS;
1892
2006
  if (active) {
1893
2007
  if (activeExisting) return;
1894
2008
  await this.ctx.storage.put(CHAT_RECOVERING_KEY, {
@@ -2024,6 +2138,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2024
2138
  try {
2025
2139
  const recoveryConfig = this._resolveChatRecoveryConfig();
2026
2140
  if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
2141
+ if (await this._parkRecoveryForPendingInteraction(data)) return;
2027
2142
  console.warn("[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state");
2028
2143
  if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryContinue", data, recoveryConfig.maxAttempts)) return;
2029
2144
  await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryContinue", data);
@@ -2039,6 +2154,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2039
2154
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2040
2155
  } finally {
2041
2156
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
2157
+ await this._reconcileOwnStaleAgentToolChildRuns();
2042
2158
  }
2043
2159
  }
2044
2160
  _applyRecoveredRequestContext(data) {
@@ -2069,6 +2185,37 @@ var AIChatAgent = class AIChatAgent extends Agent {
2069
2185
  return true;
2070
2186
  }
2071
2187
  /**
2188
+ * Park a recovery continuation that timed out waiting for stable state
2189
+ * because the turn is holding a pending CLIENT interaction (an
2190
+ * `input-available` client-tool part or an `approval-requested` part — see
2191
+ * `hasPendingClientInteraction`). Such a turn is WAITING ON THE HUMAN, not
2192
+ * stuck: the client replays the interrupted tool-result / approval after
2193
+ * reconnect, which drives a fresh continuation independently of the recovery
2194
+ * retry loop. Burning the attempt budget on that wait (each `waitUntilStable`
2195
+ * times out because the human hasn't answered) would seal a perfectly healthy
2196
+ * turn on `stable_timeout` — the symptom behind HITL "session recovery errors"
2197
+ * under deploy churn.
2198
+ *
2199
+ * So instead of rescheduling or exhausting, we stop the loop and mark the
2200
+ * incident `skipped` (reason `awaiting_client_interaction`). That retains the
2201
+ * incident record (a later genuine interruption re-evaluates it) while
2202
+ * resolving the live "recovering…" indicator via `_updateChatRecoveryIncident`
2203
+ * so the client sees the parked tool-call UI rather than an eternal spinner.
2204
+ * A client that never returns is reclaimed by the incident TTL sweep and DO
2205
+ * idle-eviction. SERVER-tool orphans are excluded by `hasPendingClientInteraction`
2206
+ * (their `execute` died with the isolate), so they still reschedule / exhaust
2207
+ * via the normal path. Mirrors the same helper in `@cloudflare/think`.
2208
+ *
2209
+ * Returns `true` when the recovery was parked (caller must return), `false`
2210
+ * when there is no pending client interaction (caller proceeds to the normal
2211
+ * reschedule / exhaustion path).
2212
+ */
2213
+ async _parkRecoveryForPendingInteraction(data) {
2214
+ if (!this.hasPendingClientInteraction()) return false;
2215
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "awaiting_client_interaction");
2216
+ return true;
2217
+ }
2218
+ /**
2072
2219
  * Resolve the stream id for a recovery turn so the give-up terminalization
2073
2220
  * can surface whatever partial the turn produced. Prefers the durable stream
2074
2221
  * row keyed by the recovery-root request id; falls back to the live active
@@ -2151,6 +2298,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2151
2298
  try {
2152
2299
  const recoveryConfig = this._resolveChatRecoveryConfig();
2153
2300
  if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
2301
+ if (await this._parkRecoveryForPendingInteraction(data)) return;
2154
2302
  console.warn("[AIChatAgent] _chatRecoveryRetry timed out waiting for stable state");
2155
2303
  if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryRetry", data, recoveryConfig.maxAttempts)) return;
2156
2304
  await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryRetry", data);
@@ -2170,6 +2318,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2170
2318
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2171
2319
  } finally {
2172
2320
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
2321
+ await this._reconcileOwnStaleAgentToolChildRuns();
2173
2322
  }
2174
2323
  }
2175
2324
  /**