@tanstack/ai 0.59.0 → 0.63.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.
- package/README.md +1 -0
- package/dist/esm/activities/chat/adapter.d.ts +9 -0
- package/dist/esm/activities/chat/adapter.js +1 -0
- package/dist/esm/activities/chat/adapter.js.map +1 -1
- package/dist/esm/activities/chat/agents/define-agent.d.ts +17 -5
- package/dist/esm/activities/chat/agents/define-agent.js.map +1 -1
- package/dist/esm/activities/chat/agents/spawn.d.ts +2 -0
- package/dist/esm/activities/chat/agents/spawn.js +8 -5
- package/dist/esm/activities/chat/agents/spawn.js.map +1 -1
- package/dist/esm/activities/chat/index.js +289 -78
- package/dist/esm/activities/chat/index.js.map +1 -1
- package/dist/esm/activities/chat/messages.js +35 -19
- package/dist/esm/activities/chat/messages.js.map +1 -1
- package/dist/esm/activities/chat/middleware/types.d.ts +1 -0
- package/dist/esm/activities/chat/middleware/types.js.map +1 -1
- package/dist/esm/activities/chat/stream/message-updaters.d.ts +2 -2
- package/dist/esm/activities/chat/stream/message-updaters.js +11 -3
- package/dist/esm/activities/chat/stream/message-updaters.js.map +1 -1
- package/dist/esm/activities/chat/stream/processor.d.ts +11 -10
- package/dist/esm/activities/chat/stream/processor.js +51 -28
- package/dist/esm/activities/chat/stream/processor.js.map +1 -1
- package/dist/esm/activities/chat/tools/tool-calls.d.ts +16 -2
- package/dist/esm/activities/chat/tools/tool-calls.js +57 -16
- package/dist/esm/activities/chat/tools/tool-calls.js.map +1 -1
- package/dist/esm/activities/chat/tools/tool-definition.d.ts +4 -0
- package/dist/esm/activities/chat/tools/tool-definition.js +4 -0
- package/dist/esm/activities/chat/tools/tool-definition.js.map +1 -1
- package/dist/esm/activities/embed/adapter.d.ts +7 -0
- package/dist/esm/activities/embed/adapter.js +1 -0
- package/dist/esm/activities/embed/adapter.js.map +1 -1
- package/dist/esm/activities/embed/index.js +2 -0
- package/dist/esm/activities/embed/index.js.map +1 -1
- package/dist/esm/activities/evaluate/adapter.d.ts +4 -0
- package/dist/esm/activities/evaluate/adapter.js.map +1 -1
- package/dist/esm/activities/evaluate/index.d.ts +4 -0
- package/dist/esm/activities/evaluate/index.js +3 -1
- package/dist/esm/activities/evaluate/index.js.map +1 -1
- package/dist/esm/activities/files/adapter.d.ts +97 -0
- package/dist/esm/activities/files/adapter.js +45 -0
- package/dist/esm/activities/files/adapter.js.map +1 -0
- package/dist/esm/activities/files/index.d.ts +66 -0
- package/dist/esm/activities/files/index.js +78 -0
- package/dist/esm/activities/files/index.js.map +1 -0
- package/dist/esm/activities/generateImage/adapter.d.ts +8 -0
- package/dist/esm/activities/generateImage/adapter.js +1 -0
- package/dist/esm/activities/generateImage/adapter.js.map +1 -1
- package/dist/esm/activities/generateImage/index.js +2 -0
- package/dist/esm/activities/generateImage/index.js.map +1 -1
- package/dist/esm/activities/generateVideo/adapter.d.ts +8 -0
- package/dist/esm/activities/generateVideo/adapter.js +1 -0
- package/dist/esm/activities/generateVideo/adapter.js.map +1 -1
- package/dist/esm/activities/generateVideo/index.js +3 -0
- package/dist/esm/activities/generateVideo/index.js.map +1 -1
- package/dist/esm/activities/generateWorld/adapter.d.ts +4 -2
- package/dist/esm/activities/generateWorld/adapter.js.map +1 -1
- package/dist/esm/activities/generateWorld/index.d.ts +4 -3
- package/dist/esm/activities/generateWorld/index.js +5 -4
- package/dist/esm/activities/generateWorld/index.js.map +1 -1
- package/dist/esm/activities/index.d.ts +6 -3
- package/dist/esm/activities/index.js +13 -11
- package/dist/esm/activities/summarize/chat-stream-summarize.d.ts +2 -0
- package/dist/esm/activities/summarize/chat-stream-summarize.js +8 -8
- package/dist/esm/activities/summarize/chat-stream-summarize.js.map +1 -1
- package/dist/esm/client.d.ts +3 -1
- package/dist/esm/client.js +2 -1
- package/dist/esm/client.js.map +1 -1
- package/dist/esm/index.d.ts +4 -3
- package/dist/esm/index.js +5 -3
- package/dist/esm/interrupt-resume.js +29 -4
- package/dist/esm/interrupt-resume.js.map +1 -1
- package/dist/esm/middlewares/otel.d.ts +5 -2
- package/dist/esm/middlewares/otel.js +114 -0
- package/dist/esm/middlewares/otel.js.map +1 -1
- package/dist/esm/types.d.ts +114 -14
- package/dist/esm/utilities/ag-ui-wire.js +39 -16
- package/dist/esm/utilities/ag-ui-wire.js.map +1 -1
- package/dist/esm/utilities/content-source.d.ts +60 -0
- package/dist/esm/utilities/content-source.js +85 -0
- package/dist/esm/utilities/content-source.js.map +1 -0
- package/dist/esm/utilities/provider-executed.d.ts +7 -0
- package/dist/esm/utilities/provider-executed.js +10 -1
- package/dist/esm/utilities/provider-executed.js.map +1 -1
- package/dist/esm/utilities/tool-result.d.ts +14 -3
- package/dist/esm/utilities/tool-result.js +26 -3
- package/dist/esm/utilities/tool-result.js.map +1 -1
- package/package.json +4 -4
- package/skills/ai-core/adapter-configuration/SKILL.md +62 -0
- package/skills/ai-core/chat-experience/SKILL.md +134 -0
- package/skills/ai-core/media-generation/SKILL.md +8 -0
- package/skills/ai-core/tool-calling/SKILL.md +103 -0
- package/src/activities/chat/adapter.ts +10 -0
- package/src/activities/chat/agents/define-agent.ts +20 -3
- package/src/activities/chat/agents/spawn.ts +20 -12
- package/src/activities/chat/index.ts +458 -99
- package/src/activities/chat/messages.ts +52 -6
- package/src/activities/chat/middleware/types.ts +1 -0
- package/src/activities/chat/stream/message-updaters.ts +27 -2
- package/src/activities/chat/stream/processor.ts +81 -49
- package/src/activities/chat/tools/tool-calls.ts +104 -9
- package/src/activities/chat/tools/tool-definition.ts +8 -0
- package/src/activities/embed/adapter.ts +7 -0
- package/src/activities/embed/index.ts +5 -0
- package/src/activities/evaluate/adapter.ts +4 -0
- package/src/activities/evaluate/index.ts +6 -0
- package/src/activities/files/adapter.ts +120 -0
- package/src/activities/files/index.ts +113 -0
- package/src/activities/generateImage/adapter.ts +8 -0
- package/src/activities/generateImage/index.ts +4 -0
- package/src/activities/generateVideo/adapter.ts +8 -0
- package/src/activities/generateVideo/index.ts +7 -0
- package/src/activities/generateWorld/adapter.ts +4 -2
- package/src/activities/generateWorld/index.ts +7 -6
- package/src/activities/index.ts +25 -1
- package/src/activities/summarize/chat-stream-summarize.ts +22 -12
- package/src/client.ts +8 -0
- package/src/index.ts +17 -0
- package/src/interrupt-resume.ts +55 -4
- package/src/middlewares/otel.ts +161 -3
- package/src/types.ts +114 -14
- package/src/utilities/ag-ui-wire.ts +72 -17
- package/src/utilities/content-source.ts +138 -0
- package/src/utilities/provider-executed.ts +13 -0
- package/src/utilities/tool-result.ts +45 -3
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { tanstackMetadata } from "../../utilities/merge-metadata.js";
|
|
2
|
-
import {
|
|
1
|
+
import { tanstackMetadata, withTanstackMetadata } from "../../utilities/merge-metadata.js";
|
|
2
|
+
import { isAssistantSegmentOf, isProviderExecutedToolCall } from "../../utilities/provider-executed.js";
|
|
3
|
+
import { isContentPartArray, isToolResultOutcome, normalizeToolResult } from "../../utilities/tool-result.js";
|
|
3
4
|
import { splitSubagentWire, subagentWireText } from "../../utilities/subagent-wire.js";
|
|
4
|
-
import { isProviderExecutedToolCall } from "../../utilities/provider-executed.js";
|
|
5
5
|
//#region src/activities/chat/messages.ts
|
|
6
6
|
function isRecord(value) {
|
|
7
7
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -351,6 +351,7 @@ function assistantMetadata(uiMessage) {
|
|
|
351
351
|
const tanstack = {};
|
|
352
352
|
if (previous?.model !== void 0) tanstack.model = previous.model;
|
|
353
353
|
if (previous?.runId !== void 0) tanstack.runId = previous.runId;
|
|
354
|
+
if (previous?.run?.id !== void 0) tanstack.run = { id: previous.run.id };
|
|
354
355
|
if (previous?.signature !== void 0) tanstack.signature = previous.signature;
|
|
355
356
|
if (fromParts.length > 0) tanstack.uiResources = fromParts;
|
|
356
357
|
const result = { ...current };
|
|
@@ -471,6 +472,7 @@ function buildAssistantMessages(uiMessage) {
|
|
|
471
472
|
case "tool-result":
|
|
472
473
|
flushSegment(messageList.length === 0);
|
|
473
474
|
if ((part.state === "complete" || part.state === "error") && !emittedToolResultIds.has(part.toolCallId)) {
|
|
475
|
+
const metadata = part.outcome === void 0 ? part.metadata : withTanstackMetadata(part, { toolResultOutcome: part.outcome }).metadata;
|
|
474
476
|
messageList.push({
|
|
475
477
|
...part.id !== void 0 && { id: part.id },
|
|
476
478
|
...optionalCreatedAt(part),
|
|
@@ -478,7 +480,7 @@ function buildAssistantMessages(uiMessage) {
|
|
|
478
480
|
content: part.content,
|
|
479
481
|
toolCallId: part.toolCallId,
|
|
480
482
|
...part.name !== void 0 && { name: part.name },
|
|
481
|
-
...
|
|
483
|
+
...metadata !== void 0 && { metadata },
|
|
482
484
|
...part.error !== void 0 && { error: part.error }
|
|
483
485
|
});
|
|
484
486
|
emittedToolResultIds.add(part.toolCallId);
|
|
@@ -538,7 +540,8 @@ function buildAssistantMessages(uiMessage) {
|
|
|
538
540
|
...approved && { pendingExecution: true },
|
|
539
541
|
message: approved ? "User approved this action" : "User denied this action"
|
|
540
542
|
}),
|
|
541
|
-
toolCallId: part.id
|
|
543
|
+
toolCallId: part.id,
|
|
544
|
+
...approved === false && { metadata: { tanstack: { toolResultOutcome: "denied" } } }
|
|
542
545
|
});
|
|
543
546
|
emittedToolResultIds.add(part.id);
|
|
544
547
|
}
|
|
@@ -584,18 +587,23 @@ function modelMessageToUIMessage(modelMessage, id) {
|
|
|
584
587
|
});
|
|
585
588
|
}
|
|
586
589
|
parts.push(structuredOutput);
|
|
587
|
-
} else if (modelMessage.role === "tool" && modelMessage.toolCallId)
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
590
|
+
} else if (modelMessage.role === "tool" && modelMessage.toolCallId) {
|
|
591
|
+
const rawToolResultOutcome = tanstackMetadata(modelMessage)?.toolResultOutcome;
|
|
592
|
+
const toolResultOutcome = isToolResultOutcome(rawToolResultOutcome) ? rawToolResultOutcome : void 0;
|
|
593
|
+
const resultState = modelMessage.error === void 0 && toolResultOutcome === void 0 ? "complete" : "error";
|
|
594
|
+
parts.push({
|
|
595
|
+
type: "tool-result",
|
|
596
|
+
toolCallId: modelMessage.toolCallId,
|
|
597
|
+
content: toolResultContent(modelMessage.content),
|
|
598
|
+
state: resultState,
|
|
599
|
+
...toolResultOutcome !== void 0 && { outcome: toolResultOutcome },
|
|
600
|
+
...modelMessage.id !== void 0 && { id: modelMessage.id },
|
|
601
|
+
...modelMessage.name !== void 0 && { name: modelMessage.name },
|
|
602
|
+
...modelMessage.metadata !== void 0 && { metadata: modelMessage.metadata },
|
|
603
|
+
...createdAt !== void 0 && { createdAt },
|
|
604
|
+
...modelMessage.error !== void 0 && { error: modelMessage.error }
|
|
605
|
+
});
|
|
606
|
+
} else if (Array.isArray(modelMessage.content)) for (const part of modelMessage.content) parts.push(part);
|
|
599
607
|
else {
|
|
600
608
|
const textContent = getTextContent(modelMessage.content);
|
|
601
609
|
if (textContent) parts.push({
|
|
@@ -810,16 +818,20 @@ function modelMessagesToUIMessages(modelMessages) {
|
|
|
810
818
|
for (const msg of modelMessages) if (msg.role === "tool") {
|
|
811
819
|
if (msg.toolCallId !== void 0 && currentAssistantMessage && currentAssistantMessage.role === "assistant") {
|
|
812
820
|
const content = toolResultContent(msg.content);
|
|
821
|
+
const rawToolResultOutcome = tanstackMetadata(msg)?.toolResultOutcome;
|
|
822
|
+
const toolResultOutcome = isToolResultOutcome(rawToolResultOutcome) ? rawToolResultOutcome : void 0;
|
|
823
|
+
const resultState = msg.error === void 0 && toolResultOutcome === void 0 ? "complete" : "error";
|
|
813
824
|
const toolCallPart = currentAssistantMessage.parts.find((part) => part.type === "tool-call" && part.id === msg.toolCallId);
|
|
814
825
|
if (toolCallPart) {
|
|
815
826
|
toolCallPart.output = typeof content === "string" ? parseToolResultContent(content) : content;
|
|
816
|
-
toolCallPart.state =
|
|
827
|
+
toolCallPart.state = resultState;
|
|
817
828
|
}
|
|
818
829
|
currentAssistantMessage.parts.push({
|
|
819
830
|
type: "tool-result",
|
|
820
831
|
toolCallId: msg.toolCallId,
|
|
821
832
|
content,
|
|
822
|
-
state:
|
|
833
|
+
state: resultState,
|
|
834
|
+
...toolResultOutcome !== void 0 && { outcome: toolResultOutcome },
|
|
823
835
|
...msg.id !== void 0 && msg.id !== currentAssistantMessage.id && { id: msg.id },
|
|
824
836
|
...msg.name !== void 0 && { name: msg.name },
|
|
825
837
|
...msg.metadata !== void 0 && { metadata: msg.metadata },
|
|
@@ -832,6 +844,10 @@ function modelMessagesToUIMessages(modelMessages) {
|
|
|
832
844
|
}
|
|
833
845
|
} else {
|
|
834
846
|
const uiMessage = modelMessageToUIMessage(msg, msg.id);
|
|
847
|
+
if (msg.role === "assistant" && currentAssistantMessage && isAssistantSegmentOf(msg.id, currentAssistantMessage.id)) {
|
|
848
|
+
currentAssistantMessage.parts.push(...uiMessage.parts);
|
|
849
|
+
continue;
|
|
850
|
+
}
|
|
835
851
|
uiMessages.push(uiMessage);
|
|
836
852
|
if (msg.role === "assistant") currentAssistantMessage = uiMessage;
|
|
837
853
|
else currentAssistantMessage = null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.js","names":[],"sources":["../../../../src/activities/chat/messages.ts"],"sourcesContent":["import { isProviderExecutedToolCall } from '../../utilities/provider-executed'\nimport {\n isContentPartArray,\n normalizeToolResult,\n} from '../../utilities/tool-result'\nimport { tanstackMetadata } from '../../utilities/merge-metadata'\nimport {\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// 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?.signature !== undefined) tanstack.signature = previous.signature\n if (fromParts.length > 0) tanstack.uiResources = fromParts\n const result = { ...current }\n if (Object.keys(tanstack).length > 0) result.tanstack = tanstack\n else delete result.tanstack\n return Object.keys(result).length > 0 ? result : undefined\n}\n\n/**\n * Convert a UIMessage to ModelMessage(s)\n *\n * Walks the parts array IN ORDER to preserve the interleaving of text,\n * tool calls, and tool results. This is critical for multi-round tool\n * flows where the model generates text, calls a tool, gets the result,\n * then generates more text and calls another tool.\n *\n * The output preserves the sequential structure:\n * text1 → toolCall1 → toolResult1 → text2 → toolCall2 → toolResult2\n * becomes:\n * assistant: {content: \"text1\", toolCalls: [toolCall1]}\n * tool: toolResult1\n * assistant: {content: \"text2\", toolCalls: [toolCall2]}\n * tool: toolResult2\n *\n * @param uiMessage - The UIMessage to convert\n * @returns An array of ModelMessages preserving part ordering\n */\nexport function uiMessageToModelMessages(\n uiMessage: UIMessage,\n): Array<ModelMessage> {\n // Skip system messages - they're handled via systemPrompts, not ModelMessages\n if (uiMessage.role === 'system') {\n return []\n }\n\n // For non-assistant messages (user), use the simpler path since they\n // don't have tool calls or tool results to interleave\n if (uiMessage.role !== 'assistant') {\n return [buildUserOrToolMessage(uiMessage)]\n }\n\n // For assistant messages, walk parts in order to preserve interleaving\n return buildAssistantMessages(uiMessage)\n}\n\n/**\n * Build a single ModelMessage for user messages (simple path).\n * Preserves ordering of text and multimodal content parts.\n */\nfunction buildUserOrToolMessage(uiMessage: UIMessage): ModelMessage {\n const contentParts: Array<ContentPart> = []\n for (const part of uiMessage.parts) {\n if (isContentPart(part)) {\n contentParts.push(part)\n }\n }\n\n return {\n id: uiMessage.id,\n role: uiMessage.role as 'user' | 'assistant' | 'tool',\n content: collapseContentParts(contentParts),\n ...optionalName(uiMessage),\n ...optionalCreatedAt(uiMessage),\n ...(uiMessage.metadata !== undefined && { metadata: uiMessage.metadata }),\n }\n}\n\n// Accumulator for building an assistant segment (content + tool calls)\ninterface AssistantSegment {\n contentParts: Array<ContentPart>\n structuredOutput?: StructuredOutputPart\n toolCalls: Array<{\n id: string\n type: 'function'\n function: { name: string; arguments: string }\n /** Provider-specific metadata that round-trips with the tool call.\n * Untyped at this framework layer; adapters narrow it via their\n * `TToolCallMetadata` generic. */\n metadata?: unknown\n }>\n}\n\nfunction createSegment(): AssistantSegment {\n return { contentParts: [], toolCalls: [] }\n}\n\nfunction isToolCallIncluded(part: ToolCallPart): boolean {\n return (\n part.state === 'input-complete' ||\n part.state === 'complete' ||\n part.state === 'approval-requested' ||\n part.state === 'approval-responded' ||\n part.state === 'error' ||\n part.output !== undefined\n )\n}\n\n/**\n * Build ModelMessages for an assistant UIMessage, preserving the\n * sequential interleaving of text, tool calls, and tool results.\n *\n * Walks parts in order. Text and tool-call parts accumulate into the\n * current \"segment\". When a tool-result part is encountered, the\n * current segment is flushed as an assistant message, then the tool\n * result is emitted as a tool message.\n */\nfunction buildAssistantMessages(uiMessage: UIMessage): Array<ModelMessage> {\n // A single UI message can fan out into several model messages. Keep the\n // shared UI id on each one so persistence can retain the original identity.\n const messageList: Array<ModelMessage> = []\n let current = createSegment()\n let pendingThinking: Array<{ content: string; signature?: string }> = []\n\n // Track emitted tool result IDs to avoid duplicates.\n // A tool call can have BOTH an explicit tool-result part AND an output\n // field on the tool-call part. We only want one per tool call ID.\n const emittedToolResultIds = new Set<string>()\n const identityFields = {\n id: uiMessage.id,\n ...optionalName(uiMessage),\n ...optionalCreatedAt(uiMessage),\n }\n const metadata = assistantMetadata(uiMessage)\n const assistantFields = {\n ...identityFields,\n ...(metadata !== undefined && { metadata }),\n }\n\n function flushSegment(force = false): void {\n const content = collapseContentParts(current.contentParts)\n const hasContent = content !== null\n const hasToolCalls = current.toolCalls.length > 0\n const hasThinking = pendingThinking.length > 0\n\n if (force || hasContent || hasToolCalls || hasThinking) {\n messageList.push({\n ...assistantFields,\n role: 'assistant',\n content,\n ...(hasToolCalls && { toolCalls: current.toolCalls }),\n ...(hasThinking && { thinking: pendingThinking }),\n ...(current.structuredOutput && {\n structuredOutput: current.structuredOutput,\n }),\n })\n pendingThinking = []\n }\n current = createSegment()\n }\n\n for (const part of uiMessage.parts) {\n switch (part.type) {\n case 'text':\n case 'image':\n case 'audio':\n case 'video':\n case 'document':\n current.contentParts.push(part)\n break\n\n case 'tool-call':\n if (isToolCallIncluded(part)) {\n current.toolCalls.push({\n id: part.id,\n type: 'function' as const,\n function: {\n name: part.name,\n arguments: part.arguments,\n },\n ...(part.metadata !== undefined && { metadata: part.metadata }),\n })\n }\n break\n\n case 'tool-result':\n // Flush the current assistant segment before emitting the tool result\n flushSegment(messageList.length === 0)\n\n // Emit the tool result\n if (\n (part.state === 'complete' || part.state === 'error') &&\n !emittedToolResultIds.has(part.toolCallId)\n ) {\n messageList.push({\n ...(part.id !== undefined && { id: part.id }),\n ...optionalCreatedAt(part),\n role: 'tool',\n content: part.content,\n toolCallId: part.toolCallId,\n ...(part.name !== undefined && { name: part.name }),\n ...(part.metadata !== undefined && { metadata: part.metadata }),\n ...(part.error !== undefined && { error: part.error }),\n })\n emittedToolResultIds.add(part.toolCallId)\n }\n break\n\n case 'thinking':\n if (part.content || part.signature) {\n // Provider-executed tools have no tool-result part, so thinking\n // after them has to start the next segment or it replays first.\n if (current.toolCalls.some(isProviderExecutedToolCall)) {\n flushSegment()\n }\n pendingThinking.push({\n content: part.content,\n ...(part.signature && { signature: part.signature }),\n })\n }\n break\n\n case 'structured-output':\n // Only emit completed structured responses into history. Streaming or\n // errored buffers would push malformed JSON into the next LLM turn's\n // assistant content. `raw` is the source of truth; `data` is the\n // defensive fallback for terminal-only completes that didn't ship raw.\n if (part.status === 'complete') {\n const serialized =\n part.raw !== ''\n ? part.raw\n : part.data !== undefined\n ? safeJsonStringify(part.data)\n : ''\n if (serialized !== '') {\n current.contentParts.push({ type: 'text', content: serialized })\n current.structuredOutput = part\n }\n }\n break\n\n case 'ui-resource':\n // MCP Apps widget — rendered client-side only. It must never enter\n // model input, so it is intentionally dropped from the model message.\n break\n\n 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 })\n emittedToolResultIds.add(part.id)\n }\n }\n\n // If no messages were produced (e.g., empty parts), emit a minimal assistant message\n if (messageList.length === 0) {\n messageList.push({\n ...assistantFields,\n role: 'assistant',\n content: null,\n })\n }\n\n return messageList\n}\n\n/**\n * Convert a ModelMessage to UIMessage\n *\n * This conversion creates a parts-based structure:\n * - content field → TextPart\n * - toolCalls array → ToolCallPart[]\n * - role=\"tool\" messages should be converted separately and merged\n *\n * @param modelMessage - The ModelMessage to convert\n * @param id - Optional ID for the UIMessage (generated if not provided)\n * @returns A UIMessage with parts\n */\nexport function modelMessageToUIMessage(\n modelMessage: ModelMessage,\n id?: string,\n): UIMessage {\n const parts: Array<MessagePart> = []\n const createdAt = coerceCreatedAt(modelMessage.createdAt)\n\n if (modelMessage.role === 'assistant' && modelMessage.thinking?.length) {\n for (const thinking of modelMessage.thinking) {\n if (!thinking.content && !thinking.signature) continue\n parts.push({\n type: 'thinking',\n content: thinking.content,\n ...(thinking.signature && { signature: thinking.signature }),\n })\n }\n }\n\n // Handle tool results (when role is \"tool\") - only produce tool-result part,\n // not a text part (the content IS the tool result, not display text)\n const structuredOutput =\n modelMessage.structuredOutput ??\n snapshotStructuredOutput(tanstackMetadata(modelMessage)?.structuredOutput)\n if (modelMessage.role === 'assistant' && structuredOutput) {\n if (\n typeof modelMessage.content === 'string' &&\n modelMessage.content &&\n modelMessage.content !== structuredOutput.raw\n ) {\n const suffix = structuredOutput.raw\n const text =\n suffix !== '' && modelMessage.content.endsWith(suffix)\n ? modelMessage.content.slice(0, -suffix.length)\n : modelMessage.content\n if (text) parts.push({ type: 'text', content: text })\n }\n parts.push(structuredOutput)\n } else if (modelMessage.role === 'tool' && modelMessage.toolCallId) {\n parts.push({\n type: 'tool-result',\n toolCallId: modelMessage.toolCallId,\n content: toolResultContent(modelMessage.content),\n state: modelMessage.error === undefined ? 'complete' : 'error',\n ...(modelMessage.id !== undefined && { id: modelMessage.id }),\n ...(modelMessage.name !== undefined && { name: modelMessage.name }),\n ...(modelMessage.metadata !== undefined && {\n metadata: modelMessage.metadata,\n }),\n ...(createdAt !== undefined && { createdAt }),\n ...(modelMessage.error !== undefined && { error: modelMessage.error }),\n })\n } else if (Array.isArray(modelMessage.content)) {\n // Multimodal content - preserve all content parts as MessageParts\n for (const part of modelMessage.content) {\n parts.push(part)\n }\n } else {\n // String or null content\n const textContent = getTextContent(modelMessage.content)\n if (textContent) {\n parts.push({\n type: 'text',\n content: textContent,\n })\n }\n }\n\n // Handle tool calls\n if (modelMessage.toolCalls && modelMessage.toolCalls.length > 0) {\n for (const toolCall of modelMessage.toolCalls) {\n // Model-message arguments are complete, so surface the parsed input.\n // A malformed arguments string just leaves `input` undefined.\n let input: unknown\n try {\n input = JSON.parse(toolCall.function.arguments)\n } catch {\n input = undefined\n }\n parts.push({\n type: 'tool-call',\n id: toolCall.id,\n name: toolCall.function.name,\n arguments: toolCall.function.arguments,\n state: 'input-complete', // Model messages have complete arguments\n ...(input !== undefined && { input }),\n ...(toolCall.metadata !== undefined && { metadata: toolCall.metadata }),\n })\n }\n }\n\n const ui: UIMessage = {\n id: id || generateMessageId(),\n role: modelMessage.role === 'tool' ? 'assistant' : modelMessage.role,\n parts,\n ...optionalName(modelMessage),\n ...(createdAt !== undefined && { createdAt }),\n ...(modelMessage.metadata !== undefined && {\n metadata: modelMessage.metadata,\n }),\n }\n const storedResources = tanstackMetadata(modelMessage)?.uiResources\n return appendUiResources(\n ui,\n Array.isArray(storedResources)\n ? storedResources.filter(isUiResourcePart)\n : [],\n )\n}\n\n/**\n * Normalize a single AG-UI `MESSAGES_SNAPSHOT` message into a `UIMessage`.\n *\n * AG-UI snapshot messages use the wire shape `{ id, role, content }` and have\n * no `parts` array. Casting them directly to `UIMessage` is unsafe: any code\n * that later reads `message.parts` (e.g. the devtools `onToolCallStateChange`\n * handler) crashes with \"Cannot read properties of undefined (reading 'find')\".\n *\n * Each role is mapped to the canonical `UIMessage` shape, reusing\n * `modelMessageToUIMessage` for the roles that share `ModelMessage`'s structure.\n * The original AG-UI `id` is preserved so later `TEXT_MESSAGE_CONTENT` /\n * `TOOL_CALL_*` events still route by `messageId` (falling back to a generated\n * id only when the snapshot omits one). Messages that already carry `parts`\n * (e.g. a TanStack server echoing `UIMessage`s back over the wire) pass through\n * unchanged apart from ensuring an id.\n */\nexport function aguiSnapshotMessageToUIMessage(\n message: AGUIMessage | UIMessage,\n): UIMessage {\n if ('parts' in message) {\n return applySnapshotMetadata(message, {\n ...message,\n id: message.id || generateMessageId(),\n })\n }\n\n const id = message.id || generateMessageId()\n\n switch (message.role) {\n case 'user':\n return applySnapshotMetadata(message, {\n id,\n role: 'user',\n parts: aguiUserContentToParts(message.content),\n })\n case 'assistant': {\n const metadata = tanstackMetadata(message)\n const toolCallMetadata = metadata?.toolCallMetadata\n const structuredOutput = snapshotStructuredOutput(\n metadata?.structuredOutput,\n )\n const toolCalls = message.toolCalls?.map((toolCall) => {\n const callMetadata =\n toolCallMetadata != null && typeof toolCallMetadata === 'object'\n ? (toolCallMetadata as Record<string, unknown>)[toolCall.id]\n : undefined\n return callMetadata !== undefined\n ? { ...toolCall, metadata: callMetadata }\n : toolCall\n })\n return applySnapshotMetadata(\n message,\n modelMessageToUIMessage(\n {\n role: 'assistant',\n content: message.content ?? null,\n ...optionalName(message),\n ...(toolCalls && { toolCalls }),\n ...(structuredOutput && { structuredOutput }),\n },\n id,\n ),\n )\n }\n case 'tool': {\n message = restoreToolResultOwnership(message)\n const createdAt =\n coerceCreatedAt(\n 'createdAt' in message ? message.createdAt : undefined,\n ) ?? createdAtFromMetadata(message)\n return applySnapshotMetadata(\n message,\n modelMessageToUIMessage(\n {\n role: 'tool',\n content: 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 toolCallPart = currentAssistantMessage.parts.find(\n (part): part is ToolCallPart =>\n part.type === 'tool-call' && part.id === msg.toolCallId,\n )\n\n if (toolCallPart) {\n toolCallPart.output =\n typeof content === 'string'\n ? parseToolResultContent(content)\n : content\n toolCallPart.state = msg.error === undefined ? 'complete' : 'error'\n }\n\n currentAssistantMessage.parts.push({\n type: 'tool-result',\n toolCallId: msg.toolCallId,\n content,\n state: msg.error === undefined ? 'complete' : 'error',\n ...(msg.id !== undefined &&\n msg.id !== currentAssistantMessage.id && { id: msg.id }),\n ...(msg.name !== undefined && { name: msg.name }),\n ...(msg.metadata !== undefined && { metadata: msg.metadata }),\n ...optionalCreatedAt(msg),\n ...(msg.error !== undefined && { error: msg.error }),\n })\n } else {\n // No assistant message to merge into, create a standalone one\n const toolResultUIMessage = modelMessageToUIMessage(msg, msg.id)\n uiMessages.push(toolResultUIMessage)\n }\n } else {\n // Regular message. Preserve a persisted stable id so a hydrated message\n // keeps the same identity as its live stream (enables in-place resume).\n const uiMessage = modelMessageToUIMessage(msg, msg.id)\n uiMessages.push(uiMessage)\n\n // Track assistant messages for potential tool result merging\n if (msg.role === 'assistant') {\n currentAssistantMessage = uiMessage\n } else {\n currentAssistantMessage = null\n }\n }\n }\n\n return uiMessages\n}\n\n/**\n * Normalize a message (UIMessage or ModelMessage) to a UIMessage\n * Ensures the message has an ID and createdAt timestamp\n *\n * @param message - Either a UIMessage or ModelMessage\n * @param generateId - Function to generate a message ID if needed\n * @returns A UIMessage with guaranteed id and createdAt\n */\nexport function normalizeToUIMessage(\n message: UIMessage | ModelMessage,\n generateId: () => string,\n): UIMessage {\n if ('parts' in message) {\n // Already a UIMessage\n const parts = message.parts.map((part) => normalizeMessagePart(part))\n return {\n ...message,\n parts,\n id: message.id || generateId(),\n createdAt: coerceCreatedAt(message.createdAt) ?? new Date(),\n }\n } else {\n // ModelMessage - convert to UIMessage\n return {\n ...modelMessageToUIMessage(message, generateId()),\n createdAt: coerceCreatedAt(message.createdAt) ?? new Date(),\n }\n }\n}\n\n/**\n * Generate a unique message ID\n */\nexport function generateMessageId(): string {\n return `msg-${Date.now()}-${Math.random().toString(36).substring(7)}`\n}\n"],"mappings":";;;;;AAyBA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;;;;AASA,SAAS,cAAc,MAAwC;CAC7D,OACE,KAAK,SAAS,UACd,KAAK,SAAS,WACd,KAAK,SAAS,WACd,KAAK,SAAS,WACd,KAAK,SAAS;AAElB;AAEA,SAAgB,kBAAkB,OAAwB;CACxD,IAAI;EACF,OAAO,KAAK,UAAU,KAAK,KAAK;CAClC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,eAAe,OAAoC;CAC1D,OAAO,OAAO,UAAU,YAAY,UAAU,KAAK,QAAQ,KAAA;AAC7D;AAEA,SAAS,mBAAmB,OAAmC;CAC7D,IAAI,oBAAoB,OAAO;EA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,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 {\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,QAA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|
approvals?: ReadonlyMap<string, ToolApprovalResolution> | undefined;
|
|
218
218
|
clientToolResults?: ReadonlyMap<string, unknown> | undefined;
|
|
219
|
+
clientToolErrors?: ReadonlyMap<string, string> | undefined;
|
|
219
220
|
genericInterrupts?: ReadonlyMap<string, ChatResumeGenericResolution> | undefined;
|
|
220
221
|
/** Durable generic requests reconstructed by server middleware. */
|
|
221
222
|
genericInterruptRequests?: ReadonlyMap<string, GenericInterruptRequest<InterruptDefinition<any, any, any, any>>> | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../../../../../src/activities/chat/middleware/types.ts"],"sourcesContent":["import type {\n StandardJSONSchemaV1,\n StandardSchemaV1,\n} from '@standard-schema/spec'\nimport type {\n AgentLoopState,\n EmitCustomEventOptions,\n Interrupt,\n JSONSchema,\n ModelMessage,\n UIMessage,\n RunAgentResumeItem,\n StreamChunk,\n TokenUsage,\n Tool,\n ToolCall,\n} from '../../../types'\nimport type { SystemPrompt } from '../../../system-prompts'\nimport type { ToolApprovalResolution } from '../../../interrupts'\nimport type {\n GenericInterruptRequest,\n InterruptDefinition,\n} from '../../../interrupt-definition'\nimport type {\n Capability,\n CapabilityHandle,\n CapabilityRegistry,\n} from './capabilities'\n\n/** A file change observed inside a sandbox during a chat run. */\nexport interface SandboxFileEvent {\n type: 'create' | 'change' | 'delete'\n /** Absolute path inside the sandbox (under the workspace root). */\n path: string\n timestamp: number\n}\n\n/** The file event a sandbox hook receives: the serializable {@link SandboxFileEvent}\n * plus lazy, git-backed content accessors. Accessors compute on call, so a hook\n * that only reads `path`/`type` pays nothing. Never present on the serialized\n * `sandbox.file` CUSTOM chunk. */\nexport interface SandboxFileHookEvent extends SandboxFileEvent {\n /** Content at the session baseline (`''` for a new file or non-git workspace). */\n before: () => Promise<string>\n /** Current content (`''` when the event is a delete). */\n after: () => Promise<string>\n /** Unified patch vs the session baseline (synthesized add-patch when non-git). */\n diff: () => Promise<string>\n}\n\n/**\n * Sandbox file-event hooks a chat middleware can declare. Fire server-side for\n * every file create/change/delete observed in the sandbox during the run.\n */\nexport interface ChatSandboxHooks<TContext = unknown> {\n onFile?: (\n ctx: ChatMiddlewareContext<TContext>,\n e: SandboxFileHookEvent,\n ) => void | Promise<void>\n onFileCreate?: (\n ctx: ChatMiddlewareContext<TContext>,\n e: SandboxFileHookEvent,\n ) => void | Promise<void>\n onFileChange?: (\n ctx: ChatMiddlewareContext<TContext>,\n e: SandboxFileHookEvent,\n ) => void | Promise<void>\n onFileDelete?: (\n ctx: ChatMiddlewareContext<TContext>,\n e: SandboxFileHookEvent,\n ) => void | Promise<void>\n}\n\n// ===========================\n// Middleware Context\n// ===========================\n\n/**\n * Phase of the chat middleware lifecycle.\n * - 'init': Initial config transform before the chat engine starts\n * - 'beforeModel': Before each adapter chatStream call (per agent iteration)\n * - 'afterModel': After each adapter chatStream call (per agent iteration)\n * - 'modelStream': During model streaming\n * - 'beforeTools': Before tool execution phase\n * - 'afterTools': After tool execution phase\n * - 'structuredOutput': During the final structured-output adapter call (set\n * for chunks from adapter.structuredOutputStream or the synthesized fallback)\n */\nexport type ChatMiddlewarePhase =\n | 'init'\n | 'beforeModel'\n | 'afterModel'\n | 'modelStream'\n | 'beforeTools'\n | 'afterTools'\n | 'structuredOutput'\n\nexport const INTERRUPT_BOUNDARY_PHASES = [\n 'beforeModel',\n 'afterModel',\n 'beforeTools',\n 'afterTools',\n] as const\n\nexport type InterruptBoundaryPhase = (typeof INTERRUPT_BOUNDARY_PHASES)[number]\n\nexport const INTERRUPT_TOOL_RESUMES = ['continue', 'cancel', 'stop'] as const\n\nexport type InterruptToolResume = (typeof INTERRUPT_TOOL_RESUMES)[number]\n\ntype AnyInterruptDefinition = InterruptDefinition<any, any, any, any>\n\ntype InterruptResponse<TDefinition> =\n TDefinition extends InterruptDefinition<any, any, infer TResponseSchema, any>\n ? TResponseSchema extends StandardSchemaV1<any, infer TResponse>\n ? TResponse\n : TResponseSchema extends StandardJSONSchemaV1<any, infer TResponse>\n ? TResponse\n : unknown\n : unknown\n\nexport type GenericInterruptResolution<\n TDefinition extends AnyInterruptDefinition,\n> = TDefinition extends AnyInterruptDefinition\n ?\n | {\n readonly request: GenericInterruptRequest<TDefinition>\n readonly status: 'resolved'\n readonly response: InterruptResponse<TDefinition>\n }\n | {\n readonly request: GenericInterruptRequest<TDefinition>\n readonly status: 'cancelled'\n readonly response?: never\n }\n : never\n\nexport interface InterruptResolutionCollection<\n TDefinitions extends AnyInterruptDefinition = AnyInterruptDefinition,\n> {\n for: <\n TDefinition extends ([TDefinitions] extends [never]\n ? AnyInterruptDefinition\n : TDefinitions),\n >(\n definition: TDefinition,\n ) => ReadonlyArray<GenericInterruptResolution<TDefinition>>\n all: {\n (): ReadonlyArray<GenericInterruptResolution<TDefinitions>>\n <const TSelected extends ReadonlyArray<TDefinitions>>(\n ...definitions: TSelected\n ): ReadonlyArray<GenericInterruptResolution<TSelected[number]>>\n }\n}\n\ntype BivariantInterruptResolutionHook<\n TContext,\n TDefinitions extends AnyInterruptDefinition,\n> = InterruptResolutionHookSignature<TContext, TDefinitions>['call']\n\ndeclare abstract class InterruptResolutionHookSignature<\n TContext,\n TDefinitions extends AnyInterruptDefinition,\n> {\n abstract call(\n ctx: ChatMiddlewareContext<TContext>,\n resolutions: InterruptResolutionCollection<TDefinitions>,\n ): InterruptResolutionResult | Promise<InterruptResolutionResult>\n}\n\nexport type InterruptBoundaryResult<\n TDefinitions extends AnyInterruptDefinition = AnyInterruptDefinition,\n> =\n | undefined\n | {\n readonly interrupts: ReadonlyArray<GenericInterruptRequest<TDefinitions>>\n }\n\nexport type InterruptResolutionResult = void | {\n readonly toolResume: InterruptToolResume\n}\n\n/**\n * Stable context object passed to all middleware hooks.\n * Created once per chat() invocation and shared across all hooks.\n */\nexport interface ChatMiddlewareContext<TContext = unknown> {\n /** Unique identifier for this chat request */\n requestId: string\n /** Unique identifier for this stream */\n streamId: string\n /** AG-UI run identifier for correlating client and server events */\n runId: string\n /** Interrupted or parent run correlated with this continuation. */\n parentRunId?: string\n /**\n * Set when this run is a subagent. The id on the child's `SUBAGENT_STARTED`\n * and on every chunk it streams. Absent on a top-level run.\n */\n subagentRunId?: string\n /**\n * AG-UI thread identifier — a stable per-conversation ID used to\n * correlate client and server devtools events. Resolves to the\n * caller-provided `threadId` (or legacy `conversationId`), or an\n * auto-generated value when neither is supplied.\n */\n threadId: string\n /**\n * @deprecated Use `threadId` instead. Retained as an alias of\n * `threadId` so middleware written before the AG-UI rename keeps\n * working unchanged. Will be removed in a future major release.\n */\n conversationId?: string\n /** Current lifecycle phase */\n phase: ChatMiddlewarePhase\n /** Current agent loop iteration (0-indexed) */\n iteration: number\n /** Running count of chunks yielded so far */\n chunkIndex: number\n /** Abort signal from the chat request */\n signal?: AbortSignal\n /** Abort the chat run with a reason */\n abort: (reason?: string) => void\n /**\n * Push a `CUSTOM` chunk onto the chat stream immediately.\n * The engine yields it as soon as it can (including while `onConfig`\n * is still awaiting work such as a summarize call). Durability then\n * flushes the event on its own, unless you pass `{ batch: true }`.\n */\n emitCustomEvent: (\n name: string,\n value: Record<string, any>,\n options?: EmitCustomEventOptions,\n ) => void\n /** Runtime context provided by chat() options */\n context: TContext\n /**\n * Defer a non-blocking side-effect promise.\n * Deferred promises do not block streaming and are awaited\n * after the terminal hook (onFinish/onAbort/onError).\n */\n defer: (promise: Promise<unknown>) => void\n\n // --- Provider / adapter info (immutable for the lifetime of the request) ---\n\n /**\n * Which activity this context describes — always `'chat'`. Present so the\n * chat context structurally satisfies the base `GenerationMiddlewareContext`,\n * letting an observe-only middleware authored against the base (e.g.\n * `otelMiddleware`) run on both chat and media activities.\n */\n activity: 'chat'\n /** Provider name (e.g., 'openai', 'anthropic') */\n provider: string\n /** Model identifier (e.g., 'gpt-5.5') */\n model: string\n /** Source of the chat invocation — always 'server' for server-side chat */\n source: 'client' | 'server'\n /** Whether the chat is streaming */\n streaming: boolean\n\n // --- Config-derived info (may update per-iteration via onConfig) ---\n\n /** System prompts configured for this chat */\n systemPrompts: Array<SystemPrompt>\n /** Names of configured tools, if any */\n toolNames?: Array<string>\n /** Flattened generation options (metadata) */\n options?: Record<string, unknown> | undefined\n /** Provider-specific model options */\n modelOptions?: Record<string, unknown> | undefined\n\n // --- Computed info ---\n\n /** Number of messages at the start of the request */\n messageCount: number\n /** Whether tools are configured */\n hasTools: boolean\n\n // --- Mutable per-iteration state ---\n\n /** Current assistant message ID (changes per iteration) */\n currentMessageId: string | null\n /** Accumulated text content for the current iteration */\n accumulatedContent: string\n\n // --- References ---\n\n /** Current messages array (read-only view) */\n messages: ReadonlyArray<ModelMessage>\n /** Generate a unique ID with the given prefix */\n createId: (prefix: string) => string\n /**\n * Capability bookkeeping for this request. Populated by middleware `setup`\n * hooks (via `provide` accessors) and read by later middleware (via `get`\n * accessors). Prefer the accessors returned by `createCapability` over using\n * this directly. Orthogonal to `context` (the user runtime context).\n */\n capabilities: CapabilityRegistry\n /**\n * Read a provided capability by its handle. Equivalent to the handle's own\n * `get` accessor (`getX(ctx)`); throws if the capability was never provided.\n */\n get: <TValue>(capability: Capability<TValue>) => TValue\n /**\n * Read a capability by its handle, returning `undefined` if it was never\n * provided (never throws).\n */\n getOptional: <TValue>(capability: Capability<TValue>) => TValue | undefined\n /**\n * Provide a capability value. Equivalent to the handle's own `provide`\n * accessor (`provideX(ctx, value)`). Typically called from `setup`.\n */\n provide: <TValue>(capability: Capability<TValue>, value: TValue) => void\n}\n\n// ===========================\n// Config passed to onConfig\n// ===========================\n\n/**\n * Chat configuration that middleware can observe or transform.\n * This is a subset of the chat engine's effective configuration\n * that middleware is allowed to modify.\n */\nexport interface ChatMiddlewareConfig {\n /** Canonical conversation history. Middleware and persistence read this. */\n messages: Array<ModelMessage>\n /** Provider-only context. Defaults to `messages` when it is not set. */\n providerMessages?: Array<ModelMessage> | undefined\n systemPrompts: Array<SystemPrompt>\n tools: Array<Tool>\n resume?: Array<RunAgentResumeItem> | undefined\n resumeToolState?: ChatResumeToolState | undefined\n metadata?: Record<string, unknown> | undefined\n modelOptions?: Record<string, unknown> | undefined\n}\n\n/**\n * Tool decisions reconstructed by server-side middleware from validated resume\n * entries. This lets empty-message interrupt resumes continue tool execution\n * without relying on client message history.\n */\nexport interface ChatResumeToolState {\n approvals?: ReadonlyMap<string, ToolApprovalResolution> | undefined\n clientToolResults?: ReadonlyMap<string, unknown> | undefined\n genericInterrupts?:\n | ReadonlyMap<string, ChatResumeGenericResolution>\n | undefined\n /** Durable generic requests reconstructed by server middleware. */\n genericInterruptRequests?:\n | ReadonlyMap<\n string,\n GenericInterruptRequest<InterruptDefinition<any, any, any, any>>\n >\n | undefined\n deniedToolResults?: ReadonlyMap<string, unknown> | undefined\n cancelledToolCallIds?: ReadonlySet<string> | undefined\n}\n\nexport type ChatResumeGenericResolution =\n | { interruptId: string; status: 'resolved'; payload: unknown }\n | { interruptId: string; status: 'cancelled'; payload?: never }\n\n/**\n * Config passed to onStructuredOutputConfig.\n *\n * Mirrors ChatMiddlewareConfig minus `tools` (the final structured-output call\n * is a single typed-response request, not an agentic loop — tools cannot be\n * forwarded to it), plus the `outputSchema` being sent to the provider.\n * Middleware may transform the schema (e.g., inject $defs, strip\n * vendor-incompatible keywords) by returning a partial that includes\n * `outputSchema`.\n */\nexport interface StructuredOutputMiddlewareConfig extends Omit<\n ChatMiddlewareConfig,\n 'tools'\n> {\n /** JSON Schema being sent to the provider for structured output. */\n outputSchema: JSONSchema\n}\n\n// ===========================\n// Tool Call Hook Context\n// ===========================\n\n/**\n * Context provided to tool call hooks (onBeforeToolCall / onAfterToolCall).\n */\nexport interface ToolCallHookContext {\n /** The tool call being executed */\n toolCall: ToolCall\n /** The resolved tool definition, if found */\n tool: Tool | undefined\n /** Parsed arguments for the tool call */\n args: unknown\n /** Name of the tool */\n toolName: string\n /** ID of the tool call */\n toolCallId: string\n}\n\n/**\n * Decision returned from onBeforeToolCall.\n * - undefined/void: continue with normal execution\n * - { type: 'transformArgs', args }: replace args used for execution\n * - { type: 'skip', result }: skip execution, use provided result\n * - { type: 'abort', reason }: abort the entire chat run\n */\nexport type BeforeToolCallDecision =\n | void\n | undefined\n | null\n | { type: 'transformArgs'; args: unknown }\n | { type: 'skip'; result: unknown }\n | { type: 'abort'; reason?: string }\n\n/**\n * Outcome information provided to onAfterToolCall.\n */\nexport interface AfterToolCallInfo {\n /** The tool call that was executed */\n toolCall: ToolCall\n /** The resolved tool definition */\n tool: Tool | undefined\n /** Name of the tool */\n toolName: string\n /** ID of the tool call */\n toolCallId: string\n /** Whether the execution succeeded */\n ok: boolean\n /** Duration of tool execution in milliseconds */\n duration: number\n /** The result (if ok) or error (if not ok) */\n result?: unknown\n error?: unknown\n}\n\n// ===========================\n// Iteration Info\n// ===========================\n\n/**\n * Information passed to onIteration at the start of each agent loop iteration.\n */\nexport interface IterationInfo {\n /** 0-based iteration index */\n iteration: number\n /** The assistant message ID created for this iteration */\n messageId: string\n}\n\n// ===========================\n// Tool Phase Complete Info\n// ===========================\n\n/**\n * Aggregate information passed to onToolPhaseComplete after all tool calls\n * in an iteration have been processed.\n */\nexport interface ToolPhaseCompleteInfo {\n /** Tool calls that were assigned to the assistant message */\n toolCalls: Array<ToolCall>\n /** Completed tool results */\n results: Array<{\n toolCallId: string\n toolName: string\n result: unknown\n duration?: number\n }>\n /** Tools that need user approval */\n needsApproval: Array<{\n toolCallId: string\n toolName: string\n input: unknown\n approvalId: string\n }>\n /** Tools that need client-side execution */\n needsClientExecution: Array<{\n toolCallId: string\n toolName: string\n input: unknown\n }>\n}\n\n// ===========================\n// Usage Info\n// ===========================\n\n/**\n * Token usage statistics passed to the onUsage hook.\n * Extracted from the RUN_FINISHED chunk when usage data is present.\n *\n * Includes optional provider-reported `cost`/`costDetails` (see {@link TokenUsage}).\n * Kept as an interface extending `TokenUsage` to preserve declaration merging for\n * this publicly exported type.\n */\nexport interface UsageInfo extends TokenUsage {}\n\n// ===========================\n// Terminal Hook Info\n// ===========================\n\n/**\n * Information passed to onFinish.\n */\nexport interface FinishInfo {\n /** The finish reason from the last model response */\n finishReason: string | null\n /** Total duration of the chat run in milliseconds */\n duration: number\n /** Final accumulated text content */\n content: string\n /** Final usage totals, if available (optionally including provider-reported cost) */\n usage?: TokenUsage | undefined\n}\n\n/**\n * Information passed to onAbort.\n */\nexport interface AbortInfo {\n /** The reason for the abort, if provided */\n reason?: string\n /** Duration until abort in milliseconds */\n duration: number\n /**\n * True only when the abort came from an explicit, out-of-band cancel (e.g. a\n * cancel endpoint setting `RunRecord.cancelRequested`), never from a mere\n * client disconnect.\n *\n * A disconnect and a user pressing \"stop\" are the SAME connection close on\n * the wire, so consumers must not infer intent from an abort alone. Middleware\n * that tears down expensive resources reads this to distinguish \"the viewer\n * left, keep going\" from \"the user wants this stopped\". Populated from the\n * abort reason: `true` exactly when the run was aborted with `RUN_CANCEL_REASON`\n * (matched with `===`, so an arbitrary error message can never be read as a\n * deliberate cancel), `false` for every other abort. The durable channel is\n * separate — middleware that must also catch a cancel recorded on a different\n * host reads `RunRecord.cancelRequested` in addition to this flag.\n */\n cancelRequested?: boolean\n}\n\n/**\n * Information passed to onError.\n */\nexport interface ErrorInfo {\n /** The error that caused the failure */\n error: unknown\n /** Duration until error in milliseconds */\n duration: number\n}\n\n/**\n * Saves subagent runs while a router owns the turn.\n * `withPersistence` sets this. `chat()` calls it. Apps do not.\n */\nexport interface RoutedSubagentPersistence {\n start: (input: {\n threadId: string\n runId: string\n messages: ReadonlyArray<UIMessage | ModelMessage>\n /**\n * The run's resume entries: answers to earlier child interrupts, plus any\n * the parent answers itself.\n */\n resume?: ReadonlyArray<RunAgentResumeItem>\n }) => Promise<void>\n chunk: (input: {\n threadId: string\n runId: string\n chunk: StreamChunk\n }) => Promise<void>\n finish: (input: { threadId: string; runId: string }) => Promise<void>\n /** The run stopped because a child waits for outside input. */\n suspend?: (input: {\n threadId: string\n runId: string\n interrupts: ReadonlyArray<Interrupt>\n }) => Promise<void>\n abort: (input: {\n threadId: string\n runId: string\n error?: unknown\n }) => Promise<void>\n}\n\n// ===========================\n// Middleware Interface\n// ===========================\n\n/**\n * Chat middleware interface.\n *\n * All hooks are optional. Middleware is composed in array order:\n * - `onConfig`: config piped through middlewares in order (first transform influences later)\n * - `onChunk`: each output chunk is fed into the next middleware in order\n *\n * @example Logging middleware\n * ```ts\n * const loggingMiddleware: ChatMiddleware = {\n * name: 'logging',\n * onStart(ctx) { console.log('Chat started', ctx.requestId) },\n * onChunk(ctx, chunk) { console.log('Chunk:', chunk.type) },\n * onFinish(ctx, info) { console.log('Done:', info.duration, 'ms') },\n * }\n * ```\n *\n * @example Redaction middleware\n * ```ts\n * const redactionMiddleware: ChatMiddleware = {\n * name: 'redaction',\n * onChunk(ctx, chunk) {\n * if (chunk.type === 'TEXT_MESSAGE_CONTENT') {\n * return { ...chunk, delta: redact(chunk.delta) }\n * }\n * },\n * }\n * ```\n */\nexport interface ChatMiddleware<\n TContext = unknown,\n TInterruptDefinitions extends AnyInterruptDefinition = never,\n> {\n /** Optional name for debugging and identification */\n name?: string\n\n /**\n * Present when this middleware stores subagent runs.\n * The router calls it. An app does not set it.\n */\n routedSubagentPersistence?: RoutedSubagentPersistence\n\n /**\n * Called at a lifecycle boundary. Return interrupt requests to pause the run.\n * Requests from every middleware in the same boundary form one batch.\n */\n onInterruptBoundary?: (\n ctx: ChatMiddlewareContext<TContext> & { phase: InterruptBoundaryPhase },\n ) =>\n | InterruptBoundaryResult<TInterruptDefinitions>\n | Promise<InterruptBoundaryResult<TInterruptDefinitions>>\n\n /**\n * Called on a continuation run after the client answers registered interrupts.\n * Return `toolResume` to decide whether pending tools continue, cancel, or stop.\n */\n onInterruptResolution?: BivariantInterruptResolutionHook<\n TContext,\n TInterruptDefinitions\n >\n\n /**\n * Capabilities this middleware requires. `chat()` validates that some\n * middleware (or the adapter) provides each one; unsatisfied requirements are\n * a compile-time error (array coverage / builder) and a runtime error before\n * the adapter runs.\n */\n requires?: ReadonlyArray<CapabilityHandle>\n\n /**\n * Capabilities this middleware provides. Each declared capability MUST be\n * provided (via its `provide` accessor) inside `setup`, or `chat()` throws\n * after the setup phase.\n */\n provides?: ReadonlyArray<CapabilityHandle>\n\n /**\n * Capabilities this middleware uses if present but does not require.\n * Non-gating: never causes a validation error. Read with\n * `getX(ctx, { optional: true })`.\n */\n optionalRequires?: ReadonlyArray<CapabilityHandle>\n\n /**\n * Provisioning hook. Runs FIRST — before `onConfig` (init) — across all\n * middleware in array order. Use it to call `provide` accessors so later\n * middleware (`onConfig` onward) can consume the capabilities. Receives the\n * stable context; does NOT receive the mutable config.\n */\n setup?: (ctx: ChatMiddlewareContext<TContext>) => void | Promise<void>\n\n /**\n * Called to observe or transform the chat configuration.\n * Called at init and at the beginning of each agent iteration.\n *\n * Return a partial config to merge with the current config, or void to pass through.\n * Only the fields you return are overwritten — everything else is preserved.\n */\n onConfig?: (\n ctx: ChatMiddlewareContext<TContext>,\n config: ChatMiddlewareConfig,\n ) =>\n | void\n | null\n | Partial<ChatMiddlewareConfig>\n | Promise<void | null | Partial<ChatMiddlewareConfig>>\n\n /**\n * Called at the start of the final structured-output call (when the chat\n * was invoked with outputSchema). Pipes through middleware in order, like\n * onConfig, but with access to the JSON Schema being sent to the provider.\n *\n * Return a partial to shallow-merge into the current config, or void to\n * pass through.\n *\n * Fires BEFORE onConfig at the structured-output boundary. onConfig also\n * re-fires at the same boundary with ctx.phase === 'structuredOutput',\n * receiving the post-onStructuredOutputConfig view of the config (minus\n * outputSchema). Use onConfig for general-purpose transforms that apply\n * to every adapter call; use this hook when you need to transform the\n * outputSchema or apply structured-output-specific behavior.\n */\n onStructuredOutputConfig?: (\n ctx: ChatMiddlewareContext<TContext>,\n config: StructuredOutputMiddlewareConfig,\n ) =>\n | void\n | null\n | Partial<StructuredOutputMiddlewareConfig>\n | Promise<void | null | Partial<StructuredOutputMiddlewareConfig>>\n\n /**\n * Called when the chat run starts (after initial onConfig).\n */\n onStart?: (ctx: ChatMiddlewareContext<TContext>) => void | Promise<void>\n\n /**\n * Called at the start of each agent loop iteration, after a new assistant message ID\n * is created. Use this to observe iteration boundaries.\n */\n onIteration?: (\n ctx: ChatMiddlewareContext<TContext>,\n info: IterationInfo,\n ) => void | Promise<void>\n\n /**\n * Called when the engine is deciding whether to start another agent-loop\n * iteration (after a tool phase or between model turns).\n *\n * Return `false` to stop further iterations. Return `true`, `void`, or\n * `undefined` to allow continuation. Combined with AND semantics across\n * middleware and with `agentLoopStrategy` — any `false` stops the loop.\n *\n * Does not abort the run: the stream finishes normally with the current\n * messages. Use `ctx.abort()` only when you need a hard abort.\n *\n * Receives the same {@link AgentLoopState} passed to strategies\n * (`iterationCount`, `toolCallCount`, `lastTurnToolCallCount`, etc.).\n */\n onShouldContinue?: (\n ctx: ChatMiddlewareContext<TContext>,\n state: AgentLoopState,\n ) => boolean | void | Promise<boolean | void>\n\n /**\n * Called for every chunk yielded by chat().\n * Can observe, transform, expand, or drop chunks.\n *\n * @returns void (pass through), chunk (replace), chunk[] (expand), null (drop)\n */\n onChunk?: (\n ctx: ChatMiddlewareContext<TContext>,\n chunk: StreamChunk,\n ) =>\n | void\n | StreamChunk\n | Array<StreamChunk>\n | null\n | Promise<void | StreamChunk | Array<StreamChunk> | null>\n\n /**\n * Called before a tool is executed.\n * Can observe, transform args, skip execution, or abort the run.\n */\n onBeforeToolCall?: (\n ctx: ChatMiddlewareContext<TContext>,\n hookCtx: ToolCallHookContext,\n ) => BeforeToolCallDecision | Promise<BeforeToolCallDecision>\n\n /**\n * Called after a tool execution completes (success or failure).\n */\n onAfterToolCall?: (\n ctx: ChatMiddlewareContext<TContext>,\n info: AfterToolCallInfo,\n ) => void | Promise<void>\n\n /**\n * Called after all tool calls in an iteration have been processed.\n * Provides aggregate data about tool execution results, approvals, and client tools.\n */\n onToolPhaseComplete?: (\n ctx: ChatMiddlewareContext<TContext>,\n info: ToolPhaseCompleteInfo,\n ) => void | Promise<void>\n\n /**\n * Called when usage data is available from a RUN_FINISHED chunk.\n * Called once per model iteration that reports usage.\n */\n onUsage?: (\n ctx: ChatMiddlewareContext<TContext>,\n usage: UsageInfo,\n ) => void | Promise<void>\n\n /**\n * Called when the chat run completes normally.\n * Exactly one of onFinish/onAbort/onError will be called per run.\n */\n onFinish?: (\n ctx: ChatMiddlewareContext<TContext>,\n info: FinishInfo,\n ) => void | Promise<void>\n\n /**\n * Called when the chat run is aborted.\n * Exactly one of onFinish/onAbort/onError will be called per run.\n */\n onAbort?: (\n ctx: ChatMiddlewareContext<TContext>,\n info: AbortInfo,\n ) => void | Promise<void>\n\n /**\n * Called when the chat run encounters an unhandled error.\n * Exactly one of onFinish/onAbort/onError will be called per run.\n */\n onError?: (\n ctx: ChatMiddlewareContext<TContext>,\n info: ErrorInfo,\n ) => void | Promise<void>\n\n /**\n * Sandbox file-event hooks. Fire when a sandbox provided by `withSandbox` is\n * active during the run and a file is created/changed/deleted. Server-side.\n */\n sandbox?: ChatSandboxHooks<TContext>\n}\n\n/** A `ChatMiddleware` with a permissive context — for use as a constraint. */\n/** A permissive middleware constraint that retains the definition parameter. */\nexport type AnyChatMiddleware = ChatMiddleware<any, any>\n"],"mappings":";AAiGA,IAAa,4BAA4B;CACvC;CACA;CACA;CACA;AACF;AAIA,IAAa,yBAAyB;CAAC;CAAY;CAAU;AAAM"}
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../../../../src/activities/chat/middleware/types.ts"],"sourcesContent":["import type {\n StandardJSONSchemaV1,\n StandardSchemaV1,\n} from '@standard-schema/spec'\nimport type {\n AgentLoopState,\n EmitCustomEventOptions,\n Interrupt,\n JSONSchema,\n ModelMessage,\n UIMessage,\n RunAgentResumeItem,\n StreamChunk,\n TokenUsage,\n Tool,\n ToolCall,\n} from '../../../types'\nimport type { SystemPrompt } from '../../../system-prompts'\nimport type { ToolApprovalResolution } from '../../../interrupts'\nimport type {\n GenericInterruptRequest,\n InterruptDefinition,\n} from '../../../interrupt-definition'\nimport type {\n Capability,\n CapabilityHandle,\n CapabilityRegistry,\n} from './capabilities'\n\n/** A file change observed inside a sandbox during a chat run. */\nexport interface SandboxFileEvent {\n type: 'create' | 'change' | 'delete'\n /** Absolute path inside the sandbox (under the workspace root). */\n path: string\n timestamp: number\n}\n\n/** The file event a sandbox hook receives: the serializable {@link SandboxFileEvent}\n * plus lazy, git-backed content accessors. Accessors compute on call, so a hook\n * that only reads `path`/`type` pays nothing. Never present on the serialized\n * `sandbox.file` CUSTOM chunk. */\nexport interface SandboxFileHookEvent extends SandboxFileEvent {\n /** Content at the session baseline (`''` for a new file or non-git workspace). */\n before: () => Promise<string>\n /** Current content (`''` when the event is a delete). */\n after: () => Promise<string>\n /** Unified patch vs the session baseline (synthesized add-patch when non-git). */\n diff: () => Promise<string>\n}\n\n/**\n * Sandbox file-event hooks a chat middleware can declare. Fire server-side for\n * every file create/change/delete observed in the sandbox during the run.\n */\nexport interface ChatSandboxHooks<TContext = unknown> {\n onFile?: (\n ctx: ChatMiddlewareContext<TContext>,\n e: SandboxFileHookEvent,\n ) => void | Promise<void>\n onFileCreate?: (\n ctx: ChatMiddlewareContext<TContext>,\n e: SandboxFileHookEvent,\n ) => void | Promise<void>\n onFileChange?: (\n ctx: ChatMiddlewareContext<TContext>,\n e: SandboxFileHookEvent,\n ) => void | Promise<void>\n onFileDelete?: (\n ctx: ChatMiddlewareContext<TContext>,\n e: SandboxFileHookEvent,\n ) => void | Promise<void>\n}\n\n// ===========================\n// Middleware Context\n// ===========================\n\n/**\n * Phase of the chat middleware lifecycle.\n * - 'init': Initial config transform before the chat engine starts\n * - 'beforeModel': Before each adapter chatStream call (per agent iteration)\n * - 'afterModel': After each adapter chatStream call (per agent iteration)\n * - 'modelStream': During model streaming\n * - 'beforeTools': Before tool execution phase\n * - 'afterTools': After tool execution phase\n * - 'structuredOutput': During the final structured-output adapter call (set\n * for chunks from adapter.structuredOutputStream or the synthesized fallback)\n */\nexport type ChatMiddlewarePhase =\n | 'init'\n | 'beforeModel'\n | 'afterModel'\n | 'modelStream'\n | 'beforeTools'\n | 'afterTools'\n | 'structuredOutput'\n\nexport const INTERRUPT_BOUNDARY_PHASES = [\n 'beforeModel',\n 'afterModel',\n 'beforeTools',\n 'afterTools',\n] as const\n\nexport type InterruptBoundaryPhase = (typeof INTERRUPT_BOUNDARY_PHASES)[number]\n\nexport const INTERRUPT_TOOL_RESUMES = ['continue', 'cancel', 'stop'] as const\n\nexport type InterruptToolResume = (typeof INTERRUPT_TOOL_RESUMES)[number]\n\ntype AnyInterruptDefinition = InterruptDefinition<any, any, any, any>\n\ntype InterruptResponse<TDefinition> =\n TDefinition extends InterruptDefinition<any, any, infer TResponseSchema, any>\n ? TResponseSchema extends StandardSchemaV1<any, infer TResponse>\n ? TResponse\n : TResponseSchema extends StandardJSONSchemaV1<any, infer TResponse>\n ? TResponse\n : unknown\n : unknown\n\nexport type GenericInterruptResolution<\n TDefinition extends AnyInterruptDefinition,\n> = TDefinition extends AnyInterruptDefinition\n ?\n | {\n readonly request: GenericInterruptRequest<TDefinition>\n readonly status: 'resolved'\n readonly response: InterruptResponse<TDefinition>\n }\n | {\n readonly request: GenericInterruptRequest<TDefinition>\n readonly status: 'cancelled'\n readonly response?: never\n }\n : never\n\nexport interface InterruptResolutionCollection<\n TDefinitions extends AnyInterruptDefinition = AnyInterruptDefinition,\n> {\n for: <\n TDefinition extends ([TDefinitions] extends [never]\n ? AnyInterruptDefinition\n : TDefinitions),\n >(\n definition: TDefinition,\n ) => ReadonlyArray<GenericInterruptResolution<TDefinition>>\n all: {\n (): ReadonlyArray<GenericInterruptResolution<TDefinitions>>\n <const TSelected extends ReadonlyArray<TDefinitions>>(\n ...definitions: TSelected\n ): ReadonlyArray<GenericInterruptResolution<TSelected[number]>>\n }\n}\n\ntype BivariantInterruptResolutionHook<\n TContext,\n TDefinitions extends AnyInterruptDefinition,\n> = InterruptResolutionHookSignature<TContext, TDefinitions>['call']\n\ndeclare abstract class InterruptResolutionHookSignature<\n TContext,\n TDefinitions extends AnyInterruptDefinition,\n> {\n abstract call(\n ctx: ChatMiddlewareContext<TContext>,\n resolutions: InterruptResolutionCollection<TDefinitions>,\n ): InterruptResolutionResult | Promise<InterruptResolutionResult>\n}\n\nexport type InterruptBoundaryResult<\n TDefinitions extends AnyInterruptDefinition = AnyInterruptDefinition,\n> =\n | undefined\n | {\n readonly interrupts: ReadonlyArray<GenericInterruptRequest<TDefinitions>>\n }\n\nexport type InterruptResolutionResult = void | {\n readonly toolResume: InterruptToolResume\n}\n\n/**\n * Stable context object passed to all middleware hooks.\n * Created once per chat() invocation and shared across all hooks.\n */\nexport interface ChatMiddlewareContext<TContext = unknown> {\n /** Unique identifier for this chat request */\n requestId: string\n /** Unique identifier for this stream */\n streamId: string\n /** AG-UI run identifier for correlating client and server events */\n runId: string\n /** Interrupted or parent run correlated with this continuation. */\n parentRunId?: string\n /**\n * Set when this run is a subagent. The id on the child's `SUBAGENT_STARTED`\n * and on every chunk it streams. Absent on a top-level run.\n */\n subagentRunId?: string\n /**\n * AG-UI thread identifier — a stable per-conversation ID used to\n * correlate client and server devtools events. Resolves to the\n * caller-provided `threadId` (or legacy `conversationId`), or an\n * auto-generated value when neither is supplied.\n */\n threadId: string\n /**\n * @deprecated Use `threadId` instead. Retained as an alias of\n * `threadId` so middleware written before the AG-UI rename keeps\n * working unchanged. Will be removed in a future major release.\n */\n conversationId?: string\n /** Current lifecycle phase */\n phase: ChatMiddlewarePhase\n /** Current agent loop iteration (0-indexed) */\n iteration: number\n /** Running count of chunks yielded so far */\n chunkIndex: number\n /** Abort signal from the chat request */\n signal?: AbortSignal\n /** Abort the chat run with a reason */\n abort: (reason?: string) => void\n /**\n * Push a `CUSTOM` chunk onto the chat stream immediately.\n * The engine yields it as soon as it can (including while `onConfig`\n * is still awaiting work such as a summarize call). Durability then\n * flushes the event on its own, unless you pass `{ batch: true }`.\n */\n emitCustomEvent: (\n name: string,\n value: Record<string, any>,\n options?: EmitCustomEventOptions,\n ) => void\n /** Runtime context provided by chat() options */\n context: TContext\n /**\n * Defer a non-blocking side-effect promise.\n * Deferred promises do not block streaming and are awaited\n * after the terminal hook (onFinish/onAbort/onError).\n */\n defer: (promise: Promise<unknown>) => void\n\n // --- Provider / adapter info (immutable for the lifetime of the request) ---\n\n /**\n * Which activity this context describes — always `'chat'`. Present so the\n * chat context structurally satisfies the base `GenerationMiddlewareContext`,\n * letting an observe-only middleware authored against the base (e.g.\n * `otelMiddleware`) run on both chat and media activities.\n */\n activity: 'chat'\n /** Provider name (e.g., 'openai', 'anthropic') */\n provider: string\n /** Model identifier (e.g., 'gpt-5.5') */\n model: string\n /** Source of the chat invocation — always 'server' for server-side chat */\n source: 'client' | 'server'\n /** Whether the chat is streaming */\n streaming: boolean\n\n // --- Config-derived info (may update per-iteration via onConfig) ---\n\n /** System prompts configured for this chat */\n systemPrompts: Array<SystemPrompt>\n /** Names of configured tools, if any */\n toolNames?: Array<string>\n /** Flattened generation options (metadata) */\n options?: Record<string, unknown> | undefined\n /** Provider-specific model options */\n modelOptions?: Record<string, unknown> | undefined\n\n // --- Computed info ---\n\n /** Number of messages at the start of the request */\n messageCount: number\n /** Whether tools are configured */\n hasTools: boolean\n\n // --- Mutable per-iteration state ---\n\n /** Current assistant message ID (changes per iteration) */\n currentMessageId: string | null\n /** Accumulated text content for the current iteration */\n accumulatedContent: string\n\n // --- References ---\n\n /** Current messages array (read-only view) */\n messages: ReadonlyArray<ModelMessage>\n /** Generate a unique ID with the given prefix */\n createId: (prefix: string) => string\n /**\n * Capability bookkeeping for this request. Populated by middleware `setup`\n * hooks (via `provide` accessors) and read by later middleware (via `get`\n * accessors). Prefer the accessors returned by `createCapability` over using\n * this directly. Orthogonal to `context` (the user runtime context).\n */\n capabilities: CapabilityRegistry\n /**\n * Read a provided capability by its handle. Equivalent to the handle's own\n * `get` accessor (`getX(ctx)`); throws if the capability was never provided.\n */\n get: <TValue>(capability: Capability<TValue>) => TValue\n /**\n * Read a capability by its handle, returning `undefined` if it was never\n * provided (never throws).\n */\n getOptional: <TValue>(capability: Capability<TValue>) => TValue | undefined\n /**\n * Provide a capability value. Equivalent to the handle's own `provide`\n * accessor (`provideX(ctx, value)`). Typically called from `setup`.\n */\n provide: <TValue>(capability: Capability<TValue>, value: TValue) => void\n}\n\n// ===========================\n// Config passed to onConfig\n// ===========================\n\n/**\n * Chat configuration that middleware can observe or transform.\n * This is a subset of the chat engine's effective configuration\n * that middleware is allowed to modify.\n */\nexport interface ChatMiddlewareConfig {\n /** Canonical conversation history. Middleware and persistence read this. */\n messages: Array<ModelMessage>\n /** Provider-only context. Defaults to `messages` when it is not set. */\n providerMessages?: Array<ModelMessage> | undefined\n systemPrompts: Array<SystemPrompt>\n tools: Array<Tool>\n resume?: Array<RunAgentResumeItem> | undefined\n resumeToolState?: ChatResumeToolState | undefined\n metadata?: Record<string, unknown> | undefined\n modelOptions?: Record<string, unknown> | undefined\n}\n\n/**\n * Tool decisions reconstructed by server-side middleware from validated resume\n * entries. This lets empty-message interrupt resumes continue tool execution\n * without relying on client message history.\n */\nexport interface ChatResumeToolState {\n approvals?: ReadonlyMap<string, ToolApprovalResolution> | undefined\n clientToolResults?: ReadonlyMap<string, unknown> | undefined\n clientToolErrors?: ReadonlyMap<string, string> | undefined\n genericInterrupts?:\n | ReadonlyMap<string, ChatResumeGenericResolution>\n | undefined\n /** Durable generic requests reconstructed by server middleware. */\n genericInterruptRequests?:\n | ReadonlyMap<\n string,\n GenericInterruptRequest<InterruptDefinition<any, any, any, any>>\n >\n | undefined\n deniedToolResults?: ReadonlyMap<string, unknown> | undefined\n cancelledToolCallIds?: ReadonlySet<string> | undefined\n}\n\nexport type ChatResumeGenericResolution =\n | { interruptId: string; status: 'resolved'; payload: unknown }\n | { interruptId: string; status: 'cancelled'; payload?: never }\n\n/**\n * Config passed to onStructuredOutputConfig.\n *\n * Mirrors ChatMiddlewareConfig minus `tools` (the final structured-output call\n * is a single typed-response request, not an agentic loop — tools cannot be\n * forwarded to it), plus the `outputSchema` being sent to the provider.\n * Middleware may transform the schema (e.g., inject $defs, strip\n * vendor-incompatible keywords) by returning a partial that includes\n * `outputSchema`.\n */\nexport interface StructuredOutputMiddlewareConfig extends Omit<\n ChatMiddlewareConfig,\n 'tools'\n> {\n /** JSON Schema being sent to the provider for structured output. */\n outputSchema: JSONSchema\n}\n\n// ===========================\n// Tool Call Hook Context\n// ===========================\n\n/**\n * Context provided to tool call hooks (onBeforeToolCall / onAfterToolCall).\n */\nexport interface ToolCallHookContext {\n /** The tool call being executed */\n toolCall: ToolCall\n /** The resolved tool definition, if found */\n tool: Tool | undefined\n /** Parsed arguments for the tool call */\n args: unknown\n /** Name of the tool */\n toolName: string\n /** ID of the tool call */\n toolCallId: string\n}\n\n/**\n * Decision returned from onBeforeToolCall.\n * - undefined/void: continue with normal execution\n * - { type: 'transformArgs', args }: replace args used for execution\n * - { type: 'skip', result }: skip execution, use provided result\n * - { type: 'abort', reason }: abort the entire chat run\n */\nexport type BeforeToolCallDecision =\n | void\n | undefined\n | null\n | { type: 'transformArgs'; args: unknown }\n | { type: 'skip'; result: unknown }\n | { type: 'abort'; reason?: string }\n\n/**\n * Outcome information provided to onAfterToolCall.\n */\nexport interface AfterToolCallInfo {\n /** The tool call that was executed */\n toolCall: ToolCall\n /** The resolved tool definition */\n tool: Tool | undefined\n /** Name of the tool */\n toolName: string\n /** ID of the tool call */\n toolCallId: string\n /** Whether the execution succeeded */\n ok: boolean\n /** Duration of tool execution in milliseconds */\n duration: number\n /** The result (if ok) or error (if not ok) */\n result?: unknown\n error?: unknown\n}\n\n// ===========================\n// Iteration Info\n// ===========================\n\n/**\n * Information passed to onIteration at the start of each agent loop iteration.\n */\nexport interface IterationInfo {\n /** 0-based iteration index */\n iteration: number\n /** The assistant message ID created for this iteration */\n messageId: string\n}\n\n// ===========================\n// Tool Phase Complete Info\n// ===========================\n\n/**\n * Aggregate information passed to onToolPhaseComplete after all tool calls\n * in an iteration have been processed.\n */\nexport interface ToolPhaseCompleteInfo {\n /** Tool calls that were assigned to the assistant message */\n toolCalls: Array<ToolCall>\n /** Completed tool results */\n results: Array<{\n toolCallId: string\n toolName: string\n result: unknown\n duration?: number\n }>\n /** Tools that need user approval */\n needsApproval: Array<{\n toolCallId: string\n toolName: string\n input: unknown\n approvalId: string\n }>\n /** Tools that need client-side execution */\n needsClientExecution: Array<{\n toolCallId: string\n toolName: string\n input: unknown\n }>\n}\n\n// ===========================\n// Usage Info\n// ===========================\n\n/**\n * Token usage statistics passed to the onUsage hook.\n * Extracted from the RUN_FINISHED chunk when usage data is present.\n *\n * Includes optional provider-reported `cost`/`costDetails` (see {@link TokenUsage}).\n * Kept as an interface extending `TokenUsage` to preserve declaration merging for\n * this publicly exported type.\n */\nexport interface UsageInfo extends TokenUsage {}\n\n// ===========================\n// Terminal Hook Info\n// ===========================\n\n/**\n * Information passed to onFinish.\n */\nexport interface FinishInfo {\n /** The finish reason from the last model response */\n finishReason: string | null\n /** Total duration of the chat run in milliseconds */\n duration: number\n /** Final accumulated text content */\n content: string\n /** Final usage totals, if available (optionally including provider-reported cost) */\n usage?: TokenUsage | undefined\n}\n\n/**\n * Information passed to onAbort.\n */\nexport interface AbortInfo {\n /** The reason for the abort, if provided */\n reason?: string\n /** Duration until abort in milliseconds */\n duration: number\n /**\n * True only when the abort came from an explicit, out-of-band cancel (e.g. a\n * cancel endpoint setting `RunRecord.cancelRequested`), never from a mere\n * client disconnect.\n *\n * A disconnect and a user pressing \"stop\" are the SAME connection close on\n * the wire, so consumers must not infer intent from an abort alone. Middleware\n * that tears down expensive resources reads this to distinguish \"the viewer\n * left, keep going\" from \"the user wants this stopped\". Populated from the\n * abort reason: `true` exactly when the run was aborted with `RUN_CANCEL_REASON`\n * (matched with `===`, so an arbitrary error message can never be read as a\n * deliberate cancel), `false` for every other abort. The durable channel is\n * separate — middleware that must also catch a cancel recorded on a different\n * host reads `RunRecord.cancelRequested` in addition to this flag.\n */\n cancelRequested?: boolean\n}\n\n/**\n * Information passed to onError.\n */\nexport interface ErrorInfo {\n /** The error that caused the failure */\n error: unknown\n /** Duration until error in milliseconds */\n duration: number\n}\n\n/**\n * Saves subagent runs while a router owns the turn.\n * `withPersistence` sets this. `chat()` calls it. Apps do not.\n */\nexport interface RoutedSubagentPersistence {\n start: (input: {\n threadId: string\n runId: string\n messages: ReadonlyArray<UIMessage | ModelMessage>\n /**\n * The run's resume entries: answers to earlier child interrupts, plus any\n * the parent answers itself.\n */\n resume?: ReadonlyArray<RunAgentResumeItem>\n }) => Promise<void>\n chunk: (input: {\n threadId: string\n runId: string\n chunk: StreamChunk\n }) => Promise<void>\n finish: (input: { threadId: string; runId: string }) => Promise<void>\n /** The run stopped because a child waits for outside input. */\n suspend?: (input: {\n threadId: string\n runId: string\n interrupts: ReadonlyArray<Interrupt>\n }) => Promise<void>\n abort: (input: {\n threadId: string\n runId: string\n error?: unknown\n }) => Promise<void>\n}\n\n// ===========================\n// Middleware Interface\n// ===========================\n\n/**\n * Chat middleware interface.\n *\n * All hooks are optional. Middleware is composed in array order:\n * - `onConfig`: config piped through middlewares in order (first transform influences later)\n * - `onChunk`: each output chunk is fed into the next middleware in order\n *\n * @example Logging middleware\n * ```ts\n * const loggingMiddleware: ChatMiddleware = {\n * name: 'logging',\n * onStart(ctx) { console.log('Chat started', ctx.requestId) },\n * onChunk(ctx, chunk) { console.log('Chunk:', chunk.type) },\n * onFinish(ctx, info) { console.log('Done:', info.duration, 'ms') },\n * }\n * ```\n *\n * @example Redaction middleware\n * ```ts\n * const redactionMiddleware: ChatMiddleware = {\n * name: 'redaction',\n * onChunk(ctx, chunk) {\n * if (chunk.type === 'TEXT_MESSAGE_CONTENT') {\n * return { ...chunk, delta: redact(chunk.delta) }\n * }\n * },\n * }\n * ```\n */\nexport interface ChatMiddleware<\n TContext = unknown,\n TInterruptDefinitions extends AnyInterruptDefinition = never,\n> {\n /** Optional name for debugging and identification */\n name?: string\n\n /**\n * Present when this middleware stores subagent runs.\n * The router calls it. An app does not set it.\n */\n routedSubagentPersistence?: RoutedSubagentPersistence\n\n /**\n * Called at a lifecycle boundary. Return interrupt requests to pause the run.\n * Requests from every middleware in the same boundary form one batch.\n */\n onInterruptBoundary?: (\n ctx: ChatMiddlewareContext<TContext> & { phase: InterruptBoundaryPhase },\n ) =>\n | InterruptBoundaryResult<TInterruptDefinitions>\n | Promise<InterruptBoundaryResult<TInterruptDefinitions>>\n\n /**\n * Called on a continuation run after the client answers registered interrupts.\n * Return `toolResume` to decide whether pending tools continue, cancel, or stop.\n */\n onInterruptResolution?: BivariantInterruptResolutionHook<\n TContext,\n TInterruptDefinitions\n >\n\n /**\n * Capabilities this middleware requires. `chat()` validates that some\n * middleware (or the adapter) provides each one; unsatisfied requirements are\n * a compile-time error (array coverage / builder) and a runtime error before\n * the adapter runs.\n */\n requires?: ReadonlyArray<CapabilityHandle>\n\n /**\n * Capabilities this middleware provides. Each declared capability MUST be\n * provided (via its `provide` accessor) inside `setup`, or `chat()` throws\n * after the setup phase.\n */\n provides?: ReadonlyArray<CapabilityHandle>\n\n /**\n * Capabilities this middleware uses if present but does not require.\n * Non-gating: never causes a validation error. Read with\n * `getX(ctx, { optional: true })`.\n */\n optionalRequires?: ReadonlyArray<CapabilityHandle>\n\n /**\n * Provisioning hook. Runs FIRST — before `onConfig` (init) — across all\n * middleware in array order. Use it to call `provide` accessors so later\n * middleware (`onConfig` onward) can consume the capabilities. Receives the\n * stable context; does NOT receive the mutable config.\n */\n setup?: (ctx: ChatMiddlewareContext<TContext>) => void | Promise<void>\n\n /**\n * Called to observe or transform the chat configuration.\n * Called at init and at the beginning of each agent iteration.\n *\n * Return a partial config to merge with the current config, or void to pass through.\n * Only the fields you return are overwritten — everything else is preserved.\n */\n onConfig?: (\n ctx: ChatMiddlewareContext<TContext>,\n config: ChatMiddlewareConfig,\n ) =>\n | void\n | null\n | Partial<ChatMiddlewareConfig>\n | Promise<void | null | Partial<ChatMiddlewareConfig>>\n\n /**\n * Called at the start of the final structured-output call (when the chat\n * was invoked with outputSchema). Pipes through middleware in order, like\n * onConfig, but with access to the JSON Schema being sent to the provider.\n *\n * Return a partial to shallow-merge into the current config, or void to\n * pass through.\n *\n * Fires BEFORE onConfig at the structured-output boundary. onConfig also\n * re-fires at the same boundary with ctx.phase === 'structuredOutput',\n * receiving the post-onStructuredOutputConfig view of the config (minus\n * outputSchema). Use onConfig for general-purpose transforms that apply\n * to every adapter call; use this hook when you need to transform the\n * outputSchema or apply structured-output-specific behavior.\n */\n onStructuredOutputConfig?: (\n ctx: ChatMiddlewareContext<TContext>,\n config: StructuredOutputMiddlewareConfig,\n ) =>\n | void\n | null\n | Partial<StructuredOutputMiddlewareConfig>\n | Promise<void | null | Partial<StructuredOutputMiddlewareConfig>>\n\n /**\n * Called when the chat run starts (after initial onConfig).\n */\n onStart?: (ctx: ChatMiddlewareContext<TContext>) => void | Promise<void>\n\n /**\n * Called at the start of each agent loop iteration, after a new assistant message ID\n * is created. Use this to observe iteration boundaries.\n */\n onIteration?: (\n ctx: ChatMiddlewareContext<TContext>,\n info: IterationInfo,\n ) => void | Promise<void>\n\n /**\n * Called when the engine is deciding whether to start another agent-loop\n * iteration (after a tool phase or between model turns).\n *\n * Return `false` to stop further iterations. Return `true`, `void`, or\n * `undefined` to allow continuation. Combined with AND semantics across\n * middleware and with `agentLoopStrategy` — any `false` stops the loop.\n *\n * Does not abort the run: the stream finishes normally with the current\n * messages. Use `ctx.abort()` only when you need a hard abort.\n *\n * Receives the same {@link AgentLoopState} passed to strategies\n * (`iterationCount`, `toolCallCount`, `lastTurnToolCallCount`, etc.).\n */\n onShouldContinue?: (\n ctx: ChatMiddlewareContext<TContext>,\n state: AgentLoopState,\n ) => boolean | void | Promise<boolean | void>\n\n /**\n * Called for every chunk yielded by chat().\n * Can observe, transform, expand, or drop chunks.\n *\n * @returns void (pass through), chunk (replace), chunk[] (expand), null (drop)\n */\n onChunk?: (\n ctx: ChatMiddlewareContext<TContext>,\n chunk: StreamChunk,\n ) =>\n | void\n | StreamChunk\n | Array<StreamChunk>\n | null\n | Promise<void | StreamChunk | Array<StreamChunk> | null>\n\n /**\n * Called before a tool is executed.\n * Can observe, transform args, skip execution, or abort the run.\n */\n onBeforeToolCall?: (\n ctx: ChatMiddlewareContext<TContext>,\n hookCtx: ToolCallHookContext,\n ) => BeforeToolCallDecision | Promise<BeforeToolCallDecision>\n\n /**\n * Called after a tool execution completes (success or failure).\n */\n onAfterToolCall?: (\n ctx: ChatMiddlewareContext<TContext>,\n info: AfterToolCallInfo,\n ) => void | Promise<void>\n\n /**\n * Called after all tool calls in an iteration have been processed.\n * Provides aggregate data about tool execution results, approvals, and client tools.\n */\n onToolPhaseComplete?: (\n ctx: ChatMiddlewareContext<TContext>,\n info: ToolPhaseCompleteInfo,\n ) => void | Promise<void>\n\n /**\n * Called when usage data is available from a RUN_FINISHED chunk.\n * Called once per model iteration that reports usage.\n */\n onUsage?: (\n ctx: ChatMiddlewareContext<TContext>,\n usage: UsageInfo,\n ) => void | Promise<void>\n\n /**\n * Called when the chat run completes normally.\n * Exactly one of onFinish/onAbort/onError will be called per run.\n */\n onFinish?: (\n ctx: ChatMiddlewareContext<TContext>,\n info: FinishInfo,\n ) => void | Promise<void>\n\n /**\n * Called when the chat run is aborted.\n * Exactly one of onFinish/onAbort/onError will be called per run.\n */\n onAbort?: (\n ctx: ChatMiddlewareContext<TContext>,\n info: AbortInfo,\n ) => void | Promise<void>\n\n /**\n * Called when the chat run encounters an unhandled error.\n * Exactly one of onFinish/onAbort/onError will be called per run.\n */\n onError?: (\n ctx: ChatMiddlewareContext<TContext>,\n info: ErrorInfo,\n ) => void | Promise<void>\n\n /**\n * Sandbox file-event hooks. Fire when a sandbox provided by `withSandbox` is\n * active during the run and a file is created/changed/deleted. Server-side.\n */\n sandbox?: ChatSandboxHooks<TContext>\n}\n\n/** A `ChatMiddleware` with a permissive context — for use as a constraint. */\n/** A permissive middleware constraint that retains the definition parameter. */\nexport type AnyChatMiddleware = ChatMiddleware<any, any>\n"],"mappings":";AAiGA,IAAa,4BAA4B;CACvC;CACA;CACA;CACA;AACF;AAIA,IAAa,yBAAyB;CAAC;CAAY;CAAU;AAAM"}
|