@tanstack/ai 0.61.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/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 +156 -57
- package/dist/esm/activities/chat/index.js.map +1 -1
- package/dist/esm/activities/chat/messages.js +30 -18
- 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 +2 -1
- package/dist/esm/activities/chat/stream/message-updaters.js.map +1 -1
- package/dist/esm/activities/chat/stream/processor.d.ts +11 -9
- package/dist/esm/activities/chat/stream/processor.js +38 -18
- 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 +55 -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/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/client.d.ts +1 -1
- package/dist/esm/client.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +2 -2
- 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 +42 -1
- package/dist/esm/utilities/ag-ui-wire.js +5 -3
- package/dist/esm/utilities/ag-ui-wire.js.map +1 -1
- package/dist/esm/utilities/tool-result.d.ts +2 -1
- package/dist/esm/utilities/tool-result.js +4 -1
- package/dist/esm/utilities/tool-result.js.map +1 -1
- package/package.json +3 -3
- package/skills/ai-core/chat-experience/SKILL.md +120 -0
- package/skills/ai-core/tool-calling/SKILL.md +103 -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 +235 -62
- package/src/activities/chat/messages.ts +40 -5
- package/src/activities/chat/middleware/types.ts +1 -0
- package/src/activities/chat/stream/message-updaters.ts +3 -0
- package/src/activities/chat/stream/processor.ts +57 -27
- package/src/activities/chat/tools/tool-calls.ts +98 -9
- package/src/activities/chat/tools/tool-definition.ts +8 -0
- package/src/activities/evaluate/adapter.ts +4 -0
- package/src/activities/evaluate/index.ts +6 -0
- package/src/client.ts +1 -0
- package/src/index.ts +1 -0
- package/src/interrupt-resume.ts +55 -4
- package/src/middlewares/otel.ts +161 -3
- package/src/types.ts +38 -1
- package/src/utilities/ag-ui-wire.ts +12 -1
- package/src/utilities/tool-result.ts +7 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ag-ui-wire.js","names":[],"sources":["../../../src/utilities/ag-ui-wire.ts"],"sourcesContent":["import type {\n AssistantMessage,\n InputContent,\n ReasoningMessage,\n SystemMessage,\n ToolCall,\n ToolMessage,\n UserMessage,\n} from '@ag-ui/core'\nimport type {\n ContentPart,\n MessagePart,\n ModelMessage,\n StructuredOutputPart,\n SubagentPart,\n TanStackMessageMetadata,\n UIMessage,\n UIResourcePart,\n} from '../types'\nimport type { MetadataRecord } from './merge-metadata'\nimport { tanstackMetadata } from './merge-metadata'\nimport { isProviderExecutedToolCall } from './provider-executed'\nimport { normalizeToolResult } from './tool-result'\nimport { wireSubagentInfo, wireSubagentRunId } from './subagent-wire'\nimport type { SubagentWireInfo } from './subagent-wire'\nimport {\n coerceCreatedAt,\n modelMessageToUIMessage,\n} from '../activities/chat/messages'\n\ntype WithMetadata<T> = T & { metadata?: MetadataRecord }\ntype WireSystemMessage = WithMetadata<SystemMessage>\ntype WireUserMessage = WithMetadata<UserMessage>\ntype WireAssistantMessage = WithMetadata<AssistantMessage>\ntype WireToolMessage = WithMetadata<\n ToolMessage & {\n name?: string\n }\n>\ntype WireReasoningMessage = WithMetadata<ReasoningMessage>\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction rebuiltToolMetadata(\n metadata: unknown,\n createdAt: unknown,\n id: string | undefined,\n content: string | null | Array<ContentPart>,\n anchorOwnsUiResources = false,\n): MetadataRecord | undefined {\n const source: MetadataRecord = isRecord(metadata) ? metadata : {}\n const tanstack = isRecord(source.tanstack) ? { ...source.tanstack } : {}\n if (anchorOwnsUiResources) delete tanstack.uiResources\n const date = coerceCreatedAt(createdAt)\n const toolResult: NonNullable<TanStackMessageMetadata['toolResult']> = {\n ...(id !== undefined ? { id } : {}),\n ...(date && { createdAt: date.toISOString() }),\n ...(Array.isArray(content) && { content }),\n }\n const result = {\n ...source,\n tanstack: { ...tanstack, toolResult },\n }\n return Object.keys(result).length ? result : undefined\n}\n\nexport type WireMessage =\n | WireSystemMessage\n | WireUserMessage\n | WireAssistantMessage\n | WireToolMessage\n | WireReasoningMessage\n\n/**\n * Serialize TanStack `UIMessage`s and `ModelMessage`s into the AG-UI\n * `RunAgentInput.messages` wire shape. Anchors are spec-only (`id`, `role`,\n * `name`, `content`, `toolCalls`, `metadata`). Tool results and thinking parts\n * on assistant messages are additionally emitted as fan-out\n * `{role:'tool',...}` and `{role:'reasoning',...}` entries for strict AG-UI\n * server consumers. Set `includeSnapshotStructuredOutput` to retain complete\n * structured-output metadata for UI snapshots.\n */\nexport function uiMessagesToWire(\n messages: Array<UIMessage | ModelMessage>,\n options?: { includeSnapshotStructuredOutput: boolean },\n): Array<WireMessage> {\n const wire: Array<WireMessage> = []\n const usedWireIds = new Set<string>(\n messages.flatMap((message) =>\n 'id' in message && message.id && message.role !== 'tool'\n ? [message.id]\n : [],\n ),\n )\n const includeSnapshotStructuredOutput =\n options?.includeSnapshotStructuredOutput ?? false\n\n const assistantIds = new Set<string>()\n for (const msg of messages) {\n if (msg.role === 'assistant' && msg.id !== undefined) {\n assistantIds.add(msg.id)\n }\n }\n\n for (const msg of messages) {\n if (!('parts' in msg) && msg.role === 'tool' && msg.toolCallId) {\n const id = uniqueToolWireId(\n toolWireId(msg.id, msg.toolCallId, assistantIds),\n usedWireIds,\n )\n const metadata = rebuiltToolMetadata(\n msg.metadata,\n msg.createdAt,\n msg.id,\n msg.content,\n )\n wire.push({\n role: 'tool',\n id,\n ...(msg.name !== undefined && { name: msg.name }),\n toolCallId: msg.toolCallId,\n content:\n typeof msg.content === 'string'\n ? msg.content\n : JSON.stringify(msg.content),\n ...(msg.error !== undefined && { error: msg.error }),\n ...(metadata !== undefined && { metadata }),\n })\n continue\n }\n\n const uiMessage: UIMessage =\n 'parts' in msg ? msg : modelMessageToUIMessage(msg, msg.id)\n const parts: ReadonlyArray<MessagePart> = uiMessage.parts\n usedWireIds.add(uiMessage.id)\n\n if (msg.role === 'system') {\n wire.push(\n toAnchor(\n uiMessage,\n 'system',\n {\n content:\n parts.length > 0\n ? collectText(parts)\n : ((msg as { content?: string }).content ?? ''),\n },\n parts,\n includeSnapshotStructuredOutput,\n ),\n )\n continue\n }\n\n if (msg.role === 'user') {\n wire.push(\n toAnchor(\n uiMessage,\n 'user',\n {\n content:\n parts.length > 0\n ? collectUserContent(parts)\n : ((msg as { content?: string }).content ?? ''),\n },\n parts,\n includeSnapshotStructuredOutput,\n ),\n )\n continue\n }\n\n // assistant: reasoning fan-outs, then anchor, then tool fan-outs.\n //\n // Provider-executed tools (Anthropic web_search / web_fetch) run inside one\n // provider response, and the provider signs every thinking block against\n // the blocks before it. Emitting all reasoning first and a single anchor\n // with the joined text and every tool call turns\n // \"thinking, tool, thinking, text, tool\" into\n // \"thinking, thinking, text, tool, tool\", and the provider rejects the next\n // turn (\"thinking blocks in the latest assistant message cannot be\n // modified\"). Split the message into ordered segments at each thinking\n // part that follows a provider-executed tool call, the same rule\n // buildAssistantMessages applies, so the wire keeps the signed order.\n // Segments after the first get derived anchor ids; strict AG-UI consumers\n // still see plain anchors.\n type Segment = {\n thinking: Array<Extract<MessagePart, { type: 'thinking' }>>\n parts: Array<MessagePart>\n }\n let current: Segment = { thinking: [], parts: [] }\n const segments: Array<Segment> = [current]\n for (const part of parts) {\n if (part.type === 'thinking') {\n if (\n current.parts.some(\n (p) => p.type === 'tool-call' && isProviderExecutedToolCall(p),\n )\n ) {\n current = { thinking: [part], parts: [] }\n segments.push(current)\n } else {\n current.thinking.push(part)\n }\n } else {\n current.parts.push(part)\n }\n }\n\n segments.forEach((segment, index) => {\n for (const part of segment.thinking) {\n const reasoning: WireReasoningMessage = {\n role: 'reasoning',\n id: uniqueWireId(deriveReasoningId(uiMessage.id, part), usedWireIds),\n content: part.content,\n }\n if (part.signature) {\n reasoning.encryptedValue = part.signature\n }\n wire.push(reasoning)\n }\n\n const text = collectText(segment.parts)\n const toolCalls = collectToolCalls(segment.parts)\n const anchorMessage: UIMessage =\n index === 0\n ? uiMessage\n : {\n ...uiMessage,\n id: uniqueWireId(`${uiMessage.id}-segment-${index}`, usedWireIds),\n }\n wire.push(\n toAnchor(\n anchorMessage,\n 'assistant',\n {\n ...(text !== '' && { content: text }),\n ...(toolCalls && { toolCalls }),\n },\n segment.parts,\n includeSnapshotStructuredOutput,\n ),\n )\n })\n\n const explicitToolResults = new Set(\n parts.flatMap((part) =>\n part.type === 'tool-result' ? [part.toolCallId] : [],\n ),\n )\n for (const part of parts) {\n if (part.type === 'tool-result') {\n const id = uniqueToolWireId(\n part.id ?? deriveToolMessageId(part.toolCallId),\n usedWireIds,\n )\n const metadata = rebuiltToolMetadata(\n part.metadata,\n part.createdAt,\n part.id,\n part.content,\n true,\n )\n wire.push({\n role: 'tool',\n id,\n toolCallId: part.toolCallId,\n ...(part.name !== undefined && { name: part.name }),\n content:\n typeof part.content === 'string'\n ? part.content\n : JSON.stringify(part.content),\n ...(part.error !== undefined && { error: part.error }),\n ...(metadata !== undefined && { metadata }),\n })\n } else if (part.type === 'tool-call') {\n const approved = part.approval?.approved\n if (\n explicitToolResults.has(part.id) ||\n (part.output === undefined &&\n (part.state !== 'approval-responded' || approved === undefined))\n ) {\n continue\n }\n const result =\n part.output !== undefined\n ? normalizeToolResult(part.output)\n : JSON.stringify({\n approved,\n ...(approved && { pendingExecution: true }),\n message: approved\n ? 'User approved this action'\n : 'User denied this action',\n })\n const content =\n typeof result === 'string' ? result : JSON.stringify(result)\n wire.push({\n role: 'tool',\n id: uniqueToolWireId(deriveToolMessageId(part.id), usedWireIds),\n toolCallId: part.id,\n content,\n metadata: rebuiltToolMetadata(\n undefined,\n undefined,\n undefined,\n result,\n ),\n })\n }\n }\n\n for (const part of parts) {\n if (part.type === 'subagent') wire.push(...subagentToWire(part, options))\n }\n }\n\n return wire\n}\n\nfunction toAnchor(\n msg: UIMessage,\n role: 'system',\n extras: { content: string },\n parts: ReadonlyArray<MessagePart>,\n includeSnapshotStructuredOutput: boolean,\n): WireSystemMessage\nfunction toAnchor(\n msg: UIMessage,\n role: 'user',\n extras: { content: string | Array<InputContent> },\n parts: ReadonlyArray<MessagePart>,\n includeSnapshotStructuredOutput: boolean,\n): WireUserMessage\nfunction toAnchor(\n msg: UIMessage,\n role: 'assistant',\n extras: {\n content?: string\n toolCalls?: Array<ToolCall>\n },\n parts: ReadonlyArray<MessagePart>,\n includeSnapshotStructuredOutput: boolean,\n): WireAssistantMessage\nfunction toAnchor(\n msg: UIMessage,\n role: UIMessage['role'],\n extras: {\n content?: string | Array<InputContent>\n toolCalls?: Array<ToolCall>\n },\n parts: ReadonlyArray<MessagePart>,\n includeSnapshotStructuredOutput: boolean,\n): WireSystemMessage | WireUserMessage | WireAssistantMessage {\n const metadata = messageMetadata(msg, parts, includeSnapshotStructuredOutput)\n const base = {\n id: msg.id,\n ...(msg.name !== undefined && { name: msg.name }),\n ...(metadata !== undefined && { metadata }),\n }\n if (role === 'system') {\n return { ...base, role, content: String(extras.content ?? '') }\n }\n if (role === 'user') {\n return { ...base, role, content: extras.content ?? '' }\n }\n return {\n ...base,\n role,\n ...(typeof extras.content === 'string' && { content: extras.content }),\n ...(extras.toolCalls !== undefined && { toolCalls: extras.toolCalls }),\n }\n}\n\nfunction messageMetadata(\n msg: UIMessage,\n parts: ReadonlyArray<MessagePart>,\n includeSnapshotStructuredOutput: boolean,\n): MetadataRecord | undefined {\n const base: MetadataRecord = { ...(msg.metadata ?? {}) }\n const previousTanstack = tanstackMetadata(msg)\n const tanstack: TanStackMessageMetadata = {}\n if (previousTanstack?.model !== undefined)\n tanstack.model = previousTanstack.model\n if (previousTanstack?.runId !== undefined)\n tanstack.runId = previousTanstack.runId\n if (previousTanstack?.signature !== undefined)\n tanstack.signature = previousTanstack.signature\n const createdAt = coerceCreatedAt(msg.createdAt)\n if (createdAt !== undefined) tanstack.createdAt = createdAt.toISOString()\n\n const structuredOutput = serializedStructuredOutput(\n parts,\n includeSnapshotStructuredOutput,\n )\n if (structuredOutput) tanstack.structuredOutput = structuredOutput\n\n const toolCallMetadata: Record<string, unknown> = {}\n for (const part of parts) {\n if (part.type === 'tool-call' && part.metadata !== undefined) {\n toolCallMetadata[part.id] = part.metadata\n }\n }\n if (Object.keys(toolCallMetadata).length > 0) {\n tanstack.toolCallMetadata = toolCallMetadata\n }\n\n const uiResources = parts.filter(\n (p): p is UIResourcePart => p.type === 'ui-resource',\n )\n if (uiResources.length > 0) tanstack.uiResources = uiResources\n\n if (Object.keys(tanstack).length > 0) base.tanstack = tanstack\n else delete base.tanstack\n return Object.keys(base).length > 0 ? base : undefined\n}\n\nfunction serializedStructuredOutput(\n parts: ReadonlyArray<MessagePart>,\n includeSnapshotStructuredOutput: boolean,\n): TanStackMessageMetadata['structuredOutput'] | undefined {\n for (const p of parts) {\n if (\n p.type === 'structured-output' &&\n (includeSnapshotStructuredOutput || p.status !== 'complete')\n ) {\n return structuredOutputMetadata(p, includeSnapshotStructuredOutput)\n }\n }\n return undefined\n}\n\nfunction structuredOutputMetadata(\n part: StructuredOutputPart,\n includeSnapshotStructuredOutput: boolean,\n): NonNullable<TanStackMessageMetadata['structuredOutput']> {\n return {\n status: part.status,\n raw: part.raw,\n ...(includeSnapshotStructuredOutput && part.partial !== undefined\n ? { partial: part.partial }\n : {}),\n ...(includeSnapshotStructuredOutput && part.data !== undefined\n ? { data: part.data }\n : {}),\n ...(includeSnapshotStructuredOutput && part.reasoning\n ? { reasoning: part.reasoning }\n : {}),\n ...(part.errorMessage !== undefined && { errorMessage: part.errorMessage }),\n }\n}\n\nfunction collectText(parts: ReadonlyArray<MessagePart>): string {\n // The streamed JSON of a completed structured-output part is the source of\n // truth for multi-turn coherence — emitting it back as assistant content\n // lets the LLM see its own prior structured response. Streaming/errored\n // parts are skipped: they'd ship malformed JSON fragments and confuse the\n // model. `completeStructuredOutputPart` tries hard to populate `raw`\n // (caller → existing buffer → `JSON.stringify(data)`), but the stringify\n // fallback can leave it empty when `data` is unserializable (BigInt,\n // circular). The `p.raw !== ''` guard below is what enforces \"no malformed\n // round-trip\" in that case — without it we'd ship `''` and the model would\n // see an empty assistant turn.\n const out: Array<string> = []\n for (const p of parts) {\n if (p.type === 'text') {\n out.push(p.content)\n } else if (\n p.type === 'structured-output' &&\n p.status === 'complete' &&\n p.raw !== ''\n ) {\n out.push(p.raw)\n }\n }\n return out.join('')\n}\n\n/**\n * A child's messages, tagged with its AG-UI `subagentRunId`. The card data\n * rides in `metadata.tanstack.subagent`, so the other side can rebuild the\n * card and continue a suspended child.\n */\nfunction subagentToWire(\n part: SubagentPart,\n options?: { includeSnapshotStructuredOutput: boolean },\n): Array<WireMessage> {\n const { subagent } = part\n const info: SubagentWireInfo = {\n name: subagent.name,\n status: subagent.status,\n ...(subagent.description !== undefined && {\n description: subagent.description,\n }),\n ...(subagent.error !== undefined && { error: subagent.error }),\n ...(subagent.interruptIds !== undefined && {\n interruptIds: subagent.interruptIds,\n }),\n ...(subagent.parentSubagentRunId !== undefined && {\n parentSubagentRunId: subagent.parentSubagentRunId,\n }),\n ...(subagent.parentToolCallId !== undefined && {\n parentToolCallId: subagent.parentToolCallId,\n }),\n ...(subagent.metadata !== undefined && { metadata: subagent.metadata }),\n }\n const child = uiMessagesToWire(subagent.messages, options)\n const own = child.some((message) => wireSubagentRunId(message) === undefined)\n const messages: Array<WireMessage> = own\n ? child\n : [{ id: `subagent:${subagent.id}`, role: 'assistant' }, ...child]\n return messages.map((message, index) => {\n const nestedId = wireSubagentRunId(message)\n if (nestedId !== undefined) {\n const nested = wireSubagentInfo(message)\n if (!nested || nested.parentSubagentRunId !== undefined) return message\n return withSubagentInfo(message, nestedId, {\n ...nested,\n parentSubagentRunId: subagent.id,\n })\n }\n return withSubagentInfo(\n message,\n subagent.id,\n !own && index === 0 ? { ...info, placeholder: true } : info,\n )\n })\n}\n\nfunction withSubagentInfo(\n message: WireMessage,\n subagentRunId: string,\n info: SubagentWireInfo,\n): WireMessage {\n const metadata = isRecord(message.metadata) ? message.metadata : {}\n const tanstack = isRecord(metadata.tanstack) ? metadata.tanstack : {}\n return {\n ...message,\n subagentRunId,\n metadata: { ...metadata, tanstack: { ...tanstack, subagent: info } },\n }\n}\n\nfunction collectUserContent(\n parts: ReadonlyArray<MessagePart>,\n): string | Array<InputContent> {\n const hasMultimodal = parts.some(\n (p) =>\n p.type === 'image' ||\n p.type === 'audio' ||\n p.type === 'video' ||\n p.type === 'document',\n )\n if (!hasMultimodal) {\n return collectText(parts)\n }\n const out: Array<InputContent> = []\n for (const p of parts) {\n if (p.type === 'text') {\n out.push({ type: 'text', text: p.content })\n } else if (\n p.type === 'image' ||\n p.type === 'audio' ||\n p.type === 'video' ||\n p.type === 'document'\n ) {\n out.push(p)\n }\n }\n return out\n}\n\nfunction thoughtSignatureFromMetadata(metadata: unknown): string | undefined {\n if (\n metadata == null ||\n typeof metadata !== 'object' ||\n Array.isArray(metadata)\n ) {\n return undefined\n }\n if (!('thoughtSignature' in metadata)) return undefined\n const value = metadata.thoughtSignature\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\nfunction collectToolCalls(\n parts: ReadonlyArray<MessagePart>,\n): Array<ToolCall> | undefined {\n const calls: Array<ToolCall> = []\n for (const p of parts) {\n if (p.type === 'tool-call') {\n const encryptedValue = thoughtSignatureFromMetadata(p.metadata)\n calls.push({\n id: p.id,\n type: 'function',\n function: { name: p.name, arguments: p.arguments },\n ...(encryptedValue !== undefined ? { encryptedValue } : {}),\n })\n }\n }\n return calls.length > 0 ? calls : undefined\n}\n\nfunction deriveReasoningId(messageId: string, part: MessagePart): string {\n return `${messageId}-reasoning-${(part as { id?: string }).id ?? hashContent((part as { content: string }).content)}`\n}\n\nfunction deriveToolMessageId(toolCallId: string): string {\n return `tool-${toolCallId}`\n}\n\nfunction uniqueToolWireId(id: string, used: Set<string>): string {\n return uniqueWireId(id, used)\n}\n\nfunction uniqueWireId(id: string, used: Set<string>): string {\n if (!used.has(id)) {\n used.add(id)\n return id\n }\n let suffix = 2\n while (used.has(`${id}-${suffix}`)) suffix++\n const unique = `${id}-${suffix}`\n used.add(unique)\n return unique\n}\n\nfunction toolWireId(\n id: string | undefined,\n toolCallId: string,\n assistantIds: ReadonlySet<string>,\n): string {\n const derived = deriveToolMessageId(toolCallId)\n if (id === undefined || assistantIds.has(id)) return derived\n return id\n}\n\nfunction hashContent(s: string): string {\n // Cheap deterministic id suffix; collisions are tolerable since\n // reasoning ids only matter for AG-UI server consumers, not for our\n // own server's dedup logic (which keys on toolCallId, not reasoning id).\n let h = 0\n for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0\n return Math.abs(h).toString(36)\n}\n"],"mappings":";;;;;;AAyCA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,oBACP,UACA,WACA,IACA,SACA,wBAAwB,OACI;CAC5B,MAAM,SAAyB,SAAS,QAAQ,IAAI,WAAW,CAAC;CAChE,MAAM,WAAW,SAAS,OAAO,QAAQ,IAAI,EAAE,GAAG,OAAO,SAAS,IAAI,CAAC;CACvE,IAAI,uBAAuB,OAAO,SAAS;CAC3C,MAAM,OAAO,gBAAgB,SAAS;CACtC,MAAM,aAAiE;EACrE,GAAI,OAAO,KAAA,IAAY,EAAE,GAAG,IAAI,CAAC;EACjC,GAAI,QAAQ,EAAE,WAAW,KAAK,YAAY,EAAE;EAC5C,GAAI,MAAM,QAAQ,OAAO,KAAK,EAAE,QAAQ;CAC1C;CACA,MAAM,SAAS;EACb,GAAG;EACH,UAAU;GAAE,GAAG;GAAU;EAAW;CACtC;CACA,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,SAAS,KAAA;AAC/C;;;;;;;;;;AAkBA,SAAgB,iBACd,UACA,SACoB;CACpB,MAAM,OAA2B,CAAC;CAClC,MAAM,cAAc,IAAI,IACtB,SAAS,SAAS,YAChB,QAAQ,WAAW,QAAQ,MAAM,QAAQ,SAAS,SAC9C,CAAC,QAAQ,EAAE,IACX,CAAC,CACP,CACF;CACA,MAAM,kCACJ,SAAS,mCAAmC;CAE9C,MAAM,+BAAe,IAAI,IAAY;CACrC,KAAK,MAAM,OAAO,UAChB,IAAI,IAAI,SAAS,eAAe,IAAI,OAAO,KAAA,GACzC,aAAa,IAAI,IAAI,EAAE;CAI3B,KAAK,MAAM,OAAO,UAAU;EAC1B,IAAI,EAAE,WAAW,QA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K,IAAI,CAAC,CAAC,CAAC,SAAS,EAAE;AAChC"}
|
|
1
|
+
{"version":3,"file":"ag-ui-wire.js","names":[],"sources":["../../../src/utilities/ag-ui-wire.ts"],"sourcesContent":["import type {\n AssistantMessage,\n InputContent,\n ReasoningMessage,\n SystemMessage,\n ToolCall,\n ToolMessage,\n UserMessage,\n} from '@ag-ui/core'\nimport type {\n ContentPart,\n MessagePart,\n ModelMessage,\n StructuredOutputPart,\n SubagentPart,\n TanStackMessageMetadata,\n ToolResultOutcome,\n UIMessage,\n UIResourcePart,\n} from '../types'\nimport type { MetadataRecord } from './merge-metadata'\nimport { tanstackMetadata } from './merge-metadata'\nimport { isProviderExecutedToolCall } from './provider-executed'\nimport { normalizeToolResult } from './tool-result'\nimport { wireSubagentInfo, wireSubagentRunId } from './subagent-wire'\nimport type { SubagentWireInfo } from './subagent-wire'\nimport {\n coerceCreatedAt,\n modelMessageToUIMessage,\n} from '../activities/chat/messages'\n\ntype WithMetadata<T> = T & { metadata?: MetadataRecord }\ntype WireSystemMessage = WithMetadata<SystemMessage>\ntype WireUserMessage = WithMetadata<UserMessage>\ntype WireAssistantMessage = WithMetadata<AssistantMessage>\ntype WireToolMessage = WithMetadata<\n ToolMessage & {\n name?: string\n }\n>\ntype WireReasoningMessage = WithMetadata<ReasoningMessage>\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction rebuiltToolMetadata(\n metadata: unknown,\n createdAt: unknown,\n id: string | undefined,\n content: string | null | Array<ContentPart>,\n anchorOwnsUiResources = false,\n outcome?: ToolResultOutcome,\n): MetadataRecord | undefined {\n const source: MetadataRecord = isRecord(metadata) ? metadata : {}\n const tanstack = isRecord(source.tanstack) ? { ...source.tanstack } : {}\n if (anchorOwnsUiResources) delete tanstack.uiResources\n const date = coerceCreatedAt(createdAt)\n const toolResult: NonNullable<TanStackMessageMetadata['toolResult']> = {\n ...(id !== undefined ? { id } : {}),\n ...(date && { createdAt: date.toISOString() }),\n ...(Array.isArray(content) && { content }),\n }\n const result = {\n ...source,\n tanstack: {\n ...tanstack,\n ...(outcome !== undefined && { toolResultOutcome: outcome }),\n toolResult,\n },\n }\n return Object.keys(result).length ? result : undefined\n}\n\nexport type WireMessage =\n | WireSystemMessage\n | WireUserMessage\n | WireAssistantMessage\n | WireToolMessage\n | WireReasoningMessage\n\n/**\n * Serialize TanStack `UIMessage`s and `ModelMessage`s into the AG-UI\n * `RunAgentInput.messages` wire shape. Anchors are spec-only (`id`, `role`,\n * `name`, `content`, `toolCalls`, `metadata`). Tool results and thinking parts\n * on assistant messages are additionally emitted as fan-out\n * `{role:'tool',...}` and `{role:'reasoning',...}` entries for strict AG-UI\n * server consumers. Set `includeSnapshotStructuredOutput` to retain complete\n * structured-output metadata for UI snapshots.\n */\nexport function uiMessagesToWire(\n messages: Array<UIMessage | ModelMessage>,\n options?: { includeSnapshotStructuredOutput: boolean },\n): Array<WireMessage> {\n const wire: Array<WireMessage> = []\n const usedWireIds = new Set<string>(\n messages.flatMap((message) =>\n 'id' in message && message.id && message.role !== 'tool'\n ? [message.id]\n : [],\n ),\n )\n const includeSnapshotStructuredOutput =\n options?.includeSnapshotStructuredOutput ?? false\n\n const assistantIds = new Set<string>()\n for (const msg of messages) {\n if (msg.role === 'assistant' && msg.id !== undefined) {\n assistantIds.add(msg.id)\n }\n }\n\n for (const msg of messages) {\n if (!('parts' in msg) && msg.role === 'tool' && msg.toolCallId) {\n const id = uniqueToolWireId(\n toolWireId(msg.id, msg.toolCallId, assistantIds),\n usedWireIds,\n )\n const metadata = rebuiltToolMetadata(\n msg.metadata,\n msg.createdAt,\n msg.id,\n msg.content,\n )\n wire.push({\n role: 'tool',\n id,\n ...(msg.name !== undefined && { name: msg.name }),\n toolCallId: msg.toolCallId,\n content:\n typeof msg.content === 'string'\n ? msg.content\n : JSON.stringify(msg.content),\n ...(msg.error !== undefined && { error: msg.error }),\n ...(metadata !== undefined && { metadata }),\n })\n continue\n }\n\n const uiMessage: UIMessage =\n 'parts' in msg ? msg : modelMessageToUIMessage(msg, msg.id)\n const parts: ReadonlyArray<MessagePart> = uiMessage.parts\n usedWireIds.add(uiMessage.id)\n\n if (msg.role === 'system') {\n wire.push(\n toAnchor(\n uiMessage,\n 'system',\n {\n content:\n parts.length > 0\n ? collectText(parts)\n : ((msg as { content?: string }).content ?? ''),\n },\n parts,\n includeSnapshotStructuredOutput,\n ),\n )\n continue\n }\n\n if (msg.role === 'user') {\n wire.push(\n toAnchor(\n uiMessage,\n 'user',\n {\n content:\n parts.length > 0\n ? collectUserContent(parts)\n : ((msg as { content?: string }).content ?? ''),\n },\n parts,\n includeSnapshotStructuredOutput,\n ),\n )\n continue\n }\n\n // assistant: reasoning fan-outs, then anchor, then tool fan-outs.\n //\n // Provider-executed tools (Anthropic web_search / web_fetch) run inside one\n // provider response, and the provider signs every thinking block against\n // the blocks before it. Emitting all reasoning first and a single anchor\n // with the joined text and every tool call turns\n // \"thinking, tool, thinking, text, tool\" into\n // \"thinking, thinking, text, tool, tool\", and the provider rejects the next\n // turn (\"thinking blocks in the latest assistant message cannot be\n // modified\"). Split the message into ordered segments at each thinking\n // part that follows a provider-executed tool call, the same rule\n // buildAssistantMessages applies, so the wire keeps the signed order.\n // Segments after the first get derived anchor ids; strict AG-UI consumers\n // still see plain anchors.\n type Segment = {\n thinking: Array<Extract<MessagePart, { type: 'thinking' }>>\n parts: Array<MessagePart>\n }\n let current: Segment = { thinking: [], parts: [] }\n const segments: Array<Segment> = [current]\n for (const part of parts) {\n if (part.type === 'thinking') {\n if (\n current.parts.some(\n (p) => p.type === 'tool-call' && isProviderExecutedToolCall(p),\n )\n ) {\n current = { thinking: [part], parts: [] }\n segments.push(current)\n } else {\n current.thinking.push(part)\n }\n } else {\n current.parts.push(part)\n }\n }\n\n segments.forEach((segment, index) => {\n for (const part of segment.thinking) {\n const reasoning: WireReasoningMessage = {\n role: 'reasoning',\n id: uniqueWireId(deriveReasoningId(uiMessage.id, part), usedWireIds),\n content: part.content,\n }\n if (part.signature) {\n reasoning.encryptedValue = part.signature\n }\n wire.push(reasoning)\n }\n\n const text = collectText(segment.parts)\n const toolCalls = collectToolCalls(segment.parts)\n const anchorMessage: UIMessage =\n index === 0\n ? uiMessage\n : {\n ...uiMessage,\n id: uniqueWireId(`${uiMessage.id}-segment-${index}`, usedWireIds),\n }\n wire.push(\n toAnchor(\n anchorMessage,\n 'assistant',\n {\n ...(text !== '' && { content: text }),\n ...(toolCalls && { toolCalls }),\n },\n segment.parts,\n includeSnapshotStructuredOutput,\n ),\n )\n })\n\n const explicitToolResults = new Set(\n parts.flatMap((part) =>\n part.type === 'tool-result' ? [part.toolCallId] : [],\n ),\n )\n for (const part of parts) {\n if (part.type === 'tool-result') {\n const id = uniqueToolWireId(\n part.id ?? deriveToolMessageId(part.toolCallId),\n usedWireIds,\n )\n const metadata = rebuiltToolMetadata(\n part.metadata,\n part.createdAt,\n part.id,\n part.content,\n true,\n part.outcome,\n )\n wire.push({\n role: 'tool',\n id,\n toolCallId: part.toolCallId,\n ...(part.name !== undefined && { name: part.name }),\n content:\n typeof part.content === 'string'\n ? part.content\n : JSON.stringify(part.content),\n ...(part.error !== undefined && { error: part.error }),\n ...(metadata !== undefined && { metadata }),\n })\n } else if (part.type === 'tool-call') {\n const approved = part.approval?.approved\n if (\n explicitToolResults.has(part.id) ||\n (part.output === undefined &&\n (part.state !== 'approval-responded' || approved === undefined))\n ) {\n continue\n }\n const result =\n part.output !== undefined\n ? normalizeToolResult(part.output)\n : JSON.stringify({\n approved,\n ...(approved && { pendingExecution: true }),\n message: approved\n ? 'User approved this action'\n : 'User denied this action',\n })\n const content =\n typeof result === 'string' ? result : JSON.stringify(result)\n wire.push({\n role: 'tool',\n id: uniqueToolWireId(deriveToolMessageId(part.id), usedWireIds),\n toolCallId: part.id,\n content,\n metadata: rebuiltToolMetadata(\n undefined,\n undefined,\n undefined,\n result,\n false,\n part.approval?.approved === false ? 'denied' : undefined,\n ),\n })\n }\n }\n\n for (const part of parts) {\n if (part.type === 'subagent') wire.push(...subagentToWire(part, options))\n }\n }\n\n return wire\n}\n\nfunction toAnchor(\n msg: UIMessage,\n role: 'system',\n extras: { content: string },\n parts: ReadonlyArray<MessagePart>,\n includeSnapshotStructuredOutput: boolean,\n): WireSystemMessage\nfunction toAnchor(\n msg: UIMessage,\n role: 'user',\n extras: { content: string | Array<InputContent> },\n parts: ReadonlyArray<MessagePart>,\n includeSnapshotStructuredOutput: boolean,\n): WireUserMessage\nfunction toAnchor(\n msg: UIMessage,\n role: 'assistant',\n extras: {\n content?: string\n toolCalls?: Array<ToolCall>\n },\n parts: ReadonlyArray<MessagePart>,\n includeSnapshotStructuredOutput: boolean,\n): WireAssistantMessage\nfunction toAnchor(\n msg: UIMessage,\n role: UIMessage['role'],\n extras: {\n content?: string | Array<InputContent>\n toolCalls?: Array<ToolCall>\n },\n parts: ReadonlyArray<MessagePart>,\n includeSnapshotStructuredOutput: boolean,\n): WireSystemMessage | WireUserMessage | WireAssistantMessage {\n const metadata = messageMetadata(msg, parts, includeSnapshotStructuredOutput)\n const base = {\n id: msg.id,\n ...(msg.name !== undefined && { name: msg.name }),\n ...(metadata !== undefined && { metadata }),\n }\n if (role === 'system') {\n return { ...base, role, content: String(extras.content ?? '') }\n }\n if (role === 'user') {\n return { ...base, role, content: extras.content ?? '' }\n }\n return {\n ...base,\n role,\n ...(typeof extras.content === 'string' && { content: extras.content }),\n ...(extras.toolCalls !== undefined && { toolCalls: extras.toolCalls }),\n }\n}\n\nfunction messageMetadata(\n msg: UIMessage,\n parts: ReadonlyArray<MessagePart>,\n includeSnapshotStructuredOutput: boolean,\n): MetadataRecord | undefined {\n const base: MetadataRecord = { ...(msg.metadata ?? {}) }\n const previousTanstack = tanstackMetadata(msg)\n const tanstack: TanStackMessageMetadata = {}\n if (previousTanstack?.model !== undefined)\n tanstack.model = previousTanstack.model\n if (previousTanstack?.runId !== undefined)\n tanstack.runId = previousTanstack.runId\n if (previousTanstack?.run?.id !== undefined)\n tanstack.run = { id: previousTanstack.run.id }\n if (previousTanstack?.signature !== undefined)\n tanstack.signature = previousTanstack.signature\n const createdAt = coerceCreatedAt(msg.createdAt)\n if (createdAt !== undefined) tanstack.createdAt = createdAt.toISOString()\n\n const structuredOutput = serializedStructuredOutput(\n parts,\n includeSnapshotStructuredOutput,\n )\n if (structuredOutput) tanstack.structuredOutput = structuredOutput\n\n const toolCallMetadata: Record<string, unknown> = {}\n for (const part of parts) {\n if (part.type === 'tool-call' && part.metadata !== undefined) {\n toolCallMetadata[part.id] = part.metadata\n }\n }\n if (Object.keys(toolCallMetadata).length > 0) {\n tanstack.toolCallMetadata = toolCallMetadata\n }\n\n const uiResources = parts.filter(\n (p): p is UIResourcePart => p.type === 'ui-resource',\n )\n if (uiResources.length > 0) tanstack.uiResources = uiResources\n\n if (Object.keys(tanstack).length > 0) base.tanstack = tanstack\n else delete base.tanstack\n return Object.keys(base).length > 0 ? base : undefined\n}\n\nfunction serializedStructuredOutput(\n parts: ReadonlyArray<MessagePart>,\n includeSnapshotStructuredOutput: boolean,\n): TanStackMessageMetadata['structuredOutput'] | undefined {\n for (const p of parts) {\n if (\n p.type === 'structured-output' &&\n (includeSnapshotStructuredOutput || p.status !== 'complete')\n ) {\n return structuredOutputMetadata(p, includeSnapshotStructuredOutput)\n }\n }\n return undefined\n}\n\nfunction structuredOutputMetadata(\n part: StructuredOutputPart,\n includeSnapshotStructuredOutput: boolean,\n): NonNullable<TanStackMessageMetadata['structuredOutput']> {\n return {\n status: part.status,\n raw: part.raw,\n ...(includeSnapshotStructuredOutput && part.partial !== undefined\n ? { partial: part.partial }\n : {}),\n ...(includeSnapshotStructuredOutput && part.data !== undefined\n ? { data: part.data }\n : {}),\n ...(includeSnapshotStructuredOutput && part.reasoning\n ? { reasoning: part.reasoning }\n : {}),\n ...(part.errorMessage !== undefined && { errorMessage: part.errorMessage }),\n }\n}\n\nfunction collectText(parts: ReadonlyArray<MessagePart>): string {\n // The streamed JSON of a completed structured-output part is the source of\n // truth for multi-turn coherence — emitting it back as assistant content\n // lets the LLM see its own prior structured response. Streaming/errored\n // parts are skipped: they'd ship malformed JSON fragments and confuse the\n // model. `completeStructuredOutputPart` tries hard to populate `raw`\n // (caller → existing buffer → `JSON.stringify(data)`), but the stringify\n // fallback can leave it empty when `data` is unserializable (BigInt,\n // circular). The `p.raw !== ''` guard below is what enforces \"no malformed\n // round-trip\" in that case — without it we'd ship `''` and the model would\n // see an empty assistant turn.\n const out: Array<string> = []\n for (const p of parts) {\n if (p.type === 'text') {\n out.push(p.content)\n } else if (\n p.type === 'structured-output' &&\n p.status === 'complete' &&\n p.raw !== ''\n ) {\n out.push(p.raw)\n }\n }\n return out.join('')\n}\n\n/**\n * A child's messages, tagged with its AG-UI `subagentRunId`. The card data\n * rides in `metadata.tanstack.subagent`, so the other side can rebuild the\n * card and continue a suspended child.\n */\nfunction subagentToWire(\n part: SubagentPart,\n options?: { includeSnapshotStructuredOutput: boolean },\n): Array<WireMessage> {\n const { subagent } = part\n const info: SubagentWireInfo = {\n name: subagent.name,\n status: subagent.status,\n ...(subagent.description !== undefined && {\n description: subagent.description,\n }),\n ...(subagent.error !== undefined && { error: subagent.error }),\n ...(subagent.interruptIds !== undefined && {\n interruptIds: subagent.interruptIds,\n }),\n ...(subagent.parentSubagentRunId !== undefined && {\n parentSubagentRunId: subagent.parentSubagentRunId,\n }),\n ...(subagent.parentToolCallId !== undefined && {\n parentToolCallId: subagent.parentToolCallId,\n }),\n ...(subagent.metadata !== undefined && { metadata: subagent.metadata }),\n }\n const child = uiMessagesToWire(subagent.messages, options)\n const own = child.some((message) => wireSubagentRunId(message) === undefined)\n const messages: Array<WireMessage> = own\n ? child\n : [{ id: `subagent:${subagent.id}`, role: 'assistant' }, ...child]\n return messages.map((message, index) => {\n const nestedId = wireSubagentRunId(message)\n if (nestedId !== undefined) {\n const nested = wireSubagentInfo(message)\n if (!nested || nested.parentSubagentRunId !== undefined) return message\n return withSubagentInfo(message, nestedId, {\n ...nested,\n parentSubagentRunId: subagent.id,\n })\n }\n return withSubagentInfo(\n message,\n subagent.id,\n !own && index === 0 ? { ...info, placeholder: true } : info,\n )\n })\n}\n\nfunction withSubagentInfo(\n message: WireMessage,\n subagentRunId: string,\n info: SubagentWireInfo,\n): WireMessage {\n const metadata = isRecord(message.metadata) ? message.metadata : {}\n const tanstack = isRecord(metadata.tanstack) ? metadata.tanstack : {}\n return {\n ...message,\n subagentRunId,\n metadata: { ...metadata, tanstack: { ...tanstack, subagent: info } },\n }\n}\n\nfunction collectUserContent(\n parts: ReadonlyArray<MessagePart>,\n): string | Array<InputContent> {\n const hasMultimodal = parts.some(\n (p) =>\n p.type === 'image' ||\n p.type === 'audio' ||\n p.type === 'video' ||\n p.type === 'document',\n )\n if (!hasMultimodal) {\n return collectText(parts)\n }\n const out: Array<InputContent> = []\n for (const p of parts) {\n if (p.type === 'text') {\n out.push({ type: 'text', text: p.content })\n } else if (\n p.type === 'image' ||\n p.type === 'audio' ||\n p.type === 'video' ||\n p.type === 'document'\n ) {\n out.push(p)\n }\n }\n return out\n}\n\nfunction thoughtSignatureFromMetadata(metadata: unknown): string | undefined {\n if (\n metadata == null ||\n typeof metadata !== 'object' ||\n Array.isArray(metadata)\n ) {\n return undefined\n }\n if (!('thoughtSignature' in metadata)) return undefined\n const value = metadata.thoughtSignature\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\nfunction collectToolCalls(\n parts: ReadonlyArray<MessagePart>,\n): Array<ToolCall> | undefined {\n const calls: Array<ToolCall> = []\n for (const p of parts) {\n if (p.type === 'tool-call') {\n const encryptedValue = thoughtSignatureFromMetadata(p.metadata)\n calls.push({\n id: p.id,\n type: 'function',\n function: { name: p.name, arguments: p.arguments },\n ...(encryptedValue !== undefined ? { encryptedValue } : {}),\n })\n }\n }\n return calls.length > 0 ? calls : undefined\n}\n\nfunction deriveReasoningId(messageId: string, part: MessagePart): string {\n return `${messageId}-reasoning-${(part as { id?: string }).id ?? hashContent((part as { content: string }).content)}`\n}\n\nfunction deriveToolMessageId(toolCallId: string): string {\n return `tool-${toolCallId}`\n}\n\nfunction uniqueToolWireId(id: string, used: Set<string>): string {\n return uniqueWireId(id, used)\n}\n\nfunction uniqueWireId(id: string, used: Set<string>): string {\n if (!used.has(id)) {\n used.add(id)\n return id\n }\n let suffix = 2\n while (used.has(`${id}-${suffix}`)) suffix++\n const unique = `${id}-${suffix}`\n used.add(unique)\n return unique\n}\n\nfunction toolWireId(\n id: string | undefined,\n toolCallId: string,\n assistantIds: ReadonlySet<string>,\n): string {\n const derived = deriveToolMessageId(toolCallId)\n if (id === undefined || assistantIds.has(id)) return derived\n return id\n}\n\nfunction hashContent(s: string): string {\n // Cheap deterministic id suffix; collisions are tolerable since\n // reasoning ids only matter for AG-UI server consumers, not for our\n // own server's dedup logic (which keys on toolCallId, not reasoning id).\n let h = 0\n for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0\n return Math.abs(h).toString(36)\n}\n"],"mappings":";;;;;;AA0CA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,oBACP,UACA,WACA,IACA,SACA,wBAAwB,OACxB,SAC4B;CAC5B,MAAM,SAAyB,SAAS,QAAQ,IAAI,WAAW,CAAC;CAChE,MAAM,WAAW,SAAS,OAAO,QAAQ,IAAI,EAAE,GAAG,OAAO,SAAS,IAAI,CAAC;CACvE,IAAI,uBAAuB,OAAO,SAAS;CAC3C,MAAM,OAAO,gBAAgB,SAAS;CACtC,MAAM,aAAiE;EACrE,GAAI,OAAO,KAAA,IAAY,EAAE,GAAG,IAAI,CAAC;EACjC,GAAI,QAAQ,EAAE,WAAW,KAAK,YAAY,EAAE;EAC5C,GAAI,MAAM,QAAQ,OAAO,KAAK,EAAE,QAAQ;CAC1C;CACA,MAAM,SAAS;EACb,GAAG;EACH,UAAU;GACR,GAAG;GACH,G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a,KAA6B,OAAO;AACpH;AAEA,SAAS,oBAAoB,YAA4B;CACvD,OAAO,QAAQ;AACjB;AAEA,SAAS,iBAAiB,IAAY,MAA2B;CAC/D,OAAO,aAAa,IAAI,IAAI;AAC9B;AAEA,SAAS,aAAa,IAAY,MAA2B;CAC3D,IAAI,CAAC,KAAK,IAAI,EAAE,GAAG;EACjB,KAAK,IAAI,EAAE;EACX,OAAO;CACT;CACA,IAAI,SAAS;CACb,OAAO,KAAK,IAAI,GAAG,GAAG,GAAG,QAAQ,GAAG;CACpC,MAAM,SAAS,GAAG,GAAG,GAAG;CACxB,KAAK,IAAI,MAAM;CACf,OAAO;AACT;AAEA,SAAS,WACP,IACA,YACA,cACQ;CACR,MAAM,UAAU,oBAAoB,UAAU;CAC9C,IAAI,OAAO,KAAA,KAAa,aAAa,IAAI,EAAE,GAAG,OAAO;CACrD,OAAO;AACT;AAEA,SAAS,YAAY,GAAmB;CAItC,IAAI,IAAI;CACR,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK,IAAK,IAAI,KAAK,EAAE,WAAW,CAAC,IAAK;CACpE,OAAO,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,EAAE;AAChC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { ContentPart } from '../types.js';
|
|
1
|
+
import { ContentPart, ToolResultOutcome } from '../types.js';
|
|
2
|
+
export declare function isToolResultOutcome(value: unknown): value is ToolResultOutcome;
|
|
2
3
|
/**
|
|
3
4
|
* Structural check for a single `ContentPart`. A text part must carry a string
|
|
4
5
|
* `content`. Every other part carries a source with a string `value`; a file
|
|
@@ -6,6 +6,9 @@ var CONTENT_PART_TYPES = /* @__PURE__ */ new Set([
|
|
|
6
6
|
"video",
|
|
7
7
|
"document"
|
|
8
8
|
]);
|
|
9
|
+
function isToolResultOutcome(value) {
|
|
10
|
+
return value === "cancelled" || value === "denied";
|
|
11
|
+
}
|
|
9
12
|
/**
|
|
10
13
|
* Structural check for a single `ContentPart`. A text part must carry a string
|
|
11
14
|
* `content`. Every other part carries a source with a string `value`; a file
|
|
@@ -64,6 +67,6 @@ function normalizeToolResult(result) {
|
|
|
64
67
|
return JSON.stringify(result);
|
|
65
68
|
}
|
|
66
69
|
//#endregion
|
|
67
|
-
export { isContentPart, isContentPartArray, normalizeToolResult, parseToolOutput, toolResultErrorText };
|
|
70
|
+
export { isContentPart, isContentPartArray, isToolResultOutcome, normalizeToolResult, parseToolOutput, toolResultErrorText };
|
|
68
71
|
|
|
69
72
|
//# sourceMappingURL=tool-result.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-result.js","names":[],"sources":["../../../src/utilities/tool-result.ts"],"sourcesContent":["import type { ContentPart } from '../types'\n\nconst CONTENT_PART_TYPES = new Set([\n 'text',\n 'image',\n 'audio',\n 'video',\n 'document',\n])\n\n/**\n * Structural check for a single `ContentPart`. A text part must carry a string\n * `content`. Every other part carries a source with a string `value`; a file\n * source's `value` is a non-empty opaque handle, and its optional `provider`\n * is a string.\n */\nexport function isContentPart(value: unknown): value is ContentPart {\n if (typeof value !== 'object' || value === null) return false\n const part = value as Record<string, unknown>\n if (typeof part.type !== 'string' || !CONTENT_PART_TYPES.has(part.type)) {\n return false\n }\n if (part.type === 'text') {\n return typeof part.content === 'string'\n }\n const source = part.source\n if (typeof source !== 'object' || source === null) return false\n const src = source as Record<string, unknown>\n if (typeof src.value !== 'string') return false\n // `file` sources carry an opaque handle in `value`; `provider`, when set,\n // names the issuer.\n if (src.type === 'file') {\n return (\n src.value.length > 0 &&\n (src.provider === undefined || typeof src.provider === 'string')\n )\n }\n // `data` sources require a mimeType (matches ContentPartDataSource); `url`\n // sources don't. Requiring it here keeps the runtime guard consistent with\n // the type and avoids emitting `data:undefined;base64,...` downstream.\n if (src.type === 'data') return typeof src.mimeType === 'string'\n return src.type === 'url'\n}\n\n/**\n * True iff `value` is a NON-EMPTY array whose every element is a valid\n * `ContentPart`. Empty arrays and mixed arrays return false so they continue\n * to be treated as ordinary (stringified) data — this keeps the auto-detection\n * footgun narrow.\n */\nexport function isContentPartArray(\n value: unknown,\n): value is Array<ContentPart> {\n return Array.isArray(value) && value.length > 0 && value.every(isContentPart)\n}\n\n/**\n * Error text for a failed tool result: `output.error` when it is a string,\n * else the output itself when it is a string, else a generic message.\n * `StreamProcessor` and `chat()` history share it, so a reload shows the\n * same text as the live stream.\n */\nexport function toolResultErrorText(output: unknown): string {\n if (\n output &&\n typeof output === 'object' &&\n 'error' in output &&\n typeof output.error === 'string'\n ) {\n return output.error\n }\n return typeof output === 'string' ? output : 'Tool execution failed'\n}\n\n/** Parse tool result content as JSON. Plain text stays a string. */\nexport function parseToolOutput(content: string): unknown {\n try {\n return JSON.parse(content)\n } catch {\n return content\n }\n}\n\n/**\n * Normalize a tool's return value for transport:\n * - string → unchanged\n * - ContentPart array → unchanged (multimodal, passed through to the adapter)\n * - anything else → `JSON.stringify`\n */\nexport function normalizeToolResult(\n result: unknown,\n): string | Array<ContentPart> {\n if (typeof result === 'string') return result\n if (isContentPartArray(result)) return result\n return JSON.stringify(result)\n}\n"],"mappings":";AAEA,IAAM,qCAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;
|
|
1
|
+
{"version":3,"file":"tool-result.js","names":[],"sources":["../../../src/utilities/tool-result.ts"],"sourcesContent":["import type { ContentPart, ToolResultOutcome } from '../types'\n\nconst CONTENT_PART_TYPES = new Set([\n 'text',\n 'image',\n 'audio',\n 'video',\n 'document',\n])\n\nexport function isToolResultOutcome(\n value: unknown,\n): value is ToolResultOutcome {\n return value === 'cancelled' || value === 'denied'\n}\n\n/**\n * Structural check for a single `ContentPart`. A text part must carry a string\n * `content`. Every other part carries a source with a string `value`; a file\n * source's `value` is a non-empty opaque handle, and its optional `provider`\n * is a string.\n */\nexport function isContentPart(value: unknown): value is ContentPart {\n if (typeof value !== 'object' || value === null) return false\n const part = value as Record<string, unknown>\n if (typeof part.type !== 'string' || !CONTENT_PART_TYPES.has(part.type)) {\n return false\n }\n if (part.type === 'text') {\n return typeof part.content === 'string'\n }\n const source = part.source\n if (typeof source !== 'object' || source === null) return false\n const src = source as Record<string, unknown>\n if (typeof src.value !== 'string') return false\n // `file` sources carry an opaque handle in `value`; `provider`, when set,\n // names the issuer.\n if (src.type === 'file') {\n return (\n src.value.length > 0 &&\n (src.provider === undefined || typeof src.provider === 'string')\n )\n }\n // `data` sources require a mimeType (matches ContentPartDataSource); `url`\n // sources don't. Requiring it here keeps the runtime guard consistent with\n // the type and avoids emitting `data:undefined;base64,...` downstream.\n if (src.type === 'data') return typeof src.mimeType === 'string'\n return src.type === 'url'\n}\n\n/**\n * True iff `value` is a NON-EMPTY array whose every element is a valid\n * `ContentPart`. Empty arrays and mixed arrays return false so they continue\n * to be treated as ordinary (stringified) data — this keeps the auto-detection\n * footgun narrow.\n */\nexport function isContentPartArray(\n value: unknown,\n): value is Array<ContentPart> {\n return Array.isArray(value) && value.length > 0 && value.every(isContentPart)\n}\n\n/**\n * Error text for a failed tool result: `output.error` when it is a string,\n * else the output itself when it is a string, else a generic message.\n * `StreamProcessor` and `chat()` history share it, so a reload shows the\n * same text as the live stream.\n */\nexport function toolResultErrorText(output: unknown): string {\n if (\n output &&\n typeof output === 'object' &&\n 'error' in output &&\n typeof output.error === 'string'\n ) {\n return output.error\n }\n return typeof output === 'string' ? output : 'Tool execution failed'\n}\n\n/** Parse tool result content as JSON. Plain text stays a string. */\nexport function parseToolOutput(content: string): unknown {\n try {\n return JSON.parse(content)\n } catch {\n return content\n }\n}\n\n/**\n * Normalize a tool's return value for transport:\n * - string → unchanged\n * - ContentPart array → unchanged (multimodal, passed through to the adapter)\n * - anything else → `JSON.stringify`\n */\nexport function normalizeToolResult(\n result: unknown,\n): string | Array<ContentPart> {\n if (typeof result === 'string') return result\n if (isContentPartArray(result)) return result\n return JSON.stringify(result)\n}\n"],"mappings":";AAEA,IAAM,qCAAqB,IAAI,IAAI;CACjC;CACA;CACA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
2
2
|
"name": "@tanstack/ai",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.63.0",
|
|
4
4
|
"description": "Type-safe TypeScript AI SDK for streaming chat, tool calling, agents, structured outputs, and multimodal generation.",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -110,9 +110,9 @@
|
|
|
110
110
|
"clean": "premove ./build ./dist",
|
|
111
111
|
"lint:fix": "oxlint src --type-aware --fix",
|
|
112
112
|
"test:build": "publint --strict",
|
|
113
|
-
"test:coverage": "vitest run --coverage",
|
|
114
|
-
"test:coverage:watch": "vitest --coverage --watch",
|
|
115
113
|
"test:oxlint": "oxlint src --type-aware",
|
|
114
|
+
"test:coverage": "vitest run --coverage --coverage.include='src/**' --coverage.reporter=text-summary --coverage.reporter=json-summary",
|
|
115
|
+
"test:coverage:watch": "vitest --coverage --watch",
|
|
116
116
|
"test:lib": "vitest",
|
|
117
117
|
"test:lib:dev": "pnpm test:lib --watch",
|
|
118
118
|
"test:types": "tsc"
|
|
@@ -399,6 +399,9 @@ Pass `mcp` to let `chat()` own discovery **and** lifecycle for one or more MCP
|
|
|
399
399
|
clients. Useful when you want minimal boilerplate and don't need to reuse the
|
|
400
400
|
clients across calls.
|
|
401
401
|
|
|
402
|
+
`createMCPClient` tries spec `2026-07-28` first.
|
|
403
|
+
If the server does not support that spec, the client uses the 2025 initialize handshake.
|
|
404
|
+
|
|
402
405
|
```typescript
|
|
403
406
|
// Prop shape:
|
|
404
407
|
// chat({
|
|
@@ -457,6 +460,123 @@ export async function POST(request: Request) {
|
|
|
457
460
|
}
|
|
458
461
|
```
|
|
459
462
|
|
|
463
|
+
**Host an MCP server.** Import `createMCPServer` from `@tanstack/ai-mcp/server`.
|
|
464
|
+
Call `server.fetch(request)` in your HTTP route.
|
|
465
|
+
|
|
466
|
+
```typescript
|
|
467
|
+
import { toolDefinition } from '@tanstack/ai'
|
|
468
|
+
import { createMCPServer } from '@tanstack/ai-mcp/server'
|
|
469
|
+
import { z } from 'zod'
|
|
470
|
+
|
|
471
|
+
const getWeather = toolDefinition({
|
|
472
|
+
name: 'get_weather',
|
|
473
|
+
description: 'Current weather for a city',
|
|
474
|
+
inputSchema: z.object({ city: z.string() }),
|
|
475
|
+
}).server(async ({ city }) => {
|
|
476
|
+
return { city, temperature: 18, conditions: 'clear' }
|
|
477
|
+
})
|
|
478
|
+
|
|
479
|
+
const server = createMCPServer({
|
|
480
|
+
name: 'weather',
|
|
481
|
+
version: '1.0.0',
|
|
482
|
+
tools: [getWeather],
|
|
483
|
+
})
|
|
484
|
+
|
|
485
|
+
export function handleMcp(request: Request) {
|
|
486
|
+
return server.fetch(request)
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// Mount handleMcp on GET, POST, and DELETE.
|
|
490
|
+
// GET is the spec 2025 stream.
|
|
491
|
+
// DELETE closes a spec 2025 session.
|
|
492
|
+
```
|
|
493
|
+
|
|
494
|
+
`serveMCPStdio` from `@tanstack/ai-mcp/server/stdio` serves that server on stdin and stdout.
|
|
495
|
+
Write logs with `console.error`.
|
|
496
|
+
stdout carries only protocol messages.
|
|
497
|
+
|
|
498
|
+
```typescript
|
|
499
|
+
import { toolDefinition } from '@tanstack/ai'
|
|
500
|
+
import { createMCPServer } from '@tanstack/ai-mcp/server'
|
|
501
|
+
import { serveMCPStdio } from '@tanstack/ai-mcp/server/stdio'
|
|
502
|
+
import { z } from 'zod'
|
|
503
|
+
|
|
504
|
+
const getWeather = toolDefinition({
|
|
505
|
+
name: 'get_weather',
|
|
506
|
+
description: 'Current weather for a city',
|
|
507
|
+
inputSchema: z.object({ city: z.string() }),
|
|
508
|
+
}).server(async ({ city }) => {
|
|
509
|
+
return { city, temperature: 18, conditions: 'clear' }
|
|
510
|
+
})
|
|
511
|
+
|
|
512
|
+
const server = createMCPServer({
|
|
513
|
+
name: 'weather',
|
|
514
|
+
version: '1.0.0',
|
|
515
|
+
tools: [getWeather],
|
|
516
|
+
})
|
|
517
|
+
|
|
518
|
+
serveMCPStdio(server)
|
|
519
|
+
```
|
|
520
|
+
|
|
521
|
+
**MCP input interrupt.** When `chat()` receives an MCP input request, the run outcome is an interrupt.
|
|
522
|
+
The stream ends with `RUN_FINISHED`.
|
|
523
|
+
The outcome type is `interrupt`.
|
|
524
|
+
Read each interrupt whose `reason` is `mcp_input`.
|
|
525
|
+
The payload key is `tanstack:interruptPayload`.
|
|
526
|
+
|
|
527
|
+
`form` means the server asks the user for input.
|
|
528
|
+
`sampling` means the server asks for a model result.
|
|
529
|
+
|
|
530
|
+
```typescript
|
|
531
|
+
import { chat, INTERRUPT_PAYLOAD_METADATA_KEY } from '@tanstack/ai'
|
|
532
|
+
import { openaiText } from '@tanstack/ai-openai'
|
|
533
|
+
import { createMCPClient } from '@tanstack/ai-mcp'
|
|
534
|
+
|
|
535
|
+
const client = await createMCPClient({
|
|
536
|
+
transport: { type: 'http', url: 'https://mcp.example.com/mcp' },
|
|
537
|
+
})
|
|
538
|
+
|
|
539
|
+
try {
|
|
540
|
+
const stream = chat({
|
|
541
|
+
adapter: openaiText('gpt-5.6'),
|
|
542
|
+
messages: [{ role: 'user', content: 'Weather in Paris?' }],
|
|
543
|
+
tools: await client.tools(),
|
|
544
|
+
})
|
|
545
|
+
|
|
546
|
+
for await (const chunk of stream) {
|
|
547
|
+
if (chunk.type !== 'RUN_FINISHED') continue
|
|
548
|
+
if (chunk.outcome?.type !== 'interrupt') continue
|
|
549
|
+
|
|
550
|
+
for (const item of chunk.outcome.interrupts) {
|
|
551
|
+
if (item.reason !== 'mcp_input') continue
|
|
552
|
+
const payload = item.metadata?.[INTERRUPT_PAYLOAD_METADATA_KEY]
|
|
553
|
+
if (typeof payload !== 'object' || payload === null) continue
|
|
554
|
+
if (!('kind' in payload)) continue
|
|
555
|
+
// payload.kind is 'form' or 'sampling'
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
} finally {
|
|
559
|
+
await client.close()
|
|
560
|
+
}
|
|
561
|
+
```
|
|
562
|
+
|
|
563
|
+
To continue, answer the interrupt:
|
|
564
|
+
|
|
565
|
+
1. In `useChat`, the item `kind` is `generic`.
|
|
566
|
+
2. For a `form`, call `resolveInterrupt` with an object that matches `request.requestedSchema`. A `createMCPServer` server asks for `{ value: string }`.
|
|
567
|
+
3. For `sampling`, call `resolveInterrupt` with the reply text.
|
|
568
|
+
4. Call `cancel()` to decline.
|
|
569
|
+
5. The route passes `parentRunId` and `resume` to `chat()`. The tool runs again with the answer.
|
|
570
|
+
|
|
571
|
+
```tsx ignore
|
|
572
|
+
// `interrupt` is one item from `useChat().interrupts`.
|
|
573
|
+
if (interrupt.reason === 'mcp_input' && interrupt.kind === 'generic') {
|
|
574
|
+
interrupt.resolveInterrupt({ value: 'Paris' })
|
|
575
|
+
}
|
|
576
|
+
```
|
|
577
|
+
|
|
578
|
+
This works on spec `2026-07-28`. On spec 2025, the server asks the client in the middle of the tool call. `chat()` cannot pause that call, so the tool call fails.
|
|
579
|
+
|
|
460
580
|
### 7. Queueing Messages Sent While Streaming
|
|
461
581
|
|
|
462
582
|
By default, a `sendMessage` call that arrives while a stream is in flight is
|
|
@@ -513,6 +513,9 @@ The post-discovery payload always returns the full description and schema regard
|
|
|
513
513
|
`@tanstack/ai-mcp` lets a server-side `chat()` call discover and invoke tools
|
|
514
514
|
hosted on any MCP server (Streamable HTTP, SSE, or stdio).
|
|
515
515
|
|
|
516
|
+
`createMCPClient` tries spec `2026-07-28` first.
|
|
517
|
+
If the server does not support that spec, the client uses the 2025 initialize handshake.
|
|
518
|
+
|
|
516
519
|
**MCP tools and UI resources:** When an MCP tool result carries a `ui://`
|
|
517
520
|
resource URI (via `_meta.ui.resourceUri`), TanStack AI surfaces it as a
|
|
518
521
|
`UIResourcePart` on the assistant `UIMessage` in the client message list.
|
|
@@ -723,6 +726,106 @@ export async function POST(request: Request) {
|
|
|
723
726
|
}
|
|
724
727
|
```
|
|
725
728
|
|
|
729
|
+
### Host your own MCP server
|
|
730
|
+
|
|
731
|
+
Import `createMCPServer` from `@tanstack/ai-mcp/server`.
|
|
732
|
+
Pass tools from `toolDefinition().server()`.
|
|
733
|
+
Call `server.fetch(request)` in your HTTP route.
|
|
734
|
+
|
|
735
|
+
```typescript
|
|
736
|
+
import { toolDefinition } from '@tanstack/ai'
|
|
737
|
+
import { createMCPServer } from '@tanstack/ai-mcp/server'
|
|
738
|
+
import { z } from 'zod'
|
|
739
|
+
|
|
740
|
+
const getWeather = toolDefinition({
|
|
741
|
+
name: 'get_weather',
|
|
742
|
+
description: 'Current weather for a city',
|
|
743
|
+
inputSchema: z.object({ city: z.string() }),
|
|
744
|
+
}).server(async ({ city }) => {
|
|
745
|
+
return { city, temperature: 18, conditions: 'clear' }
|
|
746
|
+
})
|
|
747
|
+
|
|
748
|
+
const server = createMCPServer({
|
|
749
|
+
name: 'weather',
|
|
750
|
+
version: '1.0.0',
|
|
751
|
+
tools: [getWeather],
|
|
752
|
+
})
|
|
753
|
+
|
|
754
|
+
export function POST(request: Request) {
|
|
755
|
+
return server.fetch(request)
|
|
756
|
+
}
|
|
757
|
+
```
|
|
758
|
+
|
|
759
|
+
`stdioTransport` from `@tanstack/ai-mcp/stdio` connects your client to a command.
|
|
760
|
+
`serveMCPStdio` from `@tanstack/ai-mcp/server/stdio` serves your server on stdin and stdout.
|
|
761
|
+
Write logs with `console.error`.
|
|
762
|
+
stdout carries only protocol messages.
|
|
763
|
+
|
|
764
|
+
```typescript
|
|
765
|
+
import { toolDefinition } from '@tanstack/ai'
|
|
766
|
+
import { createMCPServer } from '@tanstack/ai-mcp/server'
|
|
767
|
+
import { serveMCPStdio } from '@tanstack/ai-mcp/server/stdio'
|
|
768
|
+
import { z } from 'zod'
|
|
769
|
+
|
|
770
|
+
const getWeather = toolDefinition({
|
|
771
|
+
name: 'get_weather',
|
|
772
|
+
description: 'Current weather for a city',
|
|
773
|
+
inputSchema: z.object({ city: z.string() }),
|
|
774
|
+
}).server(async ({ city }) => {
|
|
775
|
+
return { city, temperature: 18, conditions: 'clear' }
|
|
776
|
+
})
|
|
777
|
+
|
|
778
|
+
const server = createMCPServer({
|
|
779
|
+
name: 'weather',
|
|
780
|
+
version: '1.0.0',
|
|
781
|
+
tools: [getWeather],
|
|
782
|
+
})
|
|
783
|
+
|
|
784
|
+
serveMCPStdio(server)
|
|
785
|
+
```
|
|
786
|
+
|
|
787
|
+
The `@tanstack/ai-mcp` skill shows `ctx.context.requestInput` and `ctx.context.sample`.
|
|
788
|
+
|
|
789
|
+
### Read an MCP input interrupt
|
|
790
|
+
|
|
791
|
+
When `chat()` receives an MCP input request, the run outcome is an interrupt.
|
|
792
|
+
The stream ends with `RUN_FINISHED`.
|
|
793
|
+
The outcome type is `interrupt`.
|
|
794
|
+
Read each interrupt whose `reason` is `mcp_input`.
|
|
795
|
+
The payload key is `tanstack:interruptPayload`.
|
|
796
|
+
|
|
797
|
+
`form` means the server asks the user for input.
|
|
798
|
+
`sampling` means the server asks for a model result.
|
|
799
|
+
|
|
800
|
+
```typescript
|
|
801
|
+
import { chat, INTERRUPT_PAYLOAD_METADATA_KEY } from '@tanstack/ai'
|
|
802
|
+
import { openaiText } from '@tanstack/ai-openai'
|
|
803
|
+
import { createMCPClient } from '@tanstack/ai-mcp'
|
|
804
|
+
|
|
805
|
+
const client = await createMCPClient({
|
|
806
|
+
transport: { type: 'http', url: 'https://mcp.example.com/mcp' },
|
|
807
|
+
})
|
|
808
|
+
|
|
809
|
+
const stream = chat({
|
|
810
|
+
adapter: openaiText('gpt-5.5'),
|
|
811
|
+
messages: [{ role: 'user', content: 'Weather in Paris?' }],
|
|
812
|
+
tools: await client.tools(),
|
|
813
|
+
})
|
|
814
|
+
|
|
815
|
+
for await (const chunk of stream) {
|
|
816
|
+
if (chunk.type !== 'RUN_FINISHED') continue
|
|
817
|
+
if (chunk.outcome?.type !== 'interrupt') continue
|
|
818
|
+
|
|
819
|
+
for (const item of chunk.outcome.interrupts) {
|
|
820
|
+
if (item.reason !== 'mcp_input') continue
|
|
821
|
+
const payload = item.metadata?.[INTERRUPT_PAYLOAD_METADATA_KEY]
|
|
822
|
+
if (typeof payload !== 'object' || payload === null) continue
|
|
823
|
+
if (!('kind' in payload)) continue
|
|
824
|
+
// payload.kind is 'form' or 'sampling'
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
```
|
|
828
|
+
|
|
726
829
|
## Provider Skills
|
|
727
830
|
|
|
728
831
|
> **Not to be confused with `@tanstack/ai-code-mode-snippets`**, whose snippets are TypeScript functions your application generates and runs in its own Code Mode sandbox (a local JS isolate). Provider Skills are hosted, provider-managed bundles that the model loads on demand and runs inside the provider's server-side sandbox.
|
|
@@ -2,6 +2,7 @@ import type { SubagentInfo as AGUISubagentInfo } from '@ag-ui/core'
|
|
|
2
2
|
import type { InterruptDefinition } from '../../../interrupt-definition'
|
|
3
3
|
import type {
|
|
4
4
|
AnyTool,
|
|
5
|
+
InferSchemaType,
|
|
5
6
|
ModelMessage,
|
|
6
7
|
RunAgentResumeItem,
|
|
7
8
|
SchemaInput,
|
|
@@ -12,8 +13,16 @@ import type { AnyClientTool } from '../tools/tool-definition'
|
|
|
12
13
|
|
|
13
14
|
/**
|
|
14
15
|
* Context the library passes into {@link defineAgent} `run`.
|
|
16
|
+
* `TInput` is the agent's `inputSchema`.
|
|
15
17
|
*/
|
|
16
|
-
export interface SubagentRunContext
|
|
18
|
+
export interface SubagentRunContext<
|
|
19
|
+
TInput extends SchemaInput | undefined = any,
|
|
20
|
+
> {
|
|
21
|
+
/**
|
|
22
|
+
* The input the parent model wrote for this child, checked against
|
|
23
|
+
* `inputSchema`. `undefined` when the agent has no `inputSchema`.
|
|
24
|
+
*/
|
|
25
|
+
input: TInput extends SchemaInput ? InferSchemaType<TInput> : undefined
|
|
17
26
|
messages: Array<UIMessage | ModelMessage>
|
|
18
27
|
abortSignal?: AbortSignal
|
|
19
28
|
threadId: string
|
|
@@ -53,13 +62,20 @@ export interface DefinedAgent<
|
|
|
53
62
|
TSchema extends SchemaInput | undefined = SchemaInput | undefined,
|
|
54
63
|
TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>> =
|
|
55
64
|
ReadonlyArray<InterruptDefinition<any, any, any, any>>,
|
|
65
|
+
TInput extends SchemaInput | undefined = any,
|
|
56
66
|
> extends AGUISubagentInfo {
|
|
57
67
|
name: TName
|
|
58
68
|
/** Required here: the router and the synthetic tool both read it. */
|
|
59
69
|
description: string
|
|
60
70
|
run: (
|
|
61
|
-
ctx: SubagentRunContext
|
|
71
|
+
ctx: SubagentRunContext<TInput>,
|
|
62
72
|
) => AsyncIterable<StreamChunk> | Promise<AsyncIterable<StreamChunk>>
|
|
73
|
+
/**
|
|
74
|
+
* The input the parent model writes when it calls this agent's tool, such
|
|
75
|
+
* as a short brief. `run` reads it as `ctx.input`. Tool mode only: a
|
|
76
|
+
* `subagents.router` cannot start an agent that has `inputSchema`.
|
|
77
|
+
*/
|
|
78
|
+
inputSchema?: TInput
|
|
63
79
|
tools?: TTools
|
|
64
80
|
interrupts?: TInterrupts
|
|
65
81
|
outputSchema?: TSchema
|
|
@@ -104,7 +120,8 @@ export function defineAgent<
|
|
|
104
120
|
const TInterrupts extends ReadonlyArray<
|
|
105
121
|
InterruptDefinition<any, any, any, any>
|
|
106
122
|
> = readonly [],
|
|
107
|
-
|
|
123
|
+
TInput extends SchemaInput | undefined = undefined,
|
|
124
|
+
>(agent: DefinedAgent<TName, TTools, TSchema, TInterrupts, TInput>) {
|
|
108
125
|
if (agent.name.trim() === '') {
|
|
109
126
|
throw new Error('defineAgent requires a non-empty name')
|
|
110
127
|
}
|
|
@@ -93,6 +93,8 @@ export function createSubagentSink(): SubagentSink {
|
|
|
93
93
|
/** One child to start, or a suspended child to continue. */
|
|
94
94
|
export interface SpawnEntry {
|
|
95
95
|
name: string
|
|
96
|
+
/** The checked tool input for an agent with `inputSchema`. */
|
|
97
|
+
input?: unknown
|
|
96
98
|
resume?: {
|
|
97
99
|
subagentRunId: string
|
|
98
100
|
/** The child's own messages from the interrupted run. */
|
|
@@ -248,6 +250,7 @@ function openAgentStream(
|
|
|
248
250
|
return spawnAgentStream(
|
|
249
251
|
agent,
|
|
250
252
|
{
|
|
253
|
+
input: entry.input,
|
|
251
254
|
messages: resumed?.messages ?? ctx.messages,
|
|
252
255
|
...(ctx.abortSignal ? { abortSignal: ctx.abortSignal } : {}),
|
|
253
256
|
threadId: childThreadId(bag.sandbox, ctx.threadId, entry.name),
|
|
@@ -721,8 +724,10 @@ export function createSyntheticSubagentTools(
|
|
|
721
724
|
return bag.agents.map((agent) => ({
|
|
722
725
|
name: agent.name,
|
|
723
726
|
description: agent.description,
|
|
727
|
+
...(agent.inputSchema !== undefined && { inputSchema: agent.inputSchema }),
|
|
724
728
|
[SUBAGENT_TOOL]: true,
|
|
725
|
-
|
|
729
|
+
// The tool loop checks `input` against `inputSchema` before this runs.
|
|
730
|
+
execute: async (input: unknown, context?: unknown) => {
|
|
726
731
|
const toolContext = context as
|
|
727
732
|
| {
|
|
728
733
|
toolCallId?: string
|
|
@@ -736,17 +741,20 @@ export function createSyntheticSubagentTools(
|
|
|
736
741
|
child.parentToolCallId !== undefined &&
|
|
737
742
|
child.parentToolCallId === toolCallId,
|
|
738
743
|
)
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
744
|
+
// An agent without `inputSchema` still gets `{}` from the model. Its
|
|
745
|
+
// `ctx.input` stays undefined.
|
|
746
|
+
const entry: SpawnEntry = {
|
|
747
|
+
name: agent.name,
|
|
748
|
+
...(agent.inputSchema !== undefined && { input }),
|
|
749
|
+
...(suspended && {
|
|
750
|
+
resume: {
|
|
751
|
+
subagentRunId: suspended.subagentRunId,
|
|
752
|
+
messages: suspended.messages,
|
|
753
|
+
entries: suspended.resume,
|
|
754
|
+
text: suspended.text,
|
|
755
|
+
},
|
|
756
|
+
}),
|
|
757
|
+
}
|
|
750
758
|
const sink = createSubagentSink()
|
|
751
759
|
const link = linkAbort(parent.abortSignal)
|
|
752
760
|
let subagentRunId = suspended?.subagentRunId ?? ''
|