@tanstack/ai 0.63.0 → 0.64.0

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.
Files changed (61) hide show
  1. package/dist/esm/activities/chat/agents/spawn.js +2 -28
  2. package/dist/esm/activities/chat/agents/spawn.js.map +1 -1
  3. package/dist/esm/activities/chat/index.d.ts +2 -0
  4. package/dist/esm/activities/chat/index.js +10 -3
  5. package/dist/esm/activities/chat/index.js.map +1 -1
  6. package/dist/esm/activities/chat/messages.js +13 -4
  7. package/dist/esm/activities/chat/messages.js.map +1 -1
  8. package/dist/esm/activities/chat/stream/message-updaters.js +4 -1
  9. package/dist/esm/activities/chat/stream/message-updaters.js.map +1 -1
  10. package/dist/esm/activities/chat/tools/schema-converter.d.ts +8 -0
  11. package/dist/esm/activities/chat/tools/schema-converter.js +6 -5
  12. package/dist/esm/activities/chat/tools/schema-converter.js.map +1 -1
  13. package/dist/esm/activities/chat/tools/tool-calls.d.ts +5 -2
  14. package/dist/esm/activities/chat/tools/tool-calls.js +73 -22
  15. package/dist/esm/activities/chat/tools/tool-calls.js.map +1 -1
  16. package/dist/esm/activities/generateSpeech/index.d.ts +1 -1
  17. package/dist/esm/activities/generateSpeech/index.js +1 -1
  18. package/dist/esm/activities/generateSpeech/index.js.map +1 -1
  19. package/dist/esm/activities/generateVideo/adapter.d.ts +14 -6
  20. package/dist/esm/activities/generateVideo/adapter.js +6 -3
  21. package/dist/esm/activities/generateVideo/adapter.js.map +1 -1
  22. package/dist/esm/activities/generateVideo/index.d.ts +5 -4
  23. package/dist/esm/activities/generateVideo/index.js.map +1 -1
  24. package/dist/esm/activities/generateVideo/snap.d.ts +12 -3
  25. package/dist/esm/activities/generateVideo/snap.js +47 -8
  26. package/dist/esm/activities/generateVideo/snap.js.map +1 -1
  27. package/dist/esm/activities/generateVoice/index.d.ts +1 -1
  28. package/dist/esm/activities/generateVoice/index.js +1 -1
  29. package/dist/esm/activities/generateVoice/index.js.map +1 -1
  30. package/dist/esm/activities/index.d.ts +2 -2
  31. package/dist/esm/activities/index.js +2 -2
  32. package/dist/esm/adapter-internals.d.ts +1 -0
  33. package/dist/esm/adapter-internals.js +2 -1
  34. package/dist/esm/types.d.ts +28 -3
  35. package/dist/esm/utilities/ag-ui-wire.js +3 -1
  36. package/dist/esm/utilities/ag-ui-wire.js.map +1 -1
  37. package/dist/esm/utilities/merge-streams.d.ts +6 -0
  38. package/dist/esm/utilities/merge-streams.js +37 -0
  39. package/dist/esm/utilities/merge-streams.js.map +1 -0
  40. package/dist/esm/utilities/reasoning-encrypted-value.d.ts +8 -0
  41. package/dist/esm/utilities/reasoning-encrypted-value.js +11 -1
  42. package/dist/esm/utilities/reasoning-encrypted-value.js.map +1 -1
  43. package/package.json +1 -1
  44. package/skills/ai-core/media-generation/SKILL.md +3 -3
  45. package/src/activities/chat/agents/spawn.ts +2 -31
  46. package/src/activities/chat/index.ts +13 -3
  47. package/src/activities/chat/messages.ts +14 -2
  48. package/src/activities/chat/stream/message-updaters.ts +5 -0
  49. package/src/activities/chat/tools/schema-converter.ts +17 -5
  50. package/src/activities/chat/tools/tool-calls.ts +121 -63
  51. package/src/activities/generateSpeech/index.ts +1 -1
  52. package/src/activities/generateVideo/adapter.ts +21 -7
  53. package/src/activities/generateVideo/index.ts +5 -4
  54. package/src/activities/generateVideo/snap.ts +64 -6
  55. package/src/activities/generateVoice/index.ts +1 -1
  56. package/src/activities/index.ts +2 -1
  57. package/src/adapter-internals.ts +1 -0
  58. package/src/types.ts +28 -4
  59. package/src/utilities/ag-ui-wire.ts +5 -1
  60. package/src/utilities/merge-streams.ts +34 -0
  61. package/src/utilities/reasoning-encrypted-value.ts +12 -0
@@ -1,4 +1,5 @@
1
1
  import { tanstackMetadata, withTanstackMetadata } from "../../utilities/merge-metadata.js";
2
+ import { isRedactedThinkingId } from "../../utilities/reasoning-encrypted-value.js";
2
3
  import { isAssistantSegmentOf, isProviderExecutedToolCall } from "../../utilities/provider-executed.js";
3
4
  import { isContentPartArray, isToolResultOutcome, normalizeToolResult } from "../../utilities/tool-result.js";
4
5
  import { splitSubagentWire, subagentWireText } from "../../utilities/subagent-wire.js";
@@ -30,6 +31,10 @@ function encryptedValueFrom(value) {
30
31
  }
31
32
  return nonEmptyString(tanstackMetadata(value)?.signature);
32
33
  }
34
+ /** `{ redacted: true }` when a reasoning message's id marks a redacted block. */
35
+ function redactedFrom(value) {
36
+ return "id" in value && isRedactedThinkingId(value.id) ? { redacted: true } : {};
37
+ }
33
38
  function toolCallFromWire(toolCall, bag) {
34
39
  const fromBag = bag != null && typeof bag === "object" && !Array.isArray(bag) ? bag : void 0;
35
40
  const encrypted = encryptedValueFrom(toolCall);
@@ -154,7 +159,8 @@ function convertOwnMessages(messages) {
154
159
  const signature = encryptedValueFrom(msg);
155
160
  if (content || signature !== void 0) pendingThinking.push({
156
161
  content: typeof content === "string" ? content : "",
157
- ...signature !== void 0 ? { signature } : {}
162
+ ...signature !== void 0 ? { signature } : {},
163
+ ...redactedFrom(msg)
158
164
  });
159
165
  continue;
160
166
  }
@@ -491,7 +497,8 @@ function buildAssistantMessages(uiMessage) {
491
497
  if (current.toolCalls.some(isProviderExecutedToolCall)) flushSegment();
492
498
  pendingThinking.push({
493
499
  content: part.content,
494
- ...part.signature && { signature: part.signature }
500
+ ...part.signature && { signature: part.signature },
501
+ ...part.redacted && { redacted: true }
495
502
  });
496
503
  }
497
504
  break;
@@ -573,7 +580,8 @@ function modelMessageToUIMessage(modelMessage, id) {
573
580
  parts.push({
574
581
  type: "thinking",
575
582
  content: thinking.content,
576
- ...thinking.signature && { signature: thinking.signature }
583
+ ...thinking.signature && { signature: thinking.signature },
584
+ ...thinking.redacted && { redacted: true }
577
585
  });
578
586
  }
579
587
  const structuredOutput = modelMessage.structuredOutput ?? snapshotStructuredOutput(tanstackMetadata(modelMessage)?.structuredOutput);
@@ -718,7 +726,8 @@ function aguiSnapshotMessageToUIMessage(message) {
718
726
  parts: content || signature !== void 0 ? [{
719
727
  type: "thinking",
720
728
  content,
721
- ...signature !== void 0 ? { signature } : {}
729
+ ...signature !== void 0 ? { signature } : {},
730
+ ...redactedFrom(message)
722
731
  }] : []
723
732
  });
724
733
  }
