@tanstack/ai 0.52.2 → 0.52.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/activities/chat/index.js +1 -1
- package/dist/esm/activities/chat/index.js.map +1 -1
- package/dist/esm/activities/chat/messages.js +10 -11
- package/dist/esm/activities/chat/messages.js.map +1 -1
- package/package.json +1 -1
- package/skills/ai-core/adapter-configuration/SKILL.md +19 -0
- package/skills/ai-core/adapter-configuration/references/openai-adapter.md +5 -0
- package/src/activities/chat/index.ts +1 -1
- package/src/activities/chat/messages.ts +16 -14
|
@@ -95,13 +95,11 @@ function convertMessagesToModelMessages(messages) {
|
|
|
95
95
|
if (role === "tool" && modelMessage.toolCallId && anchoredToolCallIds.has(modelMessage.toolCallId)) continue;
|
|
96
96
|
if (role === "reasoning") {
|
|
97
97
|
const content = msg.content;
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
});
|
|
104
|
-
}
|
|
98
|
+
const signature = encryptedValueFrom(msg);
|
|
99
|
+
if (content || signature !== void 0) pendingThinking.push({
|
|
100
|
+
content: typeof content === "string" ? content : "",
|
|
101
|
+
...signature !== void 0 ? { signature } : {}
|
|
102
|
+
});
|
|
105
103
|
continue;
|
|
106
104
|
}
|
|
107
105
|
if (role === "activity") continue;
|
|
@@ -381,7 +379,7 @@ function buildAssistantMessages(uiMessage) {
|
|
|
381
379
|
}
|
|
382
380
|
break;
|
|
383
381
|
case "thinking":
|
|
384
|
-
if (part.content) {
|
|
382
|
+
if (part.content || part.signature) {
|
|
385
383
|
if (current.toolCalls.some(isProviderExecutedToolCall)) flushSegment();
|
|
386
384
|
pendingThinking.push({
|
|
387
385
|
content: part.content,
|
|
@@ -448,7 +446,7 @@ function modelMessageToUIMessage(modelMessage, id) {
|
|
|
448
446
|
const parts = [];
|
|
449
447
|
const createdAt = coerceCreatedAt(modelMessage.createdAt);
|
|
450
448
|
if (modelMessage.role === "assistant" && modelMessage.thinking?.length) for (const thinking of modelMessage.thinking) {
|
|
451
|
-
if (!thinking.content) continue;
|
|
449
|
+
if (!thinking.content && !thinking.signature) continue;
|
|
452
450
|
parts.push({
|
|
453
451
|
type: "thinking",
|
|
454
452
|
content: thinking.content,
|
|
@@ -585,12 +583,13 @@ function aguiSnapshotMessageToUIMessage(message) {
|
|
|
585
583
|
});
|
|
586
584
|
case "reasoning": {
|
|
587
585
|
const signature = encryptedValueFrom(message);
|
|
586
|
+
const content = typeof message.content === "string" ? message.content : "";
|
|
588
587
|
return applySnapshotMetadata(message, {
|
|
589
588
|
id,
|
|
590
589
|
role: "assistant",
|
|
591
|
-
parts:
|
|
590
|
+
parts: content || signature !== void 0 ? [{
|
|
592
591
|
type: "thinking",
|
|
593
|
-
content
|
|
592
|
+
content,
|
|
594
593
|
...signature !== void 0 ? { signature } : {}
|
|
595
594
|
}] : []
|
|
596
595
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.js","names":[],"sources":["../../../../src/activities/chat/messages.ts"],"sourcesContent":["import { isProviderExecutedToolCall } from '../../utilities/provider-executed'\nimport {\n isContentPartArray,\n normalizeToolResult,\n} from '../../utilities/tool-result'\nimport { tanstackMetadata } from '../../utilities/merge-metadata'\nimport type { Message as AGUIMessage } from '@ag-ui/core'\nimport type {\n ContentPart,\n MessagePart,\n ModelMessage,\n StructuredOutputPart,\n TanStackMessageMetadata,\n TextPart,\n ToolCall,\n ToolCallPart,\n UIMessage,\n UIResourcePart,\n} from '../../types'\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n// ===========================\n// Message Converters\n// ===========================\n\n/**\n * Check if a MessagePart is a content part (text, image, audio, video, document)\n * that maps directly to a ModelMessage ContentPart.\n */\nfunction isContentPart(part: MessagePart): part is ContentPart {\n return (\n part.type === 'text' ||\n part.type === 'image' ||\n part.type === 'audio' ||\n part.type === 'video' ||\n part.type === 'document'\n )\n}\n\nexport function safeJsonStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? ''\n } catch {\n return ''\n }\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\nfunction encryptedValueFrom(value: object): string | undefined {\n if ('encryptedValue' in value) {\n const fromSpec = nonEmptyString(value.encryptedValue)\n if (fromSpec !== undefined) return fromSpec\n }\n return nonEmptyString(tanstackMetadata(value)?.signature)\n}\n\nfunction toolCallFromWire(toolCall: ToolCall, bag: unknown): ToolCall {\n const fromBag =\n bag != null && typeof bag === 'object' && !Array.isArray(bag)\n ? bag\n : undefined\n const encrypted = encryptedValueFrom(toolCall)\n if (bag === null && encrypted === undefined) {\n return { ...toolCall, metadata: null }\n }\n if (fromBag === undefined && encrypted === undefined) return toolCall\n return {\n ...toolCall,\n metadata: {\n ...(fromBag ?? {}),\n ...(encrypted !== undefined ? { thoughtSignature: encrypted } : {}),\n },\n }\n}\n\nfunction parseToolResultContent(content: string): unknown {\n try {\n return JSON.parse(content)\n } catch {\n return content\n }\n}\n\n/**\n * Collapse an array of ContentParts into the most compact ModelMessage content:\n * - Empty array → null\n * - All text parts → joined string (or null if empty)\n * - Mixed content → ContentPart array as-is\n */\nfunction collapseContentParts(\n parts: Array<ContentPart>,\n): string | null | Array<ContentPart> {\n if (parts.length === 0) return null\n\n const allText = parts.every((p) => p.type === 'text')\n if (allText) {\n const joined = parts.map((p) => p.content).join('')\n return joined || null\n }\n\n return parts\n}\n\n/**\n * Extract text content from ModelMessage content (string, null, or ContentPart array).\n * Used when only the text portion is needed (e.g., tool result content).\n */\nfunction getTextContent(\n content: string | null | undefined | Array<ContentPart>,\n): string {\n // Tool-call-only assistant turns carry no text and reach here as `null` or\n // `undefined`; both must collapse to an empty string rather than crash on\n // `.filter` (issue #532 — the interrupt-boundary MessagesSnapshot).\n if (content === null || content === undefined) return ''\n if (typeof content === 'string') return content\n return content\n .filter((part): part is TextPart => part.type === 'text')\n .map((part) => part.content)\n .join('')\n}\n\nfunction toolResultContent(\n content: string | null | undefined | Array<ContentPart>,\n): string | Array<ContentPart> {\n return Array.isArray(content) ? content : getTextContent(content)\n}\n\n/**\n * Convert UIMessages or ModelMessages to ModelMessages\n */\nexport function convertMessagesToModelMessages(\n messages: Array<UIMessage | ModelMessage>,\n): Array<ModelMessage> {\n // Pre-pass: collect toolCallIds already represented in anchor UIMessage parts.\n // Fan-out tool messages whose toolCallId matches an anchored ToolResultPart\n // are AG-UI duplicates and must be dropped to avoid double-feeding the LLM.\n const anchoredToolCallIds = new Set<string>()\n for (const msg of messages) {\n if ('parts' in msg) {\n for (const part of msg.parts) {\n if (part.type === 'tool-result') {\n anchoredToolCallIds.add(part.toolCallId)\n }\n }\n }\n }\n\n const modelMessages: Array<ModelMessage> = []\n let pendingThinking: Array<{ content: string; signature?: string }> = []\n for (const msg of messages) {\n if ('parts' in msg) {\n modelMessages.push(...uiMessageToModelMessages(msg))\n continue\n }\n\n const modelMessage = restoreModelMessageCreatedAt(\n restoreToolResultOwnership(msg),\n )\n const role = (modelMessage as { role: string }).role\n\n if (\n role === 'tool' &&\n modelMessage.toolCallId &&\n anchoredToolCallIds.has(modelMessage.toolCallId)\n ) {\n continue\n }\n\n if (role === 'reasoning') {\n const content = (msg as { content?: string }).content\n if (content) {\n const signature = encryptedValueFrom(msg)\n pendingThinking.push({\n content,\n ...(signature !== undefined ? { signature } : {}),\n })\n }\n continue\n }\n\n if (role === 'activity') {\n continue\n }\n\n if (role === 'developer') {\n modelMessages.push({\n role: 'system' as ModelMessage['role'],\n content: (msg as { content: string }).content,\n ...optionalName(modelMessage),\n ...optionalCreatedAt(modelMessage),\n ...(modelMessage.metadata !== undefined && {\n metadata: modelMessage.metadata,\n }),\n })\n continue\n }\n\n if (\n role === 'user' &&\n Array.isArray((msg as { content?: unknown }).content)\n ) {\n const content = (msg as { content: Array<{ type: string }> }).content\n // TanStack ModelMessage text parts use `{ content }`. AG-UI wire text\n // parts use `{ text }`. Only rewrite the AG-UI shape.\n if (\n !content.some(\n (part) =>\n part.type === 'text' && 'text' in part && !('content' in part),\n )\n ) {\n modelMessages.push(modelMessage)\n continue\n }\n const parts = aguiUserContentToParts(\n content as Extract<AGUIMessage, { role: 'user' }>['content'],\n )\n const contentParts = parts.filter(isContentPart)\n modelMessages.push({\n role: 'user',\n content: collapseContentParts(contentParts),\n ...((msg as { id?: string }).id !== undefined && {\n id: (msg as { id: string }).id,\n }),\n ...optionalName(modelMessage),\n ...optionalCreatedAt(modelMessage),\n ...(modelMessage.metadata !== undefined && {\n metadata: modelMessage.metadata,\n }),\n })\n continue\n }\n\n if (role === 'assistant') {\n const source = modelMessage\n const toolCallMetadata = tanstackMetadata(msg)?.toolCallMetadata\n const toolCalls = source.toolCalls?.map((toolCall) =>\n toolCallFromWire(toolCall, toolCallMetadata?.[toolCall.id]),\n )\n modelMessages.push({\n ...source,\n ...(toolCalls !== undefined ? { toolCalls } : {}),\n ...(pendingThinking.length > 0\n ? {\n thinking: [...(source.thinking ?? []), ...pendingThinking],\n }\n : {}),\n })\n pendingThinking = []\n continue\n }\n\n modelMessages.push(modelMessage)\n }\n return modelMessages\n}\n\nfunction restoreModelMessageCreatedAt(message: ModelMessage): ModelMessage {\n const createdAt =\n coerceCreatedAt(message.createdAt) ?? createdAtFromMetadata(message)\n if (createdAt === undefined) {\n if (message.createdAt === undefined) return message\n const { createdAt: _invalid, ...rest } = message\n return rest\n }\n return Object.is(message.createdAt, createdAt)\n ? message\n : { ...message, createdAt }\n}\n\nexport function restoreToolResultOwnership<T extends object>(message: T): T {\n if (!('role' in message) || message.role !== 'tool') return message\n const source = message\n const metadata = tanstackMetadata(source)\n const owned = metadata?.toolResult\n if (!isRecord(owned)) return message\n if ('content' in owned && !isContentPartArray(owned.content)) return message\n const next = { ...message }\n if (!('id' in owned)) Reflect.deleteProperty(next, 'id')\n if (!('createdAt' in owned)) Reflect.deleteProperty(next, 'createdAt')\n if (typeof owned.id === 'string') Reflect.set(next, 'id', owned.id)\n if (typeof owned.createdAt === 'string') {\n const createdAt = coerceCreatedAt(owned.createdAt)\n if (createdAt) Reflect.set(next, 'createdAt', createdAt)\n }\n if (isContentPartArray(owned.content)) {\n Reflect.set(next, 'content', owned.content)\n }\n const sourceMetadata: unknown = Reflect.get(source, 'metadata')\n if (isRecord(sourceMetadata)) {\n const tanstack = sourceMetadata.tanstack\n if (isRecord(tanstack)) {\n const { toolResult: _toolResult, ...restTanstack } = tanstack\n const restMetadata = { ...sourceMetadata }\n if (Object.keys(restTanstack).length) restMetadata.tanstack = restTanstack\n else delete restMetadata.tanstack\n if (Object.keys(restMetadata).length)\n Reflect.set(next, 'metadata', restMetadata)\n else Reflect.deleteProperty(next, 'metadata')\n }\n }\n return next\n}\n\n/**\n * Rebuild a `Date` from a live `Date` or from an ISO string.\n * `JSON.stringify` turns `Date` into a string, so persistence reload\n * and AG-UI wire both land here as strings.\n */\nexport function coerceCreatedAt(value: unknown): Date | undefined {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? undefined : value\n }\n if (typeof value !== 'string') return undefined\n const createdAt = new Date(value)\n return Number.isNaN(createdAt.getTime()) ? undefined : createdAt\n}\n\nfunction normalizeMessagePart(part: MessagePart): MessagePart {\n if (part.type !== 'tool-result') return part\n const createdAt = coerceCreatedAt(part.createdAt)\n const { createdAt: _createdAt, ...rest } = part\n return createdAt === undefined ? rest : { ...rest, createdAt }\n}\n\nfunction createdAtFromMetadata(source: object): Date | undefined {\n return coerceCreatedAt(tanstackMetadata(source)?.createdAt)\n}\n\nfunction optionalCreatedAt(source: { createdAt?: unknown }): {\n createdAt?: Date\n} {\n const createdAt = coerceCreatedAt(source.createdAt)\n return createdAt !== undefined ? { createdAt } : {}\n}\n\nfunction optionalName(source: { name?: string }): { name?: string } {\n return source.name !== undefined ? { name: source.name } : {}\n}\n\nfunction isUiResourcePart(value: unknown): value is UIResourcePart {\n if (value == null || typeof value !== 'object' || Array.isArray(value)) {\n return false\n }\n if (!('type' in value) || value.type !== 'ui-resource') return false\n if (!('toolCallId' in value) || typeof value.toolCallId !== 'string') {\n return false\n }\n if (!('toolName' in value) || typeof value.toolName !== 'string') {\n return false\n }\n if (\n !('resource' in value) ||\n value.resource == null ||\n typeof value.resource !== 'object' ||\n Array.isArray(value.resource)\n ) {\n return false\n }\n const resource = value.resource\n return (\n 'uri' in resource &&\n typeof resource.uri === 'string' &&\n 'mimeType' in resource &&\n typeof resource.mimeType === 'string'\n )\n}\n\nfunction uiResourceKey(part: UIResourcePart): string {\n return `${part.toolCallId}\\0${part.toolName}\\0${part.resource.uri}`\n}\n\nfunction appendUiResources(\n ui: UIMessage,\n resources: ReadonlyArray<UIResourcePart>,\n): UIMessage {\n if (resources.length === 0) return ui\n const seen = new Set(\n ui.parts.filter(isUiResourcePart).map((part) => uiResourceKey(part)),\n )\n const extra = resources.filter((part) => !seen.has(uiResourceKey(part)))\n if (extra.length === 0) return ui\n return { ...ui, parts: [...ui.parts, ...extra] }\n}\n\nfunction assistantMetadata(\n uiMessage: UIMessage,\n): UIMessage['metadata'] | undefined {\n const fromParts = uiMessage.parts.filter(isUiResourcePart)\n const current = uiMessage.metadata ?? {}\n const previous = tanstackMetadata(uiMessage)\n const tanstack: TanStackMessageMetadata = {}\n if (previous?.model !== undefined) tanstack.model = previous.model\n if (previous?.signature !== undefined) tanstack.signature = previous.signature\n if (fromParts.length > 0) tanstack.uiResources = fromParts\n const result = { ...current }\n if (Object.keys(tanstack).length > 0) result.tanstack = tanstack\n else delete result.tanstack\n return Object.keys(result).length > 0 ? result : undefined\n}\n\n/**\n * Convert a UIMessage to ModelMessage(s)\n *\n * Walks the parts array IN ORDER to preserve the interleaving of text,\n * tool calls, and tool results. This is critical for multi-round tool\n * flows where the model generates text, calls a tool, gets the result,\n * then generates more text and calls another tool.\n *\n * The output preserves the sequential structure:\n * text1 → toolCall1 → toolResult1 → text2 → toolCall2 → toolResult2\n * becomes:\n * assistant: {content: \"text1\", toolCalls: [toolCall1]}\n * tool: toolResult1\n * assistant: {content: \"text2\", toolCalls: [toolCall2]}\n * tool: toolResult2\n *\n * @param uiMessage - The UIMessage to convert\n * @returns An array of ModelMessages preserving part ordering\n */\nexport function uiMessageToModelMessages(\n uiMessage: UIMessage,\n): Array<ModelMessage> {\n // Skip system messages - they're handled via systemPrompts, not ModelMessages\n if (uiMessage.role === 'system') {\n return []\n }\n\n // For non-assistant messages (user), use the simpler path since they\n // don't have tool calls or tool results to interleave\n if (uiMessage.role !== 'assistant') {\n return [buildUserOrToolMessage(uiMessage)]\n }\n\n // For assistant messages, walk parts in order to preserve interleaving\n return buildAssistantMessages(uiMessage)\n}\n\n/**\n * Build a single ModelMessage for user messages (simple path).\n * Preserves ordering of text and multimodal content parts.\n */\nfunction buildUserOrToolMessage(uiMessage: UIMessage): ModelMessage {\n const contentParts: Array<ContentPart> = []\n for (const part of uiMessage.parts) {\n if (isContentPart(part)) {\n contentParts.push(part)\n }\n }\n\n return {\n id: uiMessage.id,\n role: uiMessage.role as 'user' | 'assistant' | 'tool',\n content: collapseContentParts(contentParts),\n ...optionalName(uiMessage),\n ...optionalCreatedAt(uiMessage),\n ...(uiMessage.metadata !== undefined && { metadata: uiMessage.metadata }),\n }\n}\n\n// Accumulator for building an assistant segment (content + tool calls)\ninterface AssistantSegment {\n contentParts: Array<ContentPart>\n structuredOutput?: StructuredOutputPart\n toolCalls: Array<{\n id: string\n type: 'function'\n function: { name: string; arguments: string }\n /** Provider-specific metadata that round-trips with the tool call.\n * Untyped at this framework layer; adapters narrow it via their\n * `TToolCallMetadata` generic. */\n metadata?: unknown\n }>\n}\n\nfunction createSegment(): AssistantSegment {\n return { contentParts: [], toolCalls: [] }\n}\n\nfunction isToolCallIncluded(part: ToolCallPart): boolean {\n return (\n part.state === 'input-complete' ||\n part.state === 'complete' ||\n part.state === 'approval-requested' ||\n part.state === 'approval-responded' ||\n part.state === 'error' ||\n part.output !== undefined\n )\n}\n\n/**\n * Build ModelMessages for an assistant UIMessage, preserving the\n * sequential interleaving of text, tool calls, and tool results.\n *\n * Walks parts in order. Text and tool-call parts accumulate into the\n * current \"segment\". When a tool-result part is encountered, the\n * current segment is flushed as an assistant message, then the tool\n * result is emitted as a tool message.\n */\nfunction buildAssistantMessages(uiMessage: UIMessage): Array<ModelMessage> {\n // A single UI message can fan out into several model messages. Keep the\n // shared UI id on each one so persistence can retain the original identity.\n const messageList: Array<ModelMessage> = []\n let current = createSegment()\n let pendingThinking: Array<{ content: string; signature?: string }> = []\n\n // Track emitted tool result IDs to avoid duplicates.\n // A tool call can have BOTH an explicit tool-result part AND an output\n // field on the tool-call part. We only want one per tool call ID.\n const emittedToolResultIds = new Set<string>()\n const identityFields = {\n id: uiMessage.id,\n ...optionalName(uiMessage),\n ...optionalCreatedAt(uiMessage),\n }\n const metadata = assistantMetadata(uiMessage)\n const assistantFields = {\n ...identityFields,\n ...(metadata !== undefined && { metadata }),\n }\n\n function flushSegment(force = false): void {\n const content = collapseContentParts(current.contentParts)\n const hasContent = content !== null\n const hasToolCalls = current.toolCalls.length > 0\n const hasThinking = pendingThinking.length > 0\n\n if (force || hasContent || hasToolCalls || hasThinking) {\n messageList.push({\n ...assistantFields,\n role: 'assistant',\n content,\n ...(hasToolCalls && { toolCalls: current.toolCalls }),\n ...(hasThinking && { thinking: pendingThinking }),\n ...(current.structuredOutput && {\n structuredOutput: current.structuredOutput,\n }),\n })\n pendingThinking = []\n }\n current = createSegment()\n }\n\n for (const part of uiMessage.parts) {\n switch (part.type) {\n case 'text':\n case 'image':\n case 'audio':\n case 'video':\n case 'document':\n current.contentParts.push(part)\n break\n\n case 'tool-call':\n if (isToolCallIncluded(part)) {\n current.toolCalls.push({\n id: part.id,\n type: 'function' as const,\n function: {\n name: part.name,\n arguments: part.arguments,\n },\n ...(part.metadata !== undefined && { metadata: part.metadata }),\n })\n }\n break\n\n case 'tool-result':\n // Flush the current assistant segment before emitting the tool result\n flushSegment(messageList.length === 0)\n\n // Emit the tool result\n if (\n (part.state === 'complete' || part.state === 'error') &&\n !emittedToolResultIds.has(part.toolCallId)\n ) {\n messageList.push({\n ...(part.id !== undefined && { id: part.id }),\n ...optionalCreatedAt(part),\n role: 'tool',\n content: part.content,\n toolCallId: part.toolCallId,\n ...(part.name !== undefined && { name: part.name }),\n ...(part.metadata !== undefined && { metadata: part.metadata }),\n ...(part.error !== undefined && { error: part.error }),\n })\n emittedToolResultIds.add(part.toolCallId)\n }\n break\n\n case 'thinking':\n if (part.content) {\n // Provider-executed tools have no tool-result part, so thinking\n // after them has to start the next segment or it replays first.\n if (current.toolCalls.some(isProviderExecutedToolCall)) {\n flushSegment()\n }\n pendingThinking.push({\n content: part.content,\n ...(part.signature && { signature: part.signature }),\n })\n }\n break\n\n case 'structured-output':\n // Only emit completed structured responses into history. Streaming or\n // errored buffers would push malformed JSON into the next LLM turn's\n // assistant content. `raw` is the source of truth; `data` is the\n // defensive fallback for terminal-only completes that didn't ship raw.\n if (part.status === 'complete') {\n const serialized =\n part.raw !== ''\n ? part.raw\n : part.data !== undefined\n ? safeJsonStringify(part.data)\n : ''\n if (serialized !== '') {\n current.contentParts.push({ type: 'text', content: serialized })\n current.structuredOutput = part\n }\n }\n break\n\n case 'ui-resource':\n // MCP Apps widget — rendered client-side only. It must never enter\n // model input, so it is intentionally dropped from the model message.\n break\n\n default:\n break\n }\n }\n\n // Flush any remaining accumulated content\n flushSegment()\n\n // Emit tool results from client tool-call parts with output or approval,\n // but only if not already covered by an explicit tool-result part above.\n // These are appended at the end since they don't have explicit tool-result\n // parts in the parts array to trigger inline emission.\n for (const part of uiMessage.parts) {\n if (part.type !== 'tool-call') continue\n\n // Output takes priority — if the tool has already produced a result,\n // emit the concrete output regardless of approval metadata.\n if (part.output !== undefined && !emittedToolResultIds.has(part.id)) {\n messageList.push({\n role: 'tool',\n content: normalizeToolResult(part.output),\n toolCallId: part.id,\n })\n emittedToolResultIds.add(part.id)\n }\n\n // Approval response without output — emit approval status for iteration tracking\n if (\n part.output === undefined &&\n part.state === 'approval-responded' &&\n part.approval?.approved !== undefined &&\n !emittedToolResultIds.has(part.id)\n ) {\n const approved = part.approval.approved\n messageList.push({\n role: 'tool',\n content: JSON.stringify({\n approved,\n ...(approved && { pendingExecution: true }),\n message: approved\n ? 'User approved this action'\n : 'User denied this action',\n }),\n toolCallId: part.id,\n })\n emittedToolResultIds.add(part.id)\n }\n }\n\n // If no messages were produced (e.g., empty parts), emit a minimal assistant message\n if (messageList.length === 0) {\n messageList.push({\n ...assistantFields,\n role: 'assistant',\n content: null,\n })\n }\n\n return messageList\n}\n\n/**\n * Convert a ModelMessage to UIMessage\n *\n * This conversion creates a parts-based structure:\n * - content field → TextPart\n * - toolCalls array → ToolCallPart[]\n * - role=\"tool\" messages should be converted separately and merged\n *\n * @param modelMessage - The ModelMessage to convert\n * @param id - Optional ID for the UIMessage (generated if not provided)\n * @returns A UIMessage with parts\n */\nexport function modelMessageToUIMessage(\n modelMessage: ModelMessage,\n id?: string,\n): UIMessage {\n const parts: Array<MessagePart> = []\n const createdAt = coerceCreatedAt(modelMessage.createdAt)\n\n if (modelMessage.role === 'assistant' && modelMessage.thinking?.length) {\n for (const thinking of modelMessage.thinking) {\n if (!thinking.content) continue\n parts.push({\n type: 'thinking',\n content: thinking.content,\n ...(thinking.signature && { signature: thinking.signature }),\n })\n }\n }\n\n // Handle tool results (when role is \"tool\") - only produce tool-result part,\n // not a text part (the content IS the tool result, not display text)\n const structuredOutput =\n modelMessage.structuredOutput ??\n snapshotStructuredOutput(tanstackMetadata(modelMessage)?.structuredOutput)\n if (modelMessage.role === 'assistant' && structuredOutput) {\n if (\n typeof modelMessage.content === 'string' &&\n modelMessage.content &&\n modelMessage.content !== structuredOutput.raw\n ) {\n const suffix = structuredOutput.raw\n const text =\n suffix !== '' && modelMessage.content.endsWith(suffix)\n ? modelMessage.content.slice(0, -suffix.length)\n : modelMessage.content\n if (text) parts.push({ type: 'text', content: text })\n }\n parts.push(structuredOutput)\n } else if (modelMessage.role === 'tool' && modelMessage.toolCallId) {\n parts.push({\n type: 'tool-result',\n toolCallId: modelMessage.toolCallId,\n content: toolResultContent(modelMessage.content),\n state: modelMessage.error === undefined ? 'complete' : 'error',\n ...(modelMessage.id !== undefined && { id: modelMessage.id }),\n ...(modelMessage.name !== undefined && { name: modelMessage.name }),\n ...(modelMessage.metadata !== undefined && {\n metadata: modelMessage.metadata,\n }),\n ...(createdAt !== undefined && { createdAt }),\n ...(modelMessage.error !== undefined && { error: modelMessage.error }),\n })\n } else if (Array.isArray(modelMessage.content)) {\n // Multimodal content - preserve all content parts as MessageParts\n for (const part of modelMessage.content) {\n parts.push(part)\n }\n } else {\n // String or null content\n const textContent = getTextContent(modelMessage.content)\n if (textContent) {\n parts.push({\n type: 'text',\n content: textContent,\n })\n }\n }\n\n // Handle tool calls\n if (modelMessage.toolCalls && modelMessage.toolCalls.length > 0) {\n for (const toolCall of modelMessage.toolCalls) {\n // Model-message arguments are complete, so surface the parsed input.\n // A malformed arguments string just leaves `input` undefined.\n let input: unknown\n try {\n input = JSON.parse(toolCall.function.arguments)\n } catch {\n input = undefined\n }\n parts.push({\n type: 'tool-call',\n id: toolCall.id,\n name: toolCall.function.name,\n arguments: toolCall.function.arguments,\n state: 'input-complete', // Model messages have complete arguments\n ...(input !== undefined && { input }),\n ...(toolCall.metadata !== undefined && { metadata: toolCall.metadata }),\n })\n }\n }\n\n const ui: UIMessage = {\n id: id || generateMessageId(),\n role: modelMessage.role === 'tool' ? 'assistant' : modelMessage.role,\n parts,\n ...optionalName(modelMessage),\n ...(createdAt !== undefined && { createdAt }),\n ...(modelMessage.metadata !== undefined && {\n metadata: modelMessage.metadata,\n }),\n }\n const storedResources = tanstackMetadata(modelMessage)?.uiResources\n return appendUiResources(\n ui,\n Array.isArray(storedResources)\n ? storedResources.filter(isUiResourcePart)\n : [],\n )\n}\n\n/**\n * Normalize a single AG-UI `MESSAGES_SNAPSHOT` message into a `UIMessage`.\n *\n * AG-UI snapshot messages use the wire shape `{ id, role, content }` and have\n * no `parts` array. Casting them directly to `UIMessage` is unsafe: any code\n * that later reads `message.parts` (e.g. the devtools `onToolCallStateChange`\n * handler) crashes with \"Cannot read properties of undefined (reading 'find')\".\n *\n * Each role is mapped to the canonical `UIMessage` shape, reusing\n * `modelMessageToUIMessage` for the roles that share `ModelMessage`'s structure.\n * The original AG-UI `id` is preserved so later `TEXT_MESSAGE_CONTENT` /\n * `TOOL_CALL_*` events still route by `messageId` (falling back to a generated\n * id only when the snapshot omits one). Messages that already carry `parts`\n * (e.g. a TanStack server echoing `UIMessage`s back over the wire) pass through\n * unchanged apart from ensuring an id.\n */\nexport function aguiSnapshotMessageToUIMessage(\n message: AGUIMessage | UIMessage,\n): UIMessage {\n if ('parts' in message) {\n return applySnapshotMetadata(message, {\n ...message,\n id: message.id || generateMessageId(),\n })\n }\n\n const id = message.id || generateMessageId()\n\n switch (message.role) {\n case 'user':\n return applySnapshotMetadata(message, {\n id,\n role: 'user',\n parts: aguiUserContentToParts(message.content),\n })\n case 'assistant': {\n const metadata = tanstackMetadata(message)\n const toolCallMetadata = metadata?.toolCallMetadata\n const structuredOutput = snapshotStructuredOutput(\n metadata?.structuredOutput,\n )\n const toolCalls = message.toolCalls?.map((toolCall) => {\n const callMetadata =\n toolCallMetadata != null && typeof toolCallMetadata === 'object'\n ? (toolCallMetadata as Record<string, unknown>)[toolCall.id]\n : undefined\n return callMetadata !== undefined\n ? { ...toolCall, metadata: callMetadata }\n : toolCall\n })\n return applySnapshotMetadata(\n message,\n modelMessageToUIMessage(\n {\n role: 'assistant',\n content: message.content ?? null,\n ...optionalName(message),\n ...(toolCalls && { toolCalls }),\n ...(structuredOutput && { structuredOutput }),\n },\n id,\n ),\n )\n }\n case 'tool': {\n message = restoreToolResultOwnership(message)\n const createdAt =\n coerceCreatedAt(\n 'createdAt' in message ? message.createdAt : undefined,\n ) ?? createdAtFromMetadata(message)\n return applySnapshotMetadata(\n message,\n modelMessageToUIMessage(\n {\n role: 'tool',\n content: message.content,\n toolCallId: message.toolCallId,\n ...('name' in message && typeof message.name === 'string'\n ? { name: message.name }\n : {}),\n ...('id' in message && typeof message.id === 'string'\n ? { id: message.id }\n : {}),\n ...('metadata' in message && message.metadata != null\n ? { metadata: message.metadata }\n : {}),\n ...(createdAt !== undefined ? { createdAt } : {}),\n ...(message.error !== undefined && { error: message.error }),\n },\n id,\n ),\n )\n }\n case 'system':\n case 'developer':\n // `ModelMessage` has no system/developer role; build the part directly.\n return applySnapshotMetadata(message, {\n id,\n role: 'system',\n parts: message.content\n ? [{ type: 'text', content: message.content }]\n : [],\n })\n case 'reasoning': {\n const signature = encryptedValueFrom(message)\n return applySnapshotMetadata(message, {\n id,\n role: 'assistant',\n parts: message.content\n ? [\n {\n type: 'thinking' as const,\n content: message.content,\n ...(signature !== undefined ? { signature } : {}),\n },\n ]\n : [],\n })\n }\n case 'activity':\n default:\n // `activity` (and any future role) has no text/parts equivalent today.\n return applySnapshotMetadata(message, {\n id,\n role: 'assistant',\n parts: [],\n })\n }\n}\n\n/** Copy snapshot metadata when it is a record. Rebuild createdAt from tanstack.createdAt. */\nfunction applySnapshotMetadata(source: object, ui: UIMessage): UIMessage {\n const normalizedParts = ui.parts.map((part) => normalizeMessagePart(part))\n if (normalizedParts !== ui.parts) ui = { ...ui, parts: normalizedParts }\n const name =\n 'name' in source && typeof source.name === 'string'\n ? source.name\n : undefined\n let next = name !== undefined ? { ...ui, name } : ui\n\n let metadata: NonNullable<UIMessage['metadata']> | undefined\n if ('metadata' in source) {\n const raw = source.metadata\n if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {\n metadata = raw as NonNullable<UIMessage['metadata']>\n next = { ...next, metadata }\n }\n }\n\n const createdAt =\n coerceCreatedAt(next.createdAt) ??\n (metadata !== undefined ? createdAtFromMetadata(metadata) : undefined)\n if (createdAt !== undefined && !Object.is(createdAt, next.createdAt)) {\n next = { ...next, createdAt }\n } else if (createdAt === undefined && next.createdAt !== undefined) {\n const { createdAt: _invalid, ...rest } = next\n next = rest\n }\n\n const uiResources = tanstackMetadata(metadata)?.uiResources\n const resources = Array.isArray(uiResources)\n ? uiResources.filter(isUiResourcePart)\n : []\n return appendUiResources(next, resources)\n}\n\nfunction snapshotStructuredOutput(\n value: TanStackMessageMetadata['structuredOutput'],\n): StructuredOutputPart | undefined {\n if (\n value == null ||\n (value.status !== 'streaming' &&\n value.status !== 'complete' &&\n value.status !== 'error') ||\n typeof value.raw !== 'string'\n ) {\n return undefined\n }\n return {\n type: 'structured-output',\n status: value.status,\n raw: value.raw,\n ...(value.partial !== undefined ? { partial: value.partial } : {}),\n ...(value.data !== undefined ? { data: value.data } : {}),\n ...(value.reasoning ? { reasoning: value.reasoning } : {}),\n ...(value.errorMessage !== undefined\n ? { errorMessage: value.errorMessage }\n : {}),\n }\n}\n\n/**\n * Convert AG-UI user message content into `UIMessage` parts.\n *\n * AG-UI user content is either a plain string or a multimodal array whose text\n * entries use `{ type: 'text', text }` (vs. TanStack's `{ type: 'text', content }`).\n * Text entries are rewritten to the TanStack shape; image/audio/video/document\n * entries already match `ContentPart` and pass through. `binary` entries have no\n * TanStack equivalent and are dropped.\n */\nfunction aguiUserContentToParts(\n content: Extract<AGUIMessage, { role: 'user' }>['content'],\n): Array<MessagePart> {\n if (typeof content === 'string') {\n return content ? [{ type: 'text', content }] : []\n }\n\n const parts: Array<MessagePart> = []\n for (const part of content) {\n if (part.type === 'text') {\n parts.push({ type: 'text', content: part.text })\n } else if (part.type !== 'binary') {\n parts.push(part)\n }\n }\n return parts\n}\n\n/**\n * Convert an array of ModelMessages to UIMessages\n *\n * This handles merging tool result messages with their corresponding assistant messages\n *\n * @param modelMessages - Array of ModelMessages to convert\n * @returns Array of UIMessages\n */\nexport function modelMessagesToUIMessages(\n modelMessages: Array<ModelMessage>,\n): Array<UIMessage> {\n const uiMessages: Array<UIMessage> = []\n let currentAssistantMessage: UIMessage | null = null\n\n for (const msg of modelMessages) {\n if (msg.role === 'tool') {\n // Tool result - merge into the last assistant message if possible\n if (\n msg.toolCallId !== undefined &&\n currentAssistantMessage &&\n currentAssistantMessage.role === 'assistant'\n ) {\n const content = toolResultContent(msg.content)\n const toolCallPart = currentAssistantMessage.parts.find(\n (part): part is ToolCallPart =>\n part.type === 'tool-call' && part.id === msg.toolCallId,\n )\n\n if (toolCallPart) {\n toolCallPart.output =\n typeof content === 'string'\n ? parseToolResultContent(content)\n : content\n toolCallPart.state = msg.error === undefined ? 'complete' : 'error'\n }\n\n currentAssistantMessage.parts.push({\n type: 'tool-result',\n toolCallId: msg.toolCallId,\n content,\n state: msg.error === undefined ? 'complete' : 'error',\n ...(msg.id !== undefined &&\n msg.id !== currentAssistantMessage.id && { id: msg.id }),\n ...(msg.name !== undefined && { name: msg.name }),\n ...(msg.metadata !== undefined && { metadata: msg.metadata }),\n ...optionalCreatedAt(msg),\n ...(msg.error !== undefined && { error: msg.error }),\n })\n } else {\n // No assistant message to merge into, create a standalone one\n const toolResultUIMessage = modelMessageToUIMessage(msg, msg.id)\n uiMessages.push(toolResultUIMessage)\n }\n } else {\n // Regular message. Preserve a persisted stable id so a hydrated message\n // keeps the same identity as its live stream (enables in-place resume).\n const uiMessage = modelMessageToUIMessage(msg, msg.id)\n uiMessages.push(uiMessage)\n\n // Track assistant messages for potential tool result merging\n if (msg.role === 'assistant') {\n currentAssistantMessage = uiMessage\n } else {\n currentAssistantMessage = null\n }\n }\n }\n\n return uiMessages\n}\n\n/**\n * Normalize a message (UIMessage or ModelMessage) to a UIMessage\n * Ensures the message has an ID and createdAt timestamp\n *\n * @param message - Either a UIMessage or ModelMessage\n * @param generateId - Function to generate a message ID if needed\n * @returns A UIMessage with guaranteed id and createdAt\n */\nexport function normalizeToUIMessage(\n message: UIMessage | ModelMessage,\n generateId: () => string,\n): UIMessage {\n if ('parts' in message) {\n // Already a UIMessage\n const parts = message.parts.map((part) => normalizeMessagePart(part))\n return {\n ...message,\n parts,\n id: message.id || generateId(),\n createdAt: coerceCreatedAt(message.createdAt) ?? new Date(),\n }\n } else {\n // ModelMessage - convert to UIMessage\n return {\n ...modelMessageToUIMessage(message, generateId()),\n createdAt: coerceCreatedAt(message.createdAt) ?? new Date(),\n }\n }\n}\n\n/**\n * Generate a unique message ID\n */\nexport function generateMessageId(): string {\n return `msg-${Date.now()}-${Math.random().toString(36).substring(7)}`\n}\n"],"mappings":";;;;AAoBA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;;AASA,SAAS,cAAc,MAAwC;CAC7D,OACE,KAAK,SAAS,UACd,KAAK,SAAS,WACd,KAAK,SAAS,WACd,KAAK,SAAS,WACd,KAAK,SAAS;AAElB;AAEA,SAAgB,kBAAkB,OAAwB;CACxD,IAAI;EACF,OAAO,KAAK,UAAU,KAAK,KAAK;CAClC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,eAAe,OAAoC;CAC1D,OAAO,OAAO,UAAU,YAAY,UAAU,KAAK,QAAQ,KAAA;AAC7D;AAEA,SAAS,mBAAmB,OAAmC;CAC7D,IAAI,oBAAoB,OAAO;EAC7B,MAAM,WAAW,eAAe,MAAM,cAAc;EACpD,IAAI,aAAa,KAAA,GAAW,OAAO;CACrC;CACA,OAAO,eAAe,iBAAiB,KAAK,CAAC,EAAE,SAAS;AAC1D;AAEA,SAAS,iBAAiB,UAAoB,KAAwB;CACpE,MAAM,UACJ,OAAO,QAAQ,OAAO,QAAQ,YAAY,CAAC,MAAM,QAAQ,GAAG,IACxD,MACA,KAAA;CACN,MAAM,YAAY,mBAAmB,QAAQ;CAC7C,IAAI,QAAQ,QAAQ,cAAc,KAAA,GAChC,OAAO;EAAE,GAAG;EAAU,UAAU;CAAK;CAEvC,IAAI,YAAY,KAAA,KAAa,cAAc,KAAA,GAAW,OAAO;CAC7D,OAAO;EACL,GAAG;EACH,UAAU;GACR,GAAI,WAAW,CAAC;GAChB,GAAI,cAAc,KAAA,IAAY,EAAE,kBAAkB,UAA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I,KAAK;CAC5D;AAEJ;;;;AAKA,SAAgB,oBAA4B;CAC1C,OAAO,OAAO,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,UAAU,CAAC;AACpE"}
|
|
1
|
+
{"version":3,"file":"messages.js","names":[],"sources":["../../../../src/activities/chat/messages.ts"],"sourcesContent":["import { isProviderExecutedToolCall } from '../../utilities/provider-executed'\nimport {\n isContentPartArray,\n normalizeToolResult,\n} from '../../utilities/tool-result'\nimport { tanstackMetadata } from '../../utilities/merge-metadata'\nimport type { Message as AGUIMessage } from '@ag-ui/core'\nimport type {\n ContentPart,\n MessagePart,\n ModelMessage,\n StructuredOutputPart,\n TanStackMessageMetadata,\n TextPart,\n ToolCall,\n ToolCallPart,\n UIMessage,\n UIResourcePart,\n} from '../../types'\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n// ===========================\n// Message Converters\n// ===========================\n\n/**\n * Check if a MessagePart is a content part (text, image, audio, video, document)\n * that maps directly to a ModelMessage ContentPart.\n */\nfunction isContentPart(part: MessagePart): part is ContentPart {\n return (\n part.type === 'text' ||\n part.type === 'image' ||\n part.type === 'audio' ||\n part.type === 'video' ||\n part.type === 'document'\n )\n}\n\nexport function safeJsonStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? ''\n } catch {\n return ''\n }\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\nfunction encryptedValueFrom(value: object): string | undefined {\n if ('encryptedValue' in value) {\n const fromSpec = nonEmptyString(value.encryptedValue)\n if (fromSpec !== undefined) return fromSpec\n }\n return nonEmptyString(tanstackMetadata(value)?.signature)\n}\n\nfunction toolCallFromWire(toolCall: ToolCall, bag: unknown): ToolCall {\n const fromBag =\n bag != null && typeof bag === 'object' && !Array.isArray(bag)\n ? bag\n : undefined\n const encrypted = encryptedValueFrom(toolCall)\n if (bag === null && encrypted === undefined) {\n return { ...toolCall, metadata: null }\n }\n if (fromBag === undefined && encrypted === undefined) return toolCall\n return {\n ...toolCall,\n metadata: {\n ...(fromBag ?? {}),\n ...(encrypted !== undefined ? { thoughtSignature: encrypted } : {}),\n },\n }\n}\n\nfunction parseToolResultContent(content: string): unknown {\n try {\n return JSON.parse(content)\n } catch {\n return content\n }\n}\n\n/**\n * Collapse an array of ContentParts into the most compact ModelMessage content:\n * - Empty array → null\n * - All text parts → joined string (or null if empty)\n * - Mixed content → ContentPart array as-is\n */\nfunction collapseContentParts(\n parts: Array<ContentPart>,\n): string | null | Array<ContentPart> {\n if (parts.length === 0) return null\n\n const allText = parts.every((p) => p.type === 'text')\n if (allText) {\n const joined = parts.map((p) => p.content).join('')\n return joined || null\n }\n\n return parts\n}\n\n/**\n * Extract text content from ModelMessage content (string, null, or ContentPart array).\n * Used when only the text portion is needed (e.g., tool result content).\n */\nfunction getTextContent(\n content: string | null | undefined | Array<ContentPart>,\n): string {\n // Tool-call-only assistant turns carry no text and reach here as `null` or\n // `undefined`; both must collapse to an empty string rather than crash on\n // `.filter` (issue #532 — the interrupt-boundary MessagesSnapshot).\n if (content === null || content === undefined) return ''\n if (typeof content === 'string') return content\n return content\n .filter((part): part is TextPart => part.type === 'text')\n .map((part) => part.content)\n .join('')\n}\n\nfunction toolResultContent(\n content: string | null | undefined | Array<ContentPart>,\n): string | Array<ContentPart> {\n return Array.isArray(content) ? content : getTextContent(content)\n}\n\n/**\n * Convert UIMessages or ModelMessages to ModelMessages\n */\nexport function convertMessagesToModelMessages(\n messages: Array<UIMessage | ModelMessage>,\n): Array<ModelMessage> {\n // Pre-pass: collect toolCallIds already represented in anchor UIMessage parts.\n // Fan-out tool messages whose toolCallId matches an anchored ToolResultPart\n // are AG-UI duplicates and must be dropped to avoid double-feeding the LLM.\n const anchoredToolCallIds = new Set<string>()\n for (const msg of messages) {\n if ('parts' in msg) {\n for (const part of msg.parts) {\n if (part.type === 'tool-result') {\n anchoredToolCallIds.add(part.toolCallId)\n }\n }\n }\n }\n\n const modelMessages: Array<ModelMessage> = []\n let pendingThinking: Array<{ content: string; signature?: string }> = []\n for (const msg of messages) {\n if ('parts' in msg) {\n modelMessages.push(...uiMessageToModelMessages(msg))\n continue\n }\n\n const modelMessage = restoreModelMessageCreatedAt(\n restoreToolResultOwnership(msg),\n )\n const role = (modelMessage as { role: string }).role\n\n if (\n role === 'tool' &&\n modelMessage.toolCallId &&\n anchoredToolCallIds.has(modelMessage.toolCallId)\n ) {\n continue\n }\n\n if (role === 'reasoning') {\n const content = (msg as { content?: string }).content\n const signature = encryptedValueFrom(msg)\n if (content || signature !== undefined) {\n pendingThinking.push({\n content: typeof content === 'string' ? content : '',\n ...(signature !== undefined ? { signature } : {}),\n })\n }\n continue\n }\n\n if (role === 'activity') {\n continue\n }\n\n if (role === 'developer') {\n modelMessages.push({\n role: 'system' as ModelMessage['role'],\n content: (msg as { content: string }).content,\n ...optionalName(modelMessage),\n ...optionalCreatedAt(modelMessage),\n ...(modelMessage.metadata !== undefined && {\n metadata: modelMessage.metadata,\n }),\n })\n continue\n }\n\n if (\n role === 'user' &&\n Array.isArray((msg as { content?: unknown }).content)\n ) {\n const content = (msg as { content: Array<{ type: string }> }).content\n // TanStack ModelMessage text parts use `{ content }`. AG-UI wire text\n // parts use `{ text }`. Only rewrite the AG-UI shape.\n if (\n !content.some(\n (part) =>\n part.type === 'text' && 'text' in part && !('content' in part),\n )\n ) {\n modelMessages.push(modelMessage)\n continue\n }\n const parts = aguiUserContentToParts(\n content as Extract<AGUIMessage, { role: 'user' }>['content'],\n )\n const contentParts = parts.filter(isContentPart)\n modelMessages.push({\n role: 'user',\n content: collapseContentParts(contentParts),\n ...((msg as { id?: string }).id !== undefined && {\n id: (msg as { id: string }).id,\n }),\n ...optionalName(modelMessage),\n ...optionalCreatedAt(modelMessage),\n ...(modelMessage.metadata !== undefined && {\n metadata: modelMessage.metadata,\n }),\n })\n continue\n }\n\n if (role === 'assistant') {\n const source = modelMessage\n const toolCallMetadata = tanstackMetadata(msg)?.toolCallMetadata\n const toolCalls = source.toolCalls?.map((toolCall) =>\n toolCallFromWire(toolCall, toolCallMetadata?.[toolCall.id]),\n )\n modelMessages.push({\n ...source,\n ...(toolCalls !== undefined ? { toolCalls } : {}),\n ...(pendingThinking.length > 0\n ? {\n thinking: [...(source.thinking ?? []), ...pendingThinking],\n }\n : {}),\n })\n pendingThinking = []\n continue\n }\n\n modelMessages.push(modelMessage)\n }\n return modelMessages\n}\n\nfunction restoreModelMessageCreatedAt(message: ModelMessage): ModelMessage {\n const createdAt =\n coerceCreatedAt(message.createdAt) ?? createdAtFromMetadata(message)\n if (createdAt === undefined) {\n if (message.createdAt === undefined) return message\n const { createdAt: _invalid, ...rest } = message\n return rest\n }\n return Object.is(message.createdAt, createdAt)\n ? message\n : { ...message, createdAt }\n}\n\nexport function restoreToolResultOwnership<T extends object>(message: T): T {\n if (!('role' in message) || message.role !== 'tool') return message\n const source = message\n const metadata = tanstackMetadata(source)\n const owned = metadata?.toolResult\n if (!isRecord(owned)) return message\n if ('content' in owned && !isContentPartArray(owned.content)) return message\n const next = { ...message }\n if (!('id' in owned)) Reflect.deleteProperty(next, 'id')\n if (!('createdAt' in owned)) Reflect.deleteProperty(next, 'createdAt')\n if (typeof owned.id === 'string') Reflect.set(next, 'id', owned.id)\n if (typeof owned.createdAt === 'string') {\n const createdAt = coerceCreatedAt(owned.createdAt)\n if (createdAt) Reflect.set(next, 'createdAt', createdAt)\n }\n if (isContentPartArray(owned.content)) {\n Reflect.set(next, 'content', owned.content)\n }\n const sourceMetadata: unknown = Reflect.get(source, 'metadata')\n if (isRecord(sourceMetadata)) {\n const tanstack = sourceMetadata.tanstack\n if (isRecord(tanstack)) {\n const { toolResult: _toolResult, ...restTanstack } = tanstack\n const restMetadata = { ...sourceMetadata }\n if (Object.keys(restTanstack).length) restMetadata.tanstack = restTanstack\n else delete restMetadata.tanstack\n if (Object.keys(restMetadata).length)\n Reflect.set(next, 'metadata', restMetadata)\n else Reflect.deleteProperty(next, 'metadata')\n }\n }\n return next\n}\n\n/**\n * Rebuild a `Date` from a live `Date` or from an ISO string.\n * `JSON.stringify` turns `Date` into a string, so persistence reload\n * and AG-UI wire both land here as strings.\n */\nexport function coerceCreatedAt(value: unknown): Date | undefined {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? undefined : value\n }\n if (typeof value !== 'string') return undefined\n const createdAt = new Date(value)\n return Number.isNaN(createdAt.getTime()) ? undefined : createdAt\n}\n\nfunction normalizeMessagePart(part: MessagePart): MessagePart {\n if (part.type !== 'tool-result') return part\n const createdAt = coerceCreatedAt(part.createdAt)\n const { createdAt: _createdAt, ...rest } = part\n return createdAt === undefined ? rest : { ...rest, createdAt }\n}\n\nfunction createdAtFromMetadata(source: object): Date | undefined {\n return coerceCreatedAt(tanstackMetadata(source)?.createdAt)\n}\n\nfunction optionalCreatedAt(source: { createdAt?: unknown }): {\n createdAt?: Date\n} {\n const createdAt = coerceCreatedAt(source.createdAt)\n return createdAt !== undefined ? { createdAt } : {}\n}\n\nfunction optionalName(source: { name?: string }): { name?: string } {\n return source.name !== undefined ? { name: source.name } : {}\n}\n\nfunction isUiResourcePart(value: unknown): value is UIResourcePart {\n if (value == null || typeof value !== 'object' || Array.isArray(value)) {\n return false\n }\n if (!('type' in value) || value.type !== 'ui-resource') return false\n if (!('toolCallId' in value) || typeof value.toolCallId !== 'string') {\n return false\n }\n if (!('toolName' in value) || typeof value.toolName !== 'string') {\n return false\n }\n if (\n !('resource' in value) ||\n value.resource == null ||\n typeof value.resource !== 'object' ||\n Array.isArray(value.resource)\n ) {\n return false\n }\n const resource = value.resource\n return (\n 'uri' in resource &&\n typeof resource.uri === 'string' &&\n 'mimeType' in resource &&\n typeof resource.mimeType === 'string'\n )\n}\n\nfunction uiResourceKey(part: UIResourcePart): string {\n return `${part.toolCallId}\\0${part.toolName}\\0${part.resource.uri}`\n}\n\nfunction appendUiResources(\n ui: UIMessage,\n resources: ReadonlyArray<UIResourcePart>,\n): UIMessage {\n if (resources.length === 0) return ui\n const seen = new Set(\n ui.parts.filter(isUiResourcePart).map((part) => uiResourceKey(part)),\n )\n const extra = resources.filter((part) => !seen.has(uiResourceKey(part)))\n if (extra.length === 0) return ui\n return { ...ui, parts: [...ui.parts, ...extra] }\n}\n\nfunction assistantMetadata(\n uiMessage: UIMessage,\n): UIMessage['metadata'] | undefined {\n const fromParts = uiMessage.parts.filter(isUiResourcePart)\n const current = uiMessage.metadata ?? {}\n const previous = tanstackMetadata(uiMessage)\n const tanstack: TanStackMessageMetadata = {}\n if (previous?.model !== undefined) tanstack.model = previous.model\n if (previous?.signature !== undefined) tanstack.signature = previous.signature\n if (fromParts.length > 0) tanstack.uiResources = fromParts\n const result = { ...current }\n if (Object.keys(tanstack).length > 0) result.tanstack = tanstack\n else delete result.tanstack\n return Object.keys(result).length > 0 ? result : undefined\n}\n\n/**\n * Convert a UIMessage to ModelMessage(s)\n *\n * Walks the parts array IN ORDER to preserve the interleaving of text,\n * tool calls, and tool results. This is critical for multi-round tool\n * flows where the model generates text, calls a tool, gets the result,\n * then generates more text and calls another tool.\n *\n * The output preserves the sequential structure:\n * text1 → toolCall1 → toolResult1 → text2 → toolCall2 → toolResult2\n * becomes:\n * assistant: {content: \"text1\", toolCalls: [toolCall1]}\n * tool: toolResult1\n * assistant: {content: \"text2\", toolCalls: [toolCall2]}\n * tool: toolResult2\n *\n * @param uiMessage - The UIMessage to convert\n * @returns An array of ModelMessages preserving part ordering\n */\nexport function uiMessageToModelMessages(\n uiMessage: UIMessage,\n): Array<ModelMessage> {\n // Skip system messages - they're handled via systemPrompts, not ModelMessages\n if (uiMessage.role === 'system') {\n return []\n }\n\n // For non-assistant messages (user), use the simpler path since they\n // don't have tool calls or tool results to interleave\n if (uiMessage.role !== 'assistant') {\n return [buildUserOrToolMessage(uiMessage)]\n }\n\n // For assistant messages, walk parts in order to preserve interleaving\n return buildAssistantMessages(uiMessage)\n}\n\n/**\n * Build a single ModelMessage for user messages (simple path).\n * Preserves ordering of text and multimodal content parts.\n */\nfunction buildUserOrToolMessage(uiMessage: UIMessage): ModelMessage {\n const contentParts: Array<ContentPart> = []\n for (const part of uiMessage.parts) {\n if (isContentPart(part)) {\n contentParts.push(part)\n }\n }\n\n return {\n id: uiMessage.id,\n role: uiMessage.role as 'user' | 'assistant' | 'tool',\n content: collapseContentParts(contentParts),\n ...optionalName(uiMessage),\n ...optionalCreatedAt(uiMessage),\n ...(uiMessage.metadata !== undefined && { metadata: uiMessage.metadata }),\n }\n}\n\n// Accumulator for building an assistant segment (content + tool calls)\ninterface AssistantSegment {\n contentParts: Array<ContentPart>\n structuredOutput?: StructuredOutputPart\n toolCalls: Array<{\n id: string\n type: 'function'\n function: { name: string; arguments: string }\n /** Provider-specific metadata that round-trips with the tool call.\n * Untyped at this framework layer; adapters narrow it via their\n * `TToolCallMetadata` generic. */\n metadata?: unknown\n }>\n}\n\nfunction createSegment(): AssistantSegment {\n return { contentParts: [], toolCalls: [] }\n}\n\nfunction isToolCallIncluded(part: ToolCallPart): boolean {\n return (\n part.state === 'input-complete' ||\n part.state === 'complete' ||\n part.state === 'approval-requested' ||\n part.state === 'approval-responded' ||\n part.state === 'error' ||\n part.output !== undefined\n )\n}\n\n/**\n * Build ModelMessages for an assistant UIMessage, preserving the\n * sequential interleaving of text, tool calls, and tool results.\n *\n * Walks parts in order. Text and tool-call parts accumulate into the\n * current \"segment\". When a tool-result part is encountered, the\n * current segment is flushed as an assistant message, then the tool\n * result is emitted as a tool message.\n */\nfunction buildAssistantMessages(uiMessage: UIMessage): Array<ModelMessage> {\n // A single UI message can fan out into several model messages. Keep the\n // shared UI id on each one so persistence can retain the original identity.\n const messageList: Array<ModelMessage> = []\n let current = createSegment()\n let pendingThinking: Array<{ content: string; signature?: string }> = []\n\n // Track emitted tool result IDs to avoid duplicates.\n // A tool call can have BOTH an explicit tool-result part AND an output\n // field on the tool-call part. We only want one per tool call ID.\n const emittedToolResultIds = new Set<string>()\n const identityFields = {\n id: uiMessage.id,\n ...optionalName(uiMessage),\n ...optionalCreatedAt(uiMessage),\n }\n const metadata = assistantMetadata(uiMessage)\n const assistantFields = {\n ...identityFields,\n ...(metadata !== undefined && { metadata }),\n }\n\n function flushSegment(force = false): void {\n const content = collapseContentParts(current.contentParts)\n const hasContent = content !== null\n const hasToolCalls = current.toolCalls.length > 0\n const hasThinking = pendingThinking.length > 0\n\n if (force || hasContent || hasToolCalls || hasThinking) {\n messageList.push({\n ...assistantFields,\n role: 'assistant',\n content,\n ...(hasToolCalls && { toolCalls: current.toolCalls }),\n ...(hasThinking && { thinking: pendingThinking }),\n ...(current.structuredOutput && {\n structuredOutput: current.structuredOutput,\n }),\n })\n pendingThinking = []\n }\n current = createSegment()\n }\n\n for (const part of uiMessage.parts) {\n switch (part.type) {\n case 'text':\n case 'image':\n case 'audio':\n case 'video':\n case 'document':\n current.contentParts.push(part)\n break\n\n case 'tool-call':\n if (isToolCallIncluded(part)) {\n current.toolCalls.push({\n id: part.id,\n type: 'function' as const,\n function: {\n name: part.name,\n arguments: part.arguments,\n },\n ...(part.metadata !== undefined && { metadata: part.metadata }),\n })\n }\n break\n\n case 'tool-result':\n // Flush the current assistant segment before emitting the tool result\n flushSegment(messageList.length === 0)\n\n // Emit the tool result\n if (\n (part.state === 'complete' || part.state === 'error') &&\n !emittedToolResultIds.has(part.toolCallId)\n ) {\n messageList.push({\n ...(part.id !== undefined && { id: part.id }),\n ...optionalCreatedAt(part),\n role: 'tool',\n content: part.content,\n toolCallId: part.toolCallId,\n ...(part.name !== undefined && { name: part.name }),\n ...(part.metadata !== undefined && { metadata: part.metadata }),\n ...(part.error !== undefined && { error: part.error }),\n })\n emittedToolResultIds.add(part.toolCallId)\n }\n break\n\n case 'thinking':\n if (part.content || part.signature) {\n // Provider-executed tools have no tool-result part, so thinking\n // after them has to start the next segment or it replays first.\n if (current.toolCalls.some(isProviderExecutedToolCall)) {\n flushSegment()\n }\n pendingThinking.push({\n content: part.content,\n ...(part.signature && { signature: part.signature }),\n })\n }\n break\n\n case 'structured-output':\n // Only emit completed structured responses into history. Streaming or\n // errored buffers would push malformed JSON into the next LLM turn's\n // assistant content. `raw` is the source of truth; `data` is the\n // defensive fallback for terminal-only completes that didn't ship raw.\n if (part.status === 'complete') {\n const serialized =\n part.raw !== ''\n ? part.raw\n : part.data !== undefined\n ? safeJsonStringify(part.data)\n : ''\n if (serialized !== '') {\n current.contentParts.push({ type: 'text', content: serialized })\n current.structuredOutput = part\n }\n }\n break\n\n case 'ui-resource':\n // MCP Apps widget — rendered client-side only. It must never enter\n // model input, so it is intentionally dropped from the model message.\n break\n\n default:\n break\n }\n }\n\n // Flush any remaining accumulated content\n flushSegment()\n\n // Emit tool results from client tool-call parts with output or approval,\n // but only if not already covered by an explicit tool-result part above.\n // These are appended at the end since they don't have explicit tool-result\n // parts in the parts array to trigger inline emission.\n for (const part of uiMessage.parts) {\n if (part.type !== 'tool-call') continue\n\n // Output takes priority — if the tool has already produced a result,\n // emit the concrete output regardless of approval metadata.\n if (part.output !== undefined && !emittedToolResultIds.has(part.id)) {\n messageList.push({\n role: 'tool',\n content: normalizeToolResult(part.output),\n toolCallId: part.id,\n })\n emittedToolResultIds.add(part.id)\n }\n\n // Approval response without output — emit approval status for iteration tracking\n if (\n part.output === undefined &&\n part.state === 'approval-responded' &&\n part.approval?.approved !== undefined &&\n !emittedToolResultIds.has(part.id)\n ) {\n const approved = part.approval.approved\n messageList.push({\n role: 'tool',\n content: JSON.stringify({\n approved,\n ...(approved && { pendingExecution: true }),\n message: approved\n ? 'User approved this action'\n : 'User denied this action',\n }),\n toolCallId: part.id,\n })\n emittedToolResultIds.add(part.id)\n }\n }\n\n // If no messages were produced (e.g., empty parts), emit a minimal assistant message\n if (messageList.length === 0) {\n messageList.push({\n ...assistantFields,\n role: 'assistant',\n content: null,\n })\n }\n\n return messageList\n}\n\n/**\n * Convert a ModelMessage to UIMessage\n *\n * This conversion creates a parts-based structure:\n * - content field → TextPart\n * - toolCalls array → ToolCallPart[]\n * - role=\"tool\" messages should be converted separately and merged\n *\n * @param modelMessage - The ModelMessage to convert\n * @param id - Optional ID for the UIMessage (generated if not provided)\n * @returns A UIMessage with parts\n */\nexport function modelMessageToUIMessage(\n modelMessage: ModelMessage,\n id?: string,\n): UIMessage {\n const parts: Array<MessagePart> = []\n const createdAt = coerceCreatedAt(modelMessage.createdAt)\n\n if (modelMessage.role === 'assistant' && modelMessage.thinking?.length) {\n for (const thinking of modelMessage.thinking) {\n if (!thinking.content && !thinking.signature) continue\n parts.push({\n type: 'thinking',\n content: thinking.content,\n ...(thinking.signature && { signature: thinking.signature }),\n })\n }\n }\n\n // Handle tool results (when role is \"tool\") - only produce tool-result part,\n // not a text part (the content IS the tool result, not display text)\n const structuredOutput =\n modelMessage.structuredOutput ??\n snapshotStructuredOutput(tanstackMetadata(modelMessage)?.structuredOutput)\n if (modelMessage.role === 'assistant' && structuredOutput) {\n if (\n typeof modelMessage.content === 'string' &&\n modelMessage.content &&\n modelMessage.content !== structuredOutput.raw\n ) {\n const suffix = structuredOutput.raw\n const text =\n suffix !== '' && modelMessage.content.endsWith(suffix)\n ? modelMessage.content.slice(0, -suffix.length)\n : modelMessage.content\n if (text) parts.push({ type: 'text', content: text })\n }\n parts.push(structuredOutput)\n } else if (modelMessage.role === 'tool' && modelMessage.toolCallId) {\n parts.push({\n type: 'tool-result',\n toolCallId: modelMessage.toolCallId,\n content: toolResultContent(modelMessage.content),\n state: modelMessage.error === undefined ? 'complete' : 'error',\n ...(modelMessage.id !== undefined && { id: modelMessage.id }),\n ...(modelMessage.name !== undefined && { name: modelMessage.name }),\n ...(modelMessage.metadata !== undefined && {\n metadata: modelMessage.metadata,\n }),\n ...(createdAt !== undefined && { createdAt }),\n ...(modelMessage.error !== undefined && { error: modelMessage.error }),\n })\n } else if (Array.isArray(modelMessage.content)) {\n // Multimodal content - preserve all content parts as MessageParts\n for (const part of modelMessage.content) {\n parts.push(part)\n }\n } else {\n // String or null content\n const textContent = getTextContent(modelMessage.content)\n if (textContent) {\n parts.push({\n type: 'text',\n content: textContent,\n })\n }\n }\n\n // Handle tool calls\n if (modelMessage.toolCalls && modelMessage.toolCalls.length > 0) {\n for (const toolCall of modelMessage.toolCalls) {\n // Model-message arguments are complete, so surface the parsed input.\n // A malformed arguments string just leaves `input` undefined.\n let input: unknown\n try {\n input = JSON.parse(toolCall.function.arguments)\n } catch {\n input = undefined\n }\n parts.push({\n type: 'tool-call',\n id: toolCall.id,\n name: toolCall.function.name,\n arguments: toolCall.function.arguments,\n state: 'input-complete', // Model messages have complete arguments\n ...(input !== undefined && { input }),\n ...(toolCall.metadata !== undefined && { metadata: toolCall.metadata }),\n })\n }\n }\n\n const ui: UIMessage = {\n id: id || generateMessageId(),\n role: modelMessage.role === 'tool' ? 'assistant' : modelMessage.role,\n parts,\n ...optionalName(modelMessage),\n ...(createdAt !== undefined && { createdAt }),\n ...(modelMessage.metadata !== undefined && {\n metadata: modelMessage.metadata,\n }),\n }\n const storedResources = tanstackMetadata(modelMessage)?.uiResources\n return appendUiResources(\n ui,\n Array.isArray(storedResources)\n ? storedResources.filter(isUiResourcePart)\n : [],\n )\n}\n\n/**\n * Normalize a single AG-UI `MESSAGES_SNAPSHOT` message into a `UIMessage`.\n *\n * AG-UI snapshot messages use the wire shape `{ id, role, content }` and have\n * no `parts` array. Casting them directly to `UIMessage` is unsafe: any code\n * that later reads `message.parts` (e.g. the devtools `onToolCallStateChange`\n * handler) crashes with \"Cannot read properties of undefined (reading 'find')\".\n *\n * Each role is mapped to the canonical `UIMessage` shape, reusing\n * `modelMessageToUIMessage` for the roles that share `ModelMessage`'s structure.\n * The original AG-UI `id` is preserved so later `TEXT_MESSAGE_CONTENT` /\n * `TOOL_CALL_*` events still route by `messageId` (falling back to a generated\n * id only when the snapshot omits one). Messages that already carry `parts`\n * (e.g. a TanStack server echoing `UIMessage`s back over the wire) pass through\n * unchanged apart from ensuring an id.\n */\nexport function aguiSnapshotMessageToUIMessage(\n message: AGUIMessage | UIMessage,\n): UIMessage {\n if ('parts' in message) {\n return applySnapshotMetadata(message, {\n ...message,\n id: message.id || generateMessageId(),\n })\n }\n\n const id = message.id || generateMessageId()\n\n switch (message.role) {\n case 'user':\n return applySnapshotMetadata(message, {\n id,\n role: 'user',\n parts: aguiUserContentToParts(message.content),\n })\n case 'assistant': {\n const metadata = tanstackMetadata(message)\n const toolCallMetadata = metadata?.toolCallMetadata\n const structuredOutput = snapshotStructuredOutput(\n metadata?.structuredOutput,\n )\n const toolCalls = message.toolCalls?.map((toolCall) => {\n const callMetadata =\n toolCallMetadata != null && typeof toolCallMetadata === 'object'\n ? (toolCallMetadata as Record<string, unknown>)[toolCall.id]\n : undefined\n return callMetadata !== undefined\n ? { ...toolCall, metadata: callMetadata }\n : toolCall\n })\n return applySnapshotMetadata(\n message,\n modelMessageToUIMessage(\n {\n role: 'assistant',\n content: message.content ?? null,\n ...optionalName(message),\n ...(toolCalls && { toolCalls }),\n ...(structuredOutput && { structuredOutput }),\n },\n id,\n ),\n )\n }\n case 'tool': {\n message = restoreToolResultOwnership(message)\n const createdAt =\n coerceCreatedAt(\n 'createdAt' in message ? message.createdAt : undefined,\n ) ?? createdAtFromMetadata(message)\n return applySnapshotMetadata(\n message,\n modelMessageToUIMessage(\n {\n role: 'tool',\n content: message.content,\n toolCallId: message.toolCallId,\n ...('name' in message && typeof message.name === 'string'\n ? { name: message.name }\n : {}),\n ...('id' in message && typeof message.id === 'string'\n ? { id: message.id }\n : {}),\n ...('metadata' in message && message.metadata != null\n ? { metadata: message.metadata }\n : {}),\n ...(createdAt !== undefined ? { createdAt } : {}),\n ...(message.error !== undefined && { error: message.error }),\n },\n id,\n ),\n )\n }\n case 'system':\n case 'developer':\n // `ModelMessage` has no system/developer role; build the part directly.\n return applySnapshotMetadata(message, {\n id,\n role: 'system',\n parts: message.content\n ? [{ type: 'text', content: message.content }]\n : [],\n })\n case 'reasoning': {\n const signature = encryptedValueFrom(message)\n const content = typeof message.content === 'string' ? message.content : ''\n return applySnapshotMetadata(message, {\n id,\n role: 'assistant',\n parts:\n content || signature !== undefined\n ? [\n {\n type: 'thinking' as const,\n content,\n ...(signature !== undefined ? { signature } : {}),\n },\n ]\n : [],\n })\n }\n case 'activity':\n default:\n // `activity` (and any future role) has no text/parts equivalent today.\n return applySnapshotMetadata(message, {\n id,\n role: 'assistant',\n parts: [],\n })\n }\n}\n\n/** Copy snapshot metadata when it is a record. Rebuild createdAt from tanstack.createdAt. */\nfunction applySnapshotMetadata(source: object, ui: UIMessage): UIMessage {\n const normalizedParts = ui.parts.map((part) => normalizeMessagePart(part))\n if (normalizedParts !== ui.parts) ui = { ...ui, parts: normalizedParts }\n const name =\n 'name' in source && typeof source.name === 'string'\n ? source.name\n : undefined\n let next = name !== undefined ? { ...ui, name } : ui\n\n let metadata: NonNullable<UIMessage['metadata']> | undefined\n if ('metadata' in source) {\n const raw = source.metadata\n if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {\n metadata = raw as NonNullable<UIMessage['metadata']>\n next = { ...next, metadata }\n }\n }\n\n const createdAt =\n coerceCreatedAt(next.createdAt) ??\n (metadata !== undefined ? createdAtFromMetadata(metadata) : undefined)\n if (createdAt !== undefined && !Object.is(createdAt, next.createdAt)) {\n next = { ...next, createdAt }\n } else if (createdAt === undefined && next.createdAt !== undefined) {\n const { createdAt: _invalid, ...rest } = next\n next = rest\n }\n\n const uiResources = tanstackMetadata(metadata)?.uiResources\n const resources = Array.isArray(uiResources)\n ? uiResources.filter(isUiResourcePart)\n : []\n return appendUiResources(next, resources)\n}\n\nfunction snapshotStructuredOutput(\n value: TanStackMessageMetadata['structuredOutput'],\n): StructuredOutputPart | undefined {\n if (\n value == null ||\n (value.status !== 'streaming' &&\n value.status !== 'complete' &&\n value.status !== 'error') ||\n typeof value.raw !== 'string'\n ) {\n return undefined\n }\n return {\n type: 'structured-output',\n status: value.status,\n raw: value.raw,\n ...(value.partial !== undefined ? { partial: value.partial } : {}),\n ...(value.data !== undefined ? { data: value.data } : {}),\n ...(value.reasoning ? { reasoning: value.reasoning } : {}),\n ...(value.errorMessage !== undefined\n ? { errorMessage: value.errorMessage }\n : {}),\n }\n}\n\n/**\n * Convert AG-UI user message content into `UIMessage` parts.\n *\n * AG-UI user content is either a plain string or a multimodal array whose text\n * entries use `{ type: 'text', text }` (vs. TanStack's `{ type: 'text', content }`).\n * Text entries are rewritten to the TanStack shape; image/audio/video/document\n * entries already match `ContentPart` and pass through. `binary` entries have no\n * TanStack equivalent and are dropped.\n */\nfunction aguiUserContentToParts(\n content: Extract<AGUIMessage, { role: 'user' }>['content'],\n): Array<MessagePart> {\n if (typeof content === 'string') {\n return content ? [{ type: 'text', content }] : []\n }\n\n const parts: Array<MessagePart> = []\n for (const part of content) {\n if (part.type === 'text') {\n parts.push({ type: 'text', content: part.text })\n } else if (part.type !== 'binary') {\n parts.push(part)\n }\n }\n return parts\n}\n\n/**\n * Convert an array of ModelMessages to UIMessages\n *\n * This handles merging tool result messages with their corresponding assistant messages\n *\n * @param modelMessages - Array of ModelMessages to convert\n * @returns Array of UIMessages\n */\nexport function modelMessagesToUIMessages(\n modelMessages: Array<ModelMessage>,\n): Array<UIMessage> {\n const uiMessages: Array<UIMessage> = []\n let currentAssistantMessage: UIMessage | null = null\n\n for (const msg of modelMessages) {\n if (msg.role === 'tool') {\n // Tool result - merge into the last assistant message if possible\n if (\n msg.toolCallId !== undefined &&\n currentAssistantMessage &&\n currentAssistantMessage.role === 'assistant'\n ) {\n const content = toolResultContent(msg.content)\n const toolCallPart = currentAssistantMessage.parts.find(\n (part): part is ToolCallPart =>\n part.type === 'tool-call' && part.id === msg.toolCallId,\n )\n\n if (toolCallPart) {\n toolCallPart.output =\n typeof content === 'string'\n ? parseToolResultContent(content)\n : content\n toolCallPart.state = msg.error === undefined ? 'complete' : 'error'\n }\n\n currentAssistantMessage.parts.push({\n type: 'tool-result',\n toolCallId: msg.toolCallId,\n content,\n state: msg.error === undefined ? 'complete' : 'error',\n ...(msg.id !== undefined &&\n msg.id !== currentAssistantMessage.id && { id: msg.id }),\n ...(msg.name !== undefined && { name: msg.name }),\n ...(msg.metadata !== undefined && { metadata: msg.metadata }),\n ...optionalCreatedAt(msg),\n ...(msg.error !== undefined && { error: msg.error }),\n })\n } else {\n // No assistant message to merge into, create a standalone one\n const toolResultUIMessage = modelMessageToUIMessage(msg, msg.id)\n uiMessages.push(toolResultUIMessage)\n }\n } else {\n // Regular message. Preserve a persisted stable id so a hydrated message\n // keeps the same identity as its live stream (enables in-place resume).\n const uiMessage = modelMessageToUIMessage(msg, msg.id)\n uiMessages.push(uiMessage)\n\n // Track assistant messages for potential tool result merging\n if (msg.role === 'assistant') {\n currentAssistantMessage = uiMessage\n } else {\n currentAssistantMessage = null\n }\n }\n }\n\n return uiMessages\n}\n\n/**\n * Normalize a message (UIMessage or ModelMessage) to a UIMessage\n * Ensures the message has an ID and createdAt timestamp\n *\n * @param message - Either a UIMessage or ModelMessage\n * @param generateId - Function to generate a message ID if needed\n * @returns A UIMessage with guaranteed id and createdAt\n */\nexport function normalizeToUIMessage(\n message: UIMessage | ModelMessage,\n generateId: () => string,\n): UIMessage {\n if ('parts' in message) {\n // Already a UIMessage\n const parts = message.parts.map((part) => normalizeMessagePart(part))\n return {\n ...message,\n parts,\n id: message.id || generateId(),\n createdAt: coerceCreatedAt(message.createdAt) ?? new Date(),\n }\n } else {\n // ModelMessage - convert to UIMessage\n return {\n ...modelMessageToUIMessage(message, generateId()),\n createdAt: coerceCreatedAt(message.createdAt) ?? new Date(),\n }\n }\n}\n\n/**\n * Generate a unique message ID\n */\nexport function generateMessageId(): string {\n return `msg-${Date.now()}-${Math.random().toString(36).substring(7)}`\n}\n"],"mappings":";;;;AAoBA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;;AASA,SAAS,cAAc,MAAwC;CAC7D,OACE,KAAK,SAAS,U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` and model ids against its live docs —
|
|
418
418
|
> they drift. See `docs/adapters/openai-compatible.md` for the full provider table.
|
|
419
419
|
|
|
420
|
+
## Behind a proxy or gateway
|
|
421
|
+
|
|
422
|
+
Every adapter's client config accepts `baseURL` and `defaultHeaders`. Use these
|
|
423
|
+
two names to route any adapter through Cloudflare AI Gateway, Vercel AI Gateway,
|
|
424
|
+
or a corporate proxy. The adapter maps them onto the vendor SDK's own option
|
|
425
|
+
names (Gemini `httpOptions`, Mistral `serverURL`, Ollama `host`, Cohere and
|
|
426
|
+
ElevenLabs `baseUrl`/`headers`). The vendor names still work; when both are
|
|
427
|
+
set, `baseURL` and `defaultHeaders` win.
|
|
428
|
+
|
|
429
|
+
```typescript
|
|
430
|
+
const gateway = {
|
|
431
|
+
baseURL: 'https://gateway.example.com/google-ai-studio',
|
|
432
|
+
defaultHeaders: {
|
|
433
|
+
'cf-aig-authorization': `Bearer ${process.env.GATEWAY_TOKEN}`,
|
|
434
|
+
},
|
|
435
|
+
}
|
|
436
|
+
createGeminiChat('gemini-3.8-flash', apiKey, { ...gateway })
|
|
437
|
+
```
|
|
438
|
+
|
|
420
439
|
## Common Mistakes
|
|
421
440
|
|
|
422
441
|
### a. HIGH: Confusing legacy monolithic with tree-shakeable adapter
|
|
@@ -95,3 +95,8 @@ OPENAI_API_KEY
|
|
|
95
95
|
`effort: 'low'` or higher to enable reasoning.
|
|
96
96
|
- `o3-pro` only supports `high` reasoning effort.
|
|
97
97
|
- `conversation` and `previous_response_id` cannot be used together.
|
|
98
|
+
- Reasoning models (`o*`, `gpt-5*` except `*-chat-latest`, `codex-mini-latest`)
|
|
99
|
+
pair each `function_call` with a `reasoning` item. The adapter requests
|
|
100
|
+
`include: ['reasoning.encrypted_content']` for those models and replays that
|
|
101
|
+
item on the next turn. Pre-5 chat models are left unchanged. If you persist
|
|
102
|
+
history by hand, keep `thinking[].signature`.
|
|
@@ -1870,7 +1870,7 @@ class TextEngine<
|
|
|
1870
1870
|
}
|
|
1871
1871
|
|
|
1872
1872
|
private finalizeCurrentThinkingStep(): void {
|
|
1873
|
-
if (this.currentThinkingContent) {
|
|
1873
|
+
if (this.currentThinkingContent || this.currentThinkingSignature) {
|
|
1874
1874
|
this.accumulatedThinking.push({
|
|
1875
1875
|
content: this.currentThinkingContent,
|
|
1876
1876
|
...(this.currentThinkingSignature && {
|
|
@@ -173,10 +173,10 @@ export function convertMessagesToModelMessages(
|
|
|
173
173
|
|
|
174
174
|
if (role === 'reasoning') {
|
|
175
175
|
const content = (msg as { content?: string }).content
|
|
176
|
-
|
|
177
|
-
|
|
176
|
+
const signature = encryptedValueFrom(msg)
|
|
177
|
+
if (content || signature !== undefined) {
|
|
178
178
|
pendingThinking.push({
|
|
179
|
-
content,
|
|
179
|
+
content: typeof content === 'string' ? content : '',
|
|
180
180
|
...(signature !== undefined ? { signature } : {}),
|
|
181
181
|
})
|
|
182
182
|
}
|
|
@@ -593,7 +593,7 @@ function buildAssistantMessages(uiMessage: UIMessage): Array<ModelMessage> {
|
|
|
593
593
|
break
|
|
594
594
|
|
|
595
595
|
case 'thinking':
|
|
596
|
-
if (part.content) {
|
|
596
|
+
if (part.content || part.signature) {
|
|
597
597
|
// Provider-executed tools have no tool-result part, so thinking
|
|
598
598
|
// after them has to start the next segment or it replays first.
|
|
599
599
|
if (current.toolCalls.some(isProviderExecutedToolCall)) {
|
|
@@ -712,7 +712,7 @@ export function modelMessageToUIMessage(
|
|
|
712
712
|
|
|
713
713
|
if (modelMessage.role === 'assistant' && modelMessage.thinking?.length) {
|
|
714
714
|
for (const thinking of modelMessage.thinking) {
|
|
715
|
-
if (!thinking.content) continue
|
|
715
|
+
if (!thinking.content && !thinking.signature) continue
|
|
716
716
|
parts.push({
|
|
717
717
|
type: 'thinking',
|
|
718
718
|
content: thinking.content,
|
|
@@ -917,18 +917,20 @@ export function aguiSnapshotMessageToUIMessage(
|
|
|
917
917
|
})
|
|
918
918
|
case 'reasoning': {
|
|
919
919
|
const signature = encryptedValueFrom(message)
|
|
920
|
+
const content = typeof message.content === 'string' ? message.content : ''
|
|
920
921
|
return applySnapshotMetadata(message, {
|
|
921
922
|
id,
|
|
922
923
|
role: 'assistant',
|
|
923
|
-
parts:
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
924
|
+
parts:
|
|
925
|
+
content || signature !== undefined
|
|
926
|
+
? [
|
|
927
|
+
{
|
|
928
|
+
type: 'thinking' as const,
|
|
929
|
+
content,
|
|
930
|
+
...(signature !== undefined ? { signature } : {}),
|
|
931
|
+
},
|
|
932
|
+
]
|
|
933
|
+
: [],
|
|
932
934
|
})
|
|
933
935
|
}
|
|
934
936
|
case 'activity':
|