@copilotkit/runtime 2.0.0-rc.34 → 2.0.0-rc.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -2
- package/dist/agent/{url-download.cjs → ai-sdk/url-download.cjs} +19 -75
- package/dist/agent/ai-sdk/url-download.cjs.map +1 -0
- package/dist/agent/{url-download.d.cts → ai-sdk/url-download.d.cts} +11 -8
- package/dist/agent/ai-sdk/url-download.d.cts.map +1 -0
- package/dist/agent/{url-download.d.mts → ai-sdk/url-download.d.mts} +11 -8
- package/dist/agent/ai-sdk/url-download.d.mts.map +1 -0
- package/dist/agent/{url-download.mjs → ai-sdk/url-download.mjs} +20 -74
- package/dist/agent/ai-sdk/url-download.mjs.map +1 -0
- package/dist/agent/ai-sdk.cjs +425 -0
- package/dist/agent/ai-sdk.cjs.map +1 -0
- package/dist/agent/ai-sdk.d.cts +119 -0
- package/dist/agent/ai-sdk.d.cts.map +1 -0
- package/dist/agent/ai-sdk.d.mts +119 -0
- package/dist/agent/ai-sdk.d.mts.map +1 -0
- package/dist/agent/ai-sdk.mjs +419 -0
- package/dist/agent/ai-sdk.mjs.map +1 -0
- package/dist/agent/classic-tools.cjs +185 -0
- package/dist/agent/classic-tools.cjs.map +1 -0
- package/dist/agent/classic-tools.mjs +183 -0
- package/dist/agent/classic-tools.mjs.map +1 -0
- package/dist/agent/converters/aisdk.cjs +0 -3
- package/dist/agent/converters/aisdk.mjs +1 -1
- package/dist/agent/converters/tanstack.cjs +200 -27
- package/dist/agent/converters/tanstack.cjs.map +1 -1
- package/dist/agent/converters/tanstack.d.cts +90 -6
- package/dist/agent/converters/tanstack.d.cts.map +1 -1
- package/dist/agent/converters/tanstack.d.mts +90 -6
- package/dist/agent/converters/tanstack.d.mts.map +1 -1
- package/dist/agent/converters/tanstack.mjs +200 -27
- package/dist/agent/converters/tanstack.mjs.map +1 -1
- package/dist/agent/learned-skills.cjs +15 -16
- package/dist/agent/learned-skills.cjs.map +1 -1
- package/dist/agent/learned-skills.d.cts +9 -3
- package/dist/agent/learned-skills.d.cts.map +1 -1
- package/dist/agent/learned-skills.d.mts +9 -3
- package/dist/agent/learned-skills.d.mts.map +1 -1
- package/dist/agent/learned-skills.mjs +15 -16
- package/dist/agent/learned-skills.mjs.map +1 -1
- package/dist/agent/model.cjs +42 -0
- package/dist/agent/model.cjs.map +1 -0
- package/dist/agent/model.d.cts +19 -0
- package/dist/agent/model.d.cts.map +1 -0
- package/dist/agent/model.d.mts +19 -0
- package/dist/agent/model.d.mts.map +1 -0
- package/dist/agent/model.mjs +41 -0
- package/dist/agent/model.mjs.map +1 -0
- package/dist/agent.cjs +558 -0
- package/dist/agent.cjs.map +1 -0
- package/dist/agent.d.cts +455 -0
- package/dist/agent.d.cts.map +1 -0
- package/dist/agent.d.mts +455 -0
- package/dist/agent.d.mts.map +1 -0
- package/dist/agent.mjs +551 -0
- package/dist/agent.mjs.map +1 -0
- package/dist/index.cjs +0 -17
- package/dist/index.d.cts +5 -10
- package/dist/index.d.mts +5 -10
- package/dist/index.mjs +1 -5
- package/dist/internal/learned-skills.d.cts +1 -1
- package/dist/internal/learned-skills.d.mts +1 -1
- package/dist/runtime/core/channel-manager.d.cts +1 -1
- package/dist/runtime/core/channel-manager.d.mts +1 -1
- package/dist/runtime/core/debug-event-bus.d.cts +1 -1
- package/dist/runtime/core/learning.d.cts +1 -1
- package/dist/runtime/core/package-info.cjs +1 -1
- package/dist/runtime/core/package-info.mjs +1 -1
- package/dist/runtime/core/runtime.d.cts +3 -3
- package/dist/runtime/core/runtime.d.mts +2 -2
- package/dist/runtime/generative-ui/surface-writer.d.cts +1 -1
- package/dist/runtime/index.d.cts +4 -6
- package/dist/runtime/index.d.mts +4 -6
- package/dist/runtime/intelligence-platform/client.d.cts +1 -1
- package/dist/runtime/intelligence-platform/client.d.mts +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/index.d.cts +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/index.d.mts +1 -1
- package/dist/runtime/telemetry/instance-created.cjs +1 -1
- package/dist/runtime/telemetry/instance-created.cjs.map +1 -1
- package/dist/runtime/telemetry/instance-created.mjs +1 -1
- package/dist/runtime/telemetry/instance-created.mjs.map +1 -1
- package/package.json +31 -13
- package/dist/agent/converters/index.d.mts +0 -2
- package/dist/agent/index.cjs +0 -1329
- package/dist/agent/index.cjs.map +0 -1
- package/dist/agent/index.d.cts +0 -459
- package/dist/agent/index.d.cts.map +0 -1
- package/dist/agent/index.d.mts +0 -460
- package/dist/agent/index.d.mts.map +0 -1
- package/dist/agent/index.mjs +0 -1321
- package/dist/agent/index.mjs.map +0 -1
- package/dist/agent/mcp-tool-names.cjs +0 -82
- package/dist/agent/mcp-tool-names.cjs.map +0 -1
- package/dist/agent/mcp-tool-names.mjs +0 -80
- package/dist/agent/mcp-tool-names.mjs.map +0 -1
- package/dist/agent/url-download.cjs.map +0 -1
- package/dist/agent/url-download.d.cts.map +0 -1
- package/dist/agent/url-download.d.mts.map +0 -1
- package/dist/agent/url-download.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AgentRunFinishedDetails } from "./usage.mjs";
|
|
2
|
-
import { BaseEvent, Interrupt, RunAgentInput } from "@ag-ui/client";
|
|
2
|
+
import { BaseEvent, Interrupt, ResumeEntry, RunAgentInput } from "@ag-ui/client";
|
|
3
3
|
|
|
4
4
|
//#region src/agent/converters/tanstack.d.ts
|
|
5
5
|
/**
|
|
@@ -57,15 +57,97 @@ interface TanStackInputResult {
|
|
|
57
57
|
*/
|
|
58
58
|
tools: TanStackClientTool[];
|
|
59
59
|
}
|
|
60
|
+
/**
|
|
61
|
+
* Options for {@link convertInputToTanStackAI}. Leave them out to get the
|
|
62
|
+
* conversion the `type: "tanstack"` factory uses. BuiltInAgent's classic mode
|
|
63
|
+
* sets them to get the same model input it builds for its own runs.
|
|
64
|
+
*/
|
|
65
|
+
interface TanStackInputOptions {
|
|
66
|
+
/**
|
|
67
|
+
* Add `system` messages from `input.messages` to `systemPrompts`. TanStack
|
|
68
|
+
* AI messages have no system role, so a forwarded system message is a
|
|
69
|
+
* system prompt. When `false`, system messages are dropped.
|
|
70
|
+
*
|
|
71
|
+
* @default true
|
|
72
|
+
*/
|
|
73
|
+
forwardSystemMessages?: boolean;
|
|
74
|
+
/**
|
|
75
|
+
* Add `developer` messages from `input.messages` to `systemPrompts`, the
|
|
76
|
+
* same way as {@link TanStackInputOptions.forwardSystemMessages}. When
|
|
77
|
+
* `false`, developer messages are dropped.
|
|
78
|
+
*
|
|
79
|
+
* @default true
|
|
80
|
+
*/
|
|
81
|
+
forwardDeveloperMessages?: boolean;
|
|
82
|
+
/**
|
|
83
|
+
* A system prompt that goes first in `systemPrompts`, before forwarded
|
|
84
|
+
* messages, context, and state. An empty string adds nothing.
|
|
85
|
+
*/
|
|
86
|
+
prompt?: string;
|
|
87
|
+
/**
|
|
88
|
+
* Interrupt responses to answer on this run, usually `input.resume`. Each
|
|
89
|
+
* entry addresses the interrupt tool call whose id is its `interruptId`.
|
|
90
|
+
* It is added after the converted messages as that call's tool result:
|
|
91
|
+
* `{"status":"cancelled"}` for a cancelled entry, else the entry's
|
|
92
|
+
* `payload`, else `{"status":"resolved"}`, as JSON text. An entry is
|
|
93
|
+
* skipped when `input.messages` already has a tool message for that call.
|
|
94
|
+
*/
|
|
95
|
+
resume?: ResumeEntry[];
|
|
96
|
+
/**
|
|
97
|
+
* Keep what a tool result holds besides text. When `true`, a URL part adds
|
|
98
|
+
* its URL on its own line, an inline-data part stays as a media part after
|
|
99
|
+
* the text, and a provider file handle is dropped with a warning. A result
|
|
100
|
+
* with nothing left is the empty string. When `false`, a tool result is
|
|
101
|
+
* only its text parts, joined.
|
|
102
|
+
*
|
|
103
|
+
* @default false
|
|
104
|
+
*/
|
|
105
|
+
keepToolResultMedia?: boolean;
|
|
106
|
+
/**
|
|
107
|
+
* How the system prompts and the frontend tool schemas are built.
|
|
108
|
+
*
|
|
109
|
+
* - `"factory"`: `systemPrompts` is `prompt`, then each forwarded message,
|
|
110
|
+
* then one entry per context item, then the state. Open objects in the
|
|
111
|
+
* tool schemas are closed (`additionalProperties: false`).
|
|
112
|
+
* - `"classic"`: what BuiltInAgent's classic mode sends. The first system
|
|
113
|
+
* prompt joins `prompt`, the context under `## Context from the
|
|
114
|
+
* application`, and the state under `## Application State`, with a note
|
|
115
|
+
* that the model can change the state with `AGUISendStateSnapshot` or
|
|
116
|
+
* `AGUISendStateDelta`. Each forwarded message follows as its own
|
|
117
|
+
* prompt. The tool schemas are kept as the client sent them, so A2UI
|
|
118
|
+
* components keep their open objects.
|
|
119
|
+
*
|
|
120
|
+
* @default "factory"
|
|
121
|
+
*/
|
|
122
|
+
format?: "factory" | "classic";
|
|
123
|
+
}
|
|
60
124
|
/**
|
|
61
125
|
* Converts a RunAgentInput into the format expected by TanStack AI's `chat()`.
|
|
62
126
|
*
|
|
63
127
|
* - Keeps only user/assistant/tool messages (activity, reasoning, and other roles are also excluded)
|
|
64
|
-
* -
|
|
65
|
-
*
|
|
128
|
+
* - Builds `systemPrompts` in this order: `options.prompt`, system/developer
|
|
129
|
+
* messages, context entries, then application state (see
|
|
130
|
+
* {@link TanStackInputOptions.format} for the classic layout)
|
|
66
131
|
* - Preserves tool calls on assistant messages and toolCallId on tool messages
|
|
132
|
+
* - Appends `options.resume` entries as tool results for interrupt tool calls
|
|
133
|
+
*
|
|
134
|
+
* @param input - The AG-UI run input.
|
|
135
|
+
* @param options - Leave out for the `type: "tanstack"` factory conversion.
|
|
136
|
+
* BuiltInAgent's classic mode passes its config and `input.resume` here.
|
|
137
|
+
*
|
|
138
|
+
* @example
|
|
139
|
+
* ```ts
|
|
140
|
+
* const { messages, systemPrompts, tools } = convertInputToTanStackAI(input, {
|
|
141
|
+
* prompt: "You are a helpful assistant.",
|
|
142
|
+
* forwardSystemMessages: false,
|
|
143
|
+
* forwardDeveloperMessages: false,
|
|
144
|
+
* resume: input.resume,
|
|
145
|
+
* keepToolResultMedia: true,
|
|
146
|
+
* format: "classic",
|
|
147
|
+
* });
|
|
148
|
+
* ```
|
|
67
149
|
*/
|
|
68
|
-
declare function convertInputToTanStackAI(input: RunAgentInput): TanStackInputResult;
|
|
150
|
+
declare function convertInputToTanStackAI(input: RunAgentInput, options?: TanStackInputOptions): TanStackInputResult;
|
|
69
151
|
/**
|
|
70
152
|
* Converts a TanStack AI stream into AG-UI `BaseEvent` objects.
|
|
71
153
|
*
|
|
@@ -74,10 +156,12 @@ declare function convertInputToTanStackAI(input: RunAgentInput): TanStackInputRe
|
|
|
74
156
|
* is responsible for those.
|
|
75
157
|
*
|
|
76
158
|
* `pendingInterrupts`, when provided, is filled with one AG-UI Interrupt per
|
|
77
|
-
*
|
|
159
|
+
* tool call that waits for approval (a tool declared `needsApproval: true`):
|
|
160
|
+
* from a CUSTOM "approval-requested" chunk (@tanstack/ai before 1.2) or from
|
|
161
|
+
* a RUN_FINISHED `outcome:interrupt` approval entry (1.2 and later).
|
|
78
162
|
* The caller turns a non-empty array into a RUN_FINISHED `outcome:interrupt`.
|
|
79
163
|
*/
|
|
80
164
|
declare function convertTanStackStream(stream: AsyncIterable<unknown>, abortSignal: AbortSignal, pendingInterrupts?: Interrupt[], initialState?: unknown, runFinishedDetails?: AgentRunFinishedDetails): AsyncGenerator<BaseEvent>;
|
|
81
165
|
//#endregion
|
|
82
|
-
export { TanStackChatMessage, TanStackInputResult, convertInputToTanStackAI, convertTanStackStream };
|
|
166
|
+
export { TanStackChatMessage, TanStackInputOptions, TanStackInputResult, convertInputToTanStackAI, convertTanStackStream };
|
|
83
167
|
//# sourceMappingURL=tanstack.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tanstack.d.mts","names":[],"sources":["../../../src/agent/converters/tanstack.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"tanstack.d.mts","names":[],"sources":["../../../src/agent/converters/tanstack.ts"],"mappings":";;;;;AAwFA;;;;;;;UAlCiB,mBAAA;EACf,IAAA;EAEA,OAAA;EACA,IAAA;EACA,SAAA,GAAY,KAAA;IACV,EAAA;IACA,IAAA;IACA,QAAA;MAAY,IAAA;MAAc,SAAA;IAAA;EAAA;EAE5B,UAAA;AAAA;;;;AAiXF;;;;;;;UApWiB,kBAAA;EACf,UAAA;EACA,IAAA;EACA,WAAA;EAEA,WAAA;AAAA;;;AA4eF;UAteiB,mBAAA;;EAEf,QAAA,EAAU,mBAAA;EAseG;EApeb,aAAA;EAueqB;;;;;;;EA/drB,KAAA,EAAO,kBAAA;AAAA;;;;;;UAQQ,oBAAA;EAwdC;;;;;;;EAhdhB,qBAAA;;;;;;;;EAQA,wBAAA;;;;;EAKA,MAAA;;;;;;;;;EASA,MAAA,GAAS,WAAA;;;;;;;;;;EAUT,mBAAA;;;;;;;;;;;;;;;;;EAiBA,MAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA4Qc,wBAAA,CACd,KAAA,EAAO,aAAA,EACP,OAAA,GAAS,oBAAA,GACR,mBAAA;;;;;;;;;;;;;;iBA0IoB,qBAAA,CACrB,MAAA,EAAQ,aAAA,WACR,WAAA,EAAa,WAAA,EACb,iBAAA,GAAoB,SAAA,IACpB,YAAA,YACA,kBAAA,GAAqB,uBAAA,GACpB,cAAA,CAAe,SAAA"}
|
|
@@ -5,6 +5,57 @@ import { EventType, contentToText } from "@ag-ui/client";
|
|
|
5
5
|
|
|
6
6
|
//#region src/agent/converters/tanstack.ts
|
|
7
7
|
/**
|
|
8
|
+
* Warns that a part was dropped because its source is a provider file handle
|
|
9
|
+
* (AG-UI `file` source), which is neither a URL nor inline data.
|
|
10
|
+
*/
|
|
11
|
+
function warnDroppedFileSource(what) {
|
|
12
|
+
console.warn(`[CopilotKit] Dropping a ${what} that references a provider file handle: it is not a URL or inline data, so it cannot be sent to the model here.`);
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Converts an AG-UI tool result for a TanStack AI tool message, keeping URL
|
|
16
|
+
* references and inline media.
|
|
17
|
+
*
|
|
18
|
+
* Providers hold one response per tool call, so all of a result's text is
|
|
19
|
+
* one text entry: text parts run together, and a URL part adds the URL it
|
|
20
|
+
* carries on a line of its own (the bytes are not here, and the reference is
|
|
21
|
+
* what the tool returned). A result with no inline media is that text alone.
|
|
22
|
+
* One with inline media is a list: the text part first, when there is any
|
|
23
|
+
* text, then each media part. A provider file handle cannot be sent from
|
|
24
|
+
* here, so that part is dropped with a warning. A result whose parts were all
|
|
25
|
+
* dropped is the empty string, because the call must still be answered.
|
|
26
|
+
*/
|
|
27
|
+
function convertToolResultContent(content) {
|
|
28
|
+
if (typeof content === "string") return content;
|
|
29
|
+
const segments = [];
|
|
30
|
+
const media = [];
|
|
31
|
+
let open = false;
|
|
32
|
+
for (const part of content) if (part.type === "text") {
|
|
33
|
+
if (open) segments[segments.length - 1] += part.text;
|
|
34
|
+
else segments.push(part.text);
|
|
35
|
+
open = true;
|
|
36
|
+
} else if (part.source.type === "file") warnDroppedFileSource(`${part.type} part in a tool result`);
|
|
37
|
+
else if (part.source.type === "url") {
|
|
38
|
+
segments.push(part.source.value);
|
|
39
|
+
open = false;
|
|
40
|
+
} else {
|
|
41
|
+
media.push({
|
|
42
|
+
type: part.type,
|
|
43
|
+
source: {
|
|
44
|
+
type: "data",
|
|
45
|
+
value: part.source.value,
|
|
46
|
+
mimeType: part.source.mimeType
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
open = false;
|
|
50
|
+
}
|
|
51
|
+
const text = segments.join("\n");
|
|
52
|
+
if (media.length === 0) return text;
|
|
53
|
+
return [...text.length > 0 ? [{
|
|
54
|
+
type: "text",
|
|
55
|
+
content: text
|
|
56
|
+
}] : [], ...media];
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
8
59
|
* Converts AG-UI user message content to TanStack AI format.
|
|
9
60
|
* Handles plain strings, multimodal parts (image/audio/video/document),
|
|
10
61
|
* and legacy BinaryInputContent for backward compatibility.
|
|
@@ -41,7 +92,7 @@ function convertUserContent(content) {
|
|
|
41
92
|
mimeType: source.mimeType
|
|
42
93
|
}
|
|
43
94
|
});
|
|
44
|
-
else if (source.type === "file")
|
|
95
|
+
else if (source.type === "file") warnDroppedFileSource(`${partType} part`);
|
|
45
96
|
else if (source.type === "url") parts.push({
|
|
46
97
|
type: partType,
|
|
47
98
|
source: {
|
|
@@ -116,14 +167,53 @@ function sanitizeClientToolSchema(schema) {
|
|
|
116
167
|
return node;
|
|
117
168
|
}
|
|
118
169
|
/**
|
|
170
|
+
* The system prompt of BuiltInAgent's classic mode: `prompt`, then the
|
|
171
|
+
* context, then the state, joined into one string. Empty when there is
|
|
172
|
+
* nothing to add. Any state other than `undefined`, `null`, or an empty
|
|
173
|
+
* object is included.
|
|
174
|
+
*/
|
|
175
|
+
function classicSystemPrompt(input, prompt) {
|
|
176
|
+
const parts = [];
|
|
177
|
+
if (prompt) parts.push(prompt);
|
|
178
|
+
if (input.context?.length) {
|
|
179
|
+
parts.push("\n## Context from the application\n");
|
|
180
|
+
for (const ctx of input.context) parts.push(`${ctx.description}:\n${ctx.value}\n`);
|
|
181
|
+
}
|
|
182
|
+
const isEmptyObject = typeof input.state === "object" && input.state !== null && Object.keys(input.state).length === 0;
|
|
183
|
+
if (input.state !== void 0 && input.state !== null && !isEmptyObject) parts.push(`
|
|
184
|
+
## Application State
|
|
185
|
+
This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.
|
|
186
|
+
\`\`\`json\n${JSON.stringify(input.state, null, 2)}\n\`\`\`\n`);
|
|
187
|
+
return parts.join("");
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
119
190
|
* Converts a RunAgentInput into the format expected by TanStack AI's `chat()`.
|
|
120
191
|
*
|
|
121
192
|
* - Keeps only user/assistant/tool messages (activity, reasoning, and other roles are also excluded)
|
|
122
|
-
* -
|
|
123
|
-
*
|
|
193
|
+
* - Builds `systemPrompts` in this order: `options.prompt`, system/developer
|
|
194
|
+
* messages, context entries, then application state (see
|
|
195
|
+
* {@link TanStackInputOptions.format} for the classic layout)
|
|
124
196
|
* - Preserves tool calls on assistant messages and toolCallId on tool messages
|
|
197
|
+
* - Appends `options.resume` entries as tool results for interrupt tool calls
|
|
198
|
+
*
|
|
199
|
+
* @param input - The AG-UI run input.
|
|
200
|
+
* @param options - Leave out for the `type: "tanstack"` factory conversion.
|
|
201
|
+
* BuiltInAgent's classic mode passes its config and `input.resume` here.
|
|
202
|
+
*
|
|
203
|
+
* @example
|
|
204
|
+
* ```ts
|
|
205
|
+
* const { messages, systemPrompts, tools } = convertInputToTanStackAI(input, {
|
|
206
|
+
* prompt: "You are a helpful assistant.",
|
|
207
|
+
* forwardSystemMessages: false,
|
|
208
|
+
* forwardDeveloperMessages: false,
|
|
209
|
+
* resume: input.resume,
|
|
210
|
+
* keepToolResultMedia: true,
|
|
211
|
+
* format: "classic",
|
|
212
|
+
* });
|
|
213
|
+
* ```
|
|
125
214
|
*/
|
|
126
|
-
function convertInputToTanStackAI(input) {
|
|
215
|
+
function convertInputToTanStackAI(input, options = {}) {
|
|
216
|
+
const { forwardSystemMessages = true, forwardDeveloperMessages = true, prompt, resume = [], keepToolResultMedia = false, format = "factory" } = options;
|
|
127
217
|
const chatRoles = new Set([
|
|
128
218
|
"user",
|
|
129
219
|
"assistant",
|
|
@@ -132,7 +222,7 @@ function convertInputToTanStackAI(input) {
|
|
|
132
222
|
const messages = input.messages.filter((m) => chatRoles.has(m.role)).map((m) => {
|
|
133
223
|
const msg = {
|
|
134
224
|
role: m.role,
|
|
135
|
-
content: m.role === "user" ? convertUserContent(m.content) : m.role === "tool" ? contentToText(m.content) : typeof m.content === "string" ? m.content : null
|
|
225
|
+
content: m.role === "user" ? convertUserContent(m.content) : m.role === "tool" ? keepToolResultMedia ? convertToolResultContent(m.content) : contentToText(m.content) : typeof m.content === "string" ? m.content : null
|
|
136
226
|
};
|
|
137
227
|
if (m.role === "assistant" && "toolCalls" in m && m.toolCalls) msg.toolCalls = m.toolCalls.map((tc) => ({
|
|
138
228
|
id: tc.id,
|
|
@@ -145,10 +235,30 @@ function convertInputToTanStackAI(input) {
|
|
|
145
235
|
if (m.role === "tool" && "toolCallId" in m) msg.toolCallId = m.toolCallId;
|
|
146
236
|
return msg;
|
|
147
237
|
});
|
|
238
|
+
const answeredToolCallIds = new Set(messages.flatMap((m) => m.role === "tool" && m.toolCallId ? [m.toolCallId] : []));
|
|
239
|
+
for (const entry of resume) {
|
|
240
|
+
if (answeredToolCallIds.has(entry.interruptId)) continue;
|
|
241
|
+
const value = entry.status === "cancelled" ? { status: "cancelled" } : entry.payload ?? { status: "resolved" };
|
|
242
|
+
messages.push({
|
|
243
|
+
role: "tool",
|
|
244
|
+
toolCallId: entry.interruptId,
|
|
245
|
+
content: JSON.stringify(value)
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
const forwardedPrompts = [];
|
|
249
|
+
for (const m of input.messages) if ((m.role === "system" && forwardSystemMessages || m.role === "developer" && forwardDeveloperMessages) && m.content) forwardedPrompts.push(typeof m.content === "string" ? m.content : JSON.stringify(m.content));
|
|
250
|
+
const isClassic = format === "classic";
|
|
148
251
|
const systemPrompts = [];
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
252
|
+
if (isClassic) {
|
|
253
|
+
const classicPrompt = classicSystemPrompt(input, prompt);
|
|
254
|
+
if (classicPrompt) systemPrompts.push(classicPrompt);
|
|
255
|
+
systemPrompts.push(...forwardedPrompts);
|
|
256
|
+
} else {
|
|
257
|
+
if (prompt) systemPrompts.push(prompt);
|
|
258
|
+
systemPrompts.push(...forwardedPrompts);
|
|
259
|
+
if (input.context?.length) for (const ctx of input.context) systemPrompts.push(`${ctx.description}:\n${ctx.value}`);
|
|
260
|
+
if (input.state !== void 0 && input.state !== null && typeof input.state === "object" && Object.keys(input.state).length > 0) systemPrompts.push(`Application State:\n\`\`\`json\n${JSON.stringify(input.state, null, 2)}\n\`\`\``);
|
|
261
|
+
}
|
|
152
262
|
return {
|
|
153
263
|
messages,
|
|
154
264
|
systemPrompts,
|
|
@@ -156,7 +266,7 @@ function convertInputToTanStackAI(input) {
|
|
|
156
266
|
__toolSide: "client",
|
|
157
267
|
name: t.name,
|
|
158
268
|
description: t.description,
|
|
159
|
-
inputSchema: sanitizeClientToolSchema(t.parameters)
|
|
269
|
+
inputSchema: isClassic ? t.parameters : sanitizeClientToolSchema(t.parameters)
|
|
160
270
|
}))
|
|
161
271
|
};
|
|
162
272
|
}
|
|
@@ -168,11 +278,13 @@ function convertInputToTanStackAI(input) {
|
|
|
168
278
|
* is responsible for those.
|
|
169
279
|
*
|
|
170
280
|
* `pendingInterrupts`, when provided, is filled with one AG-UI Interrupt per
|
|
171
|
-
*
|
|
281
|
+
* tool call that waits for approval (a tool declared `needsApproval: true`):
|
|
282
|
+
* from a CUSTOM "approval-requested" chunk (@tanstack/ai before 1.2) or from
|
|
283
|
+
* a RUN_FINISHED `outcome:interrupt` approval entry (1.2 and later).
|
|
172
284
|
* The caller turns a non-empty array into a RUN_FINISHED `outcome:interrupt`.
|
|
173
285
|
*/
|
|
174
286
|
async function* convertTanStackStream(stream, abortSignal, pendingInterrupts, initialState, runFinishedDetails) {
|
|
175
|
-
|
|
287
|
+
let messageId = randomUUID();
|
|
176
288
|
const toolNamesById = /* @__PURE__ */ new Map();
|
|
177
289
|
let reasoningRunOpen = false;
|
|
178
290
|
let reasoningMessageOpen = false;
|
|
@@ -201,24 +313,19 @@ async function* convertTanStackStream(stream, abortSignal, pendingInterrupts, in
|
|
|
201
313
|
const raw = chunk;
|
|
202
314
|
const type = raw.type;
|
|
203
315
|
if (type === "CUSTOM" && raw.name === "approval-requested") {
|
|
204
|
-
const value = raw.value
|
|
205
|
-
|
|
206
|
-
if (toolCallId) pendingInterrupts?.push({
|
|
207
|
-
id: toolCallId,
|
|
208
|
-
toolCallId,
|
|
209
|
-
reason: "tool_approval",
|
|
210
|
-
message: value.toolName ? `Approve "${value.toolName}"?` : void 0,
|
|
211
|
-
...value.toolName ? { metadata: { toolName: value.toolName } } : {}
|
|
212
|
-
});
|
|
316
|
+
const value = isRecord(raw.value) ? raw.value : {};
|
|
317
|
+
addApprovalInterrupt(pendingInterrupts, getNonEmptyString(value.toolCallId), getNonEmptyString(value.toolName));
|
|
213
318
|
continue;
|
|
214
319
|
}
|
|
215
320
|
if (type === "RUN_FINISHED") {
|
|
216
321
|
collectTanStackRunFinishedDetails(raw, runFinishedDetails);
|
|
322
|
+
collectTanStackApprovalInterrupts(raw, pendingInterrupts);
|
|
217
323
|
continue;
|
|
218
324
|
}
|
|
219
325
|
if (type === "RUN_STARTED") continue;
|
|
220
326
|
if (type === "RUN_ERROR") throw new Error(typeof raw.message === "string" ? raw.message : "TanStack AI run error");
|
|
221
|
-
if (type === "
|
|
327
|
+
if (type === "TEXT_MESSAGE_START") messageId = randomUUID();
|
|
328
|
+
else if (type === "TEXT_MESSAGE_CONTENT" && raw.delta != null) {
|
|
222
329
|
yield* closeReasoningIfOpen();
|
|
223
330
|
yield {
|
|
224
331
|
type: EventType.TEXT_MESSAGE_CHUNK,
|
|
@@ -333,17 +440,63 @@ async function* convertTanStackStream(stream, abortSignal, pendingInterrupts, in
|
|
|
333
440
|
}
|
|
334
441
|
yield* closeReasoningIfOpen();
|
|
335
442
|
}
|
|
336
|
-
/**
|
|
443
|
+
/**
|
|
444
|
+
* Adds one AG-UI approval interrupt for a `needsApproval` tool call, keyed by
|
|
445
|
+
* the tool call id. A call that already has an interrupt is skipped, so a
|
|
446
|
+
* stream that reports the same approval twice (CUSTOM chunk and RUN_FINISHED
|
|
447
|
+
* outcome) produces one interrupt.
|
|
448
|
+
*/
|
|
449
|
+
function addApprovalInterrupt(pendingInterrupts, toolCallId, toolName) {
|
|
450
|
+
if (!pendingInterrupts || !toolCallId) return;
|
|
451
|
+
if (pendingInterrupts.some((entry) => entry.toolCallId === toolCallId)) return;
|
|
452
|
+
pendingInterrupts.push({
|
|
453
|
+
id: toolCallId,
|
|
454
|
+
toolCallId,
|
|
455
|
+
reason: "tool_approval",
|
|
456
|
+
message: toolName ? `Approve "${toolName}"?` : void 0,
|
|
457
|
+
...toolName ? { metadata: { toolName } } : {}
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Reads the approval interrupts of a @tanstack/ai 1.2+ RUN_FINISHED
|
|
462
|
+
* `outcome: { type: "interrupt" }`. Only `kind: "approval"` entries are mapped.
|
|
463
|
+
* Client tool interrupts (a tool without `execute`) are already handled by
|
|
464
|
+
* the frontend tool flow and by `withClassicToolRules`.
|
|
465
|
+
*/
|
|
466
|
+
function collectTanStackApprovalInterrupts(event, pendingInterrupts) {
|
|
467
|
+
const outcome = event.outcome;
|
|
468
|
+
if (!isRecord(outcome) || outcome.type !== "interrupt") return;
|
|
469
|
+
if (!Array.isArray(outcome.interrupts)) return;
|
|
470
|
+
for (const interrupt of outcome.interrupts) {
|
|
471
|
+
if (!isRecord(interrupt) || !isRecord(interrupt.metadata)) continue;
|
|
472
|
+
if (interrupt.metadata.kind !== "approval") continue;
|
|
473
|
+
addApprovalInterrupt(pendingInterrupts, getNonEmptyString(interrupt.toolCallId), getNonEmptyString(interrupt.metadata.toolName));
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Normalizes legacy and standard TanStack usage into AG-UI token usage.
|
|
478
|
+
*
|
|
479
|
+
* @tanstack/ai 1.2+ puts the model, the finish reason, and the provider under
|
|
480
|
+
* `metadata.tanstack` (internal to TanStack). Older versions put the model and
|
|
481
|
+
* the finish reason at the top level. Both are read, the top level first, and
|
|
482
|
+
* `metadata.tanstack` is not forwarded as AG-UI metadata.
|
|
483
|
+
*/
|
|
337
484
|
function collectTanStackRunFinishedDetails(event, details) {
|
|
338
485
|
if (!details) return;
|
|
486
|
+
const { metadata, tanstack } = splitTanStackMetadata(event.metadata);
|
|
487
|
+
const source = isRecord(tanstack.source) ? tanstack.source : {};
|
|
339
488
|
const fallbackIdentity = {
|
|
340
|
-
provider: getNonEmptyString(event.provider),
|
|
341
|
-
model: getNonEmptyString(event.model)
|
|
489
|
+
provider: getNonEmptyString(event.provider) ?? getNonEmptyString(source.provider),
|
|
490
|
+
model: getNonEmptyString(event.model) ?? getNonEmptyString(tanstack.model) ?? getNonEmptyString(source.model)
|
|
342
491
|
};
|
|
343
|
-
collectStandardRunFinishedDetails(
|
|
344
|
-
|
|
492
|
+
collectStandardRunFinishedDetails({
|
|
493
|
+
...event,
|
|
494
|
+
metadata
|
|
495
|
+
}, details, fallbackIdentity);
|
|
496
|
+
const finishReason = typeof event.finishReason === "string" ? event.finishReason : tanstack.finishReason;
|
|
497
|
+
if (typeof finishReason === "string") details.metadata = {
|
|
345
498
|
...details.metadata,
|
|
346
|
-
finishReason
|
|
499
|
+
finishReason
|
|
347
500
|
};
|
|
348
501
|
const usage = event.usage;
|
|
349
502
|
if (Array.isArray(usage)) return;
|
|
@@ -359,6 +512,26 @@ function collectTanStackRunFinishedDetails(event, details) {
|
|
|
359
512
|
cachedInputTokens: getTokenCount(promptDetails.cachedTokens)
|
|
360
513
|
}]);
|
|
361
514
|
}
|
|
515
|
+
/**
|
|
516
|
+
* Splits RUN_FINISHED metadata into the AG-UI metadata to forward and
|
|
517
|
+
* TanStack's internal `metadata.tanstack` object. When `tanstack` was the only
|
|
518
|
+
* key, nothing is left to forward.
|
|
519
|
+
*/
|
|
520
|
+
function splitTanStackMetadata(value) {
|
|
521
|
+
if (!isRecord(value)) return {
|
|
522
|
+
metadata: void 0,
|
|
523
|
+
tanstack: {}
|
|
524
|
+
};
|
|
525
|
+
if (!("tanstack" in value)) return {
|
|
526
|
+
metadata: value,
|
|
527
|
+
tanstack: {}
|
|
528
|
+
};
|
|
529
|
+
const { tanstack, ...metadata } = value;
|
|
530
|
+
return {
|
|
531
|
+
metadata: Object.keys(metadata).length > 0 ? metadata : void 0,
|
|
532
|
+
tanstack: isRecord(tanstack) ? tanstack : {}
|
|
533
|
+
};
|
|
534
|
+
}
|
|
362
535
|
function safeParse(value) {
|
|
363
536
|
try {
|
|
364
537
|
return JSON.parse(value);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tanstack.mjs","names":[],"sources":["../../../src/agent/converters/tanstack.ts"],"sourcesContent":["import type {\n BaseEvent,\n Interrupt,\n RunAgentInput,\n Message,\n TextMessageChunkEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolCallResultEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n ReasoningStartEvent,\n ReasoningMessageStartEvent,\n ReasoningMessageContentEvent,\n ReasoningMessageEndEvent,\n ReasoningEndEvent,\n} from \"@ag-ui/client\";\nimport { contentToText, EventType } from \"@ag-ui/client\";\nimport { randomUUID } from \"@copilotkit/shared\";\nimport { createStateEventNormalizer } from \"../state-delta\";\nimport {\n aggregateRunUsage,\n collectStandardRunFinishedDetails,\n getNonEmptyString,\n getTokenCount,\n isRecord,\n} from \"./usage\";\nimport type { AgentRunFinishedDetails } from \"./usage\";\n\ntype ContentPartSource =\n | { type: \"data\"; value: string; mimeType: string }\n | { type: \"url\"; value: string; mimeType?: string };\n\n/**\n * A TanStack AI content part (text, image, audio, video, or document).\n */\nexport type TanStackContentPart =\n | { type: \"text\"; content: string }\n | { type: \"image\"; source: ContentPartSource }\n | { type: \"audio\"; source: ContentPartSource }\n | { type: \"video\"; source: ContentPartSource }\n | { type: \"document\"; source: ContentPartSource };\n\n/**\n * Message format expected by TanStack AI's `chat()`.\n *\n * Content is typed as `any[]` for the multimodal case so messages are directly\n * passable to any adapter without casts — different adapters constrain which\n * modalities they accept (e.g. OpenAI only allows text + image).\n * Use `TanStackContentPart` to inspect individual parts if needed.\n */\nexport interface TanStackChatMessage {\n role: \"user\" | \"assistant\" | \"tool\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n content: string | null | any[];\n name?: string;\n toolCalls?: Array<{\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n }>;\n toolCallId?: string;\n}\n\n/**\n * A TanStack AI client-side tool, derived from a frontend-provided AG-UI tool.\n *\n * Shaped to match `@tanstack/ai`'s `ClientTool` (`__toolSide: \"client\"`, no\n * `execute`): the model may CALL it, but TanStack does not run it — it pauses\n * the run and hands the call back to the AG-UI client (the CopilotKit frontend\n * / bot) to execute, mirroring CopilotKit's client-tool round-trip. `chat()`\n * accepts a JSON Schema directly as `inputSchema`, so the AG-UI tool's\n * `parameters` pass through unchanged.\n */\nexport interface TanStackClientTool {\n __toolSide: \"client\";\n name: string;\n description: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputSchema: any;\n}\n\n/**\n * Result of converting RunAgentInput to TanStack AI format.\n */\nexport interface TanStackInputResult {\n /** Chat messages (only user/assistant/tool roles; all others excluded) */\n messages: TanStackChatMessage[];\n /** System prompts extracted from system/developer messages, context, and state */\n systemPrompts: string[];\n /**\n * Client-side tools derived from `input.tools` (the frontend-provided tools\n * the CopilotKit client forwards on every run). Pass these into `chat()`\n * alongside any server/provider tools so the model can call the frontend's\n * generative-UI and human-in-the-loop tools; TanStack pauses the run on a\n * client-tool call and the client executes it.\n */\n tools: TanStackClientTool[];\n}\n\n/**\n * Converts AG-UI user message content to TanStack AI format.\n * Handles plain strings, multimodal parts (image/audio/video/document),\n * and legacy BinaryInputContent for backward compatibility.\n */\nfunction convertUserContent(\n content: unknown,\n): string | null | TanStackContentPart[] {\n if (!content) return null;\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return null;\n if (content.length === 0) return \"\";\n\n const parts: TanStackContentPart[] = [];\n\n for (const part of content) {\n if (!part || typeof part !== \"object\" || !(\"type\" in part)) continue;\n\n switch ((part as { type: string }).type) {\n case \"text\": {\n const text = (part as { text?: string }).text;\n if (text != null) parts.push({ type: \"text\", content: text });\n break;\n }\n\n case \"image\":\n case \"audio\":\n case \"video\":\n case \"document\": {\n const source = (part as { source?: any }).source;\n if (!source) break;\n const partType = (part as { type: string }).type as\n | \"image\"\n | \"audio\"\n | \"video\"\n | \"document\";\n if (source.type === \"data\") {\n parts.push({\n type: partType,\n source: {\n type: \"data\",\n value: source.value,\n mimeType: source.mimeType,\n },\n });\n } else if (source.type === \"file\") {\n // AG-UI 1.0 provider file handle: not a URL or inline data.\n console.warn(\n `[CopilotKit] Dropping a ${partType} part that references a provider file handle: it is not a URL or inline data, so it cannot be sent to the model here.`,\n );\n } else if (source.type === \"url\") {\n parts.push({\n type: partType,\n source: {\n type: \"url\",\n value: source.value,\n ...(source.mimeType ? { mimeType: source.mimeType } : {}),\n },\n });\n }\n break;\n }\n\n // Legacy BinaryInputContent backward compatibility\n case \"binary\": {\n const legacy = part as {\n mimeType?: string;\n data?: string;\n url?: string;\n };\n const mimeType = legacy.mimeType ?? \"application/octet-stream\";\n const isImage = mimeType.startsWith(\"image/\");\n\n if (legacy.data) {\n const partType = isImage ? \"image\" : \"document\";\n parts.push({\n type: partType,\n source: { type: \"data\", value: legacy.data, mimeType },\n });\n } else if (legacy.url) {\n const partType = isImage ? \"image\" : \"document\";\n parts.push({\n type: partType,\n source: { type: \"url\", value: legacy.url, mimeType },\n });\n }\n break;\n }\n }\n }\n\n return parts.length > 0 ? parts : \"\";\n}\n\n/**\n * Recursively normalizes a frontend tool's JSON Schema so OpenAI accepts it as\n * a function-tool schema.\n *\n * Frontend tools are often authored with permissive Zod (`z.any()`,\n * `z.record(...)`, `.loose()`), which serialize to open objects —\n * `additionalProperties: {}` (an empty sub-schema) or `additionalProperties:\n * true`. OpenAI rejects both: strict mode requires `additionalProperties:\n * false`, and an empty `{}` sub-schema fails base validation (\"schema must\n * have a 'type' key\"). The classic (Vercel AI SDK) path sanitized these\n * implicitly via a Zod round-trip; the TanStack path forwards the raw schema,\n * so we close open objects here to match. (Models can't supply free-form extra\n * keys either way — same as the classic path.)\n */\nfunction sanitizeClientToolSchema(schema: unknown): unknown {\n if (Array.isArray(schema)) {\n return schema.map(sanitizeClientToolSchema);\n }\n if (!schema || typeof schema !== \"object\") {\n return schema;\n }\n const node: Record<string, unknown> = {\n ...(schema as Record<string, unknown>),\n };\n\n // Any `additionalProperties` (empty `{}`, `true`, or a sub-schema) becomes\n // `false` — the only form OpenAI accepts for strict function tools.\n if (\"additionalProperties\" in node) {\n node.additionalProperties = false;\n }\n\n if (node.properties && typeof node.properties === \"object\") {\n const props: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(\n node.properties as Record<string, unknown>,\n )) {\n props[key] = sanitizeClientToolSchema(value);\n }\n node.properties = props;\n }\n\n if (\"items\" in node) {\n node.items = sanitizeClientToolSchema(node.items);\n }\n\n for (const combinator of [\"anyOf\", \"allOf\", \"oneOf\"] as const) {\n if (Array.isArray(node[combinator])) {\n node[combinator] = (node[combinator] as unknown[]).map(\n sanitizeClientToolSchema,\n );\n }\n }\n\n return node;\n}\n\n/**\n * Converts a RunAgentInput into the format expected by TanStack AI's `chat()`.\n *\n * - Keeps only user/assistant/tool messages (activity, reasoning, and other roles are also excluded)\n * - Extracts system/developer messages into `systemPrompts`\n * - Appends context entries and application state to `systemPrompts`\n * - Preserves tool calls on assistant messages and toolCallId on tool messages\n */\nexport function convertInputToTanStackAI(\n input: RunAgentInput,\n): TanStackInputResult {\n // Allowlist: only pass user/assistant/tool messages to TanStack.\n // Other roles (system, developer, activity, reasoning) are either\n // extracted into systemPrompts or not applicable.\n const chatRoles = new Set([\"user\", \"assistant\", \"tool\"]);\n const messages: TanStackChatMessage[] = input.messages\n .filter((m: Message) => chatRoles.has(m.role))\n .map((m: Message): TanStackChatMessage => {\n const msg: TanStackChatMessage = {\n role: m.role as \"user\" | \"assistant\" | \"tool\",\n content:\n m.role === \"user\"\n ? convertUserContent(m.content)\n : m.role === \"tool\"\n ? // A tool result is a string or a list of parts; TanStack takes\n // text here, so the text parts are concatenated.\n contentToText(m.content)\n : typeof m.content === \"string\"\n ? m.content\n : null,\n };\n if (m.role === \"assistant\" && \"toolCalls\" in m && m.toolCalls) {\n msg.toolCalls = m.toolCalls.map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n }));\n }\n if (m.role === \"tool\" && \"toolCallId\" in m) {\n msg.toolCallId = (m as Record<string, unknown>).toolCallId as string;\n }\n return msg;\n });\n\n const systemPrompts: string[] = [];\n for (const m of input.messages) {\n if ((m.role === \"system\" || m.role === \"developer\") && m.content) {\n systemPrompts.push(\n typeof m.content === \"string\" ? m.content : JSON.stringify(m.content),\n );\n }\n }\n\n if (input.context?.length) {\n for (const ctx of input.context) {\n systemPrompts.push(`${ctx.description}:\\n${ctx.value}`);\n }\n }\n\n if (\n input.state !== undefined &&\n input.state !== null &&\n typeof input.state === \"object\" &&\n Object.keys(input.state).length > 0\n ) {\n systemPrompts.push(\n `Application State:\\n\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\``,\n );\n }\n\n // Frontend-provided tools become client-side TanStack tools (no executor):\n // the model can call them, TanStack pauses the run, and the AG-UI client\n // executes them and resumes — the CopilotKit client-tool round-trip.\n const tools: TanStackClientTool[] = (input.tools ?? []).map((t) => ({\n __toolSide: \"client\",\n name: t.name,\n description: t.description,\n inputSchema: sanitizeClientToolSchema(t.parameters),\n }));\n\n return { messages, systemPrompts, tools };\n}\n\n/**\n * Converts a TanStack AI stream into AG-UI `BaseEvent` objects.\n *\n * This is a pure converter — it does NOT emit lifecycle events\n * (RUN_STARTED / RUN_FINISHED / RUN_ERROR). The caller (Agent class)\n * is responsible for those.\n *\n * `pendingInterrupts`, when provided, is filled with one AG-UI Interrupt per\n * CUSTOM \"approval-requested\" chunk (a tool declared `needsApproval: true`).\n * The caller turns a non-empty array into a RUN_FINISHED `outcome:interrupt`.\n */\nexport async function* convertTanStackStream(\n stream: AsyncIterable<unknown>,\n abortSignal: AbortSignal,\n pendingInterrupts?: Interrupt[],\n initialState?: unknown,\n runFinishedDetails?: AgentRunFinishedDetails,\n): AsyncGenerator<BaseEvent> {\n const messageId = randomUUID();\n const toolNamesById = new Map<string, string>();\n // Track the reasoning lifecycle at two granularities so closeReasoningIfOpen\n // emits exactly the events still owed. A single boolean conflates the run\n // (REASONING_START → REASONING_END) with the message\n // (REASONING_MESSAGE_START → REASONING_MESSAGE_END) and produces a duplicate\n // REASONING_MESSAGE_END when upstream emits MSG_END but not END before\n // text/tools resume.\n let reasoningRunOpen = false;\n let reasoningMessageOpen = false;\n let reasoningMessageId = randomUUID();\n const normalizeStateEvent = createStateEventNormalizer(initialState);\n\n function* closeReasoningIfOpen(): Generator<BaseEvent> {\n if (reasoningMessageOpen) {\n reasoningMessageOpen = false;\n const msgEnd: ReasoningMessageEndEvent = {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n };\n yield msgEnd;\n }\n if (reasoningRunOpen) {\n reasoningRunOpen = false;\n const end: ReasoningEndEvent = {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n };\n yield end;\n }\n }\n\n // TanStack's chat() engine runs a multi-turn agent loop and emits a\n // RUN_STARTED / RUN_FINISHED pair PER model turn — not once for the whole\n // run. When it executes a tool itself (an MCP server tool or a provider tool\n // like web_search), it does so between turns and streams a TOOL_CALL_RESULT\n // followed by the next turn's text. The overall run lifecycle is owned by the\n // Agent wrapper (it emits exactly one outer RUN_STARTED / RUN_FINISHED), so\n // we drop TanStack's per-turn lifecycle markers and convert every content\n // event across all turns. (A previous version stopped converting at the first\n // RUN_FINISHED — that truncated the run at the first tool turn and silently\n // dropped both the tool result and the model's final answer.)\n //\n // chat() can re-announce a tool call when it re-prompts after executing it,\n // so START / END are de-duplicated by toolCallId to avoid emitting a pair\n // twice (which would violate the ag-ui verify middleware).\n const startedToolCalls = new Set<string>();\n const endedToolCalls = new Set<string>();\n\n for await (const chunk of stream) {\n if (abortSignal.aborted) break;\n\n const raw = chunk as Record<string, unknown>;\n const type = raw.type as string;\n\n // TanStack native human-in-the-loop: a tool declared `needsApproval: true`\n // emits a CUSTOM \"approval-requested\" chunk. These are built from the\n // finish event and can arrive around lifecycle markers, so handle them\n // before dropping TanStack's per-turn lifecycle events.\n // The tool-call lifecycle was already streamed in the model pass.\n if (type === \"CUSTOM\" && raw.name === \"approval-requested\") {\n const value = (raw.value ?? {}) as {\n toolCallId?: string;\n toolName?: string;\n };\n const toolCallId = value.toolCallId;\n if (toolCallId) {\n pendingInterrupts?.push({\n id: toolCallId,\n toolCallId,\n reason: \"tool_approval\",\n message: value.toolName ? `Approve \"${value.toolName}\"?` : undefined,\n ...(value.toolName ? { metadata: { toolName: value.toolName } } : {}),\n });\n }\n continue;\n }\n\n // Per-turn lifecycle markers are owned by the Agent wrapper, not forwarded.\n if (type === \"RUN_FINISHED\") {\n collectTanStackRunFinishedDetails(raw, runFinishedDetails);\n continue;\n }\n if (type === \"RUN_STARTED\") continue;\n\n // Surface engine errors instead of dropping them: throw so the Agent\n // wrapper emits a terminal RUN_ERROR. Without this a failed run (e.g. a\n // provider 4xx) would finish empty with no indication of what went wrong.\n if (type === \"RUN_ERROR\") {\n throw new Error(\n typeof raw.message === \"string\" ? raw.message : \"TanStack AI run error\",\n );\n }\n\n if (type === \"TEXT_MESSAGE_CONTENT\" && raw.delta != null) {\n yield* closeReasoningIfOpen();\n const textEvent: TextMessageChunkEvent = {\n type: EventType.TEXT_MESSAGE_CHUNK,\n role: \"assistant\",\n messageId,\n delta: raw.delta as string,\n };\n yield textEvent;\n } else if (type === \"TOOL_CALL_START\") {\n const toolCallId = raw.toolCallId as string;\n if (startedToolCalls.has(toolCallId)) continue;\n startedToolCalls.add(toolCallId);\n yield* closeReasoningIfOpen();\n toolNamesById.set(toolCallId, raw.toolCallName as string);\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: raw.toolCallName as string,\n };\n yield startEvent;\n } else if (type === \"TOOL_CALL_ARGS\") {\n // Drop args re-announced after the call has ended (the re-prompt pass);\n // forwarding them would corrupt the already-closed call's accumulated args.\n if (endedToolCalls.has(raw.toolCallId as string)) continue;\n yield* closeReasoningIfOpen();\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: raw.toolCallId as string,\n delta: raw.delta as string,\n };\n yield argsEvent;\n } else if (type === \"TOOL_CALL_END\") {\n const toolCallId = raw.toolCallId as string;\n if (endedToolCalls.has(toolCallId)) continue;\n endedToolCalls.add(toolCallId);\n yield* closeReasoningIfOpen();\n const endEvent: ToolCallEndEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n yield endEvent;\n } else if (type === \"TOOL_CALL_RESULT\") {\n yield* closeReasoningIfOpen();\n const toolCallId = raw.toolCallId as string;\n const toolName = toolNamesById.get(toolCallId);\n // Accept the payload from either `content` (canonical TanStack shape)\n // or `result` (alternate shape used by some adapters / tests). Both\n // state-tool detection and the final TOOL_CALL_RESULT serialization\n // must read the same field, otherwise STATE_SNAPSHOT/STATE_DELTA can\n // be silently dropped when upstream uses `result`.\n const rawPayload = raw.content ?? raw.result;\n\n const parsedContent =\n typeof rawPayload === \"string\" ? safeParse(rawPayload) : rawPayload;\n\n if (\n toolName === \"AGUISendStateSnapshot\" &&\n parsedContent &&\n typeof parsedContent === \"object\" &&\n \"snapshot\" in parsedContent\n ) {\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: (parsedContent as Record<string, unknown>).snapshot,\n };\n for (const event of normalizeStateEvent(stateSnapshotEvent)) {\n yield event;\n }\n }\n\n if (\n toolName === \"AGUISendStateDelta\" &&\n parsedContent &&\n typeof parsedContent === \"object\" &&\n \"delta\" in parsedContent\n ) {\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta: (parsedContent as Record<string, unknown>).delta as never,\n };\n for (const event of normalizeStateEvent(stateDeltaEvent)) {\n yield event;\n }\n }\n\n let serializedContent: string;\n if (typeof rawPayload === \"string\") {\n serializedContent = rawPayload;\n } else {\n try {\n serializedContent = JSON.stringify(rawPayload ?? null);\n } catch {\n serializedContent = \"[Unserializable tool result]\";\n }\n }\n\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId,\n content: serializedContent,\n };\n yield resultEvent;\n toolNamesById.delete(toolCallId);\n } else if (type === \"REASONING_START\") {\n // If a prior reasoning run is still open (no REASONING_END before this\n // new START), close it cleanly first so MSG_END / END pair correctly.\n yield* closeReasoningIfOpen();\n reasoningRunOpen = true;\n reasoningMessageId = (raw.messageId as string) ?? randomUUID();\n const startEvt: ReasoningStartEvent = {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n };\n yield startEvt;\n } else if (type === \"REASONING_MESSAGE_START\") {\n reasoningMessageOpen = true;\n const evt: ReasoningMessageStartEvent = {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: \"reasoning\",\n };\n yield evt;\n } else if (type === \"REASONING_MESSAGE_CONTENT\") {\n const evt: ReasoningMessageContentEvent = {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta: raw.delta as string,\n };\n yield evt;\n } else if (type === \"REASONING_MESSAGE_END\") {\n reasoningMessageOpen = false;\n const evt: ReasoningMessageEndEvent = {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n };\n yield evt;\n } else if (type === \"REASONING_END\") {\n // If upstream sends REASONING_END while a message is still open, emit\n // the missing REASONING_MESSAGE_END FIRST so the closing pair stays in\n // order (MSG_END before END). Otherwise the next non-reasoning chunk\n // would trigger closeReasoningIfOpen and emit MSG_END after END.\n if (reasoningMessageOpen) {\n reasoningMessageOpen = false;\n const msgEnd: ReasoningMessageEndEvent = {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n };\n yield msgEnd;\n }\n reasoningRunOpen = false;\n const evt: ReasoningEndEvent = {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n };\n yield evt;\n }\n }\n\n yield* closeReasoningIfOpen();\n}\n\n/** Normalizes legacy and standard TanStack usage into AG-UI token usage. */\nfunction collectTanStackRunFinishedDetails(\n event: Record<string, unknown>,\n details?: AgentRunFinishedDetails,\n): void {\n if (!details) return;\n\n const fallbackIdentity = {\n provider: getNonEmptyString(event.provider),\n model: getNonEmptyString(event.model),\n };\n collectStandardRunFinishedDetails(event, details, fallbackIdentity);\n\n // TanStack's native finish reason becomes AG-UI terminal metadata.\n if (typeof event.finishReason === \"string\") {\n details.metadata = {\n ...details.metadata,\n finishReason: event.finishReason,\n };\n }\n\n const usage = event.usage;\n\n if (Array.isArray(usage)) {\n return;\n }\n\n if (!isRecord(usage)) return;\n\n const promptDetails = isRecord(usage.promptTokensDetails)\n ? usage.promptTokensDetails\n : {};\n const completionDetails = isRecord(usage.completionTokensDetails)\n ? usage.completionTokensDetails\n : {};\n aggregateRunUsage(details, [\n {\n ...fallbackIdentity,\n inputTokens: getTokenCount(usage.promptTokens),\n outputTokens: getTokenCount(usage.completionTokens),\n totalTokens: getTokenCount(usage.totalTokens),\n reasoningTokens: getTokenCount(completionDetails.reasoningTokens),\n cachedInputTokens: getTokenCount(promptDetails.cachedTokens),\n },\n ]);\n}\n\nfunction safeParse(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n"],"mappings":";;;;;;;;;;;AA0GA,SAAS,mBACP,SACuC;AACvC,KAAI,CAAC,QAAS,QAAO;AACrB,KAAI,OAAO,YAAY,SAAU,QAAO;AACxC,KAAI,CAAC,MAAM,QAAQ,QAAQ,CAAE,QAAO;AACpC,KAAI,QAAQ,WAAW,EAAG,QAAO;CAEjC,MAAM,QAA+B,EAAE;AAEvC,MAAK,MAAM,QAAQ,SAAS;AAC1B,MAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,EAAE,UAAU,MAAO;AAE5D,UAAS,KAA0B,MAAnC;GACE,KAAK,QAAQ;IACX,MAAM,OAAQ,KAA2B;AACzC,QAAI,QAAQ,KAAM,OAAM,KAAK;KAAE,MAAM;KAAQ,SAAS;KAAM,CAA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AS;EAC3C,OAAO,kBAAkB,MAAM,MAAM;EACtC;AACD,mCAAkC,OAAO,SAAS,iBAAiB;AAGnE,KAAI,OAAO,MAAM,iBAAiB,SAChC,SAAQ,WAAW;EACjB,GAAG,QAAQ;EACX,cAAc,MAAM;EACrB;CAGH,MAAM,QAAQ,MAAM;AAEpB,KAAI,MAAM,QAAQ,MAAM,CACtB;AAGF,KAAI,CAAC,SAAS,MAAM,CAAE;CAEtB,MAAM,gBAAgB,SAAS,MAAM,oBAAoB,GACrD,MAAM,sBACN,EAAE;CACN,MAAM,oBAAoB,SAAS,MAAM,wBAAwB,GAC7D,MAAM,0BACN,EAAE;AACN,mBAAkB,SAAS,CACzB;EACE,GAAG;EACH,aAAa,cAAc,MAAM,aAAa;EAC9C,cAAc,cAAc,MAAM,iBAAiB;EACnD,aAAa,cAAc,MAAM,YAAY;EAC7C,iBAAiB,cAAc,kBAAkB,gBAAgB;EACjE,mBAAmB,cAAc,cAAc,aAAa;EAC7D,CACF,CAAC;;AAGJ,SAAS,UAAU,OAAwB;AACzC,KAAI;AACF,SAAO,KAAK,MAAM,MAAM;SAClB;AACN,SAAO"}
|
|
1
|
+
{"version":3,"file":"tanstack.mjs","names":[],"sources":["../../../src/agent/converters/tanstack.ts"],"sourcesContent":["import type {\n BaseEvent,\n Interrupt,\n RunAgentInput,\n Message,\n ResumeEntry,\n ToolMessage,\n TextMessageChunkEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolCallResultEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n ReasoningStartEvent,\n ReasoningMessageStartEvent,\n ReasoningMessageContentEvent,\n ReasoningMessageEndEvent,\n ReasoningEndEvent,\n} from \"@ag-ui/client\";\nimport { contentToText, EventType } from \"@ag-ui/client\";\nimport { randomUUID } from \"@copilotkit/shared\";\nimport { createStateEventNormalizer } from \"../state-delta\";\nimport {\n aggregateRunUsage,\n collectStandardRunFinishedDetails,\n getNonEmptyString,\n getTokenCount,\n isRecord,\n} from \"./usage\";\nimport type { AgentRunFinishedDetails } from \"./usage\";\n\ntype ContentPartSource =\n | { type: \"data\"; value: string; mimeType: string }\n | { type: \"url\"; value: string; mimeType?: string };\n\n/**\n * A TanStack AI content part (text, image, audio, video, or document).\n */\nexport type TanStackContentPart =\n | { type: \"text\"; content: string }\n | { type: \"image\"; source: ContentPartSource }\n | { type: \"audio\"; source: ContentPartSource }\n | { type: \"video\"; source: ContentPartSource }\n | { type: \"document\"; source: ContentPartSource };\n\n/**\n * Message format expected by TanStack AI's `chat()`.\n *\n * Content is typed as `any[]` for the multimodal case so messages are directly\n * passable to any adapter without casts — different adapters constrain which\n * modalities they accept (e.g. OpenAI only allows text + image).\n * Use `TanStackContentPart` to inspect individual parts if needed.\n */\nexport interface TanStackChatMessage {\n role: \"user\" | \"assistant\" | \"tool\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n content: string | null | any[];\n name?: string;\n toolCalls?: Array<{\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n }>;\n toolCallId?: string;\n}\n\n/**\n * A TanStack AI client-side tool, derived from a frontend-provided AG-UI tool.\n *\n * Shaped to match `@tanstack/ai`'s `ClientTool` (`__toolSide: \"client\"`, no\n * `execute`): the model may CALL it, but TanStack does not run it — it pauses\n * the run and hands the call back to the AG-UI client (the CopilotKit frontend\n * / bot) to execute, mirroring CopilotKit's client-tool round-trip. `chat()`\n * accepts a JSON Schema directly as `inputSchema`, so the AG-UI tool's\n * `parameters` pass through unchanged.\n */\nexport interface TanStackClientTool {\n __toolSide: \"client\";\n name: string;\n description: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputSchema: any;\n}\n\n/**\n * Result of converting RunAgentInput to TanStack AI format.\n */\nexport interface TanStackInputResult {\n /** Chat messages (only user/assistant/tool roles; all others excluded) */\n messages: TanStackChatMessage[];\n /** System prompts extracted from system/developer messages, context, and state */\n systemPrompts: string[];\n /**\n * Client-side tools derived from `input.tools` (the frontend-provided tools\n * the CopilotKit client forwards on every run). Pass these into `chat()`\n * alongside any server/provider tools so the model can call the frontend's\n * generative-UI and human-in-the-loop tools; TanStack pauses the run on a\n * client-tool call and the client executes it.\n */\n tools: TanStackClientTool[];\n}\n\n/**\n * Options for {@link convertInputToTanStackAI}. Leave them out to get the\n * conversion the `type: \"tanstack\"` factory uses. BuiltInAgent's classic mode\n * sets them to get the same model input it builds for its own runs.\n */\nexport interface TanStackInputOptions {\n /**\n * Add `system` messages from `input.messages` to `systemPrompts`. TanStack\n * AI messages have no system role, so a forwarded system message is a\n * system prompt. When `false`, system messages are dropped.\n *\n * @default true\n */\n forwardSystemMessages?: boolean;\n /**\n * Add `developer` messages from `input.messages` to `systemPrompts`, the\n * same way as {@link TanStackInputOptions.forwardSystemMessages}. When\n * `false`, developer messages are dropped.\n *\n * @default true\n */\n forwardDeveloperMessages?: boolean;\n /**\n * A system prompt that goes first in `systemPrompts`, before forwarded\n * messages, context, and state. An empty string adds nothing.\n */\n prompt?: string;\n /**\n * Interrupt responses to answer on this run, usually `input.resume`. Each\n * entry addresses the interrupt tool call whose id is its `interruptId`.\n * It is added after the converted messages as that call's tool result:\n * `{\"status\":\"cancelled\"}` for a cancelled entry, else the entry's\n * `payload`, else `{\"status\":\"resolved\"}`, as JSON text. An entry is\n * skipped when `input.messages` already has a tool message for that call.\n */\n resume?: ResumeEntry[];\n /**\n * Keep what a tool result holds besides text. When `true`, a URL part adds\n * its URL on its own line, an inline-data part stays as a media part after\n * the text, and a provider file handle is dropped with a warning. A result\n * with nothing left is the empty string. When `false`, a tool result is\n * only its text parts, joined.\n *\n * @default false\n */\n keepToolResultMedia?: boolean;\n /**\n * How the system prompts and the frontend tool schemas are built.\n *\n * - `\"factory\"`: `systemPrompts` is `prompt`, then each forwarded message,\n * then one entry per context item, then the state. Open objects in the\n * tool schemas are closed (`additionalProperties: false`).\n * - `\"classic\"`: what BuiltInAgent's classic mode sends. The first system\n * prompt joins `prompt`, the context under `## Context from the\n * application`, and the state under `## Application State`, with a note\n * that the model can change the state with `AGUISendStateSnapshot` or\n * `AGUISendStateDelta`. Each forwarded message follows as its own\n * prompt. The tool schemas are kept as the client sent them, so A2UI\n * components keep their open objects.\n *\n * @default \"factory\"\n */\n format?: \"factory\" | \"classic\";\n}\n\n/**\n * Warns that a part was dropped because its source is a provider file handle\n * (AG-UI `file` source), which is neither a URL nor inline data.\n */\nfunction warnDroppedFileSource(what: string) {\n console.warn(\n `[CopilotKit] Dropping a ${what} that references a provider file handle: it is not a URL or inline data, so it cannot be sent to the model here.`,\n );\n}\n\n/**\n * Converts an AG-UI tool result for a TanStack AI tool message, keeping URL\n * references and inline media.\n *\n * Providers hold one response per tool call, so all of a result's text is\n * one text entry: text parts run together, and a URL part adds the URL it\n * carries on a line of its own (the bytes are not here, and the reference is\n * what the tool returned). A result with no inline media is that text alone.\n * One with inline media is a list: the text part first, when there is any\n * text, then each media part. A provider file handle cannot be sent from\n * here, so that part is dropped with a warning. A result whose parts were all\n * dropped is the empty string, because the call must still be answered.\n */\nfunction convertToolResultContent(content: ToolMessage[\"content\"]) {\n if (typeof content === \"string\") return content;\n const segments: string[] = [];\n const media: TanStackContentPart[] = [];\n let open = false; // whether the last segment is text still being appended to\n for (const part of content) {\n if (part.type === \"text\") {\n if (open) segments[segments.length - 1] += part.text;\n else segments.push(part.text);\n open = true;\n } else if (part.source.type === \"file\") {\n warnDroppedFileSource(`${part.type} part in a tool result`);\n } else if (part.source.type === \"url\") {\n segments.push(part.source.value);\n open = false;\n } else {\n media.push({\n type: part.type,\n source: {\n type: \"data\",\n value: part.source.value,\n mimeType: part.source.mimeType,\n },\n });\n open = false;\n }\n }\n const text = segments.join(\"\\n\");\n if (media.length === 0) return text;\n const textParts: TanStackContentPart[] =\n text.length > 0 ? [{ type: \"text\", content: text }] : [];\n return [...textParts, ...media];\n}\n\n/**\n * Converts AG-UI user message content to TanStack AI format.\n * Handles plain strings, multimodal parts (image/audio/video/document),\n * and legacy BinaryInputContent for backward compatibility.\n */\nfunction convertUserContent(\n content: unknown,\n): string | null | TanStackContentPart[] {\n if (!content) return null;\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return null;\n if (content.length === 0) return \"\";\n\n const parts: TanStackContentPart[] = [];\n\n for (const part of content) {\n if (!part || typeof part !== \"object\" || !(\"type\" in part)) continue;\n\n switch ((part as { type: string }).type) {\n case \"text\": {\n const text = (part as { text?: string }).text;\n if (text != null) parts.push({ type: \"text\", content: text });\n break;\n }\n\n case \"image\":\n case \"audio\":\n case \"video\":\n case \"document\": {\n const source = (part as { source?: any }).source;\n if (!source) break;\n const partType = (part as { type: string }).type as\n | \"image\"\n | \"audio\"\n | \"video\"\n | \"document\";\n if (source.type === \"data\") {\n parts.push({\n type: partType,\n source: {\n type: \"data\",\n value: source.value,\n mimeType: source.mimeType,\n },\n });\n } else if (source.type === \"file\") {\n // AG-UI 1.0 provider file handle: not a URL or inline data.\n warnDroppedFileSource(`${partType} part`);\n } else if (source.type === \"url\") {\n parts.push({\n type: partType,\n source: {\n type: \"url\",\n value: source.value,\n ...(source.mimeType ? { mimeType: source.mimeType } : {}),\n },\n });\n }\n break;\n }\n\n // Legacy BinaryInputContent backward compatibility\n case \"binary\": {\n const legacy = part as {\n mimeType?: string;\n data?: string;\n url?: string;\n };\n const mimeType = legacy.mimeType ?? \"application/octet-stream\";\n const isImage = mimeType.startsWith(\"image/\");\n\n if (legacy.data) {\n const partType = isImage ? \"image\" : \"document\";\n parts.push({\n type: partType,\n source: { type: \"data\", value: legacy.data, mimeType },\n });\n } else if (legacy.url) {\n const partType = isImage ? \"image\" : \"document\";\n parts.push({\n type: partType,\n source: { type: \"url\", value: legacy.url, mimeType },\n });\n }\n break;\n }\n }\n }\n\n return parts.length > 0 ? parts : \"\";\n}\n\n/**\n * Recursively normalizes a frontend tool's JSON Schema so OpenAI accepts it as\n * a function-tool schema.\n *\n * Frontend tools are often authored with permissive Zod (`z.any()`,\n * `z.record(...)`, `.loose()`), which serialize to open objects —\n * `additionalProperties: {}` (an empty sub-schema) or `additionalProperties:\n * true`. OpenAI rejects both: strict mode requires `additionalProperties:\n * false`, and an empty `{}` sub-schema fails base validation (\"schema must\n * have a 'type' key\"). The classic (Vercel AI SDK) path sanitized these\n * implicitly via a Zod round-trip; the TanStack path forwards the raw schema,\n * so we close open objects here to match. (Models can't supply free-form extra\n * keys either way — same as the classic path.)\n */\nfunction sanitizeClientToolSchema(schema: unknown): unknown {\n if (Array.isArray(schema)) {\n return schema.map(sanitizeClientToolSchema);\n }\n if (!schema || typeof schema !== \"object\") {\n return schema;\n }\n const node: Record<string, unknown> = {\n ...(schema as Record<string, unknown>),\n };\n\n // Any `additionalProperties` (empty `{}`, `true`, or a sub-schema) becomes\n // `false` — the only form OpenAI accepts for strict function tools.\n if (\"additionalProperties\" in node) {\n node.additionalProperties = false;\n }\n\n if (node.properties && typeof node.properties === \"object\") {\n const props: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(\n node.properties as Record<string, unknown>,\n )) {\n props[key] = sanitizeClientToolSchema(value);\n }\n node.properties = props;\n }\n\n if (\"items\" in node) {\n node.items = sanitizeClientToolSchema(node.items);\n }\n\n for (const combinator of [\"anyOf\", \"allOf\", \"oneOf\"] as const) {\n if (Array.isArray(node[combinator])) {\n node[combinator] = (node[combinator] as unknown[]).map(\n sanitizeClientToolSchema,\n );\n }\n }\n\n return node;\n}\n\n/**\n * The system prompt of BuiltInAgent's classic mode: `prompt`, then the\n * context, then the state, joined into one string. Empty when there is\n * nothing to add. Any state other than `undefined`, `null`, or an empty\n * object is included.\n */\nfunction classicSystemPrompt(input: RunAgentInput, prompt: string | undefined) {\n const parts: string[] = [];\n if (prompt) parts.push(prompt);\n\n if (input.context?.length) {\n parts.push(\"\\n## Context from the application\\n\");\n for (const ctx of input.context) {\n parts.push(`${ctx.description}:\\n${ctx.value}\\n`);\n }\n }\n\n const isEmptyObject =\n typeof input.state === \"object\" &&\n input.state !== null &&\n Object.keys(input.state).length === 0;\n const hasState =\n input.state !== undefined && input.state !== null && !isEmptyObject;\n if (hasState) {\n parts.push(\n \"\\n## Application State\\n\" +\n \"This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.\\n\" +\n `\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\`\\n`,\n );\n }\n\n return parts.join(\"\");\n}\n\n/**\n * Converts a RunAgentInput into the format expected by TanStack AI's `chat()`.\n *\n * - Keeps only user/assistant/tool messages (activity, reasoning, and other roles are also excluded)\n * - Builds `systemPrompts` in this order: `options.prompt`, system/developer\n * messages, context entries, then application state (see\n * {@link TanStackInputOptions.format} for the classic layout)\n * - Preserves tool calls on assistant messages and toolCallId on tool messages\n * - Appends `options.resume` entries as tool results for interrupt tool calls\n *\n * @param input - The AG-UI run input.\n * @param options - Leave out for the `type: \"tanstack\"` factory conversion.\n * BuiltInAgent's classic mode passes its config and `input.resume` here.\n *\n * @example\n * ```ts\n * const { messages, systemPrompts, tools } = convertInputToTanStackAI(input, {\n * prompt: \"You are a helpful assistant.\",\n * forwardSystemMessages: false,\n * forwardDeveloperMessages: false,\n * resume: input.resume,\n * keepToolResultMedia: true,\n * format: \"classic\",\n * });\n * ```\n */\nexport function convertInputToTanStackAI(\n input: RunAgentInput,\n options: TanStackInputOptions = {},\n): TanStackInputResult {\n const {\n forwardSystemMessages = true,\n forwardDeveloperMessages = true,\n prompt,\n resume = [],\n keepToolResultMedia = false,\n format = \"factory\",\n } = options;\n\n // Allowlist: only pass user/assistant/tool messages to TanStack.\n // Other roles (system, developer, activity, reasoning) are either\n // extracted into systemPrompts or not applicable.\n const chatRoles = new Set([\"user\", \"assistant\", \"tool\"]);\n const messages: TanStackChatMessage[] = input.messages\n .filter((m: Message) => chatRoles.has(m.role))\n .map((m: Message): TanStackChatMessage => {\n const msg: TanStackChatMessage = {\n role: m.role as \"user\" | \"assistant\" | \"tool\",\n content:\n m.role === \"user\"\n ? convertUserContent(m.content)\n : m.role === \"tool\"\n ? keepToolResultMedia\n ? convertToolResultContent(m.content)\n : // A tool result is a string or a list of parts; only its\n // text parts are kept, concatenated.\n contentToText(m.content)\n : typeof m.content === \"string\"\n ? m.content\n : null,\n };\n if (m.role === \"assistant\" && \"toolCalls\" in m && m.toolCalls) {\n msg.toolCalls = m.toolCalls.map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n }));\n }\n if (m.role === \"tool\" && \"toolCallId\" in m) {\n msg.toolCallId = (m as Record<string, unknown>).toolCallId as string;\n }\n return msg;\n });\n\n // Resume injection: each ResumeEntry answers the interrupt tool call it\n // addresses (interruptId === toolCallId), so the model can continue the\n // agentic loop. Idempotent: a client (useInterrupt) may already have added\n // the resolution as a tool message, so those calls are not answered twice.\n const answeredToolCallIds = new Set(\n messages.flatMap((m) =>\n m.role === \"tool\" && m.toolCallId ? [m.toolCallId] : [],\n ),\n );\n for (const entry of resume) {\n if (answeredToolCallIds.has(entry.interruptId)) continue;\n const value =\n entry.status === \"cancelled\"\n ? { status: \"cancelled\" }\n : (entry.payload ?? { status: \"resolved\" });\n messages.push({\n role: \"tool\",\n toolCallId: entry.interruptId,\n content: JSON.stringify(value),\n });\n }\n\n const forwardedPrompts: string[] = [];\n for (const m of input.messages) {\n const isForwarded =\n (m.role === \"system\" && forwardSystemMessages) ||\n (m.role === \"developer\" && forwardDeveloperMessages);\n if (isForwarded && m.content) {\n forwardedPrompts.push(\n typeof m.content === \"string\" ? m.content : JSON.stringify(m.content),\n );\n }\n }\n\n const isClassic = format === \"classic\";\n const systemPrompts: string[] = [];\n if (isClassic) {\n const classicPrompt = classicSystemPrompt(input, prompt);\n if (classicPrompt) systemPrompts.push(classicPrompt);\n systemPrompts.push(...forwardedPrompts);\n } else {\n if (prompt) systemPrompts.push(prompt);\n systemPrompts.push(...forwardedPrompts);\n\n if (input.context?.length) {\n for (const ctx of input.context) {\n systemPrompts.push(`${ctx.description}:\\n${ctx.value}`);\n }\n }\n\n if (\n input.state !== undefined &&\n input.state !== null &&\n typeof input.state === \"object\" &&\n Object.keys(input.state).length > 0\n ) {\n systemPrompts.push(\n `Application State:\\n\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\``,\n );\n }\n }\n\n // Frontend-provided tools become client-side TanStack tools (no executor):\n // the model can call them, TanStack pauses the run, and the AG-UI client\n // executes them and resumes — the CopilotKit client-tool round-trip.\n const tools: TanStackClientTool[] = (input.tools ?? []).map((t) => ({\n __toolSide: \"client\",\n name: t.name,\n description: t.description,\n inputSchema: isClassic\n ? t.parameters\n : sanitizeClientToolSchema(t.parameters),\n }));\n\n return { messages, systemPrompts, tools };\n}\n\n/**\n * Converts a TanStack AI stream into AG-UI `BaseEvent` objects.\n *\n * This is a pure converter — it does NOT emit lifecycle events\n * (RUN_STARTED / RUN_FINISHED / RUN_ERROR). The caller (Agent class)\n * is responsible for those.\n *\n * `pendingInterrupts`, when provided, is filled with one AG-UI Interrupt per\n * tool call that waits for approval (a tool declared `needsApproval: true`):\n * from a CUSTOM \"approval-requested\" chunk (@tanstack/ai before 1.2) or from\n * a RUN_FINISHED `outcome:interrupt` approval entry (1.2 and later).\n * The caller turns a non-empty array into a RUN_FINISHED `outcome:interrupt`.\n */\nexport async function* convertTanStackStream(\n stream: AsyncIterable<unknown>,\n abortSignal: AbortSignal,\n pendingInterrupts?: Interrupt[],\n initialState?: unknown,\n runFinishedDetails?: AgentRunFinishedDetails,\n): AsyncGenerator<BaseEvent> {\n // The id of the current assistant text message. Each TEXT_MESSAGE_START\n // (one per text segment, so one per model step) opens a new message with a\n // fresh UUID. The adapter's id is not used: providers repeat ids such as\n // \"0\" or \"txt-0\" on every step and run (#3410, #3623). A tool call is a\n // child of the message that precedes it.\n let messageId = randomUUID();\n const toolNamesById = new Map<string, string>();\n // Track the reasoning lifecycle at two granularities so closeReasoningIfOpen\n // emits exactly the events still owed. A single boolean conflates the run\n // (REASONING_START → REASONING_END) with the message\n // (REASONING_MESSAGE_START → REASONING_MESSAGE_END) and produces a duplicate\n // REASONING_MESSAGE_END when upstream emits MSG_END but not END before\n // text/tools resume.\n let reasoningRunOpen = false;\n let reasoningMessageOpen = false;\n let reasoningMessageId = randomUUID();\n const normalizeStateEvent = createStateEventNormalizer(initialState);\n\n function* closeReasoningIfOpen(): Generator<BaseEvent> {\n if (reasoningMessageOpen) {\n reasoningMessageOpen = false;\n const msgEnd: ReasoningMessageEndEvent = {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n };\n yield msgEnd;\n }\n if (reasoningRunOpen) {\n reasoningRunOpen = false;\n const end: ReasoningEndEvent = {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n };\n yield end;\n }\n }\n\n // TanStack's chat() engine runs a multi-turn agent loop and emits a\n // RUN_STARTED / RUN_FINISHED pair PER model turn — not once for the whole\n // run. When it executes a tool itself (an MCP server tool or a provider tool\n // like web_search), it does so between turns and streams a TOOL_CALL_RESULT\n // followed by the next turn's text. The overall run lifecycle is owned by the\n // Agent wrapper (it emits exactly one outer RUN_STARTED / RUN_FINISHED), so\n // we drop TanStack's per-turn lifecycle markers and convert every content\n // event across all turns. (A previous version stopped converting at the first\n // RUN_FINISHED — that truncated the run at the first tool turn and silently\n // dropped both the tool result and the model's final answer.)\n //\n // chat() can re-announce a tool call when it re-prompts after executing it,\n // so START / END are de-duplicated by toolCallId to avoid emitting a pair\n // twice (which would violate the ag-ui verify middleware).\n const startedToolCalls = new Set<string>();\n const endedToolCalls = new Set<string>();\n\n for await (const chunk of stream) {\n if (abortSignal.aborted) break;\n\n const raw = chunk as Record<string, unknown>;\n const type = raw.type as string;\n\n // TanStack native human-in-the-loop for a tool declared\n // `needsApproval: true`. @tanstack/ai before 1.2 emits a CUSTOM\n // \"approval-requested\" chunk. 1.2 and later end the turn with RUN_FINISHED\n // `outcome: { type: \"interrupt\" }` instead (handled below). Both can arrive\n // around lifecycle markers, so handle this before dropping TanStack's\n // per-turn lifecycle events. The tool-call lifecycle was already streamed\n // in the model pass.\n if (type === \"CUSTOM\" && raw.name === \"approval-requested\") {\n const value = isRecord(raw.value) ? raw.value : {};\n addApprovalInterrupt(\n pendingInterrupts,\n getNonEmptyString(value.toolCallId),\n getNonEmptyString(value.toolName),\n );\n continue;\n }\n\n // Per-turn lifecycle markers are owned by the Agent wrapper, not forwarded.\n if (type === \"RUN_FINISHED\") {\n collectTanStackRunFinishedDetails(raw, runFinishedDetails);\n collectTanStackApprovalInterrupts(raw, pendingInterrupts);\n continue;\n }\n if (type === \"RUN_STARTED\") continue;\n\n // Surface engine errors instead of dropping them: throw so the Agent\n // wrapper emits a terminal RUN_ERROR. Without this a failed run (e.g. a\n // provider 4xx) would finish empty with no indication of what went wrong.\n if (type === \"RUN_ERROR\") {\n throw new Error(\n typeof raw.message === \"string\" ? raw.message : \"TanStack AI run error\",\n );\n }\n\n if (type === \"TEXT_MESSAGE_START\") {\n messageId = randomUUID();\n } else if (type === \"TEXT_MESSAGE_CONTENT\" && raw.delta != null) {\n yield* closeReasoningIfOpen();\n const textEvent: TextMessageChunkEvent = {\n type: EventType.TEXT_MESSAGE_CHUNK,\n role: \"assistant\",\n messageId,\n delta: raw.delta as string,\n };\n yield textEvent;\n } else if (type === \"TOOL_CALL_START\") {\n const toolCallId = raw.toolCallId as string;\n if (startedToolCalls.has(toolCallId)) continue;\n startedToolCalls.add(toolCallId);\n yield* closeReasoningIfOpen();\n toolNamesById.set(toolCallId, raw.toolCallName as string);\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: raw.toolCallName as string,\n };\n yield startEvent;\n } else if (type === \"TOOL_CALL_ARGS\") {\n // Drop args re-announced after the call has ended (the re-prompt pass);\n // forwarding them would corrupt the already-closed call's accumulated args.\n if (endedToolCalls.has(raw.toolCallId as string)) continue;\n yield* closeReasoningIfOpen();\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: raw.toolCallId as string,\n delta: raw.delta as string,\n };\n yield argsEvent;\n } else if (type === \"TOOL_CALL_END\") {\n const toolCallId = raw.toolCallId as string;\n if (endedToolCalls.has(toolCallId)) continue;\n endedToolCalls.add(toolCallId);\n yield* closeReasoningIfOpen();\n const endEvent: ToolCallEndEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n yield endEvent;\n } else if (type === \"TOOL_CALL_RESULT\") {\n yield* closeReasoningIfOpen();\n const toolCallId = raw.toolCallId as string;\n const toolName = toolNamesById.get(toolCallId);\n // Accept the payload from either `content` (canonical TanStack shape)\n // or `result` (alternate shape used by some adapters / tests). Both\n // state-tool detection and the final TOOL_CALL_RESULT serialization\n // must read the same field, otherwise STATE_SNAPSHOT/STATE_DELTA can\n // be silently dropped when upstream uses `result`.\n const rawPayload = raw.content ?? raw.result;\n\n const parsedContent =\n typeof rawPayload === \"string\" ? safeParse(rawPayload) : rawPayload;\n\n if (\n toolName === \"AGUISendStateSnapshot\" &&\n parsedContent &&\n typeof parsedContent === \"object\" &&\n \"snapshot\" in parsedContent\n ) {\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: (parsedContent as Record<string, unknown>).snapshot,\n };\n for (const event of normalizeStateEvent(stateSnapshotEvent)) {\n yield event;\n }\n }\n\n if (\n toolName === \"AGUISendStateDelta\" &&\n parsedContent &&\n typeof parsedContent === \"object\" &&\n \"delta\" in parsedContent\n ) {\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta: (parsedContent as Record<string, unknown>).delta as never,\n };\n for (const event of normalizeStateEvent(stateDeltaEvent)) {\n yield event;\n }\n }\n\n let serializedContent: string;\n if (typeof rawPayload === \"string\") {\n serializedContent = rawPayload;\n } else {\n try {\n serializedContent = JSON.stringify(rawPayload ?? null);\n } catch {\n serializedContent = \"[Unserializable tool result]\";\n }\n }\n\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId,\n content: serializedContent,\n };\n yield resultEvent;\n toolNamesById.delete(toolCallId);\n } else if (type === \"REASONING_START\") {\n // If a prior reasoning run is still open (no REASONING_END before this\n // new START), close it cleanly first so MSG_END / END pair correctly.\n yield* closeReasoningIfOpen();\n reasoningRunOpen = true;\n reasoningMessageId = (raw.messageId as string) ?? randomUUID();\n const startEvt: ReasoningStartEvent = {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n };\n yield startEvt;\n } else if (type === \"REASONING_MESSAGE_START\") {\n reasoningMessageOpen = true;\n const evt: ReasoningMessageStartEvent = {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: \"reasoning\",\n };\n yield evt;\n } else if (type === \"REASONING_MESSAGE_CONTENT\") {\n const evt: ReasoningMessageContentEvent = {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta: raw.delta as string,\n };\n yield evt;\n } else if (type === \"REASONING_MESSAGE_END\") {\n reasoningMessageOpen = false;\n const evt: ReasoningMessageEndEvent = {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n };\n yield evt;\n } else if (type === \"REASONING_END\") {\n // If upstream sends REASONING_END while a message is still open, emit\n // the missing REASONING_MESSAGE_END FIRST so the closing pair stays in\n // order (MSG_END before END). Otherwise the next non-reasoning chunk\n // would trigger closeReasoningIfOpen and emit MSG_END after END.\n if (reasoningMessageOpen) {\n reasoningMessageOpen = false;\n const msgEnd: ReasoningMessageEndEvent = {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n };\n yield msgEnd;\n }\n reasoningRunOpen = false;\n const evt: ReasoningEndEvent = {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n };\n yield evt;\n }\n }\n\n yield* closeReasoningIfOpen();\n}\n\n/**\n * Adds one AG-UI approval interrupt for a `needsApproval` tool call, keyed by\n * the tool call id. A call that already has an interrupt is skipped, so a\n * stream that reports the same approval twice (CUSTOM chunk and RUN_FINISHED\n * outcome) produces one interrupt.\n */\nfunction addApprovalInterrupt(\n pendingInterrupts: Interrupt[] | undefined,\n toolCallId: string | undefined,\n toolName: string | undefined,\n): void {\n if (!pendingInterrupts || !toolCallId) return;\n if (pendingInterrupts.some((entry) => entry.toolCallId === toolCallId)) {\n return;\n }\n pendingInterrupts.push({\n id: toolCallId,\n toolCallId,\n reason: \"tool_approval\",\n message: toolName ? `Approve \"${toolName}\"?` : undefined,\n ...(toolName ? { metadata: { toolName } } : {}),\n });\n}\n\n/**\n * Reads the approval interrupts of a @tanstack/ai 1.2+ RUN_FINISHED\n * `outcome: { type: \"interrupt\" }`. Only `kind: \"approval\"` entries are mapped.\n * Client tool interrupts (a tool without `execute`) are already handled by\n * the frontend tool flow and by `withClassicToolRules`.\n */\nfunction collectTanStackApprovalInterrupts(\n event: Record<string, unknown>,\n pendingInterrupts?: Interrupt[],\n): void {\n const outcome = event.outcome;\n if (!isRecord(outcome) || outcome.type !== \"interrupt\") return;\n if (!Array.isArray(outcome.interrupts)) return;\n\n for (const interrupt of outcome.interrupts) {\n if (!isRecord(interrupt) || !isRecord(interrupt.metadata)) continue;\n if (interrupt.metadata.kind !== \"approval\") continue;\n addApprovalInterrupt(\n pendingInterrupts,\n getNonEmptyString(interrupt.toolCallId),\n getNonEmptyString(interrupt.metadata.toolName),\n );\n }\n}\n\n/**\n * Normalizes legacy and standard TanStack usage into AG-UI token usage.\n *\n * @tanstack/ai 1.2+ puts the model, the finish reason, and the provider under\n * `metadata.tanstack` (internal to TanStack). Older versions put the model and\n * the finish reason at the top level. Both are read, the top level first, and\n * `metadata.tanstack` is not forwarded as AG-UI metadata.\n */\nfunction collectTanStackRunFinishedDetails(\n event: Record<string, unknown>,\n details?: AgentRunFinishedDetails,\n): void {\n if (!details) return;\n\n const { metadata, tanstack } = splitTanStackMetadata(event.metadata);\n const source = isRecord(tanstack.source) ? tanstack.source : {};\n const fallbackIdentity = {\n provider:\n getNonEmptyString(event.provider) ?? getNonEmptyString(source.provider),\n model:\n getNonEmptyString(event.model) ??\n getNonEmptyString(tanstack.model) ??\n getNonEmptyString(source.model),\n };\n collectStandardRunFinishedDetails(\n { ...event, metadata },\n details,\n fallbackIdentity,\n );\n\n // TanStack's native finish reason becomes AG-UI terminal metadata.\n const finishReason =\n typeof event.finishReason === \"string\"\n ? event.finishReason\n : tanstack.finishReason;\n if (typeof finishReason === \"string\") {\n details.metadata = {\n ...details.metadata,\n finishReason,\n };\n }\n\n const usage = event.usage;\n\n if (Array.isArray(usage)) {\n return;\n }\n\n if (!isRecord(usage)) return;\n\n const promptDetails = isRecord(usage.promptTokensDetails)\n ? usage.promptTokensDetails\n : {};\n const completionDetails = isRecord(usage.completionTokensDetails)\n ? usage.completionTokensDetails\n : {};\n aggregateRunUsage(details, [\n {\n ...fallbackIdentity,\n inputTokens: getTokenCount(usage.promptTokens),\n outputTokens: getTokenCount(usage.completionTokens),\n totalTokens: getTokenCount(usage.totalTokens),\n reasoningTokens: getTokenCount(completionDetails.reasoningTokens),\n cachedInputTokens: getTokenCount(promptDetails.cachedTokens),\n },\n ]);\n}\n\n/**\n * Splits RUN_FINISHED metadata into the AG-UI metadata to forward and\n * TanStack's internal `metadata.tanstack` object. When `tanstack` was the only\n * key, nothing is left to forward.\n */\nfunction splitTanStackMetadata(value: unknown): {\n metadata: Record<string, unknown> | undefined;\n tanstack: Record<string, unknown>;\n} {\n if (!isRecord(value)) return { metadata: undefined, tanstack: {} };\n if (!(\"tanstack\" in value)) return { metadata: value, tanstack: {} };\n\n const { tanstack, ...metadata } = value;\n return {\n metadata: Object.keys(metadata).length > 0 ? metadata : undefined,\n tanstack: isRecord(tanstack) ? tanstack : {},\n };\n}\n\nfunction safeParse(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n"],"mappings":";;;;;;;;;;AA4KA,SAAS,sBAAsB,MAAc;AAC3C,SAAQ,KACN,2BAA2B,KAAK,kHACjC;;;;;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