@copilotkit/runtime 2.0.0-rc.35 → 2.0.0-rc.37

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.
Files changed (94) hide show
  1. package/README.md +9 -2
  2. package/dist/agent/{url-download.cjs → ai-sdk/url-download.cjs} +19 -75
  3. package/dist/agent/ai-sdk/url-download.cjs.map +1 -0
  4. package/dist/agent/{url-download.d.cts → ai-sdk/url-download.d.cts} +11 -8
  5. package/dist/agent/ai-sdk/url-download.d.cts.map +1 -0
  6. package/dist/agent/{url-download.d.mts → ai-sdk/url-download.d.mts} +11 -8
  7. package/dist/agent/ai-sdk/url-download.d.mts.map +1 -0
  8. package/dist/agent/{url-download.mjs → ai-sdk/url-download.mjs} +20 -74
  9. package/dist/agent/ai-sdk/url-download.mjs.map +1 -0
  10. package/dist/agent/ai-sdk.cjs +425 -0
  11. package/dist/agent/ai-sdk.cjs.map +1 -0
  12. package/dist/agent/ai-sdk.d.cts +119 -0
  13. package/dist/agent/ai-sdk.d.cts.map +1 -0
  14. package/dist/agent/ai-sdk.d.mts +119 -0
  15. package/dist/agent/ai-sdk.d.mts.map +1 -0
  16. package/dist/agent/ai-sdk.mjs +419 -0
  17. package/dist/agent/ai-sdk.mjs.map +1 -0
  18. package/dist/agent/classic-tools.cjs +185 -0
  19. package/dist/agent/classic-tools.cjs.map +1 -0
  20. package/dist/agent/classic-tools.mjs +183 -0
  21. package/dist/agent/classic-tools.mjs.map +1 -0
  22. package/dist/agent/converters/aisdk.cjs +0 -3
  23. package/dist/agent/converters/aisdk.mjs +1 -1
  24. package/dist/agent/converters/tanstack.cjs +200 -27
  25. package/dist/agent/converters/tanstack.cjs.map +1 -1
  26. package/dist/agent/converters/tanstack.d.cts +90 -6
  27. package/dist/agent/converters/tanstack.d.cts.map +1 -1
  28. package/dist/agent/converters/tanstack.d.mts +90 -6
  29. package/dist/agent/converters/tanstack.d.mts.map +1 -1
  30. package/dist/agent/converters/tanstack.mjs +200 -27
  31. package/dist/agent/converters/tanstack.mjs.map +1 -1
  32. package/dist/agent/learned-skills.cjs +15 -16
  33. package/dist/agent/learned-skills.cjs.map +1 -1
  34. package/dist/agent/learned-skills.d.cts +9 -3
  35. package/dist/agent/learned-skills.d.cts.map +1 -1
  36. package/dist/agent/learned-skills.d.mts +9 -3
  37. package/dist/agent/learned-skills.d.mts.map +1 -1
  38. package/dist/agent/learned-skills.mjs +15 -16
  39. package/dist/agent/learned-skills.mjs.map +1 -1
  40. package/dist/agent/model.cjs +42 -0
  41. package/dist/agent/model.cjs.map +1 -0
  42. package/dist/agent/model.d.cts +19 -0
  43. package/dist/agent/model.d.cts.map +1 -0
  44. package/dist/agent/model.d.mts +19 -0
  45. package/dist/agent/model.d.mts.map +1 -0
  46. package/dist/agent/model.mjs +41 -0
  47. package/dist/agent/model.mjs.map +1 -0
  48. package/dist/agent.cjs +558 -0
  49. package/dist/agent.cjs.map +1 -0
  50. package/dist/agent.d.cts +455 -0
  51. package/dist/agent.d.cts.map +1 -0
  52. package/dist/agent.d.mts +455 -0
  53. package/dist/agent.d.mts.map +1 -0
  54. package/dist/agent.mjs +551 -0
  55. package/dist/agent.mjs.map +1 -0
  56. package/dist/index.cjs +0 -17
  57. package/dist/index.d.cts +5 -10
  58. package/dist/index.d.mts +5 -10
  59. package/dist/index.mjs +1 -5
  60. package/dist/internal/learned-skills.d.cts +1 -1
  61. package/dist/internal/learned-skills.d.mts +1 -1
  62. package/dist/runtime/core/channel-manager.d.cts +1 -1
  63. package/dist/runtime/core/channel-manager.d.mts +1 -1
  64. package/dist/runtime/core/debug-event-bus.d.cts +1 -1
  65. package/dist/runtime/core/learning.d.cts +1 -1
  66. package/dist/runtime/core/package-info.cjs +1 -1
  67. package/dist/runtime/core/package-info.mjs +1 -1
  68. package/dist/runtime/core/runtime.d.cts +3 -3
  69. package/dist/runtime/core/runtime.d.mts +2 -2
  70. package/dist/runtime/generative-ui/surface-writer.d.cts +1 -1
  71. package/dist/runtime/index.d.cts +4 -6
  72. package/dist/runtime/index.d.mts +4 -6
  73. package/dist/runtime/intelligence-platform/client.d.cts +1 -1
  74. package/dist/runtime/intelligence-platform/client.d.mts +1 -1
  75. package/dist/runtime/intelligence-platform/skill-registry/index.d.cts +1 -1
  76. package/dist/runtime/intelligence-platform/skill-registry/index.d.mts +1 -1
  77. package/package.json +32 -11
  78. package/dist/agent/converters/index.d.mts +0 -2
  79. package/dist/agent/index.cjs +0 -1329
  80. package/dist/agent/index.cjs.map +0 -1
  81. package/dist/agent/index.d.cts +0 -459
  82. package/dist/agent/index.d.cts.map +0 -1
  83. package/dist/agent/index.d.mts +0 -460
  84. package/dist/agent/index.d.mts.map +0 -1
  85. package/dist/agent/index.mjs +0 -1321
  86. package/dist/agent/index.mjs.map +0 -1
  87. package/dist/agent/mcp-tool-names.cjs +0 -82
  88. package/dist/agent/mcp-tool-names.cjs.map +0 -1
  89. package/dist/agent/mcp-tool-names.mjs +0 -80
  90. package/dist/agent/mcp-tool-names.mjs.map +0 -1
  91. package/dist/agent/url-download.cjs.map +0 -1
  92. package/dist/agent/url-download.d.cts.map +0 -1
  93. package/dist/agent/url-download.d.mts.map +0 -1
  94. package/dist/agent/url-download.mjs.map +0 -1
