@tanstack/ai 0.59.0 → 0.61.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/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/index.js +134 -22
- package/dist/esm/activities/chat/index.js.map +1 -1
- package/dist/esm/activities/chat/messages.js +5 -1
- package/dist/esm/activities/chat/messages.js.map +1 -1
- package/dist/esm/activities/chat/stream/message-updaters.js +9 -2
- package/dist/esm/activities/chat/stream/message-updaters.js.map +1 -1
- package/dist/esm/activities/chat/stream/processor.d.ts +0 -1
- package/dist/esm/activities/chat/stream/processor.js +15 -12
- package/dist/esm/activities/chat/stream/processor.js.map +1 -1
- package/dist/esm/activities/chat/tools/tool-calls.js +2 -0
- package/dist/esm/activities/chat/tools/tool-calls.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/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 +2 -0
- package/dist/esm/client.js +2 -1
- package/dist/esm/client.js.map +1 -1
- package/dist/esm/index.d.ts +3 -2
- package/dist/esm/index.js +4 -2
- package/dist/esm/types.d.ts +72 -13
- package/dist/esm/utilities/ag-ui-wire.js +34 -13
- 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 +12 -2
- package/dist/esm/utilities/tool-result.js +23 -3
- package/dist/esm/utilities/tool-result.js.map +1 -1
- package/package.json +2 -2
- package/skills/ai-core/adapter-configuration/SKILL.md +62 -0
- package/skills/ai-core/chat-experience/SKILL.md +14 -0
- package/skills/ai-core/media-generation/SKILL.md +8 -0
- package/src/activities/chat/adapter.ts +10 -0
- package/src/activities/chat/index.ts +226 -40
- package/src/activities/chat/messages.ts +12 -1
- package/src/activities/chat/stream/message-updaters.ts +24 -2
- package/src/activities/chat/stream/processor.ts +24 -22
- package/src/activities/chat/tools/tool-calls.ts +6 -0
- package/src/activities/embed/adapter.ts +7 -0
- package/src/activities/embed/index.ts +5 -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 +7 -0
- package/src/index.ts +16 -0
- package/src/types.ts +76 -13
- package/src/utilities/ag-ui-wire.ts +60 -16
- package/src/utilities/content-source.ts +138 -0
- package/src/utilities/provider-executed.ts +13 -0
- package/src/utilities/tool-result.ts +38 -2
package/dist/esm/types.d.ts
CHANGED
|
@@ -132,8 +132,21 @@ export interface ContentPartUrlSource extends AGUIUrlSource {
|
|
|
132
132
|
/**
|
|
133
133
|
* A provider-issued file handle (Files API). AG-UI `FileSource`: the handle
|
|
134
134
|
* is opaque, do not fetch or parse it.
|
|
135
|
+
*
|
|
136
|
+
* The media is uploaded once via a `files` adapter (`openaiFiles()`,
|
|
137
|
+
* `anthropicFiles()`, `geminiFiles()`, `grokFiles()`, `falFiles()`) and
|
|
138
|
+
* referenced here by the returned handle instead of re-sending base64 or a
|
|
139
|
+
* public URL on each request. Only the provider that minted a handle can
|
|
140
|
+
* resolve it. Adapters that cannot consume file handles at all are rejected
|
|
141
|
+
* by the activity-layer preflight before mapping starts.
|
|
135
142
|
*/
|
|
136
|
-
export interface ContentPartFileSource extends AGUIFileSource {
|
|
143
|
+
export interface ContentPartFileSource<TProvider extends string = string> extends AGUIFileSource {
|
|
144
|
+
/**
|
|
145
|
+
* The adapter name of the provider that issued the handle (`'openai'`,
|
|
146
|
+
* `'gemini'`, ...), the same id TanStack reports as the usage provider.
|
|
147
|
+
* When present, an adapter rejects a handle another provider issued.
|
|
148
|
+
*/
|
|
149
|
+
provider?: TProvider;
|
|
137
150
|
}
|
|
138
151
|
/**
|
|
139
152
|
* Where a media part's bytes come from: inline data, a URL, or a provider
|
|
@@ -1905,7 +1918,7 @@ export interface VideoUrlResult {
|
|
|
1905
1918
|
artifacts?: Array<PersistedArtifactRef>;
|
|
1906
1919
|
}
|
|
1907
1920
|
/**
|
|
1908
|
-
* Options for world generation (live
|
|
1921
|
+
* Options for world generation (live session or finished job).
|
|
1909
1922
|
*
|
|
1910
1923
|
* @experimental World generation is an experimental feature and may change.
|
|
1911
1924
|
*/
|
|
@@ -1915,8 +1928,10 @@ export interface WorldGenerationOptions<TProviderOptions extends object = object
|
|
|
1915
1928
|
/** Natural-language description of the world or scene */
|
|
1916
1929
|
prompt: string;
|
|
1917
1930
|
/**
|
|
1918
|
-
* Provider
|
|
1919
|
-
*
|
|
1931
|
+
* Provider-specific options. Live adapters (Reactor) use mint fields here.
|
|
1932
|
+
* Job adapters (World Labs) use image/video inputs, `wait`, and poll.
|
|
1933
|
+
* Reactor resolution/seed/audio are browser `sendCommand` fields, not
|
|
1934
|
+
* token-mint fields.
|
|
1920
1935
|
*/
|
|
1921
1936
|
modelOptions?: TProviderOptions;
|
|
1922
1937
|
/**
|
|
@@ -1932,28 +1947,72 @@ export interface WorldGenerationOptions<TProviderOptions extends object = object
|
|
|
1932
1947
|
*/
|
|
1933
1948
|
abortSignal?: AbortSignal;
|
|
1934
1949
|
}
|
|
1950
|
+
/**
|
|
1951
|
+
* Assets from a finished world job. Live session adapters omit this.
|
|
1952
|
+
* URLs are often signed CDN links. They can expire and may need a proxy
|
|
1953
|
+
* to fetch from a browser.
|
|
1954
|
+
*
|
|
1955
|
+
* @experimental World generation is an experimental feature and may change.
|
|
1956
|
+
*/
|
|
1957
|
+
export interface WorldGenerationAssets {
|
|
1958
|
+
/** Auto-generated scene description */
|
|
1959
|
+
caption?: string;
|
|
1960
|
+
/** Preview image URL */
|
|
1961
|
+
thumbnailUrl?: string;
|
|
1962
|
+
splats?: {
|
|
1963
|
+
/** Quality-key map of splat URLs (`100k`, `500k`, `full_res`, …) */
|
|
1964
|
+
spzUrls?: Record<string, string>;
|
|
1965
|
+
metricScaleFactor?: number;
|
|
1966
|
+
groundPlaneOffset?: number;
|
|
1967
|
+
};
|
|
1968
|
+
mesh?: {
|
|
1969
|
+
colliderMeshUrl?: string;
|
|
1970
|
+
hqMeshUrl?: string;
|
|
1971
|
+
fullResMeshUrl?: string;
|
|
1972
|
+
};
|
|
1973
|
+
imagery?: {
|
|
1974
|
+
panoUrl?: string;
|
|
1975
|
+
};
|
|
1976
|
+
}
|
|
1935
1977
|
/**
|
|
1936
1978
|
* Result of world generation. JSON-serializable so a server route can return
|
|
1937
|
-
* it to a browser.
|
|
1938
|
-
*
|
|
1979
|
+
* it to a browser.
|
|
1980
|
+
*
|
|
1981
|
+
* Live adapters (Reactor): `status: 'ready'` with `token` and token
|
|
1982
|
+
* `expiresAt`. The browser uses `token` + `model` to open the session.
|
|
1983
|
+
*
|
|
1984
|
+
* Job adapters (World Labs): `status: 'ready'` with viewer `url` and
|
|
1985
|
+
* `worldId`, or `status: 'waiting'` with `operationId` and no `url`.
|
|
1986
|
+
* `expiresAt` on a job is operation expiry, not a session token.
|
|
1939
1987
|
*
|
|
1940
1988
|
* @experimental World generation is an experimental feature and may change.
|
|
1941
1989
|
*/
|
|
1942
1990
|
export interface WorldGenerationResult {
|
|
1943
1991
|
/** Unique identifier for this generation */
|
|
1944
1992
|
id: string;
|
|
1945
|
-
/** Model used for generation (provider connect slug) */
|
|
1993
|
+
/** Model used for generation (provider connect slug or model id) */
|
|
1946
1994
|
model: string;
|
|
1947
|
-
/** Short-lived session token for
|
|
1948
|
-
token
|
|
1949
|
-
/**
|
|
1950
|
-
|
|
1951
|
-
|
|
1995
|
+
/** Short-lived session token for a live client connection */
|
|
1996
|
+
token?: string;
|
|
1997
|
+
/**
|
|
1998
|
+
* Expiry as milliseconds since epoch. Live adapters: session token.
|
|
1999
|
+
* Job adapters: operation expiry when the provider sends it.
|
|
2000
|
+
*/
|
|
2001
|
+
expiresAt?: number;
|
|
2002
|
+
/** Prompt used to generate the world, or the prompt the client should send */
|
|
1952
2003
|
prompt: string;
|
|
1953
|
-
/**
|
|
2004
|
+
/** Status after the server half finishes */
|
|
1954
2005
|
status: 'ready' | 'waiting';
|
|
1955
2006
|
/** Provider session id, when the adapter created one */
|
|
1956
2007
|
sessionId?: string;
|
|
2008
|
+
/** Viewer URL for a finished world job (not an asset download URL) */
|
|
2009
|
+
url?: string;
|
|
2010
|
+
/** Provider world id for a finished or in-progress job */
|
|
2011
|
+
worldId?: string;
|
|
2012
|
+
/** Provider operation id for a long-running world job */
|
|
2013
|
+
operationId?: string;
|
|
2014
|
+
/** Assets when a world job has finished and the provider returned them */
|
|
2015
|
+
assets?: WorldGenerationAssets;
|
|
1957
2016
|
/** Token usage / billing, when the adapter can report it */
|
|
1958
2017
|
usage?: TokenUsage;
|
|
1959
2018
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { tanstackMetadata } from "./merge-metadata.js";
|
|
2
|
+
import { isProviderExecutedToolCall } from "./provider-executed.js";
|
|
2
3
|
import { normalizeToolResult } from "./tool-result.js";
|
|
3
4
|
import { wireSubagentInfo, wireSubagentRunId } from "./subagent-wire.js";
|
|
4
5
|
import { coerceCreatedAt, modelMessageToUIMessage } from "../activities/chat/messages.js";
|
|
@@ -66,21 +67,41 @@ function uiMessagesToWire(messages, options) {
|
|
|
66
67
|
wire.push(toAnchor(uiMessage, "user", { content: parts.length > 0 ? collectUserContent(parts) : msg.content ?? "" }, parts, includeSnapshotStructuredOutput));
|
|
67
68
|
continue;
|
|
68
69
|
}
|
|
70
|
+
let current = {
|
|
71
|
+
thinking: [],
|
|
72
|
+
parts: []
|
|
73
|
+
};
|
|
74
|
+
const segments = [current];
|
|
69
75
|
for (const part of parts) if (part.type === "thinking") {
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
76
|
+
if (current.parts.some((p) => p.type === "tool-call" && isProviderExecutedToolCall(p))) {
|
|
77
|
+
current = {
|
|
78
|
+
thinking: [part],
|
|
79
|
+
parts: []
|
|
80
|
+
};
|
|
81
|
+
segments.push(current);
|
|
82
|
+
} else current.thinking.push(part);
|
|
83
|
+
} else current.parts.push(part);
|
|
84
|
+
segments.forEach((segment, index) => {
|
|
85
|
+
for (const part of segment.thinking) {
|
|
86
|
+
const reasoning = {
|
|
87
|
+
role: "reasoning",
|
|
88
|
+
id: uniqueWireId(deriveReasoningId(uiMessage.id, part), usedWireIds),
|
|
89
|
+
content: part.content
|
|
90
|
+
};
|
|
91
|
+
if (part.signature) reasoning.encryptedValue = part.signature;
|
|
92
|
+
wire.push(reasoning);
|
|
93
|
+
}
|
|
94
|
+
const text = collectText(segment.parts);
|
|
95
|
+
const toolCalls = collectToolCalls(segment.parts);
|
|
96
|
+
const anchorMessage = index === 0 ? uiMessage : {
|
|
97
|
+
...uiMessage,
|
|
98
|
+
id: uniqueWireId(`${uiMessage.id}-segment-${index}`, usedWireIds)
|
|
74
99
|
};
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
wire.push(toAnchor(uiMessage, "assistant", {
|
|
81
|
-
...text !== "" && { content: text },
|
|
82
|
-
...toolCalls && { toolCalls }
|
|
83
|
-
}, parts, includeSnapshotStructuredOutput));
|
|
100
|
+
wire.push(toAnchor(anchorMessage, "assistant", {
|
|
101
|
+
...text !== "" && { content: text },
|
|
102
|
+
...toolCalls && { toolCalls }
|
|
103
|
+
}, segment.parts, includeSnapshotStructuredOutput));
|
|
104
|
+
});
|
|
84
105
|
const explicitToolResults = new Set(parts.flatMap((part) => part.type === "tool-result" ? [part.toolCallId] : []));
|
|
85
106
|
for (const part of parts) if (part.type === "tool-result") {
|
|
86
107
|
const id = uniqueToolWireId(part.id ?? deriveToolMessageId(part.toolCallId), usedWireIds);
|
|
@@ -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;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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T;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 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,OA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jB,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"}
|
|
@@ -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,9 @@
|
|
|
1
1
|
import { ContentPart } from '../types.js';
|
|
2
2
|
/**
|
|
3
3
|
* Structural check for a single `ContentPart`. A text part must carry a string
|
|
4
|
-
* `content
|
|
5
|
-
*
|
|
4
|
+
* `content`. Every other part carries a source with a string `value`; a file
|
|
5
|
+
* source's `value` is a non-empty opaque handle, and its optional `provider`
|
|
6
|
+
* is a string.
|
|
6
7
|
*/
|
|
7
8
|
export declare function isContentPart(value: unknown): value is ContentPart;
|
|
8
9
|
/**
|
|
@@ -12,6 +13,15 @@ export declare function isContentPart(value: unknown): value is ContentPart;
|
|
|
12
13
|
* footgun narrow.
|
|
13
14
|
*/
|
|
14
15
|
export declare function isContentPartArray(value: unknown): value is Array<ContentPart>;
|
|
16
|
+
/**
|
|
17
|
+
* Error text for a failed tool result: `output.error` when it is a string,
|
|
18
|
+
* else the output itself when it is a string, else a generic message.
|
|
19
|
+
* `StreamProcessor` and `chat()` history share it, so a reload shows the
|
|
20
|
+
* same text as the live stream.
|
|
21
|
+
*/
|
|
22
|
+
export declare function toolResultErrorText(output: unknown): string;
|
|
23
|
+
/** Parse tool result content as JSON. Plain text stays a string. */
|
|
24
|
+
export declare function parseToolOutput(content: string): unknown;
|
|
15
25
|
/**
|
|
16
26
|
* Normalize a tool's return value for transport:
|
|
17
27
|
* - string → unchanged
|
|
@@ -8,8 +8,9 @@ var CONTENT_PART_TYPES = /* @__PURE__ */ new Set([
|
|
|
8
8
|
]);
|
|
9
9
|
/**
|
|
10
10
|
* Structural check for a single `ContentPart`. A text part must carry a string
|
|
11
|
-
* `content
|
|
12
|
-
*
|
|
11
|
+
* `content`. Every other part carries a source with a string `value`; a file
|
|
12
|
+
* source's `value` is a non-empty opaque handle, and its optional `provider`
|
|
13
|
+
* is a string.
|
|
13
14
|
*/
|
|
14
15
|
function isContentPart(value) {
|
|
15
16
|
if (typeof value !== "object" || value === null) return false;
|
|
@@ -20,6 +21,7 @@ function isContentPart(value) {
|
|
|
20
21
|
if (typeof source !== "object" || source === null) return false;
|
|
21
22
|
const src = source;
|
|
22
23
|
if (typeof src.value !== "string") return false;
|
|
24
|
+
if (src.type === "file") return src.value.length > 0 && (src.provider === void 0 || typeof src.provider === "string");
|
|
23
25
|
if (src.type === "data") return typeof src.mimeType === "string";
|
|
24
26
|
return src.type === "url";
|
|
25
27
|
}
|
|
@@ -33,6 +35,24 @@ function isContentPartArray(value) {
|
|
|
33
35
|
return Array.isArray(value) && value.length > 0 && value.every(isContentPart);
|
|
34
36
|
}
|
|
35
37
|
/**
|
|
38
|
+
* Error text for a failed tool result: `output.error` when it is a string,
|
|
39
|
+
* else the output itself when it is a string, else a generic message.
|
|
40
|
+
* `StreamProcessor` and `chat()` history share it, so a reload shows the
|
|
41
|
+
* same text as the live stream.
|
|
42
|
+
*/
|
|
43
|
+
function toolResultErrorText(output) {
|
|
44
|
+
if (output && typeof output === "object" && "error" in output && typeof output.error === "string") return output.error;
|
|
45
|
+
return typeof output === "string" ? output : "Tool execution failed";
|
|
46
|
+
}
|
|
47
|
+
/** Parse tool result content as JSON. Plain text stays a string. */
|
|
48
|
+
function parseToolOutput(content) {
|
|
49
|
+
try {
|
|
50
|
+
return JSON.parse(content);
|
|
51
|
+
} catch {
|
|
52
|
+
return content;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
36
56
|
* Normalize a tool's return value for transport:
|
|
37
57
|
* - string → unchanged
|
|
38
58
|
* - ContentPart array → unchanged (multimodal, passed through to the adapter)
|
|
@@ -44,6 +64,6 @@ function normalizeToolResult(result) {
|
|
|
44
64
|
return JSON.stringify(result);
|
|
45
65
|
}
|
|
46
66
|
//#endregion
|
|
47
|
-
export { isContentPart, isContentPartArray, normalizeToolResult };
|
|
67
|
+
export { isContentPart, isContentPartArray, normalizeToolResult, parseToolOutput, toolResultErrorText };
|
|
48
68
|
|
|
49
69
|
//# sourceMappingURL=tool-result.js.map
|