@tanstack/ai 0.36.0 → 0.37.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 +163 -0
- package/dist/esm/activities/chat/adapter.js +17 -0
- package/dist/esm/activities/chat/adapter.js.map +1 -0
- package/dist/esm/activities/chat/agent-loop-strategies.d.ts +59 -0
- package/dist/esm/activities/chat/agent-loop-strategies.js +23 -0
- package/dist/esm/activities/chat/agent-loop-strategies.js.map +1 -0
- package/dist/esm/activities/chat/index.d.ts +270 -0
- package/dist/esm/activities/chat/index.js +1724 -0
- package/dist/esm/activities/chat/index.js.map +1 -0
- package/dist/esm/activities/chat/mcp/manager.d.ts +25 -0
- package/dist/esm/activities/chat/mcp/manager.js +71 -0
- package/dist/esm/activities/chat/mcp/manager.js.map +1 -0
- package/dist/esm/activities/chat/mcp/types.d.ts +56 -0
- package/dist/esm/activities/chat/messages.d.ts +78 -0
- package/dist/esm/activities/chat/messages.js +374 -0
- package/dist/esm/activities/chat/messages.js.map +1 -0
- package/dist/esm/activities/chat/middleware/builder.d.ts +46 -0
- package/dist/esm/activities/chat/middleware/builder.js +17 -0
- package/dist/esm/activities/chat/middleware/builder.js.map +1 -0
- package/dist/esm/activities/chat/middleware/capabilities.d.ts +93 -0
- package/dist/esm/activities/chat/middleware/capabilities.js +45 -0
- package/dist/esm/activities/chat/middleware/capabilities.js.map +1 -0
- package/dist/esm/activities/chat/middleware/compose.d.ts +87 -0
- package/dist/esm/activities/chat/middleware/compose.js +510 -0
- package/dist/esm/activities/chat/middleware/compose.js.map +1 -0
- package/dist/esm/activities/chat/middleware/define.d.ts +20 -0
- package/dist/esm/activities/chat/middleware/define.js +7 -0
- package/dist/esm/activities/chat/middleware/define.js.map +1 -0
- package/dist/esm/activities/chat/middleware/index.d.ts +10 -0
- package/dist/esm/activities/chat/middleware/tool-cache-middleware.d.ts +89 -0
- package/dist/esm/activities/chat/middleware/tool-cache-middleware.js +76 -0
- package/dist/esm/activities/chat/middleware/tool-cache-middleware.js.map +1 -0
- package/dist/esm/activities/chat/middleware/types.d.ts +405 -0
- package/dist/esm/activities/chat/middleware/validate.d.ts +19 -0
- package/dist/esm/activities/chat/middleware/validate.js +30 -0
- package/dist/esm/activities/chat/middleware/validate.js.map +1 -0
- package/dist/esm/activities/chat/runtime-context-types.d.ts +43 -0
- package/dist/esm/activities/chat/stream/index.d.ts +11 -0
- package/dist/esm/activities/chat/stream/json-parser.d.ts +38 -0
- package/dist/esm/activities/chat/stream/json-parser.js +28 -0
- package/dist/esm/activities/chat/stream/json-parser.js.map +1 -0
- package/dist/esm/activities/chat/stream/message-updaters.d.ts +81 -0
- package/dist/esm/activities/chat/stream/message-updaters.js +253 -0
- package/dist/esm/activities/chat/stream/message-updaters.js.map +1 -0
- package/dist/esm/activities/chat/stream/processor.d.ts +439 -0
- package/dist/esm/activities/chat/stream/processor.js +1426 -0
- package/dist/esm/activities/chat/stream/processor.js.map +1 -0
- package/dist/esm/activities/chat/stream/strategies.d.ts +43 -0
- package/dist/esm/activities/chat/stream/strategies.js +54 -0
- package/dist/esm/activities/chat/stream/strategies.js.map +1 -0
- package/dist/esm/activities/chat/stream/types.d.ts +90 -0
- package/dist/esm/activities/chat/tools/lazy-tool-manager.d.ts +82 -0
- package/dist/esm/activities/chat/tools/lazy-tool-manager.js +194 -0
- package/dist/esm/activities/chat/tools/lazy-tool-manager.js.map +1 -0
- package/dist/esm/activities/chat/tools/lazy-tools.d.ts +15 -0
- package/dist/esm/activities/chat/tools/lazy-tools.js +16 -0
- package/dist/esm/activities/chat/tools/lazy-tools.js.map +1 -0
- package/dist/esm/activities/chat/tools/schema-converter.d.ts +140 -0
- package/dist/esm/activities/chat/tools/schema-converter.js +167 -0
- package/dist/esm/activities/chat/tools/schema-converter.js.map +1 -0
- package/dist/esm/activities/chat/tools/tool-calls.d.ts +140 -0
- package/dist/esm/activities/chat/tools/tool-calls.js +512 -0
- package/dist/esm/activities/chat/tools/tool-calls.js.map +1 -0
- package/dist/esm/activities/chat/tools/tool-definition.d.ts +135 -0
- package/dist/esm/activities/chat/tools/tool-definition.js +25 -0
- package/dist/esm/activities/chat/tools/tool-definition.js.map +1 -0
- package/dist/esm/activities/error-payload.d.ts +30 -0
- package/dist/esm/activities/error-payload.js +54 -0
- package/dist/esm/activities/error-payload.js.map +1 -0
- package/dist/esm/activities/generateAudio/adapter.d.ts +62 -0
- package/dist/esm/activities/generateAudio/adapter.js +16 -0
- package/dist/esm/activities/generateAudio/adapter.js.map +1 -0
- package/dist/esm/activities/generateAudio/index.d.ts +85 -0
- package/dist/esm/activities/generateAudio/index.js +114 -0
- package/dist/esm/activities/generateAudio/index.js.map +1 -0
- package/dist/esm/activities/generateImage/adapter.d.ts +78 -0
- package/dist/esm/activities/generateImage/adapter.js +16 -0
- package/dist/esm/activities/generateImage/adapter.js.map +1 -0
- package/dist/esm/activities/generateImage/index.d.ts +134 -0
- package/dist/esm/activities/generateImage/index.js +121 -0
- package/dist/esm/activities/generateImage/index.js.map +1 -0
- package/dist/esm/activities/generateSpeech/adapter.d.ts +62 -0
- package/dist/esm/activities/generateSpeech/adapter.js +16 -0
- package/dist/esm/activities/generateSpeech/adapter.js.map +1 -0
- package/dist/esm/activities/generateSpeech/index.d.ts +96 -0
- package/dist/esm/activities/generateSpeech/index.js +119 -0
- package/dist/esm/activities/generateSpeech/index.js.map +1 -0
- package/dist/esm/activities/generateTranscription/adapter.d.ts +62 -0
- package/dist/esm/activities/generateTranscription/adapter.js +16 -0
- package/dist/esm/activities/generateTranscription/adapter.js.map +1 -0
- package/dist/esm/activities/generateTranscription/index.d.ts +109 -0
- package/dist/esm/activities/generateTranscription/index.js +109 -0
- package/dist/esm/activities/generateTranscription/index.js.map +1 -0
- package/dist/esm/activities/generateVideo/adapter.d.ts +145 -0
- package/dist/esm/activities/generateVideo/adapter.js +30 -0
- package/dist/esm/activities/generateVideo/adapter.js.map +1 -0
- package/dist/esm/activities/generateVideo/index.d.ts +223 -0
- package/dist/esm/activities/generateVideo/index.js +295 -0
- package/dist/esm/activities/generateVideo/index.js.map +1 -0
- package/dist/esm/activities/generateVideo/snap.d.ts +14 -0
- package/dist/esm/activities/generateVideo/snap.js +54 -0
- package/dist/esm/activities/generateVideo/snap.js.map +1 -0
- package/dist/esm/activities/index.d.ts +27 -0
- package/dist/esm/activities/index.js +43 -0
- package/dist/esm/activities/index.js.map +1 -0
- package/dist/esm/activities/middleware/index.d.ts +2 -0
- package/dist/esm/activities/middleware/run.d.ts +20 -0
- package/dist/esm/activities/middleware/run.js +42 -0
- package/dist/esm/activities/middleware/run.js.map +1 -0
- package/dist/esm/activities/middleware/types.d.ts +118 -0
- package/dist/esm/activities/stream-generation-result.d.ts +15 -0
- package/dist/esm/activities/stream-generation-result.js +49 -0
- package/dist/esm/activities/stream-generation-result.js.map +1 -0
- package/dist/esm/activities/summarize/adapter.d.ts +74 -0
- package/dist/esm/activities/summarize/adapter.js +16 -0
- package/dist/esm/activities/summarize/adapter.js.map +1 -0
- package/dist/esm/activities/summarize/chat-stream-summarize.d.ts +45 -0
- package/dist/esm/activities/summarize/chat-stream-summarize.js +212 -0
- package/dist/esm/activities/summarize/chat-stream-summarize.js.map +1 -0
- package/dist/esm/activities/summarize/index.d.ts +108 -0
- package/dist/esm/activities/summarize/index.js +113 -0
- package/dist/esm/activities/summarize/index.js.map +1 -0
- package/dist/esm/adapter-internals.d.ts +5 -0
- package/dist/esm/adapter-internals.js +10 -0
- package/dist/esm/adapter-internals.js.map +1 -0
- package/dist/esm/client.d.ts +44 -0
- package/dist/esm/client.js +67 -0
- package/dist/esm/client.js.map +1 -0
- package/dist/esm/extend-adapter.d.ts +152 -0
- package/dist/esm/extend-adapter.js +21 -0
- package/dist/esm/extend-adapter.js.map +1 -0
- package/dist/esm/index.d.ts +45 -0
- package/dist/esm/index.js +109 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/logger/console-logger.d.ts +29 -0
- package/dist/esm/logger/console-logger.js +83 -0
- package/dist/esm/logger/console-logger.js.map +1 -0
- package/dist/esm/logger/internal-logger.d.ts +41 -0
- package/dist/esm/logger/internal-logger.js +86 -0
- package/dist/esm/logger/internal-logger.js.map +1 -0
- package/dist/esm/logger/resolve.d.ts +14 -0
- package/dist/esm/logger/resolve.js +54 -0
- package/dist/esm/logger/resolve.js.map +1 -0
- package/dist/esm/logger/types.d.ts +75 -0
- package/dist/esm/middlewares/content-guard.d.ts +77 -0
- package/dist/esm/middlewares/content-guard.js +156 -0
- package/dist/esm/middlewares/content-guard.js.map +1 -0
- package/dist/esm/middlewares/index.d.ts +2 -0
- package/dist/esm/middlewares/index.js +7 -0
- package/dist/esm/middlewares/index.js.map +1 -0
- package/dist/esm/middlewares/otel.d.ts +81 -0
- package/dist/esm/middlewares/otel.js +745 -0
- package/dist/esm/middlewares/otel.js.map +1 -0
- package/dist/esm/middlewares/tool-cache.d.ts +1 -0
- package/dist/esm/middlewares/usage-attributes.d.ts +24 -0
- package/dist/esm/middlewares/usage-attributes.js +43 -0
- package/dist/esm/middlewares/usage-attributes.js.map +1 -0
- package/dist/esm/realtime/index.d.ts +28 -0
- package/dist/esm/realtime/index.js +8 -0
- package/dist/esm/realtime/index.js.map +1 -0
- package/dist/esm/realtime/types.d.ts +282 -0
- package/dist/esm/stream-to-response.d.ts +102 -0
- package/dist/esm/stream-to-response.js +121 -0
- package/dist/esm/stream-to-response.js.map +1 -0
- package/dist/esm/strip-to-spec-middleware.d.ts +18 -0
- package/dist/esm/strip-to-spec-middleware.js +20 -0
- package/dist/esm/strip-to-spec-middleware.js.map +1 -0
- package/dist/esm/system-prompts.d.ts +66 -0
- package/dist/esm/system-prompts.js +23 -0
- package/dist/esm/system-prompts.js.map +1 -0
- package/dist/esm/tool-registry.d.ts +81 -0
- package/dist/esm/tool-registry.js +49 -0
- package/dist/esm/tool-registry.js.map +1 -0
- package/dist/esm/tools/provider-tool.d.ts +30 -0
- package/dist/esm/tools/provider-tool.js +7 -0
- package/dist/esm/tools/provider-tool.js.map +1 -0
- package/dist/esm/types.d.ts +1594 -0
- package/dist/esm/utilities/ag-ui-wire.d.ts +44 -0
- package/dist/esm/utilities/ag-ui-wire.js +107 -0
- package/dist/esm/utilities/ag-ui-wire.js.map +1 -0
- package/dist/esm/utilities/chat-params.d.ts +85 -0
- package/dist/esm/utilities/chat-params.js +100 -0
- package/dist/esm/utilities/chat-params.js.map +1 -0
- package/dist/esm/utilities/errors.d.ts +13 -0
- package/dist/esm/utilities/errors.js +22 -0
- package/dist/esm/utilities/errors.js.map +1 -0
- package/dist/esm/utilities/media-prompt.d.ts +35 -0
- package/dist/esm/utilities/media-prompt.js +43 -0
- package/dist/esm/utilities/media-prompt.js.map +1 -0
- package/dist/esm/utilities/numbers.d.ts +8 -0
- package/dist/esm/utilities/numbers.js +12 -0
- package/dist/esm/utilities/numbers.js.map +1 -0
- package/dist/esm/utilities/sampling-keys.d.ts +20 -0
- package/dist/esm/utilities/sampling-keys.js +20 -0
- package/dist/esm/utilities/sampling-keys.js.map +1 -0
- package/dist/esm/utilities/tool-result.d.ts +21 -0
- package/dist/esm/utilities/tool-result.js +37 -0
- package/dist/esm/utilities/tool-result.js.map +1 -0
- package/dist/esm/utilities/usage.d.ts +31 -0
- package/dist/esm/utilities/usage.js +11 -0
- package/dist/esm/utilities/usage.js.map +1 -0
- package/dist/esm/utils.d.ts +17 -0
- package/dist/esm/utils.js +20 -0
- package/dist/esm/utils.js.map +1 -0
- package/package.json +3 -3
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { ContentPart, UIMessage } from '../types.js';
|
|
2
|
+
type AGUITextInputContent = {
|
|
3
|
+
type: 'text';
|
|
4
|
+
text: string;
|
|
5
|
+
};
|
|
6
|
+
type AGUIInputContent = AGUITextInputContent | (ContentPart & {
|
|
7
|
+
type: 'image' | 'audio' | 'video' | 'document';
|
|
8
|
+
});
|
|
9
|
+
type AGUIToolCallMirror = {
|
|
10
|
+
id: string;
|
|
11
|
+
type: 'function';
|
|
12
|
+
function: {
|
|
13
|
+
name: string;
|
|
14
|
+
arguments: string;
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
type AGUIToolMessage = {
|
|
18
|
+
role: 'tool';
|
|
19
|
+
id: string;
|
|
20
|
+
toolCallId: string;
|
|
21
|
+
content: string;
|
|
22
|
+
error?: string;
|
|
23
|
+
};
|
|
24
|
+
type AGUIReasoningMessage = {
|
|
25
|
+
role: 'reasoning';
|
|
26
|
+
id: string;
|
|
27
|
+
content: string;
|
|
28
|
+
};
|
|
29
|
+
type WireAnchorMessage = UIMessage & {
|
|
30
|
+
content?: string | Array<AGUIInputContent>;
|
|
31
|
+
toolCalls?: Array<AGUIToolCallMirror>;
|
|
32
|
+
};
|
|
33
|
+
export type WireMessage = WireAnchorMessage | AGUIToolMessage | AGUIReasoningMessage;
|
|
34
|
+
/**
|
|
35
|
+
* Serialize TanStack `UIMessage`s into the AG-UI `RunAgentInput.messages`
|
|
36
|
+
* wire shape. Each anchor (system/user/assistant) carries the canonical
|
|
37
|
+
* `parts` array verbatim plus AG-UI mirror fields (`content`, `toolCalls`)
|
|
38
|
+
* so AG-UI Zod parsing succeeds. Tool results and thinking parts on
|
|
39
|
+
* assistant messages are additionally emitted as fan-out
|
|
40
|
+
* `{role:'tool',...}` and `{role:'reasoning',...}` entries for strict
|
|
41
|
+
* AG-UI server consumers.
|
|
42
|
+
*/
|
|
43
|
+
export declare function uiMessagesToWire(messages: Array<UIMessage>): Array<WireMessage>;
|
|
44
|
+
export {};
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
function uiMessagesToWire(messages) {
|
|
2
|
+
const wire = [];
|
|
3
|
+
for (const msg of messages) {
|
|
4
|
+
const parts = (
|
|
5
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- runtime input may be ModelMessage-shaped (no `parts`); cast forces the optional-chain fallback below to remain in scope
|
|
6
|
+
msg.parts ?? []
|
|
7
|
+
);
|
|
8
|
+
if (msg.role === "system") {
|
|
9
|
+
wire.push({
|
|
10
|
+
...msg,
|
|
11
|
+
content: parts.length > 0 ? collectText(parts) : msg.content ?? ""
|
|
12
|
+
});
|
|
13
|
+
continue;
|
|
14
|
+
}
|
|
15
|
+
if (msg.role === "user") {
|
|
16
|
+
wire.push({
|
|
17
|
+
...msg,
|
|
18
|
+
content: parts.length > 0 ? collectUserContent(parts) : msg.content ?? ""
|
|
19
|
+
});
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
for (const part of parts) {
|
|
23
|
+
if (part.type === "thinking") {
|
|
24
|
+
wire.push({
|
|
25
|
+
role: "reasoning",
|
|
26
|
+
id: deriveReasoningId(msg.id, part),
|
|
27
|
+
content: part.content
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const text = collectText(parts);
|
|
32
|
+
const toolCalls = collectToolCalls(parts);
|
|
33
|
+
wire.push({
|
|
34
|
+
...msg,
|
|
35
|
+
...text !== "" && { content: text },
|
|
36
|
+
...toolCalls && { toolCalls }
|
|
37
|
+
});
|
|
38
|
+
for (const part of parts) {
|
|
39
|
+
if (part.type === "tool-result") {
|
|
40
|
+
wire.push({
|
|
41
|
+
role: "tool",
|
|
42
|
+
id: deriveToolMessageId(part.toolCallId),
|
|
43
|
+
toolCallId: part.toolCallId,
|
|
44
|
+
content: typeof part.content === "string" ? part.content : JSON.stringify(part.content),
|
|
45
|
+
...part.error !== void 0 && { error: part.error }
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return wire;
|
|
51
|
+
}
|
|
52
|
+
function collectText(parts) {
|
|
53
|
+
const out = [];
|
|
54
|
+
for (const p of parts) {
|
|
55
|
+
if (p.type === "text") {
|
|
56
|
+
out.push(p.content);
|
|
57
|
+
} else if (p.type === "structured-output" && p.status === "complete" && p.raw !== "") {
|
|
58
|
+
out.push(p.raw);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return out.join("");
|
|
62
|
+
}
|
|
63
|
+
function collectUserContent(parts) {
|
|
64
|
+
const hasMultimodal = parts.some(
|
|
65
|
+
(p) => p.type === "image" || p.type === "audio" || p.type === "video" || p.type === "document"
|
|
66
|
+
);
|
|
67
|
+
if (!hasMultimodal) {
|
|
68
|
+
return collectText(parts);
|
|
69
|
+
}
|
|
70
|
+
const out = [];
|
|
71
|
+
for (const p of parts) {
|
|
72
|
+
if (p.type === "text") {
|
|
73
|
+
out.push({ type: "text", text: p.content });
|
|
74
|
+
} else if (p.type === "image" || p.type === "audio" || p.type === "video" || p.type === "document") {
|
|
75
|
+
out.push(p);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
function collectToolCalls(parts) {
|
|
81
|
+
const calls = [];
|
|
82
|
+
for (const p of parts) {
|
|
83
|
+
if (p.type === "tool-call") {
|
|
84
|
+
calls.push({
|
|
85
|
+
id: p.id,
|
|
86
|
+
type: "function",
|
|
87
|
+
function: { name: p.name, arguments: p.arguments }
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return calls.length > 0 ? calls : void 0;
|
|
92
|
+
}
|
|
93
|
+
function deriveReasoningId(messageId, part) {
|
|
94
|
+
return `${messageId}-reasoning-${part.id ?? hashContent(part.content)}`;
|
|
95
|
+
}
|
|
96
|
+
function deriveToolMessageId(toolCallId) {
|
|
97
|
+
return `tool-${toolCallId}`;
|
|
98
|
+
}
|
|
99
|
+
function hashContent(s) {
|
|
100
|
+
let h = 0;
|
|
101
|
+
for (let i = 0; i < s.length; i++) h = h * 31 + s.charCodeAt(i) | 0;
|
|
102
|
+
return Math.abs(h).toString(36);
|
|
103
|
+
}
|
|
104
|
+
export {
|
|
105
|
+
uiMessagesToWire
|
|
106
|
+
};
|
|
107
|
+
//# sourceMappingURL=ag-ui-wire.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ag-ui-wire.js","sources":["../../../src/utilities/ag-ui-wire.ts"],"sourcesContent":["import type { ContentPart, MessagePart, UIMessage } from '../types'\n\ntype AGUITextInputContent = { type: 'text'; text: string }\ntype AGUIInputContent =\n | AGUITextInputContent\n | (ContentPart & { type: 'image' | 'audio' | 'video' | 'document' })\n\ntype AGUIToolCallMirror = {\n id: string\n type: 'function'\n function: { name: string; arguments: string }\n}\n\ntype AGUIToolMessage = {\n role: 'tool'\n id: string\n toolCallId: string\n content: string\n error?: string\n}\n\ntype AGUIReasoningMessage = {\n role: 'reasoning'\n id: string\n content: string\n}\n\ntype WireAnchorMessage = UIMessage & {\n content?: string | Array<AGUIInputContent>\n toolCalls?: Array<AGUIToolCallMirror>\n}\n\nexport type WireMessage =\n | WireAnchorMessage\n | AGUIToolMessage\n | AGUIReasoningMessage\n\n/**\n * Serialize TanStack `UIMessage`s into the AG-UI `RunAgentInput.messages`\n * wire shape. Each anchor (system/user/assistant) carries the canonical\n * `parts` array verbatim plus AG-UI mirror fields (`content`, `toolCalls`)\n * so AG-UI Zod parsing succeeds. Tool results and thinking parts on\n * assistant messages are additionally emitted as fan-out\n * `{role:'tool',...}` and `{role:'reasoning',...}` entries for strict\n * AG-UI server consumers.\n */\nexport function uiMessagesToWire(\n messages: Array<UIMessage>,\n): Array<WireMessage> {\n const wire: Array<WireMessage> = []\n\n for (const msg of messages) {\n // Defensive: if parts is missing (ModelMessage-shaped input), pass through as-is.\n // UIMessage always has parts; ModelMessage uses content directly.\n const parts: ReadonlyArray<MessagePart> =\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- runtime input may be ModelMessage-shaped (no `parts`); cast forces the optional-chain fallback below to remain in scope\n (msg.parts as ReadonlyArray<MessagePart> | undefined) ?? []\n\n if (msg.role === 'system') {\n wire.push({\n ...msg,\n content:\n parts.length > 0\n ? collectText(parts)\n : ((msg as { content?: string }).content ?? ''),\n })\n continue\n }\n\n if (msg.role === 'user') {\n wire.push({\n ...msg,\n content:\n parts.length > 0\n ? collectUserContent(parts)\n : ((msg as { content?: string }).content ?? ''),\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 wire.push({\n role: 'reasoning',\n id: deriveReasoningId(msg.id, part),\n content: part.content,\n })\n }\n }\n\n const text = collectText(parts)\n const toolCalls = collectToolCalls(parts)\n wire.push({\n ...msg,\n ...(text !== '' && { content: text }),\n ...(toolCalls && { toolCalls }),\n })\n\n for (const part of parts) {\n if (part.type === 'tool-result') {\n wire.push({\n role: 'tool',\n id: deriveToolMessageId(part.toolCallId),\n toolCallId: part.toolCallId,\n content:\n typeof part.content === 'string'\n ? part.content\n : JSON.stringify(part.content),\n ...(part.error !== undefined && { error: part.error }),\n })\n }\n }\n }\n\n return wire\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\nfunction collectUserContent(\n parts: ReadonlyArray<MessagePart>,\n): string | Array<AGUIInputContent> {\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<AGUIInputContent> = []\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 collectToolCalls(\n parts: ReadonlyArray<MessagePart>,\n): Array<AGUIToolCallMirror> | undefined {\n const calls: Array<AGUIToolCallMirror> = []\n for (const p of parts) {\n if (p.type === 'tool-call') {\n calls.push({\n id: p.id,\n type: 'function',\n function: { name: p.name, arguments: p.arguments },\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 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"],"names":[],"mappings":"AA8CO,SAAS,iBACd,UACoB;AACpB,QAAM,OAA2B,CAAA;AAEjC,aAAW,OAAO,UAAU;AAG1B,UAAM;AAAA;AAAA,MAEH,IAAI,SAAoD,CAAA;AAAA;AAE3D,QAAI,IAAI,SAAS,UAAU;AACzB,WAAK,KAAK;AAAA,QACR,GAAG;AAAA,QACH,SACE,MAAM,SAAS,IACX,YAAY,KAAK,IACf,IAA6B,WAAW;AAAA,MAAA,CACjD;AACD;AAAA,IACF;AAEA,QAAI,IAAI,SAAS,QAAQ;AACvB,WAAK,KAAK;AAAA,QACR,GAAG;AAAA,QACH,SACE,MAAM,SAAS,IACX,mBAAmB,KAAK,IACtB,IAA6B,WAAW;AAAA,MAAA,CACjD;AACD;AAAA,IACF;AAGA,eAAW,QAAQ,OAAO;AACxB,UAAI,KAAK,SAAS,YAAY;AAC5B,aAAK,KAAK;AAAA,UACR,MAAM;AAAA,UACN,IAAI,kBAAkB,IAAI,IAAI,IAAI;AAAA,UAClC,SAAS,KAAK;AAAA,QAAA,CACf;AAAA,MACH;AAAA,IACF;AAEA,UAAM,OAAO,YAAY,KAAK;AAC9B,UAAM,YAAY,iBAAiB,KAAK;AACxC,SAAK,KAAK;AAAA,MACR,GAAG;AAAA,MACH,GAAI,SAAS,MAAM,EAAE,SAAS,KAAA;AAAA,MAC9B,GAAI,aAAa,EAAE,UAAA;AAAA,IAAU,CAC9B;AAED,eAAW,QAAQ,OAAO;AACxB,UAAI,KAAK,SAAS,eAAe;AAC/B,aAAK,KAAK;AAAA,UACR,MAAM;AAAA,UACN,IAAI,oBAAoB,KAAK,UAAU;AAAA,UACvC,YAAY,KAAK;AAAA,UACjB,SACE,OAAO,KAAK,YAAY,WACpB,KAAK,UACL,KAAK,UAAU,KAAK,OAAO;AAAA,UACjC,GAAI,KAAK,UAAU,UAAa,EAAE,OAAO,KAAK,MAAA;AAAA,QAAM,CACrD;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEA,SAAS,YAAY,OAA2C;AAW9D,QAAM,MAAqB,CAAA;AAC3B,aAAW,KAAK,OAAO;AACrB,QAAI,EAAE,SAAS,QAAQ;AACrB,UAAI,KAAK,EAAE,OAAO;AAAA,IACpB,WACE,EAAE,SAAS,uBACX,EAAE,WAAW,cACb,EAAE,QAAQ,IACV;AACA,UAAI,KAAK,EAAE,GAAG;AAAA,IAChB;AAAA,EACF;AACA,SAAO,IAAI,KAAK,EAAE;AACpB;AAEA,SAAS,mBACP,OACkC;AAClC,QAAM,gBAAgB,MAAM;AAAA,IAC1B,CAAC,MACC,EAAE,SAAS,WACX,EAAE,SAAS,WACX,EAAE,SAAS,WACX,EAAE,SAAS;AAAA,EAAA;AAEf,MAAI,CAAC,eAAe;AAClB,WAAO,YAAY,KAAK;AAAA,EAC1B;AACA,QAAM,MAA+B,CAAA;AACrC,aAAW,KAAK,OAAO;AACrB,QAAI,EAAE,SAAS,QAAQ;AACrB,UAAI,KAAK,EAAE,MAAM,QAAQ,MAAM,EAAE,SAAS;AAAA,IAC5C,WACE,EAAE,SAAS,WACX,EAAE,SAAS,WACX,EAAE,SAAS,WACX,EAAE,SAAS,YACX;AACA,UAAI,KAAK,CAAC;AAAA,IACZ;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,iBACP,OACuC;AACvC,QAAM,QAAmC,CAAA;AACzC,aAAW,KAAK,OAAO;AACrB,QAAI,EAAE,SAAS,aAAa;AAC1B,YAAM,KAAK;AAAA,QACT,IAAI,EAAE;AAAA,QACN,MAAM;AAAA,QACN,UAAU,EAAE,MAAM,EAAE,MAAM,WAAW,EAAE,UAAA;AAAA,MAAU,CAClD;AAAA,IACH;AAAA,EACF;AACA,SAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;AAEA,SAAS,kBAAkB,WAAmB,MAA2B;AACvE,SAAO,GAAG,SAAS,cAAe,KAAyB,MAAM,YAAa,KAA6B,OAAO,CAAC;AACrH;AAEA,SAAS,oBAAoB,YAA4B;AACvD,SAAO,QAAQ,UAAU;AAC3B;AAEA,SAAS,YAAY,GAAmB;AAItC,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,IAAK,KAAK,IAAI,KAAK,EAAE,WAAW,CAAC,IAAK;AACpE,SAAO,KAAK,IAAI,CAAC,EAAE,SAAS,EAAE;AAChC;"}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { Context as AGUIContext } from '@ag-ui/core';
|
|
2
|
+
import { JSONSchema, ModelMessage, SchemaInput, Tool, UIMessage } from '../types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Parse and validate an HTTP request body as an AG-UI `RunAgentInput`.
|
|
5
|
+
*
|
|
6
|
+
* Returns a spread-friendly object whose `messages` field is suitable for
|
|
7
|
+
* passing directly to `chat({ messages })`. The existing
|
|
8
|
+
* `convertMessagesToModelMessages` handles AG-UI fan-out dedup and
|
|
9
|
+
* reasoning/activity/developer-role normalization internally.
|
|
10
|
+
*
|
|
11
|
+
* @throws An error with a migration-pointing message when the body does
|
|
12
|
+
* not conform to AG-UI 0.0.52 `RunAgentInputSchema`. Surface this as a
|
|
13
|
+
* 400 Bad Request to the client.
|
|
14
|
+
*/
|
|
15
|
+
export declare function chatParamsFromRequestBody(body: unknown): Promise<{
|
|
16
|
+
messages: Array<UIMessage | ModelMessage>;
|
|
17
|
+
threadId: string;
|
|
18
|
+
runId: string;
|
|
19
|
+
parentRunId?: string;
|
|
20
|
+
tools: Array<{
|
|
21
|
+
name: string;
|
|
22
|
+
description: string;
|
|
23
|
+
parameters: JSONSchema;
|
|
24
|
+
}>;
|
|
25
|
+
forwardedProps: Record<string, unknown>;
|
|
26
|
+
state: unknown;
|
|
27
|
+
/**
|
|
28
|
+
* @deprecated Use `aguiContext` instead. This alias will be removed in a
|
|
29
|
+
* future release.
|
|
30
|
+
*/
|
|
31
|
+
context: Array<AGUIContext>;
|
|
32
|
+
aguiContext: Array<AGUIContext>;
|
|
33
|
+
}>;
|
|
34
|
+
/**
|
|
35
|
+
* Read an HTTP `Request`, parse its JSON body, and validate it as an
|
|
36
|
+
* AG-UI `RunAgentInput` — collapsing the standard `req.json()` +
|
|
37
|
+
* `chatParamsFromRequestBody(...)` pair into a single call.
|
|
38
|
+
*
|
|
39
|
+
* On a malformed body or invalid AG-UI shape, this **throws a
|
|
40
|
+
* `Response`** with status 400 and a migration-pointing message in the
|
|
41
|
+
* body. Frameworks that natively handle thrown `Response` objects
|
|
42
|
+
* (TanStack Start, SolidStart, Remix, React Router 7) will return the
|
|
43
|
+
* 400 to the client automatically, so the handler reduces to:
|
|
44
|
+
*
|
|
45
|
+
* ```ts
|
|
46
|
+
* export async function POST(req: Request) {
|
|
47
|
+
* const params = await chatParamsFromRequest(req)
|
|
48
|
+
* // ...use params
|
|
49
|
+
* }
|
|
50
|
+
* ```
|
|
51
|
+
*
|
|
52
|
+
* In frameworks that do not auto-handle thrown `Response` objects
|
|
53
|
+
* (Next.js Route Handlers, SvelteKit, Hono, raw Node), wrap the call
|
|
54
|
+
* with try/catch and return the caught Response yourself, or use
|
|
55
|
+
* `chatParamsFromRequestBody` directly with your own JSON-parsing.
|
|
56
|
+
*
|
|
57
|
+
* @throws {Response} 400 on malformed JSON or invalid AG-UI shape.
|
|
58
|
+
*/
|
|
59
|
+
export declare function chatParamsFromRequest(req: Request): Promise<Awaited<ReturnType<typeof chatParamsFromRequestBody>>>;
|
|
60
|
+
/**
|
|
61
|
+
* Merge a server-side tool array with the AG-UI client-declared tools
|
|
62
|
+
* received in the request body.
|
|
63
|
+
*
|
|
64
|
+
* Rules:
|
|
65
|
+
* - Server tools win on name collision. The client's declaration is
|
|
66
|
+
* ignored if the server already has a tool with that name. The client's
|
|
67
|
+
* UI-side handler still fires when the streamed tool-result event comes
|
|
68
|
+
* through (see `chat-client.ts` `onToolCall`), giving the
|
|
69
|
+
* "after server execution the client also handles" semantic for free.
|
|
70
|
+
* - Client-only tools (name not in `serverTools`) become no-execute
|
|
71
|
+
* entries: the runtime's existing `ClientToolRequest` path handles
|
|
72
|
+
* them — server emits a tool-call request, client executes via its
|
|
73
|
+
* registered handler, client posts back the result.
|
|
74
|
+
*
|
|
75
|
+
* @param serverTools - The server's tool array (e.g. from
|
|
76
|
+
* `[myToolDef.server(...)]`). Pass directly to `chat({ tools })`.
|
|
77
|
+
* @param clientTools - The `tools` array received from
|
|
78
|
+
* `chatParamsFromRequest(...)` / `chatParamsFromRequestBody(...)`.
|
|
79
|
+
* @returns A merged array suitable for `chat({ tools })`.
|
|
80
|
+
*/
|
|
81
|
+
export declare function mergeAgentTools<TContext = unknown>(serverTools: ReadonlyArray<Tool<SchemaInput, SchemaInput, string, TContext>>, clientTools: ReadonlyArray<{
|
|
82
|
+
name: string;
|
|
83
|
+
description: string;
|
|
84
|
+
parameters: JSONSchema;
|
|
85
|
+
}>): Array<Tool<SchemaInput, SchemaInput, string, TContext>>;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { RunAgentInputSchema, AGUIError } from "@ag-ui/core";
|
|
2
|
+
const KNOWN_PART_TYPES = /* @__PURE__ */ new Set([
|
|
3
|
+
"text",
|
|
4
|
+
"image",
|
|
5
|
+
"audio",
|
|
6
|
+
"video",
|
|
7
|
+
"document",
|
|
8
|
+
"tool-call",
|
|
9
|
+
"tool-result",
|
|
10
|
+
"thinking"
|
|
11
|
+
]);
|
|
12
|
+
function isValidParts(value) {
|
|
13
|
+
if (!Array.isArray(value)) return false;
|
|
14
|
+
for (const p of value) {
|
|
15
|
+
if (!p || typeof p !== "object") return false;
|
|
16
|
+
const type = p.type;
|
|
17
|
+
if (typeof type !== "string" || !KNOWN_PART_TYPES.has(type)) return false;
|
|
18
|
+
}
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
function chatParamsFromRequestBody(body) {
|
|
22
|
+
const parseResult = RunAgentInputSchema.safeParse(body);
|
|
23
|
+
if (!parseResult.success) {
|
|
24
|
+
return Promise.reject(
|
|
25
|
+
new AGUIError(
|
|
26
|
+
`Request body is not a valid AG-UI RunAgentInput. If you're upgrading from a previous @tanstack/ai-client release, see docs/migration/ag-ui-compliance.md. Validation errors: ${parseResult.error.message}`
|
|
27
|
+
)
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
const parsed = parseResult.data;
|
|
31
|
+
const aguiContext = parsed.context;
|
|
32
|
+
const rawMessages = body.messages ?? [];
|
|
33
|
+
const messages = parsed.messages.map((m, i) => {
|
|
34
|
+
const raw = rawMessages[i];
|
|
35
|
+
if (raw && typeof raw === "object" && "parts" in raw && isValidParts(raw.parts)) {
|
|
36
|
+
return { ...m, parts: raw.parts };
|
|
37
|
+
}
|
|
38
|
+
return m;
|
|
39
|
+
});
|
|
40
|
+
return Promise.resolve({
|
|
41
|
+
messages,
|
|
42
|
+
threadId: parsed.threadId,
|
|
43
|
+
runId: parsed.runId,
|
|
44
|
+
parentRunId: parsed.parentRunId,
|
|
45
|
+
tools: parsed.tools,
|
|
46
|
+
forwardedProps: parsed.forwardedProps ?? {},
|
|
47
|
+
state: parsed.state,
|
|
48
|
+
context: aguiContext,
|
|
49
|
+
aguiContext
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
async function chatParamsFromRequest(req) {
|
|
53
|
+
let body;
|
|
54
|
+
try {
|
|
55
|
+
body = await req.json();
|
|
56
|
+
} catch (cause) {
|
|
57
|
+
const res = new Response(
|
|
58
|
+
"Invalid AG-UI request body. See docs/migration/ag-ui-compliance.md.",
|
|
59
|
+
{ status: 400 }
|
|
60
|
+
);
|
|
61
|
+
res.cause = cause;
|
|
62
|
+
throw res;
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
return await chatParamsFromRequestBody(body);
|
|
66
|
+
} catch (cause) {
|
|
67
|
+
const res = new Response(
|
|
68
|
+
"Invalid AG-UI request body. See docs/migration/ag-ui-compliance.md.",
|
|
69
|
+
{ status: 400 }
|
|
70
|
+
);
|
|
71
|
+
res.cause = cause;
|
|
72
|
+
throw res;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function mergeAgentTools(serverTools, clientTools) {
|
|
76
|
+
const seen = new Set(serverTools.map((t) => t.name));
|
|
77
|
+
const merged = [
|
|
78
|
+
...serverTools
|
|
79
|
+
];
|
|
80
|
+
for (const ct of clientTools) {
|
|
81
|
+
if (seen.has(ct.name)) {
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
seen.add(ct.name);
|
|
85
|
+
merged.push({
|
|
86
|
+
name: ct.name,
|
|
87
|
+
description: ct.description,
|
|
88
|
+
inputSchema: ct.parameters
|
|
89
|
+
// No `execute` — runtime treats this as a client-side tool and
|
|
90
|
+
// emits ClientToolRequest events.
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
return merged;
|
|
94
|
+
}
|
|
95
|
+
export {
|
|
96
|
+
chatParamsFromRequest,
|
|
97
|
+
chatParamsFromRequestBody,
|
|
98
|
+
mergeAgentTools
|
|
99
|
+
};
|
|
100
|
+
//# sourceMappingURL=chat-params.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat-params.js","sources":["../../../src/utilities/chat-params.ts"],"sourcesContent":["import { AGUIError, RunAgentInputSchema } from '@ag-ui/core'\nimport type { Context as AGUIContext } from '@ag-ui/core'\nimport type {\n JSONSchema,\n ModelMessage,\n SchemaInput,\n Tool,\n UIMessage,\n} from '../types'\n\nconst KNOWN_PART_TYPES = new Set([\n 'text',\n 'image',\n 'audio',\n 'video',\n 'document',\n 'tool-call',\n 'tool-result',\n 'thinking',\n])\n\nfunction isValidParts(value: unknown): value is Array<{ type: string }> {\n if (!Array.isArray(value)) return false\n for (const p of value) {\n if (!p || typeof p !== 'object') return false\n const type = (p as { type?: unknown }).type\n if (typeof type !== 'string' || !KNOWN_PART_TYPES.has(type)) return false\n }\n return true\n}\n\n/**\n * Parse and validate an HTTP request body as an AG-UI `RunAgentInput`.\n *\n * Returns a spread-friendly object whose `messages` field is suitable for\n * passing directly to `chat({ messages })`. The existing\n * `convertMessagesToModelMessages` handles AG-UI fan-out dedup and\n * reasoning/activity/developer-role normalization internally.\n *\n * @throws An error with a migration-pointing message when the body does\n * not conform to AG-UI 0.0.52 `RunAgentInputSchema`. Surface this as a\n * 400 Bad Request to the client.\n */\nexport function chatParamsFromRequestBody(body: unknown): Promise<{\n messages: Array<UIMessage | ModelMessage>\n threadId: string\n runId: string\n parentRunId?: string\n tools: Array<{ name: string; description: string; parameters: JSONSchema }>\n forwardedProps: Record<string, unknown>\n state: unknown\n /**\n * @deprecated Use `aguiContext` instead. This alias will be removed in a\n * future release.\n */\n context: Array<AGUIContext>\n aguiContext: Array<AGUIContext>\n}> {\n const parseResult = RunAgentInputSchema.safeParse(body)\n if (!parseResult.success) {\n return Promise.reject(\n new AGUIError(\n `Request body is not a valid AG-UI RunAgentInput. ` +\n `If you're upgrading from a previous @tanstack/ai-client release, ` +\n `see docs/migration/ag-ui-compliance.md. ` +\n `Validation errors: ${parseResult.error.message}`,\n ),\n )\n }\n\n const parsed = parseResult.data\n const aguiContext = parsed.context\n\n // AG-UI Zod uses `.strip()` so extra fields like `parts` on messages are\n // dropped during parse. We re-attach them from the original body so the\n // existing UIMessage path inside `chat()` can use them directly.\n const rawMessages =\n (body as { messages?: Array<Record<string, unknown>> }).messages ?? []\n const messages = parsed.messages.map((m, i) => {\n const raw = rawMessages[i]\n if (\n raw &&\n typeof raw === 'object' &&\n 'parts' in raw &&\n isValidParts(raw.parts)\n ) {\n return { ...m, parts: raw.parts } as UIMessage | ModelMessage\n }\n return m as ModelMessage\n })\n\n return Promise.resolve({\n messages,\n threadId: parsed.threadId,\n runId: parsed.runId,\n parentRunId: parsed.parentRunId,\n tools: parsed.tools as Array<{\n name: string\n description: string\n parameters: JSONSchema\n }>,\n forwardedProps: (parsed.forwardedProps ?? {}) as Record<string, unknown>,\n state: parsed.state,\n context: aguiContext,\n aguiContext,\n })\n}\n\n/**\n * Read an HTTP `Request`, parse its JSON body, and validate it as an\n * AG-UI `RunAgentInput` — collapsing the standard `req.json()` +\n * `chatParamsFromRequestBody(...)` pair into a single call.\n *\n * On a malformed body or invalid AG-UI shape, this **throws a\n * `Response`** with status 400 and a migration-pointing message in the\n * body. Frameworks that natively handle thrown `Response` objects\n * (TanStack Start, SolidStart, Remix, React Router 7) will return the\n * 400 to the client automatically, so the handler reduces to:\n *\n * ```ts\n * export async function POST(req: Request) {\n * const params = await chatParamsFromRequest(req)\n * // ...use params\n * }\n * ```\n *\n * In frameworks that do not auto-handle thrown `Response` objects\n * (Next.js Route Handlers, SvelteKit, Hono, raw Node), wrap the call\n * with try/catch and return the caught Response yourself, or use\n * `chatParamsFromRequestBody` directly with your own JSON-parsing.\n *\n * @throws {Response} 400 on malformed JSON or invalid AG-UI shape.\n */\nexport async function chatParamsFromRequest(\n req: Request,\n): Promise<Awaited<ReturnType<typeof chatParamsFromRequestBody>>> {\n let body: unknown\n try {\n body = await req.json()\n } catch (cause) {\n // Preserve the underlying error on the thrown Response for\n // server-side observability without leaking it to the client.\n const res = new Response(\n 'Invalid AG-UI request body. See docs/migration/ag-ui-compliance.md.',\n { status: 400 },\n )\n ;(res as { cause?: unknown }).cause = cause\n throw res\n }\n try {\n return await chatParamsFromRequestBody(body)\n } catch (cause) {\n // Generic public message — avoid echoing Zod paths (which can contain\n // user payload fragments) or internal validator strings to the client.\n // The original AGUIError is attached as `cause` so server logs can\n // surface it without exposing it to remote callers.\n const res = new Response(\n 'Invalid AG-UI request body. See docs/migration/ag-ui-compliance.md.',\n { status: 400 },\n )\n ;(res as { cause?: unknown }).cause = cause\n throw res\n }\n}\n\n/**\n * Merge a server-side tool array with the AG-UI client-declared tools\n * received in the request body.\n *\n * Rules:\n * - Server tools win on name collision. The client's declaration is\n * ignored if the server already has a tool with that name. The client's\n * UI-side handler still fires when the streamed tool-result event comes\n * through (see `chat-client.ts` `onToolCall`), giving the\n * \"after server execution the client also handles\" semantic for free.\n * - Client-only tools (name not in `serverTools`) become no-execute\n * entries: the runtime's existing `ClientToolRequest` path handles\n * them — server emits a tool-call request, client executes via its\n * registered handler, client posts back the result.\n *\n * @param serverTools - The server's tool array (e.g. from\n * `[myToolDef.server(...)]`). Pass directly to `chat({ tools })`.\n * @param clientTools - The `tools` array received from\n * `chatParamsFromRequest(...)` / `chatParamsFromRequestBody(...)`.\n * @returns A merged array suitable for `chat({ tools })`.\n */\nexport function mergeAgentTools<TContext = unknown>(\n serverTools: ReadonlyArray<Tool<SchemaInput, SchemaInput, string, TContext>>,\n clientTools: ReadonlyArray<{\n name: string\n description: string\n parameters: JSONSchema\n }>,\n): Array<Tool<SchemaInput, SchemaInput, string, TContext>> {\n const seen = new Set(serverTools.map((t) => t.name))\n const merged: Array<Tool<SchemaInput, SchemaInput, string, TContext>> = [\n ...serverTools,\n ]\n for (const ct of clientTools) {\n if (seen.has(ct.name)) {\n // Server wins on name collision.\n continue\n }\n seen.add(ct.name)\n merged.push({\n name: ct.name,\n description: ct.description,\n inputSchema: ct.parameters,\n // No `execute` — runtime treats this as a client-side tool and\n // emits ClientToolRequest events.\n } as Tool<SchemaInput, SchemaInput, string, TContext>)\n }\n return merged\n}\n"],"names":[],"mappings":";AAUA,MAAM,uCAAuB,IAAI;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,SAAS,aAAa,OAAkD;AACtE,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO;AAClC,aAAW,KAAK,OAAO;AACrB,QAAI,CAAC,KAAK,OAAO,MAAM,SAAU,QAAO;AACxC,UAAM,OAAQ,EAAyB;AACvC,QAAI,OAAO,SAAS,YAAY,CAAC,iBAAiB,IAAI,IAAI,EAAG,QAAO;AAAA,EACtE;AACA,SAAO;AACT;AAcO,SAAS,0BAA0B,MAcvC;AACD,QAAM,cAAc,oBAAoB,UAAU,IAAI;AACtD,MAAI,CAAC,YAAY,SAAS;AACxB,WAAO,QAAQ;AAAA,MACb,IAAI;AAAA,QACF,gLAGwB,YAAY,MAAM,OAAO;AAAA,MAAA;AAAA,IACnD;AAAA,EAEJ;AAEA,QAAM,SAAS,YAAY;AAC3B,QAAM,cAAc,OAAO;AAK3B,QAAM,cACH,KAAuD,YAAY,CAAA;AACtE,QAAM,WAAW,OAAO,SAAS,IAAI,CAAC,GAAG,MAAM;AAC7C,UAAM,MAAM,YAAY,CAAC;AACzB,QACE,OACA,OAAO,QAAQ,YACf,WAAW,OACX,aAAa,IAAI,KAAK,GACtB;AACA,aAAO,EAAE,GAAG,GAAG,OAAO,IAAI,MAAA;AAAA,IAC5B;AACA,WAAO;AAAA,EACT,CAAC;AAED,SAAO,QAAQ,QAAQ;AAAA,IACrB;AAAA,IACA,UAAU,OAAO;AAAA,IACjB,OAAO,OAAO;AAAA,IACd,aAAa,OAAO;AAAA,IACpB,OAAO,OAAO;AAAA,IAKd,gBAAiB,OAAO,kBAAkB,CAAA;AAAA,IAC1C,OAAO,OAAO;AAAA,IACd,SAAS;AAAA,IACT;AAAA,EAAA,CACD;AACH;AA2BA,eAAsB,sBACpB,KACgE;AAChE,MAAI;AACJ,MAAI;AACF,WAAO,MAAM,IAAI,KAAA;AAAA,EACnB,SAAS,OAAO;AAGd,UAAM,MAAM,IAAI;AAAA,MACd;AAAA,MACA,EAAE,QAAQ,IAAA;AAAA,IAAI;AAEd,QAA4B,QAAQ;AACtC,UAAM;AAAA,EACR;AACA,MAAI;AACF,WAAO,MAAM,0BAA0B,IAAI;AAAA,EAC7C,SAAS,OAAO;AAKd,UAAM,MAAM,IAAI;AAAA,MACd;AAAA,MACA,EAAE,QAAQ,IAAA;AAAA,IAAI;AAEd,QAA4B,QAAQ;AACtC,UAAM;AAAA,EACR;AACF;AAuBO,SAAS,gBACd,aACA,aAKyD;AACzD,QAAM,OAAO,IAAI,IAAI,YAAY,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC;AACnD,QAAM,SAAkE;AAAA,IACtE,GAAG;AAAA,EAAA;AAEL,aAAW,MAAM,aAAa;AAC5B,QAAI,KAAK,IAAI,GAAG,IAAI,GAAG;AAErB;AAAA,IACF;AACA,SAAK,IAAI,GAAG,IAAI;AAChB,WAAO,KAAK;AAAA,MACV,MAAM,GAAG;AAAA,MACT,aAAa,GAAG;AAAA,MAChB,aAAa,GAAG;AAAA;AAAA;AAAA,IAAA,CAGmC;AAAA,EACvD;AACA,SAAO;AACT;"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Best-effort extraction of a human-readable message from an unknown thrown
|
|
3
|
+
* value, returning `undefined` when none can be found.
|
|
4
|
+
*
|
|
5
|
+
* Used by `otelMiddleware` so error reporting stays identical across chat and
|
|
6
|
+
* media spans.
|
|
7
|
+
*/
|
|
8
|
+
export declare function errorMessage(err: unknown): string | undefined;
|
|
9
|
+
/**
|
|
10
|
+
* Best-effort extraction of an error's type name (used for the `error.type`
|
|
11
|
+
* metric attribute), falling back to `'Error'` when no name is available.
|
|
12
|
+
*/
|
|
13
|
+
export declare function errorTypeName(err: unknown): string;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
function errorMessage(err) {
|
|
2
|
+
if (err instanceof Error) return err.message;
|
|
3
|
+
if (typeof err === "string") return err;
|
|
4
|
+
if (err && typeof err === "object" && "message" in err) {
|
|
5
|
+
const m = err.message;
|
|
6
|
+
if (typeof m === "string") return m;
|
|
7
|
+
}
|
|
8
|
+
return void 0;
|
|
9
|
+
}
|
|
10
|
+
function errorTypeName(err) {
|
|
11
|
+
if (err instanceof Error) return err.name || "Error";
|
|
12
|
+
if (err && typeof err === "object" && "name" in err) {
|
|
13
|
+
const n = err.name;
|
|
14
|
+
if (typeof n === "string") return n;
|
|
15
|
+
}
|
|
16
|
+
return "Error";
|
|
17
|
+
}
|
|
18
|
+
export {
|
|
19
|
+
errorMessage,
|
|
20
|
+
errorTypeName
|
|
21
|
+
};
|
|
22
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","sources":["../../../src/utilities/errors.ts"],"sourcesContent":["/**\n * Best-effort extraction of a human-readable message from an unknown thrown\n * value, returning `undefined` when none can be found.\n *\n * Used by `otelMiddleware` so error reporting stays identical across chat and\n * media spans.\n */\nexport function errorMessage(err: unknown): string | undefined {\n if (err instanceof Error) return err.message\n if (typeof err === 'string') return err\n if (err && typeof err === 'object' && 'message' in err) {\n const m = (err as { message?: unknown }).message\n if (typeof m === 'string') return m\n }\n return undefined\n}\n\n/**\n * Best-effort extraction of an error's type name (used for the `error.type`\n * metric attribute), falling back to `'Error'` when no name is available.\n */\nexport function errorTypeName(err: unknown): string {\n if (err instanceof Error) return err.name || 'Error'\n if (err && typeof err === 'object' && 'name' in err) {\n const n = (err as { name?: unknown }).name\n if (typeof n === 'string') return n\n }\n return 'Error'\n}\n"],"names":[],"mappings":"AAOO,SAAS,aAAa,KAAkC;AAC7D,MAAI,eAAe,MAAO,QAAO,IAAI;AACrC,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,MAAI,OAAO,OAAO,QAAQ,YAAY,aAAa,KAAK;AACtD,UAAM,IAAK,IAA8B;AACzC,QAAI,OAAO,MAAM,SAAU,QAAO;AAAA,EACpC;AACA,SAAO;AACT;AAMO,SAAS,cAAc,KAAsB;AAClD,MAAI,eAAe,MAAO,QAAO,IAAI,QAAQ;AAC7C,MAAI,OAAO,OAAO,QAAQ,YAAY,UAAU,KAAK;AACnD,UAAM,IAAK,IAA2B;AACtC,QAAI,OAAO,MAAM,SAAU,QAAO;AAAA,EACpC;AACA,SAAO;AACT;"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { AudioPart, ImagePart, MediaInputMetadata, MediaPrompt, MediaPromptPart, VideoPart } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* A {@link MediaPrompt} decomposed into the views adapters consume.
|
|
4
|
+
*
|
|
5
|
+
* Adapters with native multimodal prompts (Gemini `contents`, OpenRouter
|
|
6
|
+
* chat content parts) consume `parts` to preserve interleaving; named-field
|
|
7
|
+
* providers (fal, OpenAI) consume `text` plus the typed media buckets.
|
|
8
|
+
*
|
|
9
|
+
* Prompt text is **never rewritten**: text parts are concatenated verbatim.
|
|
10
|
+
* Providers that support referencing inputs from the prompt (e.g. fal's
|
|
11
|
+
* `@Image1`, OpenAI's "image 1" prose) expect the user to write that syntax
|
|
12
|
+
* themselves — the SDK does not inject or substitute markers.
|
|
13
|
+
*/
|
|
14
|
+
export interface ResolvedMediaPrompt {
|
|
15
|
+
/**
|
|
16
|
+
* Text parts concatenated verbatim (paragraph-separated). Empty string
|
|
17
|
+
* for media-only prompts.
|
|
18
|
+
*/
|
|
19
|
+
text: string;
|
|
20
|
+
/** The prompt as ordered parts; a string prompt becomes one text part. */
|
|
21
|
+
parts: Array<MediaPromptPart>;
|
|
22
|
+
/** Image parts in prompt order. */
|
|
23
|
+
images: Array<ImagePart<MediaInputMetadata>>;
|
|
24
|
+
/** Video parts in prompt order. */
|
|
25
|
+
videos: Array<VideoPart<MediaInputMetadata>>;
|
|
26
|
+
/** Audio parts in prompt order. */
|
|
27
|
+
audios: Array<AudioPart<MediaInputMetadata>>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Decompose a {@link MediaPrompt} into flattened text and per-modality part
|
|
31
|
+
* buckets, preserving prompt order everywhere. This is the single downrev
|
|
32
|
+
* point from the canonical interleaved prompt shape to the named-field
|
|
33
|
+
* request shapes most providers expose.
|
|
34
|
+
*/
|
|
35
|
+
export declare function resolveMediaPrompt(prompt: MediaPrompt): ResolvedMediaPrompt;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
function resolveMediaPrompt(prompt) {
|
|
2
|
+
if (typeof prompt === "string") {
|
|
3
|
+
const textPart = { type: "text", content: prompt };
|
|
4
|
+
return {
|
|
5
|
+
text: prompt,
|
|
6
|
+
parts: [textPart],
|
|
7
|
+
images: [],
|
|
8
|
+
videos: [],
|
|
9
|
+
audios: []
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
const images = [];
|
|
13
|
+
const videos = [];
|
|
14
|
+
const audios = [];
|
|
15
|
+
const textSegments = [];
|
|
16
|
+
for (const part of prompt) {
|
|
17
|
+
switch (part.type) {
|
|
18
|
+
case "text":
|
|
19
|
+
if (part.content) textSegments.push(part.content);
|
|
20
|
+
break;
|
|
21
|
+
case "image":
|
|
22
|
+
images.push(part);
|
|
23
|
+
break;
|
|
24
|
+
case "video":
|
|
25
|
+
videos.push(part);
|
|
26
|
+
break;
|
|
27
|
+
case "audio":
|
|
28
|
+
audios.push(part);
|
|
29
|
+
break;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
text: textSegments.join("\n\n"),
|
|
34
|
+
parts: prompt,
|
|
35
|
+
images,
|
|
36
|
+
videos,
|
|
37
|
+
audios
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
export {
|
|
41
|
+
resolveMediaPrompt
|
|
42
|
+
};
|
|
43
|
+
//# sourceMappingURL=media-prompt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"media-prompt.js","sources":["../../../src/utilities/media-prompt.ts"],"sourcesContent":["import type {\n AudioPart,\n ImagePart,\n MediaInputMetadata,\n MediaPrompt,\n MediaPromptPart,\n TextPart,\n VideoPart,\n} from '../types'\n\n/**\n * A {@link MediaPrompt} decomposed into the views adapters consume.\n *\n * Adapters with native multimodal prompts (Gemini `contents`, OpenRouter\n * chat content parts) consume `parts` to preserve interleaving; named-field\n * providers (fal, OpenAI) consume `text` plus the typed media buckets.\n *\n * Prompt text is **never rewritten**: text parts are concatenated verbatim.\n * Providers that support referencing inputs from the prompt (e.g. fal's\n * `@Image1`, OpenAI's \"image 1\" prose) expect the user to write that syntax\n * themselves — the SDK does not inject or substitute markers.\n */\nexport interface ResolvedMediaPrompt {\n /**\n * Text parts concatenated verbatim (paragraph-separated). Empty string\n * for media-only prompts.\n */\n text: string\n /** The prompt as ordered parts; a string prompt becomes one text part. */\n parts: Array<MediaPromptPart>\n /** Image parts in prompt order. */\n images: Array<ImagePart<MediaInputMetadata>>\n /** Video parts in prompt order. */\n videos: Array<VideoPart<MediaInputMetadata>>\n /** Audio parts in prompt order. */\n audios: Array<AudioPart<MediaInputMetadata>>\n}\n\n/**\n * Decompose a {@link MediaPrompt} into flattened text and per-modality part\n * buckets, preserving prompt order everywhere. This is the single downrev\n * point from the canonical interleaved prompt shape to the named-field\n * request shapes most providers expose.\n */\nexport function resolveMediaPrompt(prompt: MediaPrompt): ResolvedMediaPrompt {\n if (typeof prompt === 'string') {\n const textPart: TextPart = { type: 'text', content: prompt }\n return {\n text: prompt,\n parts: [textPart],\n images: [],\n videos: [],\n audios: [],\n }\n }\n\n const images: Array<ImagePart<MediaInputMetadata>> = []\n const videos: Array<VideoPart<MediaInputMetadata>> = []\n const audios: Array<AudioPart<MediaInputMetadata>> = []\n const textSegments: Array<string> = []\n\n for (const part of prompt) {\n switch (part.type) {\n case 'text':\n if (part.content) textSegments.push(part.content)\n break\n case 'image':\n images.push(part)\n break\n case 'video':\n videos.push(part)\n break\n case 'audio':\n audios.push(part)\n break\n }\n }\n\n return {\n text: textSegments.join('\\n\\n'),\n parts: prompt,\n images,\n videos,\n audios,\n }\n}\n"],"names":[],"mappings":"AA4CO,SAAS,mBAAmB,QAA0C;AAC3E,MAAI,OAAO,WAAW,UAAU;AAC9B,UAAM,WAAqB,EAAE,MAAM,QAAQ,SAAS,OAAA;AACpD,WAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO,CAAC,QAAQ;AAAA,MAChB,QAAQ,CAAA;AAAA,MACR,QAAQ,CAAA;AAAA,MACR,QAAQ,CAAA;AAAA,IAAC;AAAA,EAEb;AAEA,QAAM,SAA+C,CAAA;AACrD,QAAM,SAA+C,CAAA;AACrD,QAAM,SAA+C,CAAA;AACrD,QAAM,eAA8B,CAAA;AAEpC,aAAW,QAAQ,QAAQ;AACzB,YAAQ,KAAK,MAAA;AAAA,MACX,KAAK;AACH,YAAI,KAAK,QAAS,cAAa,KAAK,KAAK,OAAO;AAChD;AAAA,MACF,KAAK;AACH,eAAO,KAAK,IAAI;AAChB;AAAA,MACF,KAAK;AACH,eAAO,KAAK,IAAI;AAChB;AAAA,MACF,KAAK;AACH,eAAO,KAAK,IAAI;AAChB;AAAA,IAAA;AAAA,EAEN;AAEA,SAAO;AAAA,IACL,MAAM,aAAa,KAAK,MAAM;AAAA,IAC9B,OAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Return the first candidate that is a finite `number`, or `undefined`.
|
|
3
|
+
*
|
|
4
|
+
* Handy for picking a value from among several possible spellings/sources where
|
|
5
|
+
* only some are populated — e.g. the provider-native sampling option names read
|
|
6
|
+
* by the OTel middleware, or the optional numeric fields on `TokenUsage`.
|
|
7
|
+
*/
|
|
8
|
+
export declare function firstNumber(...candidates: Array<unknown>): number | undefined;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
function firstNumber(...candidates) {
|
|
2
|
+
for (const candidate of candidates) {
|
|
3
|
+
if (typeof candidate === "number" && Number.isFinite(candidate)) {
|
|
4
|
+
return candidate;
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
return void 0;
|
|
8
|
+
}
|
|
9
|
+
export {
|
|
10
|
+
firstNumber
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=numbers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"numbers.js","sources":["../../../src/utilities/numbers.ts"],"sourcesContent":["/**\n * Return the first candidate that is a finite `number`, or `undefined`.\n *\n * Handy for picking a value from among several possible spellings/sources where\n * only some are populated — e.g. the provider-native sampling option names read\n * by the OTel middleware, or the optional numeric fields on `TokenUsage`.\n */\nexport function firstNumber(...candidates: Array<unknown>): number | undefined {\n for (const candidate of candidates) {\n if (typeof candidate === 'number' && Number.isFinite(candidate)) {\n return candidate\n }\n }\n return undefined\n}\n"],"names":[],"mappings":"AAOO,SAAS,eAAe,YAAgD;AAC7E,aAAW,aAAa,YAAY;AAClC,QAAI,OAAO,cAAc,YAAY,OAAO,SAAS,SAAS,GAAG;AAC/D,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Single source of truth for the provider-native key spellings that cap output
|
|
3
|
+
* tokens. Sampling options live in opaque, provider-native `modelOptions`, and
|
|
4
|
+
* every provider spells the token cap differently. Two call sites must agree on
|
|
5
|
+
* this set or they silently drift:
|
|
6
|
+
*
|
|
7
|
+
* - `activities/summarize/chat-stream-summarize.ts` — detects a caller-supplied
|
|
8
|
+
* token limit so the summarize default never overrides it.
|
|
9
|
+
* - `middlewares/otel.ts` — picks the first numeric spelling to populate the
|
|
10
|
+
* `gen_ai.request.max_tokens` attribute across providers.
|
|
11
|
+
*
|
|
12
|
+
* Keep this list in lockstep with `MAX_TOKENS_KEY_BY_ADAPTER` (the adapter →
|
|
13
|
+
* native-key map) in the summarize wrapper.
|
|
14
|
+
*/
|
|
15
|
+
export declare const MAX_TOKENS_KEYS: readonly ["max_output_tokens", "max_tokens", "max_completion_tokens", "maxOutputTokens", "maxCompletionTokens", "maxTokens"];
|
|
16
|
+
/**
|
|
17
|
+
* Ollama nests sampling under `options`; its token cap is `options.num_predict`
|
|
18
|
+
* rather than a flat key.
|
|
19
|
+
*/
|
|
20
|
+
export declare const NESTED_MAX_TOKENS_KEY: "num_predict";
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const MAX_TOKENS_KEYS = [
|
|
2
|
+
"max_output_tokens",
|
|
3
|
+
// OpenAI (Responses)
|
|
4
|
+
"max_tokens",
|
|
5
|
+
// Anthropic / Grok
|
|
6
|
+
"max_completion_tokens",
|
|
7
|
+
// Groq
|
|
8
|
+
"maxOutputTokens",
|
|
9
|
+
// Gemini
|
|
10
|
+
"maxCompletionTokens",
|
|
11
|
+
// OpenRouter
|
|
12
|
+
"maxTokens"
|
|
13
|
+
// generic / migration leftover (no adapter reads it)
|
|
14
|
+
];
|
|
15
|
+
const NESTED_MAX_TOKENS_KEY = "num_predict";
|
|
16
|
+
export {
|
|
17
|
+
MAX_TOKENS_KEYS,
|
|
18
|
+
NESTED_MAX_TOKENS_KEY
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=sampling-keys.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sampling-keys.js","sources":["../../../src/utilities/sampling-keys.ts"],"sourcesContent":["/**\n * Single source of truth for the provider-native key spellings that cap output\n * tokens. Sampling options live in opaque, provider-native `modelOptions`, and\n * every provider spells the token cap differently. Two call sites must agree on\n * this set or they silently drift:\n *\n * - `activities/summarize/chat-stream-summarize.ts` — detects a caller-supplied\n * token limit so the summarize default never overrides it.\n * - `middlewares/otel.ts` — picks the first numeric spelling to populate the\n * `gen_ai.request.max_tokens` attribute across providers.\n *\n * Keep this list in lockstep with `MAX_TOKENS_KEY_BY_ADAPTER` (the adapter →\n * native-key map) in the summarize wrapper.\n */\nexport const MAX_TOKENS_KEYS = [\n 'max_output_tokens', // OpenAI (Responses)\n 'max_tokens', // Anthropic / Grok\n 'max_completion_tokens', // Groq\n 'maxOutputTokens', // Gemini\n 'maxCompletionTokens', // OpenRouter\n 'maxTokens', // generic / migration leftover (no adapter reads it)\n] as const\n\n/**\n * Ollama nests sampling under `options`; its token cap is `options.num_predict`\n * rather than a flat key.\n */\nexport const NESTED_MAX_TOKENS_KEY = 'num_predict' as const\n"],"names":[],"mappings":"AAcO,MAAM,kBAAkB;AAAA,EAC7B;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AACF;AAMO,MAAM,wBAAwB;"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { ContentPart } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Structural check for a single `ContentPart`. A text part must carry a string
|
|
4
|
+
* `content`; every other modality must carry a `source` with `type` of
|
|
5
|
+
* `'url' | 'data'` and a string `value`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function isContentPart(value: unknown): value is ContentPart;
|
|
8
|
+
/**
|
|
9
|
+
* True iff `value` is a NON-EMPTY array whose every element is a valid
|
|
10
|
+
* `ContentPart`. Empty arrays and mixed arrays return false so they continue
|
|
11
|
+
* to be treated as ordinary (stringified) data — this keeps the auto-detection
|
|
12
|
+
* footgun narrow.
|
|
13
|
+
*/
|
|
14
|
+
export declare function isContentPartArray(value: unknown): value is Array<ContentPart>;
|
|
15
|
+
/**
|
|
16
|
+
* Normalize a tool's return value for transport:
|
|
17
|
+
* - string → unchanged
|
|
18
|
+
* - ContentPart array → unchanged (multimodal, passed through to the adapter)
|
|
19
|
+
* - anything else → `JSON.stringify`
|
|
20
|
+
*/
|
|
21
|
+
export declare function normalizeToolResult(result: unknown): string | Array<ContentPart>;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
const CONTENT_PART_TYPES = /* @__PURE__ */ new Set([
|
|
2
|
+
"text",
|
|
3
|
+
"image",
|
|
4
|
+
"audio",
|
|
5
|
+
"video",
|
|
6
|
+
"document"
|
|
7
|
+
]);
|
|
8
|
+
function isContentPart(value) {
|
|
9
|
+
if (typeof value !== "object" || value === null) return false;
|
|
10
|
+
const part = value;
|
|
11
|
+
if (typeof part.type !== "string" || !CONTENT_PART_TYPES.has(part.type)) {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
if (part.type === "text") {
|
|
15
|
+
return typeof part.content === "string";
|
|
16
|
+
}
|
|
17
|
+
const source = part.source;
|
|
18
|
+
if (typeof source !== "object" || source === null) return false;
|
|
19
|
+
const src = source;
|
|
20
|
+
if (typeof src.value !== "string") return false;
|
|
21
|
+
if (src.type === "data") return typeof src.mimeType === "string";
|
|
22
|
+
return src.type === "url";
|
|
23
|
+
}
|
|
24
|
+
function isContentPartArray(value) {
|
|
25
|
+
return Array.isArray(value) && value.length > 0 && value.every(isContentPart);
|
|
26
|
+
}
|
|
27
|
+
function normalizeToolResult(result) {
|
|
28
|
+
if (typeof result === "string") return result;
|
|
29
|
+
if (isContentPartArray(result)) return result;
|
|
30
|
+
return JSON.stringify(result);
|
|
31
|
+
}
|
|
32
|
+
export {
|
|
33
|
+
isContentPart,
|
|
34
|
+
isContentPartArray,
|
|
35
|
+
normalizeToolResult
|
|
36
|
+
};
|
|
37
|
+
//# sourceMappingURL=tool-result.js.map
|