@@ -1,1329 +0,0 @@
1
- const require_describe_endpoint = require('../runtime/handlers/shared/describe-endpoint.cjs');
2
- const require_url_download = require('./url-download.cjs');
3
- const require_state_delta = require('./state-delta.cjs');
4
- const require_usage = require('./converters/usage.cjs');
5
- const require_aisdk = require('./converters/aisdk.cjs');
6
- const require_tanstack = require('./converters/tanstack.cjs');
7
- const require_registry = require('../runtime/intelligence-platform/skill-registry/registry.cjs');
8
- const require_learned_skills = require('./learned-skills.cjs');
9
- const require_mcp_tool_names = require('./mcp-tool-names.cjs');
10
- let _copilotkit_shared = require("@copilotkit/shared");
11
- let zod = require("zod");
12
- let rxjs = require("rxjs");
13
- let _ag_ui_client = require("@ag-ui/client");
14
- let _ag_ui_a2ui_middleware = require("@ag-ui/a2ui-middleware");
15
- let _cfworker_json_schema = require("@cfworker/json-schema");
16
- let ai = require("ai");
17
- let _ai_sdk_mcp = require("@ai-sdk/mcp");
18
- let _ai_sdk_openai = require("@ai-sdk/openai");
19
- let _ai_sdk_anthropic = require("@ai-sdk/anthropic");
20
- let _ai_sdk_google = require("@ai-sdk/google");
21
- let _ai_sdk_google_vertex = require("@ai-sdk/google-vertex");
22
- let _modelcontextprotocol_sdk_client_streamableHttp_js = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
23
-
24
- //#region src/agent/index.ts
25
- /**
26
- * Resolves a model specifier to a LanguageModel instance
27
- * @param spec - Model string (e.g., "openai/gpt-6-luna") or LanguageModel instance
28
- * @param apiKey - Optional API key to use instead of environment variables
29
- * @returns LanguageModel instance
30
- */
31
- /**
32
- * An AG-UI tool result as the AI SDK's tool result output.
33
- *
34
- * Providers hold one response per tool call, and the Google adapter emits one
35
- * functionResponse per text entry of a content list, so all of a result's text
36
- * is collected into a single entry: text parts run together, and a
37
- * URL-referenced part contributes the URL it carries on a line of its own —
38
- * the bytes are not here to hand over, and the reference is the content the
39
- * tool actually returned. A result with no inline media is that text alone.
40
- * One with inline media is a content list: the text entry first, when there is
41
- * any, then each media part with its bytes and media type. A media-only result
42
- * is media alone: a placeholder text would be content the tool never returned.
43
- * Which adapters can place media inside a tool response is theirs to decide.
44
- * A provider file handle (`file` source) is neither bytes nor a URL, and this
45
- * path cannot hand it to the provider, so the part is dropped with a warning.
46
- * A result whose parts were all dropped is the empty string, as AG-UI 1.0
47
- * requires: the call must still be answered.
48
- */
49
- function warnDroppedFileSource(what) {
50
- 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.`);
51
- }
52
- function toolResultOutput(content) {
53
- if (typeof content === "string") return {
54
- type: "text",
55
- value: content
56
- };
57
- const segments = [];
58
- const media = [];
59
- let open = false;
60
- for (const part of content) if (part.type === "text") {
61
- if (open) segments[segments.length - 1] += part.text;
62
- else segments.push(part.text);
63
- open = true;
64
- } else if (part.source.type === "file") warnDroppedFileSource(`${part.type} part in a tool result`);
65
- else if (part.source.type === "url") {
66
- segments.push(part.source.value);
67
- open = false;
68
- } else {
69
- media.push({
70
- type: "media",
71
- data: part.source.value,
72
- mediaType: part.source.mimeType
73
- });
74
- open = false;
75
- }
76
- const text = segments.join("\n");
77
- if (media.length === 0) return {
78
- type: "text",
79
- value: text
80
- };
81
- return {
82
- type: "content",
83
- value: [...text.length > 0 ? [{
84
- type: "text",
85
- text
86
- }] : [], ...media]
87
- };
88
- }
89
- /**
90
- * Split a model string into provider and model id. The provider is the text
91
- * before the FIRST ":" or "/"; everything after it is the model id, unchanged.
92
- * So "openai:meta-llama/llama-3.3-70b" keeps the slash in its model id, and
93
- * "openai/ft:gpt-4o-mini:org::id" keeps its colons. Empty strings mean the
94
- * part is missing.
95
- */
96
- function parseModelSpec(spec) {
97
- const trimmed = spec.trim();
98
- const separator = trimmed.search(/[:/]/);
99
- if (separator === -1) return {
100
- provider: trimmed.toLowerCase(),
101
- model: ""
102
- };
103
- return {
104
- provider: trimmed.slice(0, separator).toLowerCase(),
105
- model: trimmed.slice(separator + 1).trim()
106
- };
107
- }
108
- /**
109
- * Whether an `OPENAI_BASE_URL` should get Chat Completions instead of the
110
- * Responses API. OpenAI's own hosts (including `*.api.openai.com`, such as the
111
- * EU data-residency host) and Azure serve `/responses`, so they keep it, as
112
- * does an unset value. Any other host gets `/chat/completions`, which is what
113
- * most OpenAI-compatible servers implement. The host rule is
114
- * `classifyModelHost`, the same one telemetry uses.
115
- *
116
- * A value `new URL` throws on keeps the Responses route; the request will
117
- * fail on that base URL either way. A schemeless value such as
118
- * `localhost:11434/v1` does not throw (it parses with scheme `localhost:` and
119
- * an empty host), so it classifies as `other` and gets Chat Completions.
120
- */
121
- function usesChatCompletions(baseURL) {
122
- const trimmed = baseURL?.trim();
123
- if (!trimmed) return false;
124
- try {
125
- new URL(trimmed);
126
- } catch {
127
- return false;
128
- }
129
- const host = (0, _copilotkit_shared.classifyModelHost)(trimmed, "openai");
130
- return host !== "openai" && host !== "azure";
131
- }
132
- /** Whether the Chat Completions notice below was already logged. */
133
- let loggedChatCompletionsRoute = false;
134
- /**
135
- * Which OpenAI API an `openai/...` model string targets.
136
- *
137
- * `COPILOTKIT_OPENAI_API` (`responses` or `chat`) wins when set, so a proxy in
138
- * front of OpenAI can keep the Responses API, and an OpenAI host can use Chat
139
- * Completions. Unset or blank, `usesChatCompletions` decides from
140
- * `OPENAI_BASE_URL`.
141
- *
142
- * When that rule picks Chat Completions, this logs once per process. Through a
143
- * proxy, Chat Completions drops Responses-only features (such as reasoning
144
- * summaries) without an error, and the notice names the way back.
145
- */
146
- function openAIApiFor(baseURL) {
147
- const raw = (0, _copilotkit_shared.processEnv)().COPILOTKIT_OPENAI_API;
148
- const override = raw?.trim().toLowerCase();
149
- if (override === "responses" || override === "chat") return override;
150
- if (override) throw new Error(`Invalid COPILOTKIT_OPENAI_API "${raw}". Use "responses" or "chat", or leave it unset.`);
151
- if (!usesChatCompletions(baseURL)) return "responses";
152
- if (!loggedChatCompletionsRoute) {
153
- loggedChatCompletionsRoute = true;
154
- console.info("[CopilotKit] OPENAI_BASE_URL is not an OpenAI or Azure host, so \"openai/...\" models use the Chat Completions API. To use the Responses API instead, set COPILOTKIT_OPENAI_API=responses.");
155
- }
156
- return "chat";
157
- }
158
- function resolveModel(spec, apiKey) {
159
- if (typeof spec !== "string") return spec;
160
- const { provider, model } = parseModelSpec(spec);
161
- if (!provider) throw new Error(`Invalid model string "${spec}". Use "openai/gpt-6-luna", "anthropic/claude-sonnet-4.5", or "google/gemini-3.8-flash".`);
162
- if (!model) throw new Error(`Invalid model string "${spec}". Use "openai/gpt-6-luna", "anthropic/claude-sonnet-4.5", or "google/gemini-3.8-flash".`);
163
- switch (provider) {
164
- case "openai": {
165
- const openai = (0, _ai_sdk_openai.createOpenAI)({
166
- apiKey: apiKey || (0, _copilotkit_shared.processEnv)().OPENAI_API_KEY,
167
- baseURL: (0, _copilotkit_shared.processEnv)().OPENAI_BASE_URL
168
- });
169
- return openAIApiFor((0, _copilotkit_shared.processEnv)().OPENAI_BASE_URL) === "chat" ? openai.chat(model) : openai(model);
170
- }
171
- case "anthropic": return (0, _ai_sdk_anthropic.createAnthropic)({
172
- apiKey: apiKey || (0, _copilotkit_shared.processEnv)().ANTHROPIC_API_KEY,
173
- baseURL: (0, _copilotkit_shared.processEnv)().ANTHROPIC_BASE_URL
174
- })(model);
175
- case "google":
176
- case "gemini":
177
- case "google-gemini": return (0, _ai_sdk_google.createGoogleGenerativeAI)({
178
- apiKey: apiKey || (0, _copilotkit_shared.processEnv)().GOOGLE_API_KEY,
179
- baseURL: (0, _copilotkit_shared.processEnv)().GOOGLE_GENERATIVE_AI_BASE_URL
180
- })(model);
181
- case "minimax": return (0, _ai_sdk_openai.createOpenAI)({
182
- name: "minimax",
183
- apiKey: apiKey || (0, _copilotkit_shared.processEnv)().MINIMAX_API_KEY,
184
- baseURL: (0, _copilotkit_shared.processEnv)().MINIMAX_BASE_URL || "https://api.minimax.io/v1"
185
- })(model);
186
- case "vertex": return (0, _ai_sdk_google_vertex.createVertex)()(model);
187
- default: throw new Error(`Unknown provider "${provider}" in "${spec}". Supported: openai, anthropic, google (gemini).`);
188
- }
189
- }
190
- /**
191
- * Which vendor a model specifier will actually reach, as a closed vocabulary.
192
- *
193
- * `resolveModel` above is the only place this runtime builds a provider, so it
194
- * is the only place that knows the endpoint. Once built, the endpoint is gone:
195
- * an AI SDK model's `provider` names only the wire API (`"openai.responses"`
196
- * on OpenAI and Azure, `"openai.chat"` on any other host), so it cannot tell
197
- * OpenRouter from a laptop, and its base URL survives
198
- * only inside a closure that the public `LanguageModelV3` type does not
199
- * expose. Azure's own migration guide tells customers to use that same OpenAI
200
- * client, so the case we are blindest to is the common one.
201
- *
202
- * A caller who hands us an already-built LanguageModel gets `unknown`. Nobody
203
- * can recover the host from it, and saying so is more useful than guessing
204
- * `openai` from a provider label that means only "speaks the OpenAI wire".
205
- *
206
- * The branches below mirror `resolveModel`'s switch and must change with it.
207
- * `model-host-class.test.ts` walks every provider that switch accepts and
208
- * fails if one lands here as `unknown`.
209
- */
210
- function classifyModelSpec(spec) {
211
- if (typeof spec !== "string") return "unknown";
212
- const { provider } = parseModelSpec(spec);
213
- switch (provider) {
214
- case "openai": return (0, _copilotkit_shared.classifyModelHost)((0, _copilotkit_shared.processEnv)().OPENAI_BASE_URL, "openai");
215
- case "anthropic": return (0, _copilotkit_shared.classifyModelHost)((0, _copilotkit_shared.processEnv)().ANTHROPIC_BASE_URL, "anthropic");
216
- case "google":
217
- case "gemini":
218
- case "google-gemini": return (0, _copilotkit_shared.classifyModelHost)((0, _copilotkit_shared.processEnv)().GOOGLE_GENERATIVE_AI_BASE_URL, "google");
219
- case "minimax": return (0, _copilotkit_shared.classifyModelHost)((0, _copilotkit_shared.processEnv)().MINIMAX_BASE_URL || "https://api.minimax.io/v1", "minimax");
220
- case "vertex": return "vertex";
221
- default: return "unknown";
222
- }
223
- }
224
- /**
225
- * Thrown by `AgentFactoryContext.interrupt()` on a fresh (non-resume) run to
226
- * pause the factory. Caught in `runFactory` and translated into a RUN_FINISHED
227
- * event carrying `outcome:{type:"interrupt",interrupts}`. Not a real error.
228
- */
229
- var InterruptSignal = class extends Error {
230
- constructor(interrupts) {
231
- super("CopilotKit interrupt: run paused awaiting human input");
232
- this.interrupts = interrupts;
233
- this.name = "InterruptSignal";
234
- }
235
- };
236
- /**
237
- * Define a tool for use with BuiltInAgent
238
- * @param name - The name of the tool
239
- * @param description - Description of what the tool does
240
- * @param parameters - Schema for the tool's input parameters (any Standard Schema V1 compatible library: Zod, Valibot, ArkType, etc.)
241
- * @param execute - Function to execute the tool server-side
242
- * @returns Tool definition
243
- */
244
- function defineTool(config) {
245
- return {
246
- name: config.name,
247
- description: config.description,
248
- parameters: config.parameters,
249
- execute: config.execute,
250
- interrupt: config.interrupt,
251
- interruptReason: config.interruptReason,
252
- interruptMessage: config.interruptMessage
253
- };
254
- }
255
- /**
256
- * Converts AG-UI user message content to Vercel AI SDK UserContent format.
257
- * Handles plain strings, new modality-specific parts (image/audio/video/document),
258
- * and legacy BinaryInputContent for backward compatibility.
259
- */
260
- function convertUserMessageContent(content) {
261
- if (!content) return "";
262
- if (typeof content === "string") return content;
263
- const parts = [];
264
- for (const part of content) {
265
- if (!part || typeof part !== "object" || !("type" in part)) continue;
266
- switch (part.type) {
267
- case "text": {
268
- const text = part.text;
269
- if (text) parts.push({
270
- type: "text",
271
- text
272
- });
273
- break;
274
- }
275
- case "image": {
276
- const source = part.source;
277
- if (!source) break;
278
- if (source.type === "data") parts.push({
279
- type: "image",
280
- image: source.value,
281
- mediaType: source.mimeType
282
- });
283
- else if (source.type === "file") warnDroppedFileSource("image part");
284
- else if (source.type === "url") try {
285
- parts.push({
286
- type: "image",
287
- image: new URL(source.value),
288
- mediaType: source.mimeType
289
- });
290
- } catch {
291
- console.error(`[CopilotKit] convertUserMessageContent: invalid URL "${source.value}" in image part — skipping`);
292
- }
293
- break;
294
- }
295
- case "audio":
296
- case "video":
297
- case "document": {
298
- const source = part.source;
299
- if (!source) break;
300
- if (source.type === "data") parts.push({
301
- type: "file",
302
- data: source.value,
303
- mediaType: source.mimeType
304
- });
305
- else if (source.type === "file") warnDroppedFileSource(`${part.type} part`);
306
- else if (source.type === "url") try {
307
- parts.push({
308
- type: "file",
309
- data: new URL(source.value),
310
- mediaType: source.mimeType ?? "application/octet-stream"
311
- });
312
- } catch {
313
- console.error(`[CopilotKit] convertUserMessageContent: invalid URL "${source.value}" in ${part.type} part — skipping`);
314
- }
315
- break;
316
- }
317
- case "binary": {
318
- const legacy = part;
319
- const mimeType = legacy.mimeType ?? "application/octet-stream";
320
- const isImage = mimeType.startsWith("image/");
321
- if (legacy.data) if (isImage) parts.push({
322
- type: "image",
323
- image: legacy.data,
324
- mediaType: mimeType
325
- });
326
- else parts.push({
327
- type: "file",
328
- data: legacy.data,
329
- mediaType: mimeType
330
- });
331
- else if (legacy.url) try {
332
- const url = new URL(legacy.url);
333
- if (isImage) parts.push({
334
- type: "image",
335
- image: url,
336
- mediaType: mimeType
337
- });
338
- else parts.push({
339
- type: "file",
340
- data: url,
341
- mediaType: mimeType
342
- });
343
- } catch {
344
- console.error(`[CopilotKit] convertUserMessageContent: invalid URL "${legacy.url}" in binary part — skipping`);
345
- }
346
- break;
347
- }
348
- default:
349
- console.error(`[CopilotKit] convertUserMessageContent: unrecognized content part type "${part.type}" — skipping`);
350
- break;
351
- }
352
- }
353
- return parts.length > 0 ? parts : "";
354
- }
355
- /**
356
- * Converts AG-UI messages to Vercel AI SDK ModelMessage format
357
- */
358
- function convertMessagesToVercelAISDKMessages(messages, options = {}) {
359
- const result = [];
360
- for (const message of messages) if (message.role === "system" && options.forwardSystemMessages) {
361
- const systemMsg = {
362
- role: "system",
363
- content: message.content ?? ""
364
- };
365
- result.push(systemMsg);
366
- } else if (message.role === "developer" && options.forwardDeveloperMessages) {
367
- const systemMsg = {
368
- role: "system",
369
- content: message.content ?? ""
370
- };
371
- result.push(systemMsg);
372
- } else if (message.role === "assistant") {
373
- const parts = message.content ? [{
374
- type: "text",
375
- text: message.content
376
- }] : [];
377
- for (const toolCall of message.toolCalls ?? []) {
378
- const toolCallPart = {
379
- type: "tool-call",
380
- toolCallId: toolCall.id,
381
- toolName: toolCall.function.name,
382
- input: (0, _copilotkit_shared.safeParseToolArgs)(toolCall.function.arguments),
383
- ...toolCall.encryptedValue ? { providerOptions: { google: { thoughtSignature: toolCall.encryptedValue } } } : {}
384
- };
385
- parts.push(toolCallPart);
386
- }
387
- const assistantMsg = {
388
- role: "assistant",
389
- content: parts
390
- };
391
- result.push(assistantMsg);
392
- } else if (message.role === "user") {
393
- const userMsg = {
394
- role: "user",
395
- content: convertUserMessageContent(message.content)
396
- };
397
- result.push(userMsg);
398
- } else if (message.role === "tool") {
399
- let toolName = "unknown";
400
- for (const msg of messages) if (msg.role === "assistant") {
401
- for (const toolCall of msg.toolCalls ?? []) if (toolCall.id === message.toolCallId) {
402
- toolName = toolCall.function.name;
403
- break;
404
- }
405
- }
406
- const toolMsg = {
407
- role: "tool",
408
- content: [{
409
- type: "tool-result",
410
- toolCallId: message.toolCallId,
411
- toolName,
412
- output: toolResultOutput(message.content)
413
- }]
414
- };
415
- result.push(toolMsg);
416
- }
417
- return result;
418
- }
419
- /**
420
- * Converts JSON Schema to Zod schema
421
- */
422
- function convertJsonSchemaToZodSchema(jsonSchema, required) {
423
- const describe = (schema) => jsonSchema.description ? schema.describe(jsonSchema.description) : schema;
424
- if (jsonSchema.type === "null") {
425
- const schema = describe(zod.z.null());
426
- return required ? schema : schema.optional();
427
- }
428
- const unionVariants = jsonSchema.anyOf ?? jsonSchema.oneOf;
429
- if (Array.isArray(unionVariants) && unionVariants.length > 0) {
430
- if (unionVariants.length === 1) return convertJsonSchemaToZodSchema(unionVariants[0], required);
431
- const variantSchemas = unionVariants.map((variant) => convertJsonSchemaToZodSchema(variant, true));
432
- const schema = describe(zod.z.union(variantSchemas));
433
- return required ? schema : schema.optional();
434
- }
435
- if (!jsonSchema.type) return required ? zod.z.object({}) : zod.z.object({}).optional();
436
- if (jsonSchema.type === "object") {
437
- const spec = {};
438
- if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) return !required ? zod.z.object(spec).optional() : zod.z.object(spec);
439
- for (const [key, value] of Object.entries(jsonSchema.properties)) spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false);
440
- const schema = describe(zod.z.object(spec));
441
- return required ? schema : schema.optional();
442
- } else if (jsonSchema.type === "string") {
443
- if (jsonSchema.enum && jsonSchema.enum.length > 0) {
444
- const schema = describe(zod.z.enum(jsonSchema.enum));
445
- return required ? schema : schema.optional();
446
- }
447
- const schema = describe(zod.z.string());
448
- return required ? schema : schema.optional();
449
- } else if (jsonSchema.type === "number" || jsonSchema.type === "integer") {
450
- const schema = describe(zod.z.number());
451
- return required ? schema : schema.optional();
452
- } else if (jsonSchema.type === "boolean") {
453
- const schema = describe(zod.z.boolean());
454
- return required ? schema : schema.optional();
455
- } else if (jsonSchema.type === "array") {
456
- if (!jsonSchema.items) throw new Error("Array type must have items property");
457
- const itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);
458
- const schema = describe(zod.z.array(itemSchema));
459
- return required ? schema : schema.optional();
460
- }
461
- console.error("Invalid JSON schema:", JSON.stringify(jsonSchema, null, 2));
462
- throw new Error("Invalid JSON schema");
463
- }
464
- /**
465
- * Converts AG-UI tools to Vercel AI SDK ToolSet
466
- */
467
- function isJsonSchema(obj) {
468
- if (typeof obj !== "object" || obj === null) return false;
469
- const schema = obj;
470
- if (Object.keys(schema).length === 0) return true;
471
- return typeof schema.type === "string" && [
472
- "object",
473
- "string",
474
- "number",
475
- "integer",
476
- "boolean",
477
- "array"
478
- ].includes(schema.type);
479
- }
480
- /**
481
- * Type-only pass-through for handing a Zod schema to the AI SDK's `tool()`.
482
- * The raw Zod schema is returned unchanged at runtime — the SDK's `asSchema()`
483
- * converts and validates it internally exactly as before.
484
- *
485
- * The Zod type is erased through `unknown` deliberately: letting tsc relate
486
- * Zod schema types to the AI SDK's `FlexibleSchema` union (conditional types
487
- * spanning zod v3/v4) makes type instantiation explode (TS2589 / compiler
488
- * OOM) under this package's `moduleResolution: node`.
489
- */
490
- function toLanguageModelSchema(schema) {
491
- return schema;
492
- }
493
- /** Preserve AG-UI tool schemas when passing them to the model provider. */
494
- function convertToolsToVercelAITools(tools) {
495
- const result = {};
496
- for (const tool of tools) {
497
- if (!isJsonSchema(tool.parameters)) throw new Error(`Invalid JSON schema for tool ${tool.name}`);
498
- const validator = new _cfworker_json_schema.Validator(tool.parameters, "7");
499
- result[tool.name] = (0, ai.tool)({
500
- description: tool.description,
501
- inputSchema: (0, ai.jsonSchema)(tool.parameters, { validate: (value) => {
502
- return validator.validate(value).valid ? {
503
- success: true,
504
- value
505
- } : {
506
- success: false,
507
- error: /* @__PURE__ */ new Error(`Invalid arguments for tool ${tool.name}`)
508
- };
509
- } }),
510
- ...tool.name === _ag_ui_a2ui_middleware.RENDER_A2UI_TOOL.name ? { strict: false } : {}
511
- });
512
- }
513
- return result;
514
- }
515
- /**
516
- * Check whether a schema is a Zod schema by inspecting its Standard Schema vendor.
517
- */
518
- function isZodSchema(schema) {
519
- return schema["~standard"]?.vendor === "zod";
520
- }
521
- /**
522
- * Converts ToolDefinition array to Vercel AI SDK ToolSet.
523
- *
524
- * For Zod schemas, passes them directly to the AI SDK (Zod satisfies FlexibleSchema).
525
- * For non-Zod schemas, converts to JSON Schema via schemaToJsonSchema() and wraps
526
- * with the AI SDK's jsonSchema() helper.
527
- */
528
- function convertToolDefinitionsToVercelAITools(tools) {
529
- const result = {};
530
- for (const tool of tools) if (isZodSchema(tool.parameters)) result[tool.name] = (0, ai.tool)({
531
- description: tool.description,
532
- inputSchema: tool.parameters,
533
- execute: tool.execute
534
- });
535
- else {
536
- const jsonSchemaObj = (0, _copilotkit_shared.schemaToJsonSchema)(tool.parameters);
537
- result[tool.name] = (0, ai.tool)({
538
- description: tool.description,
539
- inputSchema: (0, ai.jsonSchema)(jsonSchemaObj),
540
- execute: tool.execute
541
- });
542
- }
543
- return result;
544
- }
545
- /**
546
- * Type guard: returns true if this is a factory-mode config.
547
- */
548
- function isFactoryConfig(config) {
549
- return "factory" in config;
550
- }
551
- var BuiltInAgent = class BuiltInAgent extends _ag_ui_client.AbstractAgent {
552
- constructor(config) {
553
- super();
554
- this.config = config;
555
- if (!isFactoryConfig(config)) this.urlDownload = require_url_download.resolveUrlDownloadSetting(config.urlDownload);
556
- else if ("urlDownload" in config) throw new Error("BuiltInAgent: urlDownload has no effect in factory mode. Pass experimental_download: createSafeUrlDownload({ signal: ctx.abortSignal }) (from @copilotkit/runtime) to your own streamText() call instead.");
557
- this.skillRegistry = config.learnedSkills === void 0 ? void 0 : new require_registry.SkillRegistry(config.learnedSkills);
558
- this.modelHostClass = isFactoryConfig(config) ? "unknown" : classifyModelSpec(config.model);
559
- }
560
- /**
561
- * Check if a property can be overridden by forwardedProps
562
- */
563
- canOverride(property) {
564
- if (isFactoryConfig(this.config)) return false;
565
- return this.config?.overridableProperties?.includes(property) ?? false;
566
- }
567
- async getCapabilities() {
568
- const inferred = {
569
- tools: {
570
- supported: true,
571
- clientProvided: true
572
- },
573
- transport: { streaming: true },
574
- humanInTheLoop: { interrupts: true }
575
- };
576
- const capabilities = isFactoryConfig(this.config) ? void 0 : this.config.capabilities;
577
- if (!capabilities) return inferred;
578
- return {
579
- ...inferred,
580
- ...capabilities
581
- };
582
- }
583
- run(input) {
584
- if (isFactoryConfig(this.config)) return this.runFactory(input, this.config);
585
- const config = this.config;
586
- if (this.abortController) throw new Error("Agent is already running. Call abortRun() first or create a new instance.");
587
- this.abortController = new AbortController();
588
- const abortController = this.abortController;
589
- return new rxjs.Observable((subscriber) => {
590
- const startEvent = {
591
- type: _ag_ui_client.EventType.RUN_STARTED,
592
- threadId: input.threadId,
593
- runId: input.runId,
594
- protocolVersion: _ag_ui_client.PROTOCOL_VERSION
595
- };
596
- subscriber.next(startEvent);
597
- const model = resolveModel(config.model, config.apiKey);
598
- let systemPrompt = void 0;
599
- const hasPrompt = !!config.prompt;
600
- const hasContext = input.context && input.context.length > 0;
601
- const hasState = input.state !== void 0 && input.state !== null && !(typeof input.state === "object" && Object.keys(input.state).length === 0);
602
- if (hasPrompt || hasContext || hasState) {
603
- const parts = [];
604
- if (hasPrompt) parts.push(config.prompt);
605
- if (hasContext) {
606
- parts.push("\n## Context from the application\n");
607
- for (const ctx of input.context) parts.push(`${ctx.description}:\n${ctx.value}\n`);
608
- }
609
- if (hasState) parts.push(`
610
- ## Application State
611
- This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.
612
- \`\`\`json\n${JSON.stringify(input.state, null, 2)}\n\`\`\`\n`);
613
- systemPrompt = parts.join("");
614
- }
615
- const systemMessages = [];
616
- if (systemPrompt) systemMessages.push({
617
- role: "system",
618
- content: systemPrompt
619
- });
620
- const messages = convertMessagesToVercelAISDKMessages(input.messages, {
621
- forwardSystemMessages: config.forwardSystemMessages,
622
- forwardDeveloperMessages: config.forwardDeveloperMessages
623
- });
624
- const resumeEntries = input.resume ?? [];
625
- if (resumeEntries.length > 0) {
626
- const toolNameById = /* @__PURE__ */ new Map();
627
- for (const m of input.messages) {
628
- if (m.role !== "assistant") continue;
629
- for (const tc of m.toolCalls ?? []) if (tc.id && tc.function?.name) toolNameById.set(tc.id, tc.function.name);
630
- }
631
- const alreadyAnswered = /* @__PURE__ */ new Set();
632
- for (const m of messages) {
633
- if (m.role !== "tool" || !Array.isArray(m.content)) continue;
634
- for (const part of m.content) if (part && typeof part === "object" && "toolCallId" in part) alreadyAnswered.add(part.toolCallId);
635
- }
636
- for (const entry of resumeEntries) {
637
- if (alreadyAnswered.has(entry.interruptId)) continue;
638
- const value = entry.status === "cancelled" ? { status: "cancelled" } : entry.payload ?? { status: "resolved" };
639
- const toolResultMessage = {
640
- role: "tool",
641
- content: [{
642
- type: "tool-result",
643
- toolCallId: entry.interruptId,
644
- toolName: toolNameById.get(entry.interruptId) ?? "",
645
- output: {
646
- type: "json",
647
- value
648
- }
649
- }]
650
- };
651
- messages.push(toolResultMessage);
652
- }
653
- }
654
- let allTools = convertToolsToVercelAITools(input.tools);
655
- if (config.tools && config.tools.length > 0) {
656
- const configTools = convertToolDefinitionsToVercelAITools(config.tools);
657
- allTools = {
658
- ...allTools,
659
- ...configTools
660
- };
661
- }
662
- const streamTextParams = {
663
- model,
664
- messages,
665
- tools: allTools,
666
- toolChoice: config.toolChoice,
667
- stopWhen: config.maxSteps ? (0, ai.stepCountIs)(config.maxSteps) : void 0,
668
- maxOutputTokens: config.maxOutputTokens,
669
- temperature: config.temperature,
670
- topP: config.topP,
671
- topK: config.topK,
672
- presencePenalty: config.presencePenalty,
673
- frequencyPenalty: config.frequencyPenalty,
674
- stopSequences: config.stopSequences,
675
- seed: config.seed,
676
- providerOptions: config.providerOptions,
677
- maxRetries: config.maxRetries,
678
- experimental_download: this.urlDownload?.(abortController.signal)
679
- };
680
- if (input.forwardedProps && typeof input.forwardedProps === "object") {
681
- const props = input.forwardedProps;
682
- if (props.model !== void 0 && this.canOverride("model")) {
683
- if (typeof props.model === "string" || typeof props.model === "object") streamTextParams.model = resolveModel(props.model, config.apiKey);
684
- }
685
- if (props.toolChoice !== void 0 && this.canOverride("toolChoice")) {
686
- const toolChoice = props.toolChoice;
687
- if (toolChoice === "auto" || toolChoice === "required" || toolChoice === "none" || typeof toolChoice === "object" && toolChoice !== null && "type" in toolChoice && toolChoice.type === "tool") streamTextParams.toolChoice = toolChoice;
688
- }
689
- if (typeof props.maxOutputTokens === "number" && this.canOverride("maxOutputTokens")) streamTextParams.maxOutputTokens = props.maxOutputTokens;
690
- if (typeof props.temperature === "number" && this.canOverride("temperature")) streamTextParams.temperature = props.temperature;
691
- if (typeof props.topP === "number" && this.canOverride("topP")) streamTextParams.topP = props.topP;
692
- if (typeof props.topK === "number" && this.canOverride("topK")) streamTextParams.topK = props.topK;
693
- if (typeof props.presencePenalty === "number" && this.canOverride("presencePenalty")) streamTextParams.presencePenalty = props.presencePenalty;
694
- if (typeof props.frequencyPenalty === "number" && this.canOverride("frequencyPenalty")) streamTextParams.frequencyPenalty = props.frequencyPenalty;
695
- if (Array.isArray(props.stopSequences) && this.canOverride("stopSequences")) {
696
- if (props.stopSequences.every((item) => typeof item === "string")) streamTextParams.stopSequences = props.stopSequences;
697
- }
698
- if (typeof props.seed === "number" && this.canOverride("seed")) streamTextParams.seed = props.seed;
699
- if (typeof props.maxRetries === "number" && this.canOverride("maxRetries")) streamTextParams.maxRetries = props.maxRetries;
700
- if (props.providerOptions !== void 0 && this.canOverride("providerOptions")) {
701
- if (typeof props.providerOptions === "object" && props.providerOptions !== null) streamTextParams.providerOptions = props.providerOptions;
702
- }
703
- }
704
- const mcpClients = [];
705
- (async () => {
706
- let terminalEventEmitted = false;
707
- let messageId = (0, _copilotkit_shared.randomUUID)();
708
- let reasoningMessageId = (0, _copilotkit_shared.randomUUID)();
709
- let isInReasoning = false;
710
- const closeReasoningIfOpen = () => {
711
- if (!isInReasoning) return;
712
- isInReasoning = false;
713
- const reasoningMsgEnd = {
714
- type: _ag_ui_client.EventType.REASONING_MESSAGE_END,
715
- messageId: reasoningMessageId
716
- };
717
- subscriber.next(reasoningMsgEnd);
718
- const reasoningEnd = {
719
- type: _ag_ui_client.EventType.REASONING_END,
720
- messageId: reasoningMessageId
721
- };
722
- subscriber.next(reasoningEnd);
723
- };
724
- try {
725
- const learnedSkills = await require_learned_skills.prepareLearnedSkills(this.skillRegistry, abortController.signal);
726
- abortController.signal.throwIfAborted();
727
- if (learnedSkills.catalog) {
728
- systemMessages.unshift({
729
- role: "system",
730
- content: learnedSkills.catalog
731
- });
732
- if (config.maxSteps === void 0) streamTextParams.stopWhen = (0, ai.stepCountIs)(10);
733
- }
734
- streamTextParams.tools = {
735
- ...streamTextParams.tools,
736
- AGUISendStateSnapshot: (0, ai.tool)({
737
- description: "Replace the entire application state with a new snapshot",
738
- inputSchema: toLanguageModelSchema(zod.z.object({ snapshot: zod.z.any().describe("The complete new state object") })),
739
- execute: async ({ snapshot }) => {
740
- return {
741
- success: true,
742
- snapshot
743
- };
744
- }
745
- }),
746
- AGUISendStateDelta: (0, ai.tool)({
747
- description: "Apply incremental updates to application state using JSON Patch operations",
748
- inputSchema: toLanguageModelSchema(zod.z.object({ delta: zod.z.array(zod.z.object({
749
- op: zod.z.enum([
750
- "add",
751
- "replace",
752
- "remove"
753
- ]).describe("The operation to perform"),
754
- path: zod.z.string().describe("JSON Pointer path (e.g., '/foo/bar')"),
755
- value: zod.z.any().optional().describe("The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.")
756
- })).describe("Array of JSON Patch operations") })),
757
- execute: async ({ delta }) => {
758
- return {
759
- success: true,
760
- delta
761
- };
762
- }
763
- })
764
- };
765
- const mcpToolSources = [];
766
- const userMcpClients = config.mcpClients ?? [];
767
- for (const [index, client] of userMcpClients.entries()) {
768
- const mcpTools = await client.tools();
769
- abortController.signal.throwIfAborted();
770
- mcpToolSources.push({
771
- label: `mcp${index + 1}`,
772
- tools: mcpTools
773
- });
774
- }
775
- const allMcpServers = [...config.mcpServers ?? []];
776
- if (allMcpServers.length > 0) for (const [index, serverConfig] of allMcpServers.entries()) {
777
- const label = serverConfig.name ? require_mcp_tool_names.toToolNamePrefix(serverConfig.name) : `mcp${userMcpClients.length + index + 1}`;
778
- let transport;
779
- if (serverConfig.type === "http") transport = new _modelcontextprotocol_sdk_client_streamableHttp_js.StreamableHTTPClientTransport(new URL(serverConfig.url), serverConfig.options);
780
- else if (serverConfig.type === "sse") {
781
- const { SSEClientTransport } = await import("@modelcontextprotocol/sdk/client/sse.js");
782
- abortController.signal.throwIfAborted();
783
- transport = new SSEClientTransport(new URL(serverConfig.url), serverConfig.headers ? { requestInit: { headers: serverConfig.headers } } : void 0);
784
- }
785
- if (transport) {
786
- let mcpClient;
787
- try {
788
- mcpClient = await (0, _ai_sdk_mcp.createMCPClient)({ transport });
789
- } catch (err) {
790
- abortController.signal.throwIfAborted();
791
- console.error(`[CopilotKit] MCP server ${require_describe_endpoint.describeEndpoint(serverConfig.url)} failed to connect — skipping it for this run:`, err);
792
- continue;
793
- }
794
- if (abortController.signal.aborted) {
795
- await mcpClient.close();
796
- abortController.signal.throwIfAborted();
797
- }
798
- mcpClients.push(mcpClient);
799
- try {
800
- const mcpTools = await mcpClient.tools();
801
- abortController.signal.throwIfAborted();
802
- mcpToolSources.push({
803
- label,
804
- tools: mcpTools
805
- });
806
- } catch (err) {
807
- abortController.signal.throwIfAborted();
808
- console.error(`[CopilotKit] MCP server ${require_describe_endpoint.describeEndpoint(serverConfig.url)} tools() failed — skipping its tools for this run:`, err);
809
- }
810
- }
811
- }
812
- if (mcpToolSources.length > 0) streamTextParams.tools = require_mcp_tool_names.mergeMCPTools(streamTextParams.tools ?? {}, mcpToolSources);
813
- if (this.skillRegistry) {
814
- require_learned_skills.assertNoSkillToolConflicts(streamTextParams.tools ?? {});
815
- streamTextParams.tools = {
816
- ...streamTextParams.tools,
817
- ...learnedSkills.tools
818
- };
819
- }
820
- abortController.signal.throwIfAborted();
821
- const requestModel = streamTextParams.model;
822
- if (typeof requestModel === "object" && requestModel.modelId === "gpt-6-luna" && requestModel.provider === "openai.chat") streamTextParams.providerOptions = {
823
- ...streamTextParams.providerOptions,
824
- openai: {
825
- ...streamTextParams.providerOptions?.openai,
826
- reasoningEffort: "none"
827
- }
828
- };
829
- const response = (0, ai.streamText)({
830
- ...streamTextParams,
831
- ...messages.length > 0 ? { system: systemMessages.length > 0 ? systemMessages : void 0 } : { messages: systemMessages },
832
- abortSignal: abortController.signal,
833
- onError: ({ error }) => require_url_download.logModelCallError(error)
834
- });
835
- const interruptToolNames = new Set((isFactoryConfig(this.config) ? [] : this.config.tools ?? []).filter((t) => t.interrupt).map((t) => t.name));
836
- const interruptToolMeta = new Map((isFactoryConfig(this.config) ? [] : this.config.tools ?? []).filter((t) => t.interrupt).map((t) => [t.name, {
837
- reason: t.interruptReason ?? "tool_call",
838
- message: t.interruptMessage
839
- }]));
840
- const pendingInterrupts = [];
841
- const normalizeStateEvent = require_state_delta.createStateEventNormalizer(input.state);
842
- const toolCallStates = /* @__PURE__ */ new Map();
843
- const ensureToolCallState = (toolCallId) => {
844
- let state = toolCallStates.get(toolCallId);
845
- if (!state) {
846
- state = {
847
- started: false,
848
- hasArgsDelta: false,
849
- ended: false
850
- };
851
- toolCallStates.set(toolCallId, state);
852
- }
853
- return state;
854
- };
855
- const warnedUnknownPartTypes = /* @__PURE__ */ new Set();
856
- for await (const part of response.fullStream) {
857
- if (part.type !== "reasoning-delta") closeReasoningIfOpen();
858
- switch (part.type) {
859
- case "abort": {
860
- const abortEndEvent = {
861
- type: _ag_ui_client.EventType.RUN_FINISHED,
862
- threadId: input.threadId,
863
- runId: input.runId,
864
- ...input.protocolVersion !== void 0 ? { outcome: { type: "cancelled" } } : {}
865
- };
866
- subscriber.next(abortEndEvent);
867
- terminalEventEmitted = true;
868
- subscriber.complete();
869
- break;
870
- }
871
- case "reasoning-start": {
872
- reasoningMessageId = require_aisdk.resolveStreamPartMessageId("id" in part ? part.id : void 0);
873
- const reasoningStartEvent = {
874
- type: _ag_ui_client.EventType.REASONING_START,
875
- messageId: reasoningMessageId
876
- };
877
- subscriber.next(reasoningStartEvent);
878
- const reasoningMessageStart = {
879
- type: _ag_ui_client.EventType.REASONING_MESSAGE_START,
880
- messageId: reasoningMessageId,
881
- role: "reasoning"
882
- };
883
- subscriber.next(reasoningMessageStart);
884
- isInReasoning = true;
885
- break;
886
- }
887
- case "reasoning-delta": {
888
- const delta = part.text ?? "";
889
- if (!delta) break;
890
- const reasoningDeltaEvent = {
891
- type: _ag_ui_client.EventType.REASONING_MESSAGE_CONTENT,
892
- messageId: reasoningMessageId,
893
- delta
894
- };
895
- subscriber.next(reasoningDeltaEvent);
896
- break;
897
- }
898
- case "reasoning-end": break;
899
- case "tool-input-start": {
900
- const toolCallId = part.id;
901
- const state = ensureToolCallState(toolCallId);
902
- state.toolName = part.toolName;
903
- if (!state.started) {
904
- state.started = true;
905
- const startEvent = {
906
- type: _ag_ui_client.EventType.TOOL_CALL_START,
907
- parentMessageId: messageId,
908
- toolCallId,
909
- toolCallName: part.toolName
910
- };
911
- subscriber.next(startEvent);
912
- }
913
- break;
914
- }
915
- case "tool-input-delta": {
916
- const toolCallId = part.id;
917
- const state = ensureToolCallState(toolCallId);
918
- state.hasArgsDelta = true;
919
- const argsEvent = {
920
- type: _ag_ui_client.EventType.TOOL_CALL_ARGS,
921
- toolCallId,
922
- delta: part.delta
923
- };
924
- subscriber.next(argsEvent);
925
- break;
926
- }
927
- case "tool-input-end": break;
928
- case "text-start":
929
- messageId = require_aisdk.resolveStreamPartMessageId("id" in part ? part.id : void 0);
930
- break;
931
- case "text-delta": {
932
- const textDelta = "text" in part ? part.text : "";
933
- const textEvent = {
934
- type: _ag_ui_client.EventType.TEXT_MESSAGE_CHUNK,
935
- role: "assistant",
936
- messageId,
937
- delta: textDelta
938
- };
939
- subscriber.next(textEvent);
940
- break;
941
- }
942
- case "tool-call": {
943
- const toolCallId = part.toolCallId;
944
- const state = ensureToolCallState(toolCallId);
945
- state.toolName = part.toolName ?? state.toolName;
946
- if (!state.started) {
947
- state.started = true;
948
- const startEvent = {
949
- type: _ag_ui_client.EventType.TOOL_CALL_START,
950
- parentMessageId: messageId,
951
- toolCallId,
952
- toolCallName: part.toolName
953
- };
954
- subscriber.next(startEvent);
955
- }
956
- if (!state.hasArgsDelta && "input" in part && part.input !== void 0) {
957
- let serializedInput = "";
958
- if (typeof part.input === "string") serializedInput = part.input;
959
- else try {
960
- serializedInput = JSON.stringify(part.input);
961
- } catch {
962
- serializedInput = String(part.input);
963
- }
964
- if (serializedInput.length > 0) {
965
- const argsEvent = {
966
- type: _ag_ui_client.EventType.TOOL_CALL_ARGS,
967
- toolCallId,
968
- delta: serializedInput
969
- };
970
- subscriber.next(argsEvent);
971
- state.hasArgsDelta = true;
972
- }
973
- }
974
- if (!state.ended) {
975
- const signatureEvent = require_aisdk.toolCallThoughtSignatureEvent(toolCallId, part.providerMetadata);
976
- if (signatureEvent) subscriber.next(signatureEvent);
977
- state.ended = true;
978
- const endEvent = {
979
- type: _ag_ui_client.EventType.TOOL_CALL_END,
980
- toolCallId
981
- };
982
- subscriber.next(endEvent);
983
- }
984
- if (state.toolName && interruptToolNames.has(state.toolName)) {
985
- const meta = interruptToolMeta.get(state.toolName);
986
- pendingInterrupts.push({
987
- id: toolCallId,
988
- toolCallId,
989
- reason: meta?.reason ?? "tool_call",
990
- ...meta?.message ? { message: meta.message } : {}
991
- });
992
- }
993
- break;
994
- }
995
- case "tool-result": {
996
- const toolName = "toolName" in part && part.toolName || toolCallStates.get(part.toolCallId)?.toolName || "";
997
- if (toolName && interruptToolNames.has(toolName)) {
998
- toolCallStates.delete(part.toolCallId);
999
- break;
1000
- }
1001
- const legacyPart = part;
1002
- const toolResult = "output" in part ? part.output : "result" in legacyPart ? legacyPart.result : null;
1003
- toolCallStates.delete(part.toolCallId);
1004
- if (toolName === "AGUISendStateSnapshot" && toolResult && typeof toolResult === "object") {
1005
- const snapshot = toolResult.snapshot;
1006
- if (snapshot !== void 0) {
1007
- const stateSnapshotEvent = {
1008
- type: _ag_ui_client.EventType.STATE_SNAPSHOT,
1009
- snapshot
1010
- };
1011
- for (const event of normalizeStateEvent(stateSnapshotEvent)) subscriber.next(event);
1012
- }
1013
- } else if (toolName === "AGUISendStateDelta" && toolResult && typeof toolResult === "object") {
1014
- const delta = toolResult.delta;
1015
- if (delta !== void 0) {
1016
- const stateDeltaEvent = {
1017
- type: _ag_ui_client.EventType.STATE_DELTA,
1018
- delta
1019
- };
1020
- for (const event of normalizeStateEvent(stateDeltaEvent)) subscriber.next(event);
1021
- }
1022
- }
1023
- let serializedResult;
1024
- try {
1025
- serializedResult = JSON.stringify(toolResult);
1026
- } catch {
1027
- serializedResult = `[Unserializable tool result from ${toolName || part.toolCallId}]`;
1028
- }
1029
- const resultEvent = {
1030
- type: _ag_ui_client.EventType.TOOL_CALL_RESULT,
1031
- role: "tool",
1032
- messageId: (0, _copilotkit_shared.randomUUID)(),
1033
- toolCallId: part.toolCallId,
1034
- content: serializedResult
1035
- };
1036
- subscriber.next(resultEvent);
1037
- break;
1038
- }
1039
- case "tool-error": {
1040
- const toolCallId = part.toolCallId;
1041
- const toolName = "toolName" in part && part.toolName || toolCallStates.get(toolCallId)?.toolName || "";
1042
- if (toolName && interruptToolNames.has(toolName)) {
1043
- toolCallStates.delete(toolCallId);
1044
- break;
1045
- }
1046
- toolCallStates.delete(toolCallId);
1047
- const resultEvent = {
1048
- type: _ag_ui_client.EventType.TOOL_CALL_RESULT,
1049
- role: "tool",
1050
- messageId: (0, _copilotkit_shared.randomUUID)(),
1051
- toolCallId,
1052
- content: `Error: ${require_aisdk.formatToolError(part.error)}`
1053
- };
1054
- subscriber.next(resultEvent);
1055
- break;
1056
- }
1057
- case "finish": {
1058
- const model = streamTextParams.model;
1059
- const finishedEvent = {
1060
- type: _ag_ui_client.EventType.RUN_FINISHED,
1061
- threadId: input.threadId,
1062
- runId: input.runId,
1063
- ...require_aisdk.getAISDKRunFinishedDetails(part, {
1064
- provider: require_usage.isRecord(model) ? require_usage.getNonEmptyString(model.provider) : void 0,
1065
- model: require_usage.isRecord(model) ? require_usage.getNonEmptyString(model.modelId) : void 0
1066
- }),
1067
- ...pendingInterrupts.length > 0 ? { outcome: {
1068
- type: "interrupt",
1069
- interrupts: pendingInterrupts
1070
- } } : {}
1071
- };
1072
- subscriber.next(finishedEvent);
1073
- terminalEventEmitted = true;
1074
- subscriber.complete();
1075
- break;
1076
- }
1077
- case "error": {
1078
- if (abortController.signal.aborted) break;
1079
- const err = part.error ?? ("message" in part ? part.message : void 0) ?? ("cause" in part ? part.cause : void 0);
1080
- const runErrorEvent = {
1081
- type: _ag_ui_client.EventType.RUN_ERROR,
1082
- message: err instanceof Error ? err.message : typeof err === "string" ? err : `AI SDK stream error: ${JSON.stringify(part)}`,
1083
- threadId: input.threadId,
1084
- runId: input.runId
1085
- };
1086
- subscriber.next(runErrorEvent);
1087
- terminalEventEmitted = true;
1088
- if (err instanceof Error) subscriber.error(err);
1089
- else subscriber.error(new Error(typeof err === "string" ? err : `AI SDK stream error`));
1090
- break;
1091
- }
1092
- case "start":
1093
- case "start-step":
1094
- case "finish-step":
1095
- case "text-end":
1096
- case "source":
1097
- case "file":
1098
- case "tool-output-denied":
1099
- case "tool-approval-request":
1100
- case "raw": break;
1101
- default: {
1102
- const _exhaustive = part;
1103
- const unknownType = String(_exhaustive.type);
1104
- if (!warnedUnknownPartTypes.has(unknownType)) {
1105
- warnedUnknownPartTypes.add(unknownType);
1106
- console.warn(`[BuiltInAgent] Ignoring unhandled AI SDK stream part: ${unknownType}`);
1107
- }
1108
- break;
1109
- }
1110
- }
1111
- }
1112
- if (!terminalEventEmitted) {
1113
- closeReasoningIfOpen();
1114
- if (abortController.signal.aborted) {} else {
1115
- const finishedEvent = {
1116
- type: _ag_ui_client.EventType.RUN_FINISHED,
1117
- threadId: input.threadId,
1118
- runId: input.runId,
1119
- ...pendingInterrupts.length > 0 ? { outcome: {
1120
- type: "interrupt",
1121
- interrupts: pendingInterrupts
1122
- } } : {}
1123
- };
1124
- subscriber.next(finishedEvent);
1125
- }
1126
- terminalEventEmitted = true;
1127
- subscriber.complete();
1128
- }
1129
- } catch (error) {
1130
- closeReasoningIfOpen();
1131
- if (abortController.signal.aborted) subscriber.complete();
1132
- else {
1133
- const runErrorEvent = {
1134
- type: _ag_ui_client.EventType.RUN_ERROR,
1135
- message: error instanceof Error ? error.message : String(error),
1136
- threadId: input.threadId,
1137
- runId: input.runId
1138
- };
1139
- subscriber.next(runErrorEvent);
1140
- terminalEventEmitted = true;
1141
- subscriber.error(error);
1142
- }
1143
- } finally {
1144
- if (this.abortController === abortController) this.abortController = void 0;
1145
- await Promise.all(mcpClients.map((client) => client.close()));
1146
- }
1147
- })();
1148
- return () => {
1149
- abortController.abort();
1150
- if (this.abortController === abortController) this.abortController = void 0;
1151
- Promise.all(mcpClients.map((client) => client.close())).catch(() => {});
1152
- };
1153
- });
1154
- }
1155
- runFactory(input, config) {
1156
- if (this.abortController) throw new Error("Agent is already running. Call abortRun() first or create a new instance.");
1157
- this.abortController = new AbortController();
1158
- const controller = this.abortController;
1159
- return new rxjs.Observable((subscriber) => {
1160
- const startEvent = {
1161
- type: _ag_ui_client.EventType.RUN_STARTED,
1162
- threadId: input.threadId,
1163
- runId: input.runId,
1164
- protocolVersion: _ag_ui_client.PROTOCOL_VERSION
1165
- };
1166
- subscriber.next(startEvent);
1167
- const ctx = {
1168
- input,
1169
- abortController: controller,
1170
- abortSignal: controller.signal,
1171
- interrupt: async (interrupts) => {
1172
- const resume = input.resume ?? [];
1173
- const ids = new Set(interrupts.map((i) => i.id));
1174
- const matching = resume.filter((r) => ids.has(r.interruptId));
1175
- if (interrupts.length > 0 && matching.length === interrupts.length) return matching;
1176
- throw new InterruptSignal(interrupts);
1177
- }
1178
- };
1179
- (async () => {
1180
- const runFinishedDetails = {};
1181
- try {
1182
- const toolCallIds = new Set(input.messages.flatMap((message) => message.role === "assistant" ? (message.toolCalls ?? []).map((call) => call.id) : []));
1183
- const answeredToolMessages = input.messages.filter((message) => message.role === "tool");
1184
- const answeredToolCallIds = new Set(answeredToolMessages.map((message) => message.toolCallId));
1185
- const nativeResume = config.type === "custom" ? [] : input.resume ?? [];
1186
- const resumeToolMessages = [];
1187
- const decisionsByCall = /* @__PURE__ */ new Map();
1188
- for (const entry of nativeResume) {
1189
- if (!toolCallIds.has(entry.interruptId)) continue;
1190
- const content = JSON.stringify(entry.status === "cancelled" ? { status: "cancelled" } : entry.payload ?? { status: "resolved" });
1191
- if (decisionsByCall.has(entry.interruptId)) {
1192
- if (decisionsByCall.get(entry.interruptId) !== content) throw new Error(`Conflicting decisions for resumed tool call ${entry.interruptId}`);
1193
- continue;
1194
- }
1195
- decisionsByCall.set(entry.interruptId, content);
1196
- if (answeredToolCallIds.has(entry.interruptId)) continue;
1197
- resumeToolMessages.push({
1198
- id: (0, _copilotkit_shared.randomUUID)(),
1199
- role: "tool",
1200
- toolCallId: entry.interruptId,
1201
- content
1202
- });
1203
- }
1204
- const resumedIds = new Set(nativeResume.map((entry) => entry.interruptId));
1205
- const resumedResults = new Map([...answeredToolMessages, ...resumeToolMessages].filter((message) => resumedIds.has(message.toolCallId)).map((message) => [message.toolCallId, message.content]));
1206
- for (const message of resumeToolMessages) {
1207
- const event = {
1208
- type: _ag_ui_client.EventType.TOOL_CALL_RESULT,
1209
- messageId: message.id,
1210
- toolCallId: message.toolCallId,
1211
- role: "tool",
1212
- content: message.content
1213
- };
1214
- subscriber.next(event);
1215
- }
1216
- const factoryInput = resumeToolMessages.length > 0 && config.type !== "custom" ? {
1217
- ...input,
1218
- messages: [...input.messages, ...resumeToolMessages]
1219
- } : input;
1220
- const learnedSkills = await require_learned_skills.prepareLearnedSkills(this.skillRegistry, controller.signal);
1221
- controller.signal.throwIfAborted();
1222
- const factoryCtx = {
1223
- ...ctx,
1224
- input: factoryInput,
1225
- learnedSkills
1226
- };
1227
- let events;
1228
- let customRunFinishedEvent;
1229
- const pendingInterrupts = [];
1230
- switch (config.type) {
1231
- case "aisdk":
1232
- events = require_aisdk.convertAISDKStream((await config.factory(factoryCtx)).fullStream, controller.signal, pendingInterrupts, input.state, runFinishedDetails);
1233
- break;
1234
- case "tanstack":
1235
- events = require_tanstack.convertTanStackStream(await config.factory(factoryCtx), controller.signal, pendingInterrupts, input.state, runFinishedDetails);
1236
- break;
1237
- case "custom":
1238
- events = await config.factory(factoryCtx);
1239
- break;
1240
- default: {
1241
- const _exhaustive = config;
1242
- throw new Error(`Unknown agent config type: ${_exhaustive.type}`);
1243
- }
1244
- }
1245
- for await (const event of events) {
1246
- if (event.type === _ag_ui_client.EventType.TOOL_CALL_RESULT && "toolCallId" in event && typeof event.toolCallId === "string" && "content" in event && resumedResults.has(event.toolCallId)) {
1247
- if (resumedResults.get(event.toolCallId) !== event.content) throw new Error(`Conflicting result for resumed tool call ${event.toolCallId}`);
1248
- continue;
1249
- }
1250
- if (config.type === "custom" && event.type === _ag_ui_client.EventType.RUN_FINISHED) {
1251
- customRunFinishedEvent = event;
1252
- require_usage.collectStandardRunFinishedDetails(event, runFinishedDetails);
1253
- continue;
1254
- }
1255
- subscriber.next(event);
1256
- }
1257
- if (pendingInterrupts.length > 0 && !controller.signal.aborted) throw new InterruptSignal(pendingInterrupts);
1258
- if (!controller.signal.aborted) {
1259
- const finishedEvent = {
1260
- ...customRunFinishedEvent,
1261
- type: _ag_ui_client.EventType.RUN_FINISHED,
1262
- threadId: input.threadId,
1263
- runId: input.runId,
1264
- ...runFinishedDetails
1265
- };
1266
- subscriber.next(finishedEvent);
1267
- }
1268
- subscriber.complete();
1269
- } catch (error) {
1270
- if (error instanceof InterruptSignal) {
1271
- const finishedEvent = {
1272
- type: _ag_ui_client.EventType.RUN_FINISHED,
1273
- threadId: input.threadId,
1274
- runId: input.runId,
1275
- ...runFinishedDetails,
1276
- outcome: {
1277
- type: "interrupt",
1278
- interrupts: error.interrupts
1279
- }
1280
- };
1281
- subscriber.next(finishedEvent);
1282
- subscriber.complete();
1283
- } else if (controller.signal.aborted) subscriber.complete();
1284
- else {
1285
- const runErrorEvent = {
1286
- type: _ag_ui_client.EventType.RUN_ERROR,
1287
- message: error instanceof Error ? error.message : String(error),
1288
- threadId: input.threadId,
1289
- runId: input.runId
1290
- };
1291
- subscriber.next(runErrorEvent);
1292
- subscriber.error(error);
1293
- }
1294
- } finally {
1295
- if (this.abortController === controller) this.abortController = void 0;
1296
- }
1297
- })();
1298
- return () => {
1299
- controller.abort();
1300
- if (this.abortController === controller) this.abortController = void 0;
1301
- };
1302
- });
1303
- }
1304
- clone() {
1305
- const cloned = new BuiltInAgent({
1306
- ...this.config,
1307
- learnedSkills: void 0
1308
- });
1309
- cloned.config = this.config;
1310
- cloned.skillRegistry = this.skillRegistry;
1311
- cloned.middlewares = [...this.middlewares];
1312
- return cloned;
1313
- }
1314
- abortRun() {
1315
- this.abortController?.abort();
1316
- }
1317
- };
1318
-
1319
- //#endregion
1320
- exports.BuiltInAgent = BuiltInAgent;
1321
- exports.InterruptSignal = InterruptSignal;
1322
- exports.classifyModelSpec = classifyModelSpec;
1323
- exports.convertJsonSchemaToZodSchema = convertJsonSchemaToZodSchema;
1324
- exports.convertMessagesToVercelAISDKMessages = convertMessagesToVercelAISDKMessages;
1325
- exports.convertToolDefinitionsToVercelAITools = convertToolDefinitionsToVercelAITools;
1326
- exports.convertToolsToVercelAITools = convertToolsToVercelAITools;
1327
- exports.defineTool = defineTool;
1328
- exports.resolveModel = resolveModel;
1329
- //# sourceMappingURL=index.cjs.map