@cloudflare/ai-chat 0.8.0 → 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.
- package/dist/ai-chat-v5-migration.js +44 -3
- package/dist/ai-chat-v5-migration.js.map +1 -1
- package/dist/index.d.ts +113 -1
- package/dist/index.js +190 -21
- package/dist/index.js.map +1 -1
- package/dist/react.js +37 -11
- package/dist/react.js.map +1 -1
- package/package.json +4 -4
|
@@ -1,9 +1,50 @@
|
|
|
1
|
+
import { normalizeToolInput } from "agents/chat";
|
|
1
2
|
//#region src/ai-chat-v5-migration.ts
|
|
2
3
|
/**
|
|
3
4
|
* AI SDK v5 Migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages
|
|
4
5
|
* Using exact types from the official AI SDK documentation
|
|
5
6
|
*/
|
|
6
7
|
/**
|
|
8
|
+
* Heal tool parts whose persisted `input` is not a provider-acceptable object.
|
|
9
|
+
*
|
|
10
|
+
* The write boundary (`applyChunkToParts`) now coerces malformed input to `{}`,
|
|
11
|
+
* but sessions corrupted before that guard shipped still carry a `null`,
|
|
12
|
+
* `undefined`, `""`, array, or stringified-JSON `input` in storage. Because
|
|
13
|
+
* the Anthropic Messages API rejects a `tool_use` block whose `input` is not an
|
|
14
|
+
* object, such a session 400s on every later turn and stays wedged across
|
|
15
|
+
* reconnects/redeploys/evictions. Repairing on load (where there's no
|
|
16
|
+
* framework-side `convertToModelMessages` to hook) unwedges them without
|
|
17
|
+
* per-DO storage surgery. Only malformed inputs are touched; a healthy message
|
|
18
|
+
* is returned by reference so the persistence cache stays a no-op.
|
|
19
|
+
*
|
|
20
|
+
* An absent `input` key is treated as `undefined` (→ `{}`): a JSON round-trip of
|
|
21
|
+
* `input: undefined` drops the key entirely (e.g. a tool call interrupted at the
|
|
22
|
+
* `tool-input-start` stage), so the missing-key case must coerce too. Mirrors
|
|
23
|
+
* the read-side repair in `@cloudflare/think`.
|
|
24
|
+
*/
|
|
25
|
+
function normalizeToolPartInputs(message) {
|
|
26
|
+
const parts = message.parts;
|
|
27
|
+
const isMalformedToolPart = (part) => {
|
|
28
|
+
const record = part;
|
|
29
|
+
const type = typeof record.type === "string" ? record.type : "";
|
|
30
|
+
if (!(type.startsWith("tool-") || type === "dynamic-tool")) return false;
|
|
31
|
+
return normalizeToolInput(record.input).changed;
|
|
32
|
+
};
|
|
33
|
+
if (!parts.some(isMalformedToolPart)) return message;
|
|
34
|
+
const nextParts = parts.map((part) => {
|
|
35
|
+
if (!isMalformedToolPart(part)) return part;
|
|
36
|
+
const record = part;
|
|
37
|
+
return {
|
|
38
|
+
...record,
|
|
39
|
+
input: normalizeToolInput(record.input).input
|
|
40
|
+
};
|
|
41
|
+
});
|
|
42
|
+
return {
|
|
43
|
+
...message,
|
|
44
|
+
parts: nextParts
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
7
48
|
* One-shot deprecation warnings (warns once per key per session).
|
|
8
49
|
*/
|
|
9
50
|
const _deprecationWarnings = /* @__PURE__ */ new Set();
|
|
@@ -49,7 +90,7 @@ function isCorruptArrayMessage(message) {
|
|
|
49
90
|
* @returns UIMessage in v5 format
|
|
50
91
|
*/
|
|
51
92
|
function autoTransformMessage(message, index = 0) {
|
|
52
|
-
if (isUIMessage(message)) return message;
|
|
93
|
+
if (isUIMessage(message)) return normalizeToolPartInputs(message);
|
|
53
94
|
const parts = [];
|
|
54
95
|
if (message.reasoning) parts.push({
|
|
55
96
|
type: "reasoning",
|
|
@@ -95,11 +136,11 @@ function autoTransformMessage(message, index = 0) {
|
|
|
95
136
|
type: "text",
|
|
96
137
|
text: typeof message === "string" ? message : JSON.stringify(message)
|
|
97
138
|
});
|
|
98
|
-
return {
|
|
139
|
+
return normalizeToolPartInputs({
|
|
99
140
|
id: message.id || `msg-${index}`,
|
|
100
141
|
role: message.role === "data" ? "system" : message.role || "user",
|
|
101
142
|
parts
|
|
102
|
-
};
|
|
143
|
+
});
|
|
103
144
|
}
|
|
104
145
|
/**
|
|
105
146
|
* Legacy single message migration for backward compatibility.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-chat-v5-migration.js","names":[],"sources":["../src/ai-chat-v5-migration.ts"],"sourcesContent":["import type { UIMessage } from \"ai\";\n\n/**\n * AI SDK v5 Migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages\n * Using exact types from the official AI SDK documentation\n */\n\n/**\n * One-shot deprecation warnings (warns once per key per session).\n */\nconst _deprecationWarnings = new Set<string>();\nfunction warnDeprecated(id: string, message: string) {\n if (!_deprecationWarnings.has(id)) {\n _deprecationWarnings.add(id);\n console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);\n }\n}\n\n/**\n * AI SDK v5 Message Part types reference (from official AI SDK documentation)\n *\n * The migration logic below transforms legacy messages to match these official AI SDK v5 formats:\n * - TextUIPart: { type: \"text\", text: string, state?: \"streaming\" | \"done\" }\n * - ReasoningUIPart: { type: \"reasoning\", text: string, state?: \"streaming\" | \"done\", providerMetadata?: Record<string, unknown> }\n * - FileUIPart: { type: \"file\", mediaType: string, filename?: string, url: string }\n * - ToolUIPart: { type: `tool-${string}`, toolCallId: string, state: \"input-streaming\" | \"input-available\" | \"output-available\" | \"output-error\", input?: Record<string, unknown>, output?: unknown, errorText?: string, providerExecuted?: boolean }\n */\n\n/**\n * Tool invocation from v4 format\n */\ntype ToolInvocation = {\n toolCallId: string;\n toolName: string;\n args: Record<string, unknown>;\n result?: unknown;\n state: \"partial-call\" | \"call\" | \"result\" | \"error\";\n};\n\n/**\n * Legacy part from v4 format\n */\ntype LegacyPart = {\n type: string;\n text?: string;\n url?: string;\n data?: string;\n mimeType?: string;\n mediaType?: string;\n filename?: string;\n};\n\n/**\n * Legacy message format from AI SDK v4\n */\nexport type LegacyMessage = {\n id?: string;\n role: string;\n content: string;\n reasoning?: string;\n toolInvocations?: ToolInvocation[];\n parts?: LegacyPart[];\n [key: string]: unknown;\n};\n\n/**\n * Corrupt content item\n */\ntype CorruptContentItem = {\n type: string;\n text: string;\n};\n\n/**\n * Corrupted message format - has content as array instead of parts\n */\nexport type CorruptArrayMessage = {\n id?: string;\n role: string;\n content: CorruptContentItem[];\n reasoning?: string;\n toolInvocations?: ToolInvocation[];\n [key: string]: unknown;\n};\n\n/**\n * Union type for messages that could be in any format\n */\nexport type MigratableMessage = LegacyMessage | CorruptArrayMessage | UIMessage;\n\n/**\n * Tool call state mapping for v4 to v5 migration\n */\nconst STATE_MAP = {\n \"partial-call\": \"input-streaming\",\n call: \"input-available\",\n result: \"output-available\",\n error: \"output-error\"\n} as const;\n\n/**\n * Checks if a message is already in the UIMessage format (has parts array)\n */\nexport function isUIMessage(message: unknown): message is UIMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"parts\" in message &&\n Array.isArray((message as { parts: unknown }).parts)\n );\n}\n\n/**\n * Type guard to check if a message is in legacy format (content as string)\n */\nfunction isLegacyMessage(message: unknown): message is LegacyMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"role\" in message &&\n \"content\" in message &&\n typeof (message as { role: unknown }).role === \"string\" &&\n typeof (message as { content: unknown }).content === \"string\"\n );\n}\n\n/**\n * Type guard to check if a message has corrupted array content format\n * Detects: {role: \"user\", content: [{type: \"text\", text: \"...\"}]}\n */\nfunction isCorruptArrayMessage(\n message: unknown\n): message is CorruptArrayMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"role\" in message &&\n \"content\" in message &&\n typeof (message as { role: unknown }).role === \"string\" &&\n Array.isArray((message as { content: unknown }).content) &&\n !(\"parts\" in message) // Ensure it's not already a UIMessage\n );\n}\n\n/**\n * Internal message part type for transformation\n */\ntype TransformMessagePart = {\n type: string;\n text?: string;\n toolCallId?: string;\n state?: string;\n input?: Record<string, unknown>;\n output?: unknown;\n url?: string;\n mediaType?: string;\n errorText?: string;\n filename?: string;\n};\n\n/**\n * Input message that could be in any format - using unknown for flexibility\n */\ntype InputMessage = {\n id?: string;\n role?: string;\n content?: unknown;\n reasoning?: string;\n toolInvocations?: unknown[];\n parts?: unknown[];\n [key: string]: unknown;\n};\n\n/**\n * Automatic message transformer following the blog post pattern\n * Handles comprehensive migration from AI SDK v4 to v5 format\n * @param message - Message in any legacy format\n * @param index - Index for ID generation fallback\n * @returns UIMessage in v5 format\n */\nexport function autoTransformMessage(\n message: UIMessage | InputMessage,\n index = 0\n): UIMessage {\n // Already in v5 format\n if (isUIMessage(message)) {\n return message;\n }\n\n const parts: TransformMessagePart[] = [];\n\n // Handle reasoning transformation\n if (message.reasoning) {\n parts.push({\n type: \"reasoning\",\n text: message.reasoning\n });\n }\n\n // Handle tool invocations transformation\n if (message.toolInvocations && Array.isArray(message.toolInvocations)) {\n message.toolInvocations.forEach((inv: unknown) => {\n if (typeof inv === \"object\" && inv !== null && \"toolName\" in inv) {\n const invObj = inv as ToolInvocation;\n parts.push({\n type: `tool-${invObj.toolName}`,\n toolCallId: invObj.toolCallId,\n state:\n STATE_MAP[invObj.state as keyof typeof STATE_MAP] ||\n \"input-available\",\n input: invObj.args,\n output: invObj.result !== undefined ? invObj.result : null\n });\n }\n });\n }\n\n // Handle file parts transformation\n if (message.parts && Array.isArray(message.parts)) {\n message.parts.forEach((part: unknown) => {\n if (typeof part === \"object\" && part !== null && \"type\" in part) {\n const partObj = part as LegacyPart;\n if (partObj.type === \"file\") {\n parts.push({\n type: \"file\",\n url:\n partObj.url ||\n (partObj.data\n ? `data:${partObj.mimeType || partObj.mediaType};base64,${partObj.data}`\n : undefined),\n mediaType: partObj.mediaType || partObj.mimeType,\n filename: partObj.filename\n });\n }\n }\n });\n }\n\n // Handle corrupt array format: {role: \"user\", content: [{type: \"text\", text: \"...\"}]}\n if (Array.isArray(message.content)) {\n message.content.forEach((item: unknown) => {\n if (typeof item === \"object\" && item !== null && \"text\" in item) {\n const itemObj = item as CorruptContentItem;\n parts.push({\n type: itemObj.type || \"text\",\n text: itemObj.text || \"\"\n });\n }\n });\n }\n\n // Fallback: convert plain content to text part\n if (!parts.length && message.content !== undefined) {\n parts.push({\n type: \"text\",\n text:\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content)\n });\n }\n\n // If still no parts, create a default text part\n if (!parts.length) {\n parts.push({\n type: \"text\",\n text: typeof message === \"string\" ? message : JSON.stringify(message)\n });\n }\n\n return {\n id: message.id || `msg-${index}`,\n role:\n message.role === \"data\"\n ? \"system\"\n : (message.role as \"user\" | \"assistant\" | \"system\") || \"user\",\n parts: parts as UIMessage[\"parts\"]\n };\n}\n\n/**\n * Legacy single message migration for backward compatibility.\n * @deprecated Use `autoTransformMessage` instead. Will be removed in the next major version.\n */\nexport function migrateToUIMessage(message: MigratableMessage): UIMessage {\n warnDeprecated(\n \"migrateToUIMessage\",\n \"migrateToUIMessage() is deprecated. Use autoTransformMessage() instead. It will be removed in the next major version.\"\n );\n return autoTransformMessage(message as InputMessage);\n}\n\n/**\n * Automatic message transformer for arrays following the blog post pattern\n * @param messages - Array of messages in any format\n * @returns Array of UIMessages in v5 format\n */\nexport function autoTransformMessages(messages: unknown[]): UIMessage[] {\n return messages.map((msg, i) => autoTransformMessage(msg as InputMessage, i));\n}\n\n/**\n * Migrates an array of messages to UIMessage format (legacy compatibility).\n * @param messages - Array of messages in old or new format\n * @returns Array of UIMessages in the new format\n * @deprecated Use `autoTransformMessages` instead. Will be removed in the next major version.\n */\nexport function migrateMessagesToUIFormat(\n messages: MigratableMessage[]\n): UIMessage[] {\n warnDeprecated(\n \"migrateMessagesToUIFormat\",\n \"migrateMessagesToUIFormat() is deprecated. Use autoTransformMessages() instead. It will be removed in the next major version.\"\n );\n return autoTransformMessages(messages as InputMessage[]);\n}\n\n/**\n * Checks if any messages in an array need migration.\n * @param messages - Array of messages to check\n * @returns true if any messages are not in proper UIMessage format\n * @deprecated Migration is now automatic via `autoTransformMessages`. Will be removed in the next major version.\n */\nexport function needsMigration(messages: unknown[]): boolean {\n warnDeprecated(\n \"needsMigration\",\n \"needsMigration() is deprecated. Migration is automatic via autoTransformMessages(). It will be removed in the next major version.\"\n );\n return messages.some((message) => {\n // If it's already a UIMessage, no migration needed\n if (isUIMessage(message)) {\n return false;\n }\n\n // Check for corrupt array format specifically\n if (isCorruptArrayMessage(message)) {\n return true;\n }\n\n // Check for legacy string format\n if (isLegacyMessage(message)) {\n return true;\n }\n\n // Any other format needs migration\n return true;\n });\n}\n\n/**\n * Analyzes the corruption types in a message array for debugging.\n * @param messages - Array of messages to analyze\n * @returns Statistics about corruption types found\n * @deprecated Migration is now automatic. Use this only for debugging legacy data. Will be removed in the next major version.\n */\nexport function analyzeCorruption(messages: unknown[]): {\n total: number;\n clean: number;\n legacyString: number;\n corruptArray: number;\n unknown: number;\n examples: {\n legacyString?: unknown;\n corruptArray?: unknown;\n unknown?: unknown;\n };\n} {\n const stats = {\n total: messages.length,\n clean: 0,\n legacyString: 0,\n corruptArray: 0,\n unknown: 0,\n examples: {} as {\n legacyString?: unknown;\n corruptArray?: unknown;\n unknown?: unknown;\n }\n };\n\n for (const message of messages) {\n if (isUIMessage(message)) {\n stats.clean++;\n } else if (isCorruptArrayMessage(message)) {\n stats.corruptArray++;\n if (!stats.examples.corruptArray) {\n stats.examples.corruptArray = message;\n }\n } else if (isLegacyMessage(message)) {\n stats.legacyString++;\n if (!stats.examples.legacyString) {\n stats.examples.legacyString = message;\n }\n } else {\n stats.unknown++;\n if (!stats.examples.unknown) {\n stats.examples.unknown = message;\n }\n }\n }\n\n return stats;\n}\n"],"mappings":";;;;;;;;AAUA,MAAM,uCAAuB,IAAI,IAAY;AAC7C,SAAS,eAAe,IAAY,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,Y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,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,IA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ED
|
@@ -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,
|
|
@@ -139,6 +140,14 @@ declare class AIChatAgent<
|
|
|
139
140
|
* cleared when it settles. Used by waitUntilStable to avoid polling.
|
|
140
141
|
*/
|
|
141
142
|
private _pendingInteractionPromise;
|
|
143
|
+
/**
|
|
144
|
+
* Serialization tail for client-tool result/approval applies (#1649). Each
|
|
145
|
+
* apply is a read-modify-write of the full message; running siblings from a
|
|
146
|
+
* parallel tool batch concurrently lets last-write-wins clobber the others
|
|
147
|
+
* back to `input-available`. Chaining every apply off this tail makes them
|
|
148
|
+
* commit atomically in arrival order.
|
|
149
|
+
*/
|
|
150
|
+
private _interactionApplyTail;
|
|
142
151
|
/**
|
|
143
152
|
* Tracks the ID of a streaming message that was persisted early due to
|
|
144
153
|
* a tool entering approval-requested state. When set, stream completion
|
|
@@ -155,6 +164,12 @@ declare class AIChatAgent<
|
|
|
155
164
|
* When true, chat turns are wrapped in `runFiber` for durable execution.
|
|
156
165
|
* Enables `onChatRecovery` hook and `this.stash()` during streaming.
|
|
157
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}.
|
|
158
173
|
*/
|
|
159
174
|
chatRecovery: ChatRecoveryConfig$1;
|
|
160
175
|
/** First queued overlap message index for merge strategy, keyed by epoch. */
|
|
@@ -430,9 +445,42 @@ declare class AIChatAgent<
|
|
|
430
445
|
* concurrency state — use {@link resetTurnState} for the full
|
|
431
446
|
* teardown that runs on `chat-clear`.
|
|
432
447
|
*/
|
|
433
|
-
protected abortAllRequests(): void;
|
|
448
|
+
protected abortAllRequests(reason?: unknown): void;
|
|
434
449
|
private _awaitWithDeadline;
|
|
435
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;
|
|
436
484
|
/**
|
|
437
485
|
* Run a chat turn exclusively so `_reply()` never overlaps with another
|
|
438
486
|
* streaming turn.
|
|
@@ -600,6 +648,22 @@ declare class AIChatAgent<
|
|
|
600
648
|
* Mutates `row` in place when it settles so the caller can report it.
|
|
601
649
|
*/
|
|
602
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;
|
|
603
667
|
inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
|
|
604
668
|
getAgentToolChunks(
|
|
605
669
|
runId: string,
|
|
@@ -768,6 +832,33 @@ declare class AIChatAgent<
|
|
|
768
832
|
* attempt budget is exhausted (caller should then fail terminally).
|
|
769
833
|
*/
|
|
770
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;
|
|
771
862
|
/**
|
|
772
863
|
* Resolve the stream id for a recovery turn so the give-up terminalization
|
|
773
864
|
* can surface whatever partial the turn produced. Prefers the durable stream
|
|
@@ -936,6 +1027,26 @@ declare class AIChatAgent<
|
|
|
936
1027
|
* SQLite writes plus `MESSAGE_UPDATED` broadcasts.
|
|
937
1028
|
*/
|
|
938
1029
|
private static _isToolPartUnchanged;
|
|
1030
|
+
/**
|
|
1031
|
+
* Serialize a client-tool result/approval apply behind any in-flight apply
|
|
1032
|
+
* (#1649, defensive). Each apply is a read-modify-write of the message and
|
|
1033
|
+
* parallel tool results arrive as independent WebSocket messages. Today
|
|
1034
|
+
* `_findAndUpdateToolPart` performs that read-modify-write synchronously (no
|
|
1035
|
+
* await between reading `this.messages` and the SQLite write), so concurrent
|
|
1036
|
+
* applies can't actually interleave — unlike Think, ai-chat does not exhibit
|
|
1037
|
+
* the #1649 clobber. This queue is a guard so the invariant survives if the
|
|
1038
|
+
* apply ever gains an await between read and write (e.g. async storage): each
|
|
1039
|
+
* apply commits atomically in arrival order.
|
|
1040
|
+
*
|
|
1041
|
+
* `_pendingInteractionPromise` is set to the newest link so the barrier's
|
|
1042
|
+
* single-slot wake-up observes the latest apply; because the chain is serial,
|
|
1043
|
+
* awaiting it transitively waits for every predecessor.
|
|
1044
|
+
*
|
|
1045
|
+
* @internal
|
|
1046
|
+
*/
|
|
1047
|
+
protected _enqueueInteractionApply(
|
|
1048
|
+
apply: () => Promise<boolean>
|
|
1049
|
+
): Promise<boolean>;
|
|
939
1050
|
/**
|
|
940
1051
|
* Applies a tool result to an existing assistant message.
|
|
941
1052
|
* This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
|
|
@@ -988,6 +1099,7 @@ export {
|
|
|
988
1099
|
type ChatRecoveryContext,
|
|
989
1100
|
type ChatRecoveryExhaustedContext,
|
|
990
1101
|
type ChatRecoveryOptions,
|
|
1102
|
+
type ChatRecoveryProgressContext,
|
|
991
1103
|
type ChatResponseResult,
|
|
992
1104
|
type ClientToolSchema,
|
|
993
1105
|
type MessageConcurrency,
|