@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 +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 { 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: emit reasoning fan-outs first, then anchor, then tool fan-outs\n for (const part of parts) {\n if (part.type === '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\n const text = collectText(parts)\n const toolCalls = collectToolCalls(parts)\n wire.push(\n toAnchor(\n uiMessage,\n 'assistant',\n {\n ...(text !== '' && { content: text }),\n ...(toolCalls && { toolCalls }),\n },\n parts,\n includeSnapshotStructuredOutput,\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":";;;;;AAwCA,SAAS,SAAS,OAAkD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Y,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
|
+
{"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,UA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OAAO,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,EAAE;AAChC"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { ContentPartFileSource, ContentPartSource } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Narrow a {@link ContentPartSource} to the provider-file-reference arm.
|
|
4
|
+
*
|
|
5
|
+
* Issuer adapters use this to route a file source to their native wire field;
|
|
6
|
+
* everyone else is protected by the core preflight (see
|
|
7
|
+
* {@link assertMessagesFileSourceSupport}) plus a defensive throw at their own
|
|
8
|
+
* mapping site.
|
|
9
|
+
*/
|
|
10
|
+
export declare function isFileSource(source: ContentPartSource): source is ContentPartFileSource;
|
|
11
|
+
/**
|
|
12
|
+
* Resolve the handle `providerName` should send for a file source.
|
|
13
|
+
*
|
|
14
|
+
* A file source carries one opaque handle (`value`) and, optionally, the
|
|
15
|
+
* provider that issued it. An adapter always knows which provider it talks
|
|
16
|
+
* to, so a source that names no provider is taken as-is.
|
|
17
|
+
*
|
|
18
|
+
* @throws when the source names a different issuing provider. A handle only
|
|
19
|
+
* resolves at the provider that minted it.
|
|
20
|
+
*/
|
|
21
|
+
export declare function fileReferenceFor(source: ContentPartFileSource, providerName: string): string;
|
|
22
|
+
/**
|
|
23
|
+
* Build the standard error a non-issuer adapter throws when it encounters a
|
|
24
|
+
* `{ type: 'file' }` source it can't consume — either because the provider has
|
|
25
|
+
* no file-reference input surface, or because the endpoint requires raw bytes
|
|
26
|
+
* (image edits, Veo) rather than a reference.
|
|
27
|
+
*
|
|
28
|
+
* @param detail Optional context appended to the message (e.g. a modality or
|
|
29
|
+
* endpoint name, or a pointer to the adapter that does support references).
|
|
30
|
+
* When provided it replaces the generic remediation tail, so a site-specific
|
|
31
|
+
* hint ("pass inline bytes") is never contradicted by generic advice.
|
|
32
|
+
*/
|
|
33
|
+
export declare function unsupportedFileSourceError(providerName: string, detail?: string): Error;
|
|
34
|
+
/**
|
|
35
|
+
* The slice of an adapter the file-source preflight reads. Adapters that can
|
|
36
|
+
* consume `{ type: 'file' }` sources declare `supportsFileSources: true`;
|
|
37
|
+
* everything else — including adapters written before this arm existed —
|
|
38
|
+
* fails closed at the activity layer instead of falling through to a
|
|
39
|
+
* URL/data branch and silently mis-mapping the reference.
|
|
40
|
+
*/
|
|
41
|
+
export interface FileSourceCapable {
|
|
42
|
+
name: string;
|
|
43
|
+
supportsFileSources?: boolean;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Fail-closed preflight for media prompts and embedding inputs
|
|
47
|
+
* (`generateImage` / `generateVideo` / `embed`): throws when the input
|
|
48
|
+
* carries a `{ type: 'file' }` source and the adapter hasn't declared
|
|
49
|
+
* `supportsFileSources`. Runs in the activity dispatcher — the same layer
|
|
50
|
+
* that validates modality — so an adapter that predates the file arm can
|
|
51
|
+
* never receive one. Walks a single part, an array of parts, and nested
|
|
52
|
+
* arrays (fused embedding items).
|
|
53
|
+
*/
|
|
54
|
+
export declare function assertPromptFileSourceSupport(adapter: FileSourceCapable, prompt: unknown): void;
|
|
55
|
+
/**
|
|
56
|
+
* Fail-closed preflight for chat messages: throws when any message content
|
|
57
|
+
* part carries a `{ type: 'file' }` source and the adapter hasn't declared
|
|
58
|
+
* `supportsFileSources`. See {@link assertPromptFileSourceSupport}.
|
|
59
|
+
*/
|
|
60
|
+
export declare function assertMessagesFileSourceSupport(adapter: FileSourceCapable, messages: ReadonlyArray<unknown>): void;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
//#region src/utilities/content-source.ts
|
|
2
|
+
/**
|
|
3
|
+
* Narrow a {@link ContentPartSource} to the provider-file-reference arm.
|
|
4
|
+
*
|
|
5
|
+
* Issuer adapters use this to route a file source to their native wire field;
|
|
6
|
+
* everyone else is protected by the core preflight (see
|
|
7
|
+
* {@link assertMessagesFileSourceSupport}) plus a defensive throw at their own
|
|
8
|
+
* mapping site.
|
|
9
|
+
*/
|
|
10
|
+
function isFileSource(source) {
|
|
11
|
+
return source.type === "file";
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Resolve the handle `providerName` should send for a file source.
|
|
15
|
+
*
|
|
16
|
+
* A file source carries one opaque handle (`value`) and, optionally, the
|
|
17
|
+
* provider that issued it. An adapter always knows which provider it talks
|
|
18
|
+
* to, so a source that names no provider is taken as-is.
|
|
19
|
+
*
|
|
20
|
+
* @throws when the source names a different issuing provider. A handle only
|
|
21
|
+
* resolves at the provider that minted it.
|
|
22
|
+
*/
|
|
23
|
+
function fileReferenceFor(source, providerName) {
|
|
24
|
+
if (source.provider !== void 0 && source.provider !== providerName) throw new Error(`${providerName}: file source was issued by ${source.provider}. A provider file handle only works with the provider that issued it. Upload the file with ${providerName}Files(), or pass a data or url source instead.`);
|
|
25
|
+
return source.value;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Build the standard error a non-issuer adapter throws when it encounters a
|
|
29
|
+
* `{ type: 'file' }` source it can't consume — either because the provider has
|
|
30
|
+
* no file-reference input surface, or because the endpoint requires raw bytes
|
|
31
|
+
* (image edits, Veo) rather than a reference.
|
|
32
|
+
*
|
|
33
|
+
* @param detail Optional context appended to the message (e.g. a modality or
|
|
34
|
+
* endpoint name, or a pointer to the adapter that does support references).
|
|
35
|
+
* When provided it replaces the generic remediation tail, so a site-specific
|
|
36
|
+
* hint ("pass inline bytes") is never contradicted by generic advice.
|
|
37
|
+
*/
|
|
38
|
+
function unsupportedFileSourceError(providerName, detail) {
|
|
39
|
+
return /* @__PURE__ */ new Error(`${providerName} does not support provider file-handle sources ({ type: 'file' })` + (detail ? ` ${detail}.` : ". Pass a data or url source, or upload via the provider's files adapter where supported."));
|
|
40
|
+
}
|
|
41
|
+
/** True when a content-part-like value carries a `{ type: 'file' }` source. */
|
|
42
|
+
function partHasFileSource(part) {
|
|
43
|
+
if (typeof part !== "object" || part === null) return false;
|
|
44
|
+
const source = part.source;
|
|
45
|
+
return typeof source === "object" && source !== null && source.type === "file";
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* True when `value` is a content part with a file source, or an array
|
|
49
|
+
* (possibly nested — fused embedding items) that contains one.
|
|
50
|
+
*/
|
|
51
|
+
function inputHasFileSource(value) {
|
|
52
|
+
if (Array.isArray(value)) return value.some(inputHasFileSource);
|
|
53
|
+
return partHasFileSource(value);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Fail-closed preflight for media prompts and embedding inputs
|
|
57
|
+
* (`generateImage` / `generateVideo` / `embed`): throws when the input
|
|
58
|
+
* carries a `{ type: 'file' }` source and the adapter hasn't declared
|
|
59
|
+
* `supportsFileSources`. Runs in the activity dispatcher — the same layer
|
|
60
|
+
* that validates modality — so an adapter that predates the file arm can
|
|
61
|
+
* never receive one. Walks a single part, an array of parts, and nested
|
|
62
|
+
* arrays (fused embedding items).
|
|
63
|
+
*/
|
|
64
|
+
function assertPromptFileSourceSupport(adapter, prompt) {
|
|
65
|
+
if (adapter.supportsFileSources === true) return;
|
|
66
|
+
if (inputHasFileSource(prompt)) throw unsupportedFileSourceError(adapter.name);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Fail-closed preflight for chat messages: throws when any message content
|
|
70
|
+
* part carries a `{ type: 'file' }` source and the adapter hasn't declared
|
|
71
|
+
* `supportsFileSources`. See {@link assertPromptFileSourceSupport}.
|
|
72
|
+
*/
|
|
73
|
+
function assertMessagesFileSourceSupport(adapter, messages) {
|
|
74
|
+
if (adapter.supportsFileSources === true) return;
|
|
75
|
+
for (const message of messages) {
|
|
76
|
+
if (typeof message !== "object" || message === null) continue;
|
|
77
|
+
const content = message.content;
|
|
78
|
+
if (!Array.isArray(content)) continue;
|
|
79
|
+
for (const part of content) if (partHasFileSource(part)) throw unsupportedFileSourceError(adapter.name);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
//#endregion
|
|
83
|
+
export { assertMessagesFileSourceSupport, assertPromptFileSourceSupport, fileReferenceFor, isFileSource, unsupportedFileSourceError };
|
|
84
|
+
|
|
85
|
+
//# sourceMappingURL=content-source.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"content-source.js","names":[],"sources":["../../../src/utilities/content-source.ts"],"sourcesContent":["import type { ContentPartFileSource, ContentPartSource } from '../types'\n\n/**\n * Narrow a {@link ContentPartSource} to the provider-file-reference arm.\n *\n * Issuer adapters use this to route a file source to their native wire field;\n * everyone else is protected by the core preflight (see\n * {@link assertMessagesFileSourceSupport}) plus a defensive throw at their own\n * mapping site.\n */\nexport function isFileSource(\n source: ContentPartSource,\n): source is ContentPartFileSource {\n return source.type === 'file'\n}\n\n/**\n * Resolve the handle `providerName` should send for a file source.\n *\n * A file source carries one opaque handle (`value`) and, optionally, the\n * provider that issued it. An adapter always knows which provider it talks\n * to, so a source that names no provider is taken as-is.\n *\n * @throws when the source names a different issuing provider. A handle only\n * resolves at the provider that minted it.\n */\nexport function fileReferenceFor(\n source: ContentPartFileSource,\n providerName: string,\n): string {\n if (source.provider !== undefined && source.provider !== providerName) {\n throw new Error(\n `${providerName}: file source was issued by ${source.provider}. ` +\n `A provider file handle only works with the provider that issued ` +\n `it. Upload the file with ${providerName}Files(), or pass a data or ` +\n `url source instead.`,\n )\n }\n return source.value\n}\n\n/**\n * Build the standard error a non-issuer adapter throws when it encounters a\n * `{ type: 'file' }` source it can't consume — either because the provider has\n * no file-reference input surface, or because the endpoint requires raw bytes\n * (image edits, Veo) rather than a reference.\n *\n * @param detail Optional context appended to the message (e.g. a modality or\n * endpoint name, or a pointer to the adapter that does support references).\n * When provided it replaces the generic remediation tail, so a site-specific\n * hint (\"pass inline bytes\") is never contradicted by generic advice.\n */\nexport function unsupportedFileSourceError(\n providerName: string,\n detail?: string,\n): Error {\n return new Error(\n `${providerName} does not support provider file-handle sources ` +\n `({ type: 'file' })` +\n (detail\n ? ` ${detail}.`\n : `. Pass a data or url source, or upload via the provider's files ` +\n `adapter where supported.`),\n )\n}\n\n/**\n * The slice of an adapter the file-source preflight reads. Adapters that can\n * consume `{ type: 'file' }` sources declare `supportsFileSources: true`;\n * everything else — including adapters written before this arm existed —\n * fails closed at the activity layer instead of falling through to a\n * URL/data branch and silently mis-mapping the reference.\n */\nexport interface FileSourceCapable {\n name: string\n supportsFileSources?: boolean\n}\n\n/** True when a content-part-like value carries a `{ type: 'file' }` source. */\nfunction partHasFileSource(part: unknown): boolean {\n if (typeof part !== 'object' || part === null) return false\n const source = (part as { source?: unknown }).source\n return (\n typeof source === 'object' &&\n source !== null &&\n (source as { type?: unknown }).type === 'file'\n )\n}\n\n/**\n * True when `value` is a content part with a file source, or an array\n * (possibly nested — fused embedding items) that contains one.\n */\nfunction inputHasFileSource(value: unknown): boolean {\n if (Array.isArray(value)) return value.some(inputHasFileSource)\n return partHasFileSource(value)\n}\n\n/**\n * Fail-closed preflight for media prompts and embedding inputs\n * (`generateImage` / `generateVideo` / `embed`): throws when the input\n * carries a `{ type: 'file' }` source and the adapter hasn't declared\n * `supportsFileSources`. Runs in the activity dispatcher — the same layer\n * that validates modality — so an adapter that predates the file arm can\n * never receive one. Walks a single part, an array of parts, and nested\n * arrays (fused embedding items).\n */\nexport function assertPromptFileSourceSupport(\n adapter: FileSourceCapable,\n prompt: unknown,\n): void {\n if (adapter.supportsFileSources === true) return\n if (inputHasFileSource(prompt)) {\n throw unsupportedFileSourceError(adapter.name)\n }\n}\n\n/**\n * Fail-closed preflight for chat messages: throws when any message content\n * part carries a `{ type: 'file' }` source and the adapter hasn't declared\n * `supportsFileSources`. See {@link assertPromptFileSourceSupport}.\n */\nexport function assertMessagesFileSourceSupport(\n adapter: FileSourceCapable,\n messages: ReadonlyArray<unknown>,\n): void {\n if (adapter.supportsFileSources === true) return\n for (const message of messages) {\n if (typeof message !== 'object' || message === null) continue\n const content = (message as { content?: unknown }).content\n if (!Array.isArray(content)) continue\n for (const part of content) {\n if (partHasFileSource(part)) {\n throw unsupportedFileSourceError(adapter.name)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,aACd,QACiC;CACjC,OAAO,OAAO,SAAS;AACzB;;;;;;;;;;;AAYA,SAAgB,iBACd,QACA,cACQ;CACR,IAAI,OAAO,aAAa,KAAA,KAAa,OAAO,aAAa,cACvD,MAAM,IAAI,MACR,GAAG,aAAa,8BAA8B,OAAO,SAAS,6FAEhC,aAAa,+CAE7C;CAEF,OAAO,OAAO;AAChB;;;;;;;;;;;;AAaA,SAAgB,2BACd,cACA,QACO;CACP,uBAAO,IAAI,MACT,GAAG,aAAa,sEAEb,SACG,IAAI,OAAO,KACX,2FAER;AACF;;AAeA,SAAS,kBAAkB,MAAwB;CACjD,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM,OAAO;CACtD,MAAM,SAAU,KAA8B;CAC9C,OACE,OAAO,WAAW,YAClB,WAAW,QACV,OAA8B,SAAS;AAE5C;;;;;AAMA,SAAS,mBAAmB,OAAyB;CACnD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,KAAK,kBAAkB;CAC9D,OAAO,kBAAkB,KAAK;AAChC;;;;;;;;;;AAWA,SAAgB,8BACd,SACA,QACM;CACN,IAAI,QAAQ,wBAAwB,MAAM;CAC1C,IAAI,mBAAmB,MAAM,GAC3B,MAAM,2BAA2B,QAAQ,IAAI;AAEjD;;;;;;AAOA,SAAgB,gCACd,SACA,UACM;CACN,IAAI,QAAQ,wBAAwB,MAAM;CAC1C,KAAK,MAAM,WAAW,UAAU;EAC9B,IAAI,OAAO,YAAY,YAAY,YAAY,MAAM;EACrD,MAAM,UAAW,QAAkC;EACnD,IAAI,CAAC,MAAM,QAAQ,OAAO,GAAG;EAC7B,KAAK,MAAM,QAAQ,SACjB,IAAI,kBAAkB,IAAI,GACxB,MAAM,2BAA2B,QAAQ,IAAI;CAGnD;AACF"}
|
|
@@ -16,3 +16,10 @@ export declare function getProviderExecutedMetadata(toolCall: {
|
|
|
16
16
|
export declare function isProviderExecutedToolCall(toolCall: {
|
|
17
17
|
metadata?: unknown;
|
|
18
18
|
} | null | undefined): boolean;
|
|
19
|
+
/**
|
|
20
|
+
* True when `id` is a `${parentId}-segment-${n}` message. The wire and the
|
|
21
|
+
* run loop split one provider turn into segments at thinking that follows a
|
|
22
|
+
* provider-executed tool call, to keep signed thinking order. Readers fold a
|
|
23
|
+
* segment back into its parent so the UI still shows one message.
|
|
24
|
+
*/
|
|
25
|
+
export declare function isAssistantSegmentOf(id: string | undefined, parentId: string): boolean;
|
|
@@ -18,7 +18,16 @@ function getProviderExecutedMetadata(toolCall) {
|
|
|
18
18
|
function isProviderExecutedToolCall(toolCall) {
|
|
19
19
|
return getProviderExecutedMetadata(toolCall) !== null;
|
|
20
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* True when `id` is a `${parentId}-segment-${n}` message. The wire and the
|
|
23
|
+
* run loop split one provider turn into segments at thinking that follows a
|
|
24
|
+
* provider-executed tool call, to keep signed thinking order. Readers fold a
|
|
25
|
+
* segment back into its parent so the UI still shows one message.
|
|
26
|
+
*/
|
|
27
|
+
function isAssistantSegmentOf(id, parentId) {
|
|
28
|
+
return id?.startsWith(`${parentId}-segment-`) === true;
|
|
29
|
+
}
|
|
21
30
|
//#endregion
|
|
22
|
-
export { getProviderExecutedMetadata, isProviderExecutedToolCall };
|
|
31
|
+
export { getProviderExecutedMetadata, isAssistantSegmentOf, isProviderExecutedToolCall };
|
|
23
32
|
|
|
24
33
|
//# sourceMappingURL=provider-executed.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-executed.js","names":[],"sources":["../../../src/utilities/provider-executed.ts"],"sourcesContent":["import type { ProviderExecutedToolMetadata } from '../types'\n\n/**\n * Narrow a tool call's opaque `metadata` to the provider-executed convention.\n * Returns the typed metadata when the call is provider-executed, else `null`.\n *\n * @see ProviderExecutedToolMetadata\n */\nexport function getProviderExecutedMetadata(\n toolCall: { metadata?: unknown } | null | undefined,\n): ProviderExecutedToolMetadata | null {\n const metadata = toolCall?.metadata\n if (\n typeof metadata === 'object' &&\n metadata !== null &&\n (metadata as ProviderExecutedToolMetadata).providerExecuted === true\n ) {\n return metadata as ProviderExecutedToolMetadata\n }\n return null\n}\n\n/**\n * True when a tool call was executed by the provider (e.g. Anthropic\n * `web_search` / `web_fetch` server tools) rather than the agent loop. Such\n * calls must not be routed to client-side execution and are already \"complete\".\n */\nexport function isProviderExecutedToolCall(\n toolCall: { metadata?: unknown } | null | undefined,\n): boolean {\n return getProviderExecutedMetadata(toolCall) !== null\n}\n"],"mappings":";;;;;;;AAQA,SAAgB,4BACd,UACqC;CACrC,MAAM,WAAW,UAAU;CAC3B,IACE,OAAO,aAAa,YACpB,aAAa,QACZ,SAA0C,qBAAqB,MAEhE,OAAO;CAET,OAAO;AACT;;;;;;AAOA,SAAgB,2BACd,UACS;CACT,OAAO,4BAA4B,QAAQ,MAAM;AACnD"}
|
|
1
|
+
{"version":3,"file":"provider-executed.js","names":[],"sources":["../../../src/utilities/provider-executed.ts"],"sourcesContent":["import type { ProviderExecutedToolMetadata } from '../types'\n\n/**\n * Narrow a tool call's opaque `metadata` to the provider-executed convention.\n * Returns the typed metadata when the call is provider-executed, else `null`.\n *\n * @see ProviderExecutedToolMetadata\n */\nexport function getProviderExecutedMetadata(\n toolCall: { metadata?: unknown } | null | undefined,\n): ProviderExecutedToolMetadata | null {\n const metadata = toolCall?.metadata\n if (\n typeof metadata === 'object' &&\n metadata !== null &&\n (metadata as ProviderExecutedToolMetadata).providerExecuted === true\n ) {\n return metadata as ProviderExecutedToolMetadata\n }\n return null\n}\n\n/**\n * True when a tool call was executed by the provider (e.g. Anthropic\n * `web_search` / `web_fetch` server tools) rather than the agent loop. Such\n * calls must not be routed to client-side execution and are already \"complete\".\n */\nexport function isProviderExecutedToolCall(\n toolCall: { metadata?: unknown } | null | undefined,\n): boolean {\n return getProviderExecutedMetadata(toolCall) !== null\n}\n\n/**\n * True when `id` is a `${parentId}-segment-${n}` message. The wire and the\n * run loop split one provider turn into segments at thinking that follows a\n * provider-executed tool call, to keep signed thinking order. Readers fold a\n * segment back into its parent so the UI still shows one message.\n */\nexport function isAssistantSegmentOf(\n id: string | undefined,\n parentId: string,\n): boolean {\n return id?.startsWith(`${parentId}-segment-`) === true\n}\n"],"mappings":";;;;;;;AAQA,SAAgB,4BACd,UACqC;CACrC,MAAM,WAAW,UAAU;CAC3B,IACE,OAAO,aAAa,YACpB,aAAa,QACZ,SAA0C,qBAAqB,MAEhE,OAAO;CAET,OAAO;AACT;;;;;;AAOA,SAAgB,2BACd,UACS;CACT,OAAO,4BAA4B,QAAQ,MAAM;AACnD;;;;;;;AAQA,SAAgB,qBACd,IACA,UACS;CACT,OAAO,IAAI,WAAW,GAAG,SAAS,UAAU,MAAM;AACpD"}
|
|
@@ -1,8 +1,10 @@
|
|
|
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
|
-
* `content
|
|
5
|
-
*
|
|
5
|
+
* `content`. Every other part carries a source with a string `value`; a file
|
|
6
|
+
* source's `value` is a non-empty opaque handle, and its optional `provider`
|
|
7
|
+
* is a string.
|
|
6
8
|
*/
|
|
7
9
|
export declare function isContentPart(value: unknown): value is ContentPart;
|
|
8
10
|
/**
|
|
@@ -12,6 +14,15 @@ export declare function isContentPart(value: unknown): value is ContentPart;
|
|
|
12
14
|
* footgun narrow.
|
|
13
15
|
*/
|
|
14
16
|
export declare function isContentPartArray(value: unknown): value is Array<ContentPart>;
|
|
17
|
+
/**
|
|
18
|
+
* Error text for a failed tool result: `output.error` when it is a string,
|
|
19
|
+
* else the output itself when it is a string, else a generic message.
|
|
20
|
+
* `StreamProcessor` and `chat()` history share it, so a reload shows the
|
|
21
|
+
* same text as the live stream.
|
|
22
|
+
*/
|
|
23
|
+
export declare function toolResultErrorText(output: unknown): string;
|
|
24
|
+
/** Parse tool result content as JSON. Plain text stays a string. */
|
|
25
|
+
export declare function parseToolOutput(content: string): unknown;
|
|
15
26
|
/**
|
|
16
27
|
* Normalize a tool's return value for transport:
|
|
17
28
|
* - string → unchanged
|
|
@@ -6,10 +6,14 @@ 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
|
-
* `content
|
|
12
|
-
*
|
|
14
|
+
* `content`. Every other part carries a source with a string `value`; a file
|
|
15
|
+
* source's `value` is a non-empty opaque handle, and its optional `provider`
|
|
16
|
+
* is a string.
|
|
13
17
|
*/
|
|
14
18
|
function isContentPart(value) {
|
|
15
19
|
if (typeof value !== "object" || value === null) return false;
|
|
@@ -20,6 +24,7 @@ function isContentPart(value) {
|
|
|
20
24
|
if (typeof source !== "object" || source === null) return false;
|
|
21
25
|
const src = source;
|
|
22
26
|
if (typeof src.value !== "string") return false;
|
|
27
|
+
if (src.type === "file") return src.value.length > 0 && (src.provider === void 0 || typeof src.provider === "string");
|
|
23
28
|
if (src.type === "data") return typeof src.mimeType === "string";
|
|
24
29
|
return src.type === "url";
|
|
25
30
|
}
|
|
@@ -33,6 +38,24 @@ function isContentPartArray(value) {
|
|
|
33
38
|
return Array.isArray(value) && value.length > 0 && value.every(isContentPart);
|
|
34
39
|
}
|
|
35
40
|
/**
|
|
41
|
+
* Error text for a failed tool result: `output.error` when it is a string,
|
|
42
|
+
* else the output itself when it is a string, else a generic message.
|
|
43
|
+
* `StreamProcessor` and `chat()` history share it, so a reload shows the
|
|
44
|
+
* same text as the live stream.
|
|
45
|
+
*/
|
|
46
|
+
function toolResultErrorText(output) {
|
|
47
|
+
if (output && typeof output === "object" && "error" in output && typeof output.error === "string") return output.error;
|
|
48
|
+
return typeof output === "string" ? output : "Tool execution failed";
|
|
49
|
+
}
|
|
50
|
+
/** Parse tool result content as JSON. Plain text stays a string. */
|
|
51
|
+
function parseToolOutput(content) {
|
|
52
|
+
try {
|
|
53
|
+
return JSON.parse(content);
|
|
54
|
+
} catch {
|
|
55
|
+
return content;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
36
59
|
* Normalize a tool's return value for transport:
|
|
37
60
|
* - string → unchanged
|
|
38
61
|
* - ContentPart array → unchanged (multimodal, passed through to the adapter)
|
|
@@ -44,6 +67,6 @@ function normalizeToolResult(result) {
|
|
|
44
67
|
return JSON.stringify(result);
|
|
45
68
|
}
|
|
46
69
|
//#endregion
|
|
47
|
-
export { isContentPart, isContentPartArray, normalizeToolResult };
|
|
70
|
+
export { isContentPart, isContentPartArray, isToolResultOutcome, normalizeToolResult, parseToolOutput, toolResultErrorText };
|
|
48
71
|
|
|
49
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
|
|
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"],"mapp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
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
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",
|
|
@@ -88,7 +88,7 @@
|
|
|
88
88
|
"@ag-ui/core": "1.0.0",
|
|
89
89
|
"@standard-schema/spec": "^1.1.0",
|
|
90
90
|
"partial-json": "^0.1.7",
|
|
91
|
-
"@tanstack/ai-event-client": "^0.
|
|
91
|
+
"@tanstack/ai-event-client": "^0.13.0",
|
|
92
92
|
"@tanstack/ai-utils": "^0.4.1"
|
|
93
93
|
},
|
|
94
94
|
"peerDependencies": {
|
|
@@ -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"
|
|
@@ -456,6 +456,68 @@ compatible providers speak.
|
|
|
456
456
|
> Verify the provider's current `baseURL` and model ids against its live docs —
|
|
457
457
|
> they drift. See `docs/adapters/openai-compatible.md` for the full provider table.
|
|
458
458
|
|
|
459
|
+
### 7. Files Adapters (upload once, reference by handle)
|
|
460
|
+
|
|
461
|
+
Four providers expose a native Files/storage API as a tree-shakeable `files`
|
|
462
|
+
adapter: `openaiFiles()`, `anthropicFiles()`, `geminiFiles()` (each reads the
|
|
463
|
+
same env var as the provider's text adapter; `create*Files(apiKey)` variants
|
|
464
|
+
take an explicit key), and `falFiles(config)`. Upload media once with
|
|
465
|
+
`uploadFile()`, then reference the returned `FileHandle` in messages via a
|
|
466
|
+
`{ type: 'file' }` content source instead of re-sending base64 each request:
|
|
467
|
+
|
|
468
|
+
```typescript
|
|
469
|
+
import { chat, fileSourceFromHandle, uploadFile } from '@tanstack/ai'
|
|
470
|
+
import { openaiFiles, openaiText } from '@tanstack/ai-openai'
|
|
471
|
+
import { pdfBase64 } from './pdf-data'
|
|
472
|
+
|
|
473
|
+
const handle = await uploadFile({
|
|
474
|
+
adapter: openaiFiles(),
|
|
475
|
+
input: { data: pdfBase64, mimeType: 'application/pdf' },
|
|
476
|
+
})
|
|
477
|
+
|
|
478
|
+
chat({
|
|
479
|
+
adapter: openaiText('gpt-5.5'),
|
|
480
|
+
messages: [
|
|
481
|
+
{
|
|
482
|
+
role: 'user',
|
|
483
|
+
content: [
|
|
484
|
+
{ type: 'text', content: 'Summarize this document' },
|
|
485
|
+
{ type: 'document', source: fileSourceFromHandle(handle) },
|
|
486
|
+
],
|
|
487
|
+
},
|
|
488
|
+
],
|
|
489
|
+
})
|
|
490
|
+
```
|
|
491
|
+
|
|
492
|
+
Rules agents must respect:
|
|
493
|
+
|
|
494
|
+
- **The source is one opaque handle plus its issuer.** `fileSourceFromHandle`
|
|
495
|
+
builds `{ type: 'file', value: 'file-…', provider: 'openai' }`, matching the
|
|
496
|
+
AG-UI `FileSource` arm. A handle only resolves at the provider that issued
|
|
497
|
+
it, so an adapter throws when `provider` names a different adapter.
|
|
498
|
+
`provider` is optional, as on the AG-UI wire; a source without it is taken
|
|
499
|
+
as-is. To use the same bytes with two providers,
|
|
500
|
+
upload to each and send the matching handle.
|
|
501
|
+
- **Adapters declare `supportsFileSources`.** For adapters that don't (Groq, Bedrock, Mistral, OpenRouter, Ollama, BytePlus, Cohere, and anything
|
|
502
|
+
written before this feature), `chat()` / `generateImage()` /
|
|
503
|
+
`generateVideo()` / `embed()` reject file sources in preflight, before any
|
|
504
|
+
request is built — pass `data`/`url` sources there instead.
|
|
505
|
+
- **Lifecycle:** `getFile()` / `deleteFile()` work for OpenAI, Anthropic,
|
|
506
|
+
Gemini, and Grok, and accept the handle itself (provider-literal typed, so a
|
|
507
|
+
foreign handle is a compile error). fal storage is upload-only, so those
|
|
508
|
+
calls throw for `falFiles()`. `grokFiles().get()` mints the public URL again,
|
|
509
|
+
so do not call it after `revokePublicUrl()`.
|
|
510
|
+
- **Some endpoints need raw bytes even on supporting providers:** OpenAI
|
|
511
|
+
`images/edits` + Sora `input_reference`, Gemini Veo, and Chat Completions
|
|
512
|
+
image inputs throw endpoint-specific errors for file sources.
|
|
513
|
+
- **A file source crosses the chat wire.** A browser that holds a handle puts
|
|
514
|
+
`fileSourceFromHandle(handle)` straight into the `sendMessage` content, and
|
|
515
|
+
the server passes the messages to `chat()` as usual. `fileSourceFromHandle`
|
|
516
|
+
and the `FileHandle` type are exported from the browser-safe
|
|
517
|
+
`@tanstack/ai/client` entry.
|
|
518
|
+
|
|
519
|
+
See `docs/advanced/files-api.md` for the full guide.
|
|
520
|
+
|
|
459
521
|
## Behind a proxy or gateway
|
|
460
522
|
|
|
461
523
|
Every adapter's client config accepts `baseURL` and `defaultHeaders`. Use these
|