@@ -1 +1 @@
1
- {"version":3,"file":"messages.js","names":[],"sources":["../../../../src/activities/chat/messages.ts"],"sourcesContent":["import {\n isAssistantSegmentOf,\n isProviderExecutedToolCall,\n} from '../../utilities/provider-executed'\nimport {\n isContentPartArray,\n isToolResultOutcome,\n normalizeToolResult,\n} from '../../utilities/tool-result'\nimport {\n tanstackMetadata,\n withTanstackMetadata,\n} from '../../utilities/merge-metadata'\nimport {\n splitSubagentWire,\n subagentWireText,\n} from '../../utilities/subagent-wire'\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 SubagentPart,\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// ===========================\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 historyTextFromParts(parts: ReadonlyArray<MessagePart>): string {\n const blocks: Array<string> = []\n for (const part of parts) {\n if (part.type === 'text' && part.content !== '') {\n blocks.push(part.content)\n } else if (\n part.type === 'structured-output' &&\n part.status === 'complete' &&\n part.raw !== ''\n ) {\n blocks.push(part.raw)\n } else if (part.type === 'subagent') {\n const nested = subagentHistoryText(part)\n if (nested !== '') blocks.push(nested)\n }\n }\n return blocks.join('\\n\\n')\n}\n\n/** Child text for a later turn. The name stays so the next agent can tell the notes apart. */\nexport function subagentHistoryText(part: SubagentPart): string {\n const blocks: Array<string> = []\n for (const message of part.subagent.messages) {\n if (!('parts' in message)) continue\n const text = historyTextFromParts(message.parts).trim()\n if (text !== '') blocks.push(text)\n }\n if (blocks.length === 0) return ''\n return `${part.subagent.name}:\\n${blocks.join('\\n\\n')}`\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 const { top, groups } = splitSubagentWire(messages)\n if (groups.length === 0) return convertOwnMessages(messages)\n\n // Child wire messages leave the parent history. The parent model reads each\n // child's text on the assistant message before it, the same as for a UI\n // subagent part. A child that a tool call started reports through the tool\n // result instead.\n const blocks = new Map<string | undefined, Array<string>>()\n for (const group of groups) {\n if (group.info.parentToolCallId !== undefined) continue\n const text = subagentWireText(group.messages)\n if (text === '') continue\n const host = top\n .slice(0, group.hostIndex + 1)\n .findLast((message) => message.role === 'assistant')\n const hostId = host && 'id' in host ? host.id : undefined\n blocks.set(hostId, [\n ...(blocks.get(hostId) ?? []),\n `${group.info.name}:\\n${text}`,\n ])\n }\n const converted = convertOwnMessages(top)\n for (const [hostId, texts] of blocks) {\n const block = texts.join('\\n\\n')\n const index =\n hostId === undefined\n ? -1\n : converted.findIndex(\n (message) => message.role === 'assistant' && message.id === hostId,\n )\n const host = converted[index]\n if (!host) {\n converted.push({ role: 'assistant', content: block })\n continue\n }\n converted[index] = {\n ...host,\n content:\n typeof host.content === 'string' && host.content !== ''\n ? `${host.content}\\n\\n${block}`\n : Array.isArray(host.content)\n ? [...host.content, { type: 'text', content: block }]\n : block,\n }\n }\n return converted\n}\n\nfunction convertOwnMessages(\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\n/**\n * Build a UIResourcePart from the value of a CUSTOM `ui-resource` chunk\n * emitted via `ctx.emitCustomEvent('ui-resource', ...)` (MCP Apps). The\n * emission-side value carries `resource`/`serverId`/`toolName` plus the\n * `toolCallId` stamped by the tool-call context wrapper — the `type`\n * discriminator is added here. Returns undefined when the value does not\n * match the ui-resource shape.\n */\nexport function uiResourcePartFromCustomValue(\n value: unknown,\n): UIResourcePart | undefined {\n if (!isRecord(value)) return undefined\n const part: unknown = { type: 'ui-resource', ...value }\n return isUiResourcePart(part) ? part : undefined\n}\n\n/**\n * Store an emitted ui-resource part on the assistant ModelMessage that owns\n * its `toolCallId` (the tool-call anchor), so it survives later\n * MESSAGES_SNAPSHOT chunks — e.g. the interrupt snapshot emitted when the\n * run pauses on a client tool (#1397). Mirrors how `toolCallMetadata` is\n * preserved on the anchor (#867).\n *\n * Returns the SAME array reference when no anchor owns the tool call or the\n * resource is already stored (idempotent).\n */\nexport function appendUiResourceToModelMessages(\n messages: Array<ModelMessage>,\n part: UIResourcePart,\n): Array<ModelMessage> {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index]\n if (!message || message.role !== 'assistant') continue\n const ownsToolCall = message.toolCalls?.some(\n (toolCall) => toolCall.id === part.toolCallId,\n )\n if (!ownsToolCall) continue\n const previous = tanstackMetadata(message)?.uiResources ?? []\n if (\n previous.some((stored) => uiResourceKey(stored) === uiResourceKey(part))\n ) {\n return messages\n }\n const nextMessage = {\n ...message,\n metadata: {\n ...message.metadata,\n tanstack: {\n ...tanstackMetadata(message),\n uiResources: [...previous, part],\n },\n },\n }\n const next = messages.slice()\n next[index] = nextMessage\n return next\n }\n return messages\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?.runId !== undefined) tanstack.runId = previous.runId\n if (previous?.run?.id !== undefined) tanstack.run = { id: previous.run.id }\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 const metadata =\n part.outcome === undefined\n ? part.metadata\n : withTanstackMetadata(part, { toolResultOutcome: part.outcome })\n .metadata\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 ...(metadata !== undefined && { 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 case 'subagent': {\n // A child that a tool call started reports through the tool result.\n const block =\n part.subagent.parentToolCallId === undefined\n ? subagentHistoryText(part)\n : ''\n if (block !== '') {\n const prefix = current.contentParts.length > 0 ? '\\n\\n' : ''\n current.contentParts.push({\n type: 'text',\n content: `${prefix}${block}`,\n })\n }\n break\n }\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 ...(approved === false && {\n metadata: { tanstack: { toolResultOutcome: 'denied' } },\n }),\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 const rawToolResultOutcome =\n tanstackMetadata(modelMessage)?.toolResultOutcome\n const toolResultOutcome = isToolResultOutcome(rawToolResultOutcome)\n ? rawToolResultOutcome\n : undefined\n const resultState =\n modelMessage.error === undefined && toolResultOutcome === undefined\n ? 'complete'\n : 'error'\n parts.push({\n type: 'tool-result',\n toolCallId: modelMessage.toolCallId,\n content: toolResultContent(modelMessage.content),\n state: resultState,\n ...(toolResultOutcome !== undefined && { outcome: toolResultOutcome }),\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: isContentPartArray(message.content)\n ? message.content\n : aguiContentToContentParts(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.\n */\nfunction aguiUserContentToParts(\n content: Extract<AGUIMessage, { role: 'user' }>['content'],\n): Array<MessagePart> {\n const converted = aguiContentToContentParts(content)\n return typeof converted === 'string'\n ? converted\n ? [{ type: 'text', content: converted }]\n : []\n : converted\n}\n\n/** Convert wire content parts. Data, url, and file sources pass through. */\nexport function aguiContentToContentParts(\n content: Extract<AGUIMessage, { role: 'user' }>['content'],\n): string | Array<ContentPart> {\n if (typeof content === 'string') return content\n return content.map((part) => {\n if (part.type !== 'text') return part\n const { text, ...rest } = part\n return { ...rest, content: text }\n })\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 rawToolResultOutcome = tanstackMetadata(msg)?.toolResultOutcome\n const toolResultOutcome = isToolResultOutcome(rawToolResultOutcome)\n ? rawToolResultOutcome\n : undefined\n const resultState =\n msg.error === undefined && toolResultOutcome === undefined\n ? 'complete'\n : 'error'\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 = resultState\n }\n\n currentAssistantMessage.parts.push({\n type: 'tool-result',\n toolCallId: msg.toolCallId,\n content,\n state: resultState,\n ...(toolResultOutcome !== undefined && {\n outcome: toolResultOutcome,\n }),\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 if (\n msg.role === 'assistant' &&\n currentAssistantMessage &&\n isAssistantSegmentOf(msg.id, currentAssistantMessage.id)\n ) {\n currentAssistantMessage.parts.push(...uiMessage.parts)\n continue\n }\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":";;;;;AAgCA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;;AAUA,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,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AK;IAC/C,GAAI,IAAI,aAAa,KAAA,KAAa,EAAE,UAAU,IAAI,SAAS;IAC3D,GAAG,kBAAkB,GAAG;IACxB,GAAI,IAAI,UAAU,KAAA,KAAa,EAAE,OAAO,IAAI,MAAM;GACpD,CAAC;EACH,OAAO;GAEL,MAAM,sBAAsB,wBAAwB,KAAK,IAAI,EAAE;GAC/D,WAAW,KAAK,mBAAmB;EACrC;CACF,OAAO;EAGL,MAAM,YAAY,wBAAwB,KAAK,IAAI,EAAE;EACrD,IACE,IAAI,SAAS,eACb,2BACA,qBAAqB,IAAI,IAAI,wBAAwB,EAAE,GACvD;GACA,wBAAwB,MAAM,KAAK,GAAG,UAAU,KAAK;GACrD;EACF;EACA,WAAW,KAAK,SAAS;EAGzB,IAAI,IAAI,SAAS,aACf,0BAA0B;OAE1B,0BAA0B;CAE9B;CAGF,OAAO;AACT;;;;;;;;;AAUA,SAAgB,qBACd,SACA,YACW;CACX,IAAI,WAAW,SAAS;EAEtB,MAAM,QAAQ,QAAQ,MAAM,KAAK,SAAS,qBAAqB,IAAI,CAAC;EACpE,OAAO;GACL,GAAG;GACH;GACA,IAAI,QAAQ,MAAM,WAAW;GAC7B,WAAW,gBAAgB,QAAQ,SAAS,qBAAK,IAAI,KAAK;EAC5D;CACF,OAEE,OAAO;EACL,GAAG,wBAAwB,SAAS,WAAW,CAAC;EAChD,WAAW,gBAAgB,QAAQ,SAAS,qBAAK,IAAI,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 {\n isAssistantSegmentOf,\n isProviderExecutedToolCall,\n} from '../../utilities/provider-executed'\nimport {\n isContentPartArray,\n isToolResultOutcome,\n normalizeToolResult,\n} from '../../utilities/tool-result'\nimport {\n tanstackMetadata,\n withTanstackMetadata,\n} from '../../utilities/merge-metadata'\nimport { isRedactedThinkingId } from '../../utilities/reasoning-encrypted-value'\nimport {\n splitSubagentWire,\n subagentWireText,\n} from '../../utilities/subagent-wire'\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 SubagentPart,\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// ===========================\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\n/** `{ redacted: true }` when a reasoning message's id marks a redacted block. */\nfunction redactedFrom(value: object) {\n return 'id' in value && isRedactedThinkingId(value.id)\n ? { redacted: true }\n : {}\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 historyTextFromParts(parts: ReadonlyArray<MessagePart>): string {\n const blocks: Array<string> = []\n for (const part of parts) {\n if (part.type === 'text' && part.content !== '') {\n blocks.push(part.content)\n } else if (\n part.type === 'structured-output' &&\n part.status === 'complete' &&\n part.raw !== ''\n ) {\n blocks.push(part.raw)\n } else if (part.type === 'subagent') {\n const nested = subagentHistoryText(part)\n if (nested !== '') blocks.push(nested)\n }\n }\n return blocks.join('\\n\\n')\n}\n\n/** Child text for a later turn. The name stays so the next agent can tell the notes apart. */\nexport function subagentHistoryText(part: SubagentPart): string {\n const blocks: Array<string> = []\n for (const message of part.subagent.messages) {\n if (!('parts' in message)) continue\n const text = historyTextFromParts(message.parts).trim()\n if (text !== '') blocks.push(text)\n }\n if (blocks.length === 0) return ''\n return `${part.subagent.name}:\\n${blocks.join('\\n\\n')}`\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 const { top, groups } = splitSubagentWire(messages)\n if (groups.length === 0) return convertOwnMessages(messages)\n\n // Child wire messages leave the parent history. The parent model reads each\n // child's text on the assistant message before it, the same as for a UI\n // subagent part. A child that a tool call started reports through the tool\n // result instead.\n const blocks = new Map<string | undefined, Array<string>>()\n for (const group of groups) {\n if (group.info.parentToolCallId !== undefined) continue\n const text = subagentWireText(group.messages)\n if (text === '') continue\n const host = top\n .slice(0, group.hostIndex + 1)\n .findLast((message) => message.role === 'assistant')\n const hostId = host && 'id' in host ? host.id : undefined\n blocks.set(hostId, [\n ...(blocks.get(hostId) ?? []),\n `${group.info.name}:\\n${text}`,\n ])\n }\n const converted = convertOwnMessages(top)\n for (const [hostId, texts] of blocks) {\n const block = texts.join('\\n\\n')\n const index =\n hostId === undefined\n ? -1\n : converted.findIndex(\n (message) => message.role === 'assistant' && message.id === hostId,\n )\n const host = converted[index]\n if (!host) {\n converted.push({ role: 'assistant', content: block })\n continue\n }\n converted[index] = {\n ...host,\n content:\n typeof host.content === 'string' && host.content !== ''\n ? `${host.content}\\n\\n${block}`\n : Array.isArray(host.content)\n ? [...host.content, { type: 'text', content: block }]\n : block,\n }\n }\n return converted\n}\n\nfunction convertOwnMessages(\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: NonNullable<ModelMessage['thinking']> = []\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 ...redactedFrom(msg),\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\n/**\n * Build a UIResourcePart from the value of a CUSTOM `ui-resource` chunk\n * emitted via `ctx.emitCustomEvent('ui-resource', ...)` (MCP Apps). The\n * emission-side value carries `resource`/`serverId`/`toolName` plus the\n * `toolCallId` stamped by the tool-call context wrapper — the `type`\n * discriminator is added here. Returns undefined when the value does not\n * match the ui-resource shape.\n */\nexport function uiResourcePartFromCustomValue(\n value: unknown,\n): UIResourcePart | undefined {\n if (!isRecord(value)) return undefined\n const part: unknown = { type: 'ui-resource', ...value }\n return isUiResourcePart(part) ? part : undefined\n}\n\n/**\n * Store an emitted ui-resource part on the assistant ModelMessage that owns\n * its `toolCallId` (the tool-call anchor), so it survives later\n * MESSAGES_SNAPSHOT chunks — e.g. the interrupt snapshot emitted when the\n * run pauses on a client tool (#1397). Mirrors how `toolCallMetadata` is\n * preserved on the anchor (#867).\n *\n * Returns the SAME array reference when no anchor owns the tool call or the\n * resource is already stored (idempotent).\n */\nexport function appendUiResourceToModelMessages(\n messages: Array<ModelMessage>,\n part: UIResourcePart,\n): Array<ModelMessage> {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index]\n if (!message || message.role !== 'assistant') continue\n const ownsToolCall = message.toolCalls?.some(\n (toolCall) => toolCall.id === part.toolCallId,\n )\n if (!ownsToolCall) continue\n const previous = tanstackMetadata(message)?.uiResources ?? []\n if (\n previous.some((stored) => uiResourceKey(stored) === uiResourceKey(part))\n ) {\n return messages\n }\n const nextMessage = {\n ...message,\n metadata: {\n ...message.metadata,\n tanstack: {\n ...tanstackMetadata(message),\n uiResources: [...previous, part],\n },\n },\n }\n const next = messages.slice()\n next[index] = nextMessage\n return next\n }\n return messages\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?.runId !== undefined) tanstack.runId = previous.runId\n if (previous?.run?.id !== undefined) tanstack.run = { id: previous.run.id }\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: NonNullable<ModelMessage['thinking']> = []\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 const metadata =\n part.outcome === undefined\n ? part.metadata\n : withTanstackMetadata(part, { toolResultOutcome: part.outcome })\n .metadata\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 ...(metadata !== undefined && { 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 ...(part.redacted && { redacted: true }),\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 case 'subagent': {\n // A child that a tool call started reports through the tool result.\n const block =\n part.subagent.parentToolCallId === undefined\n ? subagentHistoryText(part)\n : ''\n if (block !== '') {\n const prefix = current.contentParts.length > 0 ? '\\n\\n' : ''\n current.contentParts.push({\n type: 'text',\n content: `${prefix}${block}`,\n })\n }\n break\n }\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 ...(approved === false && {\n metadata: { tanstack: { toolResultOutcome: 'denied' } },\n }),\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 ...(thinking.redacted && { redacted: true }),\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 const rawToolResultOutcome =\n tanstackMetadata(modelMessage)?.toolResultOutcome\n const toolResultOutcome = isToolResultOutcome(rawToolResultOutcome)\n ? rawToolResultOutcome\n : undefined\n const resultState =\n modelMessage.error === undefined && toolResultOutcome === undefined\n ? 'complete'\n : 'error'\n parts.push({\n type: 'tool-result',\n toolCallId: modelMessage.toolCallId,\n content: toolResultContent(modelMessage.content),\n state: resultState,\n ...(toolResultOutcome !== undefined && { outcome: toolResultOutcome }),\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: isContentPartArray(message.content)\n ? message.content\n : aguiContentToContentParts(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 ...redactedFrom(message),\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.\n */\nfunction aguiUserContentToParts(\n content: Extract<AGUIMessage, { role: 'user' }>['content'],\n): Array<MessagePart> {\n const converted = aguiContentToContentParts(content)\n return typeof converted === 'string'\n ? converted\n ? [{ type: 'text', content: converted }]\n : []\n : converted\n}\n\n/** Convert wire content parts. Data, url, and file sources pass through. */\nexport function aguiContentToContentParts(\n content: Extract<AGUIMessage, { role: 'user' }>['content'],\n): string | Array<ContentPart> {\n if (typeof content === 'string') return content\n return content.map((part) => {\n if (part.type !== 'text') return part\n const { text, ...rest } = part\n return { ...rest, content: text }\n })\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 rawToolResultOutcome = tanstackMetadata(msg)?.toolResultOutcome\n const toolResultOutcome = isToolResultOutcome(rawToolResultOutcome)\n ? rawToolResultOutcome\n : undefined\n const resultState =\n msg.error === undefined && toolResultOutcome === undefined\n ? 'complete'\n : 'error'\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 = resultState\n }\n\n currentAssistantMessage.parts.push({\n type: 'tool-result',\n toolCallId: msg.toolCallId,\n content,\n state: resultState,\n ...(toolResultOutcome !== undefined && {\n outcome: toolResultOutcome,\n }),\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 if (\n msg.role === 'assistant' &&\n currentAssistantMessage &&\n isAssistantSegmentOf(msg.id, currentAssistantMessage.id)\n ) {\n currentAssistantMessage.parts.push(...uiMessage.parts)\n continue\n }\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":";;;;;;AAiCA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;;AAUA,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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@
1
+ import { isRedactedThinkingId } from "../../../utilities/reasoning-encrypted-value.js";
1
2
  import { parsePartialJSON } from "./json-parser.js";
2
3
  //#region src/activities/chat/stream/message-updaters.ts
3
4
  /**
@@ -284,11 +285,13 @@ function updateThinkingPart(messages, messageId, stepId, content, signature) {
284
285
  if (candidate?.type === "thinking") adopted = candidate;
285
286
  }
286
287
  const nextSignature = signature ?? adopted?.signature;
288
+ const redacted = isRedactedThinkingId(stepId) || adopted?.redacted === true;
287
289
  const thinkingPart = {
288
290
  type: "thinking",
289
291
  content,
290
292
  stepId,
291
- ...nextSignature && { signature: nextSignature }
293
+ ...nextSignature && { signature: nextSignature },
294
+ ...redacted && { redacted: true }
292
295
  };
293
296
  if (thinkingPartIndex >= 0) parts[thinkingPartIndex] = thinkingPart;
294
297
  else parts.push(thinkingPart);
@@ -1 +1 @@
1
- {"version":3,"file":"message-updaters.js","names":[],"sources":["../../../../../src/activities/chat/stream/message-updaters.ts"],"sourcesContent":["/**\n * Message Updaters (Internal)\n *\n * Internal helper functions for updating UIMessage parts.\n * These are used by StreamProcessor to manage the message array.\n */\n\nimport { parsePartialJSON } from './json-parser'\nimport type {\n ContentPart,\n StructuredOutputPart,\n ThinkingPart,\n ToolCallPart,\n ToolResultOutcome,\n ToolResultPart,\n UIMessage,\n} from '../../../types'\nimport type { ToolCallState, ToolResultState } from './types'\n\n/**\n * Update or add a text part to a message.\n *\n * If the last part is a text part, update it (continuing the same text segment).\n * Otherwise, create a new text part (starting a new text segment after tool calls).\n */\nexport function updateTextPart(\n messages: Array<UIMessage>,\n messageId: string,\n content: string,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const lastPart = parts.length > 0 ? parts[parts.length - 1] : null\n\n if (lastPart && lastPart.type === 'text') {\n // Update the last text part (continuing same text segment)\n parts[parts.length - 1] = { type: 'text', content }\n } else {\n // Create new text part (starting new text segment after tool calls/results)\n parts.push({ type: 'text', content })\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Update or add a tool call part to a message.\n */\nexport function updateToolCallPart(\n messages: Array<UIMessage>,\n messageId: string,\n toolCall: {\n id: string\n name: string\n arguments: string\n state: ToolCallState\n /** Parsed input — set when the arguments are complete. */\n input?: unknown\n metadata?: Record<string, unknown>\n },\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const existing = parts.find(\n (p): p is ToolCallPart => p.type === 'tool-call' && p.id === toolCall.id,\n )\n\n // Carry forward metadata from either the new toolCall or the existing\n // part. Once the adapter has emitted metadata for a tool call (e.g.\n // Gemini's thoughtSignature on TOOL_CALL_START) we must not lose it on\n // subsequent updates that don't re-supply it.\n const metadata = toolCall.metadata ?? existing?.metadata\n // Same for the parsed input: it's supplied once at completion, so\n // subsequent arg-less updates (approval, etc.) must not drop it.\n const input = toolCall.input ?? existing?.input\n\n const toolCallPart: ToolCallPart = {\n type: 'tool-call',\n id: toolCall.id,\n name: toolCall.name,\n arguments: toolCall.arguments,\n state: toolCall.state,\n // Carry forward approval, output and parsed input from the existing part\n ...(existing?.approval && { approval: { ...existing.approval } }),\n ...(existing?.output !== undefined && { output: existing.output }),\n ...(input !== undefined && { input }),\n ...(metadata !== undefined && { metadata }),\n }\n\n if (existing) {\n // Update existing tool call\n parts[parts.indexOf(existing)] = toolCallPart\n } else {\n // Add new tool call at the end (preserve natural streaming order)\n parts.push(toolCallPart)\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Update or add a tool result part to a message.\n */\nexport function updateToolResultPart(\n messages: Array<UIMessage>,\n messageId: string,\n toolCallId: string,\n content: string | Array<ContentPart>,\n state: ToolResultState,\n error?: string,\n outcome?: ToolResultOutcome,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const resultPartIndex = parts.findIndex(\n (p): p is ToolResultPart =>\n p.type === 'tool-result' && p.toolCallId === toolCallId,\n )\n\n const toolResultPart: ToolResultPart = {\n type: 'tool-result',\n toolCallId,\n content,\n state,\n ...(outcome !== undefined && { outcome }),\n ...(error && { error }),\n }\n\n if (resultPartIndex >= 0) {\n parts[resultPartIndex] = toolResultPart\n } else {\n parts.push(toolResultPart)\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Update a tool call part with approval request metadata.\n */\nexport function updateToolCallApproval(\n messages: Array<UIMessage>,\n messageId: string,\n toolCallId: string,\n approvalId: string,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const toolCallPart = parts.find(\n (p): p is ToolCallPart => p.type === 'tool-call' && p.id === toolCallId,\n )\n\n if (toolCallPart) {\n const index = parts.indexOf(toolCallPart)\n parts[index] = {\n ...toolCallPart,\n state: 'approval-requested',\n approval: {\n id: approvalId,\n needsApproval: true,\n },\n }\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Update a tool call part's state (e.g., to \"input-complete\").\n */\nexport function updateToolCallState(\n messages: Array<UIMessage>,\n messageId: string,\n toolCallId: string,\n state: ToolCallState,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const toolCallPart = parts.find(\n (p): p is ToolCallPart => p.type === 'tool-call' && p.id === toolCallId,\n )\n\n if (toolCallPart) {\n const index = parts.indexOf(toolCallPart)\n parts[index] = { ...toolCallPart, state }\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Update a tool call part with output.\n * Searches all messages to find the tool call by ID.\n */\nexport function updateToolCallWithOutput(\n messages: Array<UIMessage>,\n toolCallId: string,\n output: any,\n state?: ToolCallState,\n errorText?: string,\n): Array<UIMessage> {\n return messages.map((msg) => {\n const parts = [...msg.parts]\n const toolCallPart = parts.find(\n (p): p is ToolCallPart => p.type === 'tool-call' && p.id === toolCallId,\n )\n\n if (toolCallPart) {\n const index = parts.indexOf(toolCallPart)\n parts[index] = {\n ...toolCallPart,\n output: errorText ? { error: errorText } : output,\n state: state ?? (errorText ? 'error' : 'complete'),\n }\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Update a tool call part with approval response.\n * Searches all messages to find the tool call by approval ID.\n */\nexport function updateToolCallApprovalResponse(\n messages: Array<UIMessage>,\n approvalId: string,\n approved: boolean,\n): Array<UIMessage> {\n return messages.map((msg) => {\n const parts = [...msg.parts]\n const toolCallPart = parts.find(\n (p): p is ToolCallPart =>\n p.type === 'tool-call' && p.approval?.id === approvalId,\n )\n\n if (toolCallPart && toolCallPart.approval) {\n const index = parts.indexOf(toolCallPart)\n parts[index] = {\n ...toolCallPart,\n approval: { ...toolCallPart.approval, approved },\n state: 'approval-responded',\n }\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Append a delta to the structured-output part on `messageId`, or create one\n * if absent. Progressive parse of the accumulated buffer fills `partial`.\n *\n * Callers must only invoke this while the part is still in flight — the\n * helper unconditionally writes `status: 'streaming'`, so feeding it a delta\n * after a `complete`/`error` terminal would regress the part. In practice the\n * processor gates calls via `structuredMessageIds`, which is dropped on\n * terminal events.\n *\n * If the progressive parse returns null/undefined (the buffer is not yet a\n * parseable JSON prefix), the previously-good `partial` is preserved so the\n * UI doesn't flicker back to empty for a single render.\n */\nexport function appendStructuredOutputDelta(\n messages: Array<UIMessage>,\n messageId: string,\n delta: string,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const existingIndex = parts.findIndex(\n (p): p is StructuredOutputPart => p.type === 'structured-output',\n )\n const existing =\n existingIndex >= 0 ? (parts[existingIndex] as StructuredOutputPart) : null\n\n const nextRaw = (existing?.raw ?? '') + delta\n const progressive = parsePartialJSON(nextRaw)\n const nextPartial =\n progressive !== undefined && progressive !== null\n ? progressive\n : existing?.partial\n\n const nextPart: StructuredOutputPart = {\n type: 'structured-output',\n status: 'streaming',\n raw: nextRaw,\n ...(nextPartial !== undefined ? { partial: nextPartial } : {}),\n ...(existing?.reasoning !== undefined\n ? { reasoning: existing.reasoning }\n : {}),\n }\n\n if (existingIndex >= 0) {\n parts[existingIndex] = nextPart\n } else {\n parts.push(nextPart)\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Snap the structured-output part on `messageId` to `complete` with the\n * validated `data`. Picks the freshest available `raw` so the wire\n * round-trip stays internally consistent:\n *\n * 1. Caller-supplied `raw` (the original streamed bytes from the model).\n * 2. The existing part's `raw` (deltas accumulated before this terminal).\n * 3. `JSON.stringify(data)` as a defensive fallback for terminal-only\n * completes that never shipped raw — keeps the part self-consistent\n * so downstream consumers never see a complete part with empty raw.\n */\nexport function completeStructuredOutputPart(\n messages: Array<UIMessage>,\n messageId: string,\n data: unknown,\n raw: string,\n reasoning?: string,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const existingIndex = parts.findIndex(\n (p): p is StructuredOutputPart => p.type === 'structured-output',\n )\n\n const existingRaw =\n existingIndex >= 0\n ? (parts[existingIndex] as StructuredOutputPart).raw\n : ''\n let resolvedRaw = raw || existingRaw\n if (resolvedRaw === '' && data !== undefined) {\n try {\n resolvedRaw = JSON.stringify(data)\n } catch {\n // Unserializable (circular, BigInt, throwing toJSON). Leave raw\n // empty. Both downstream paths handle this: `ag-ui-wire.ts`\n // `collectText` skips complete parts with empty raw entirely, and\n // `uiMessageToModelMessages` falls back to a defensive\n // `safeJsonStringify(data)` which itself returns `''` for the same\n // unserializable inputs — so the turn is silently dropped from the\n // next request rather than shipping garbage or crashing the stream.\n }\n }\n\n const nextPart: StructuredOutputPart = {\n type: 'structured-output',\n status: 'complete',\n data,\n partial: data,\n raw: resolvedRaw,\n ...(reasoning !== undefined ? { reasoning } : {}),\n }\n\n if (existingIndex >= 0) {\n parts[existingIndex] = nextPart\n } else {\n parts.push(nextPart)\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Mark the structured-output part on `messageId` as errored. If no part\n * exists yet — RUN_ERROR fired after `structured-output.start` but before\n * any delta — create an empty errored placeholder so consumers have\n * something renderable. Existing complete parts are left alone (an error\n * after a successful complete should not retroactively un-complete it).\n */\nexport function errorStructuredOutputPart(\n messages: Array<UIMessage>,\n messageId: string,\n errorMessage: string,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const existingIndex = parts.findIndex(\n (p): p is StructuredOutputPart => p.type === 'structured-output',\n )\n\n if (existingIndex < 0) {\n parts.push({\n type: 'structured-output',\n status: 'error',\n raw: '',\n errorMessage,\n })\n return { ...msg, parts }\n }\n\n const existing = parts[existingIndex] as StructuredOutputPart\n if (existing.status === 'complete') {\n return msg\n }\n parts[existingIndex] = {\n ...existing,\n status: 'error',\n errorMessage,\n }\n return { ...msg, parts }\n })\n}\n\n/**\n * Update or add a thinking part to a message, keyed by stepId.\n * Each distinct stepId produces its own ThinkingPart.\n */\nexport function updateThinkingPart(\n messages: Array<UIMessage>,\n messageId: string,\n stepId: string,\n content: string,\n signature?: string,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n let thinkingPartIndex = parts.findIndex(\n (p) => p.type === 'thinking' && p.stepId === stepId,\n )\n\n // A hydrated message carries its thinking without a stepId: the stored form\n // has no field for one, so `modelMessageToUIMessage` cannot put it back.\n // When a run is rejoined mid-stream the replayed reasoning is keyed by\n // stepId, matches nothing, and gets appended -- leaving a second thinking\n // part sitting after the answer text. Adopt the first stepId-less thinking\n // part instead, so the replay lands on the part it belongs to. Live\n // streaming always writes a stepId, so the only parts this can match are\n // hydrated ones.\n let adopted: ThinkingPart | undefined\n if (thinkingPartIndex < 0) {\n thinkingPartIndex = parts.findIndex(\n (p) => p.type === 'thinking' && p.stepId === undefined,\n )\n const candidate = parts[thinkingPartIndex]\n if (candidate?.type === 'thinking') adopted = candidate\n }\n\n // Keep the signature the hydrated part already had when this update does\n // not carry one; losing it would strip the provider's encrypted reasoning\n // from a message that is about to be sent back.\n const nextSignature = signature ?? adopted?.signature\n\n const thinkingPart: ThinkingPart = {\n type: 'thinking',\n content,\n stepId,\n ...(nextSignature && { signature: nextSignature }),\n }\n\n if (thinkingPartIndex >= 0) {\n // Update existing thinking part for this step\n parts[thinkingPartIndex] = thinkingPart\n } else {\n // Add new thinking part at the end (preserve natural streaming order)\n parts.push(thinkingPart)\n }\n\n return { ...msg, parts }\n })\n}\n"],"mappings":";;;;;;;;;;;;;;AAyBA,SAAgB,eACd,UACA,WACA,SACkB;CAClB,OAAO,SAAS,KAAK,QAAQ;EAC3B,IAAI,IAAI,OAAO,WACb,OAAO;EAGT,MAAM,QAAQ,CAAC,GAAG,IAAI,KAAK;EAC3B,MAAM,WAAW,MAAM,SAAS,IAAI,MAAM,MAAM,SAAS,KAAK;EAE9D,IAAI,YAAY,SAAS,SAAS,QAEhC,MAAM,MAAM,SAAS,KAAK;GAAE,MAAM;GAAQ;EAAQ;OAGlD,MAAM,KAAK;GAAE,MAAM;GAAQ;EAAQ,CAAC;EAGtC,OAAO;GAAE,GAAG;GAAK;EAAM;CACzB,CAAC;AACH;;;;AAKA,SAAgB,mBACd,UACA,WACA,UASkB;CAClB,OAAO,SAAS,KAAK,QAAQ;EAC3B,IAAI,IAAI,OAAO,WACb,OAAO;EAGT,MAAM,QAAQ,CAAC,GAAG,IAAI,KAAK;EAC3B,MAAM,WAAW,MAAM,MACpB,MAAyB,EAAE,SAAS,eAAe,EAAE,OAAO,SAAS,EACxE;EAMA,MAAM,WAAW,SAAS,YAAY,UAAU;EAGhD,MAAM,QAAQ,SAAS,SAAS,UAAU;EAE1C,MAAM,eAA6B;GACjC,MAAM;GACN,IAAI,SAAS;GACb,MAAM,SAAS;GACf,WAAW,SAAS;GACpB,OAAO,SAAS;GAEhB,GAAI,UAAU,YAAY,EAAE,UAAU,EAAE,GAAG,SAAS,SAAS,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IACN,QAAQ;IACR,KAAK;IACL;GACF,CAAC;GACD,OAAO;IAAE,GAAG;IAAK;GAAM;EACzB;EAEA,MAAM,WAAW,MAAM;EACvB,IAAI,SAAS,WAAW,YACtB,OAAO;EAET,MAAM,iBAAiB;GACrB,GAAG;GACH,QAAQ;GACR;EACF;EACA,OAAO;GAAE,GAAG;GAAK;EAAM;CACzB,CAAC;AACH;;;;;AAMA,SAAgB,mBACd,UACA,WACA,QACA,SACA,WACkB;CAClB,OAAO,SAAS,KAAK,QAAQ;EAC3B,IAAI,IAAI,OAAO,WACb,OAAO;EAGT,MAAM,QAAQ,CAAC,GAAG,IAAI,KAAK;EAC3B,IAAI,oBAAoB,MAAM,WAC3B,MAAM,EAAE,SAAS,cAAc,EAAE,WAAW,MAC/C;EAUA,IAAI;EACJ,IAAI,oBAAoB,GAAG;GACzB,oBAAoB,MAAM,WACvB,MAAM,EAAE,SAAS,cAAc,EAAE,WAAW,KAAA,CAC/C;GACA,MAAM,YAAY,MAAM;GACxB,IAAI,WAAW,SAAS,YAAY,UAAU;EAChD;EAKA,MAAM,gBAAgB,aAAa,SAAS;EAE5C,MAAM,eAA6B;GACjC,MAAM;GACN;GACA;GACA,GAAI,iBAAiB,EAAE,WAAW,cAAc;EAClD;EAEA,IAAI,qBAAqB,GAEvB,MAAM,qBAAqB;OAG3B,MAAM,KAAK,YAAY;EAGzB,OAAO;GAAE,GAAG;GAAK;EAAM;CACzB,CAAC;AACH"}
1
+ {"version":3,"file":"message-updaters.js","names":[],"sources":["../../../../../src/activities/chat/stream/message-updaters.ts"],"sourcesContent":["/**\n * Message Updaters (Internal)\n *\n * Internal helper functions for updating UIMessage parts.\n * These are used by StreamProcessor to manage the message array.\n */\n\nimport { isRedactedThinkingId } from '../../../utilities/reasoning-encrypted-value'\nimport { parsePartialJSON } from './json-parser'\nimport type {\n ContentPart,\n StructuredOutputPart,\n ThinkingPart,\n ToolCallPart,\n ToolResultOutcome,\n ToolResultPart,\n UIMessage,\n} from '../../../types'\nimport type { ToolCallState, ToolResultState } from './types'\n\n/**\n * Update or add a text part to a message.\n *\n * If the last part is a text part, update it (continuing the same text segment).\n * Otherwise, create a new text part (starting a new text segment after tool calls).\n */\nexport function updateTextPart(\n messages: Array<UIMessage>,\n messageId: string,\n content: string,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const lastPart = parts.length > 0 ? parts[parts.length - 1] : null\n\n if (lastPart && lastPart.type === 'text') {\n // Update the last text part (continuing same text segment)\n parts[parts.length - 1] = { type: 'text', content }\n } else {\n // Create new text part (starting new text segment after tool calls/results)\n parts.push({ type: 'text', content })\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Update or add a tool call part to a message.\n */\nexport function updateToolCallPart(\n messages: Array<UIMessage>,\n messageId: string,\n toolCall: {\n id: string\n name: string\n arguments: string\n state: ToolCallState\n /** Parsed input — set when the arguments are complete. */\n input?: unknown\n metadata?: Record<string, unknown>\n },\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const existing = parts.find(\n (p): p is ToolCallPart => p.type === 'tool-call' && p.id === toolCall.id,\n )\n\n // Carry forward metadata from either the new toolCall or the existing\n // part. Once the adapter has emitted metadata for a tool call (e.g.\n // Gemini's thoughtSignature on TOOL_CALL_START) we must not lose it on\n // subsequent updates that don't re-supply it.\n const metadata = toolCall.metadata ?? existing?.metadata\n // Same for the parsed input: it's supplied once at completion, so\n // subsequent arg-less updates (approval, etc.) must not drop it.\n const input = toolCall.input ?? existing?.input\n\n const toolCallPart: ToolCallPart = {\n type: 'tool-call',\n id: toolCall.id,\n name: toolCall.name,\n arguments: toolCall.arguments,\n state: toolCall.state,\n // Carry forward approval, output and parsed input from the existing part\n ...(existing?.approval && { approval: { ...existing.approval } }),\n ...(existing?.output !== undefined && { output: existing.output }),\n ...(input !== undefined && { input }),\n ...(metadata !== undefined && { metadata }),\n }\n\n if (existing) {\n // Update existing tool call\n parts[parts.indexOf(existing)] = toolCallPart\n } else {\n // Add new tool call at the end (preserve natural streaming order)\n parts.push(toolCallPart)\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Update or add a tool result part to a message.\n */\nexport function updateToolResultPart(\n messages: Array<UIMessage>,\n messageId: string,\n toolCallId: string,\n content: string | Array<ContentPart>,\n state: ToolResultState,\n error?: string,\n outcome?: ToolResultOutcome,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const resultPartIndex = parts.findIndex(\n (p): p is ToolResultPart =>\n p.type === 'tool-result' && p.toolCallId === toolCallId,\n )\n\n const toolResultPart: ToolResultPart = {\n type: 'tool-result',\n toolCallId,\n content,\n state,\n ...(outcome !== undefined && { outcome }),\n ...(error && { error }),\n }\n\n if (resultPartIndex >= 0) {\n parts[resultPartIndex] = toolResultPart\n } else {\n parts.push(toolResultPart)\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Update a tool call part with approval request metadata.\n */\nexport function updateToolCallApproval(\n messages: Array<UIMessage>,\n messageId: string,\n toolCallId: string,\n approvalId: string,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const toolCallPart = parts.find(\n (p): p is ToolCallPart => p.type === 'tool-call' && p.id === toolCallId,\n )\n\n if (toolCallPart) {\n const index = parts.indexOf(toolCallPart)\n parts[index] = {\n ...toolCallPart,\n state: 'approval-requested',\n approval: {\n id: approvalId,\n needsApproval: true,\n },\n }\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Update a tool call part's state (e.g., to \"input-complete\").\n */\nexport function updateToolCallState(\n messages: Array<UIMessage>,\n messageId: string,\n toolCallId: string,\n state: ToolCallState,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const toolCallPart = parts.find(\n (p): p is ToolCallPart => p.type === 'tool-call' && p.id === toolCallId,\n )\n\n if (toolCallPart) {\n const index = parts.indexOf(toolCallPart)\n parts[index] = { ...toolCallPart, state }\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Update a tool call part with output.\n * Searches all messages to find the tool call by ID.\n */\nexport function updateToolCallWithOutput(\n messages: Array<UIMessage>,\n toolCallId: string,\n output: any,\n state?: ToolCallState,\n errorText?: string,\n): Array<UIMessage> {\n return messages.map((msg) => {\n const parts = [...msg.parts]\n const toolCallPart = parts.find(\n (p): p is ToolCallPart => p.type === 'tool-call' && p.id === toolCallId,\n )\n\n if (toolCallPart) {\n const index = parts.indexOf(toolCallPart)\n parts[index] = {\n ...toolCallPart,\n output: errorText ? { error: errorText } : output,\n state: state ?? (errorText ? 'error' : 'complete'),\n }\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Update a tool call part with approval response.\n * Searches all messages to find the tool call by approval ID.\n */\nexport function updateToolCallApprovalResponse(\n messages: Array<UIMessage>,\n approvalId: string,\n approved: boolean,\n): Array<UIMessage> {\n return messages.map((msg) => {\n const parts = [...msg.parts]\n const toolCallPart = parts.find(\n (p): p is ToolCallPart =>\n p.type === 'tool-call' && p.approval?.id === approvalId,\n )\n\n if (toolCallPart && toolCallPart.approval) {\n const index = parts.indexOf(toolCallPart)\n parts[index] = {\n ...toolCallPart,\n approval: { ...toolCallPart.approval, approved },\n state: 'approval-responded',\n }\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Append a delta to the structured-output part on `messageId`, or create one\n * if absent. Progressive parse of the accumulated buffer fills `partial`.\n *\n * Callers must only invoke this while the part is still in flight — the\n * helper unconditionally writes `status: 'streaming'`, so feeding it a delta\n * after a `complete`/`error` terminal would regress the part. In practice the\n * processor gates calls via `structuredMessageIds`, which is dropped on\n * terminal events.\n *\n * If the progressive parse returns null/undefined (the buffer is not yet a\n * parseable JSON prefix), the previously-good `partial` is preserved so the\n * UI doesn't flicker back to empty for a single render.\n */\nexport function appendStructuredOutputDelta(\n messages: Array<UIMessage>,\n messageId: string,\n delta: string,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const existingIndex = parts.findIndex(\n (p): p is StructuredOutputPart => p.type === 'structured-output',\n )\n const existing =\n existingIndex >= 0 ? (parts[existingIndex] as StructuredOutputPart) : null\n\n const nextRaw = (existing?.raw ?? '') + delta\n const progressive = parsePartialJSON(nextRaw)\n const nextPartial =\n progressive !== undefined && progressive !== null\n ? progressive\n : existing?.partial\n\n const nextPart: StructuredOutputPart = {\n type: 'structured-output',\n status: 'streaming',\n raw: nextRaw,\n ...(nextPartial !== undefined ? { partial: nextPartial } : {}),\n ...(existing?.reasoning !== undefined\n ? { reasoning: existing.reasoning }\n : {}),\n }\n\n if (existingIndex >= 0) {\n parts[existingIndex] = nextPart\n } else {\n parts.push(nextPart)\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Snap the structured-output part on `messageId` to `complete` with the\n * validated `data`. Picks the freshest available `raw` so the wire\n * round-trip stays internally consistent:\n *\n * 1. Caller-supplied `raw` (the original streamed bytes from the model).\n * 2. The existing part's `raw` (deltas accumulated before this terminal).\n * 3. `JSON.stringify(data)` as a defensive fallback for terminal-only\n * completes that never shipped raw — keeps the part self-consistent\n * so downstream consumers never see a complete part with empty raw.\n */\nexport function completeStructuredOutputPart(\n messages: Array<UIMessage>,\n messageId: string,\n data: unknown,\n raw: string,\n reasoning?: string,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const existingIndex = parts.findIndex(\n (p): p is StructuredOutputPart => p.type === 'structured-output',\n )\n\n const existingRaw =\n existingIndex >= 0\n ? (parts[existingIndex] as StructuredOutputPart).raw\n : ''\n let resolvedRaw = raw || existingRaw\n if (resolvedRaw === '' && data !== undefined) {\n try {\n resolvedRaw = JSON.stringify(data)\n } catch {\n // Unserializable (circular, BigInt, throwing toJSON). Leave raw\n // empty. Both downstream paths handle this: `ag-ui-wire.ts`\n // `collectText` skips complete parts with empty raw entirely, and\n // `uiMessageToModelMessages` falls back to a defensive\n // `safeJsonStringify(data)` which itself returns `''` for the same\n // unserializable inputs — so the turn is silently dropped from the\n // next request rather than shipping garbage or crashing the stream.\n }\n }\n\n const nextPart: StructuredOutputPart = {\n type: 'structured-output',\n status: 'complete',\n data,\n partial: data,\n raw: resolvedRaw,\n ...(reasoning !== undefined ? { reasoning } : {}),\n }\n\n if (existingIndex >= 0) {\n parts[existingIndex] = nextPart\n } else {\n parts.push(nextPart)\n }\n\n return { ...msg, parts }\n })\n}\n\n/**\n * Mark the structured-output part on `messageId` as errored. If no part\n * exists yet — RUN_ERROR fired after `structured-output.start` but before\n * any delta — create an empty errored placeholder so consumers have\n * something renderable. Existing complete parts are left alone (an error\n * after a successful complete should not retroactively un-complete it).\n */\nexport function errorStructuredOutputPart(\n messages: Array<UIMessage>,\n messageId: string,\n errorMessage: string,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n const existingIndex = parts.findIndex(\n (p): p is StructuredOutputPart => p.type === 'structured-output',\n )\n\n if (existingIndex < 0) {\n parts.push({\n type: 'structured-output',\n status: 'error',\n raw: '',\n errorMessage,\n })\n return { ...msg, parts }\n }\n\n const existing = parts[existingIndex] as StructuredOutputPart\n if (existing.status === 'complete') {\n return msg\n }\n parts[existingIndex] = {\n ...existing,\n status: 'error',\n errorMessage,\n }\n return { ...msg, parts }\n })\n}\n\n/**\n * Update or add a thinking part to a message, keyed by stepId.\n * Each distinct stepId produces its own ThinkingPart.\n */\nexport function updateThinkingPart(\n messages: Array<UIMessage>,\n messageId: string,\n stepId: string,\n content: string,\n signature?: string,\n): Array<UIMessage> {\n return messages.map((msg) => {\n if (msg.id !== messageId) {\n return msg\n }\n\n const parts = [...msg.parts]\n let thinkingPartIndex = parts.findIndex(\n (p) => p.type === 'thinking' && p.stepId === stepId,\n )\n\n // A hydrated message carries its thinking without a stepId: the stored form\n // has no field for one, so `modelMessageToUIMessage` cannot put it back.\n // When a run is rejoined mid-stream the replayed reasoning is keyed by\n // stepId, matches nothing, and gets appended -- leaving a second thinking\n // part sitting after the answer text. Adopt the first stepId-less thinking\n // part instead, so the replay lands on the part it belongs to. Live\n // streaming always writes a stepId, so the only parts this can match are\n // hydrated ones.\n let adopted: ThinkingPart | undefined\n if (thinkingPartIndex < 0) {\n thinkingPartIndex = parts.findIndex(\n (p) => p.type === 'thinking' && p.stepId === undefined,\n )\n const candidate = parts[thinkingPartIndex]\n if (candidate?.type === 'thinking') adopted = candidate\n }\n\n // Keep the signature the hydrated part already had when this update does\n // not carry one; losing it would strip the provider's encrypted reasoning\n // from a message that is about to be sent back.\n const nextSignature = signature ?? adopted?.signature\n // A hydrated part has no stepId to carry the redacted marker, so it keeps\n // its own flag.\n const redacted = isRedactedThinkingId(stepId) || adopted?.redacted === true\n\n const thinkingPart: ThinkingPart = {\n type: 'thinking',\n content,\n stepId,\n ...(nextSignature && { signature: nextSignature }),\n ...(redacted && { redacted: true }),\n }\n\n if (thinkingPartIndex >= 0) {\n // Update existing thinking part for this step\n parts[thinkingPartIndex] = thinkingPart\n } else {\n // Add new thinking part at the end (preserve natural streaming order)\n parts.push(thinkingPart)\n }\n\n return { ...msg, parts }\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;AA0BA,SAAgB,eACd,UACA,WACA,SACkB;CAClB,OAAO,SAAS,KAAK,QAAQ;EAC3B,IAAI,IAAI,OAAO,WACb,OAAO;EAGT,MAAM,QAAQ,CAAC,GAAG,IAAI,KAAK;EAC3B,MAAM,WAAW,MAAM,SAAS,IAAI,MAAM,MAAM,SAAS,KAAK;EAE9D,IAAI,YAAY,SAAS,SAAS,QAEhC,MAAM,MAAM,SAAS,KAAK;GAAE,MAAM;GAAQ;EAAQ;OAGlD,MAAM,KAAK;GAAE,MAAM;GAAQ;EAAQ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AM,WAAW,qBAAqB,MAAM,KAAK,SAAS,aAAa;EAEvE,MAAM,eAA6B;GACjC,MAAM;GACN;GACA;GACA,GAAI,iBAAiB,EAAE,WAAW,cAAc;GAChD,GAAI,YAAY,EAAE,UAAU,KAAK;EACnC;EAEA,IAAI,qBAAqB,GAEvB,MAAM,qBAAqB;OAG3B,MAAM,KAAK,YAAY;EAGzB,OAAO;GAAE,GAAG;GAAK;EAAM;CACzB,CAAC;AACH"}
@@ -25,6 +25,14 @@ export interface ConvertSchemaOptions {
25
25
  * @default false
26
26
  */
27
27
  forStructuredOutput?: boolean;
28
+ /**
29
+ * Which view of a Standard JSON Schema to convert. A schema with a
30
+ * transform or a pipe has a different `output` view. Use `'output'` to
31
+ * describe the value that parsing returns.
32
+ *
33
+ * @default 'input'
34
+ */
35
+ io?: 'input' | 'output';
28
36
  }
29
37
  /**
30
38
  * Converts a Standard JSON Schema compliant schema or plain JSONSchema to JSON Schema format
@@ -151,16 +151,17 @@ function makeStructuredOutputCompatible(schema, originalRequired = []) {
151
151
  *
152
152
  * - Standard JSON Schemas are rebuilt structurally (dropping `$schema`, which
153
153
  * LLM providers ignore) and given the explicit `type`/`properties`/`required`
154
- * defaults object shapes need downstream.
154
+ * defaults object shapes need downstream. `io` picks the `input` (default)
155
+ * or `output` view.
155
156
  * - Plain `JSONSchema` inputs are rebuilt into the typed view; non-object inputs
156
157
  * are surfaced untouched (they can't be widened).
157
158
  * - Standard Schema validators lacking a `~standard.jsonSchema` converter throw
158
159
  * with actionable guidance, rather than shipping `{ '~standard': … }` to the
159
160
  * provider and producing an opaque downstream error.
160
161
  */
161
- function toTypedJsonSchema(schema) {
162
+ function toTypedJsonSchema(schema, io = "input") {
162
163
  if (isStandardJSONSchema(schema)) {
163
- const result = toJsonSchema(schema["~standard"].jsonSchema.input({ target: "draft-07" }));
164
+ const result = toJsonSchema(schema["~standard"].jsonSchema[io]({ target: "draft-07" }));
164
165
  if ("properties" in result && !result.type) result.type = "object";
165
166
  if (result.type === "object" && !("properties" in result)) result.properties = {};
166
167
  if (result.type === "object" && !("required" in result)) result.required = [];
@@ -232,9 +233,9 @@ function toTypedJsonSchema(schema) {
232
233
  */
233
234
  function convertSchemaToJsonSchema(schema, options = {}) {
234
235
  if (!schema) return void 0;
235
- const { forStructuredOutput = false } = options;
236
+ const { forStructuredOutput = false, io } = options;
236
237
  if (!forStructuredOutput && !isStandardJSONSchema(schema) && !isStandardSchema(schema)) return schema;
237
- const base = toTypedJsonSchema(schema);
238
+ const base = toTypedJsonSchema(schema, io);
238
239
  if (!base || typeof base !== "object") return base;
239
240
  if (!forStructuredOutput) return base;
240
241
  return makeStructuredOutputCompatible(base, base.required || []).schema;