{{ message }}
Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
2655 lines (2493 loc) · 95.7 KB
/
Copy pathindex.ts
File metadata and controls
2655 lines (2493 loc) · 95.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { RENDER_A2UI_TOOL } from "@ag-ui/a2ui-middleware";
import type {
BaseEvent,
RunAgentInput,
Message,
ContentPart,
ReasoningEndEvent,
ReasoningMessageContentEvent,
ReasoningMessageEndEvent,
ReasoningMessageStartEvent,
ReasoningStartEvent,
RunFinishedEvent,
RunStartedEvent,
TextMessageChunkEvent,
ToolCallArgsEvent,
ToolCallEndEvent,
ToolCallStartEvent,
ToolCallResultEvent,
RunErrorEvent,
Interrupt,
ResumeEntry,
ToolMessage,
} from "@ag-ui/client";
import { AbstractAgent, EventType, PROTOCOL_VERSION } from "@ag-ui/client";
import { Validator } from "@cfworker/json-schema";
import type { AgentCapabilities } from "@ag-ui/core";
import type {
LanguageModel,
ModelMessage,
AssistantModelMessage,
UserModelMessage,
ToolModelMessage,
SystemModelMessage,
ToolCallPart,
ToolResultPart,
TextPart,
ImagePart,
FilePart,
ToolChoice,
ToolSet,
Schema,
} from "ai";
import { streamText, tool as createVercelAISDKTool, stepCountIs } from "ai";
import { createMCPClient } from "@ai-sdk/mcp";
import type { MCPClient, MCPTransport } from "@ai-sdk/mcp";
import { Observable } from "rxjs";
import { createOpenAI } from "@ai-sdk/openai";
import { createAnthropic } from "@ai-sdk/anthropic";
import { createGoogleGenerativeAI } from "@ai-sdk/google";
import { createVertex } from "@ai-sdk/google-vertex";
import { safeParseToolArgs, classifyModelHost } from "@copilotkit/shared";
import type { ModelHostClass } from "@copilotkit/shared";
import { z } from "zod";
import type { StandardSchemaV1, InferSchemaOutput } from "@copilotkit/shared";
import { schemaToJsonSchema } from "@copilotkit/shared";
import { jsonSchema as aiJsonSchema } from "ai";
import type { Experimental_DownloadFunction } from "ai";
import { logModelCallError, resolveUrlDownloadSetting } from "./url-download";
import type { SafeUrlDownloadOptions } from "./url-download";
import {
convertAISDKStream,
formatToolError,
getAISDKRunFinishedDetails,
resolveStreamPartMessageId,
} from "./converters/aisdk";
import { convertTanStackStream } from "./converters/tanstack";
import {
collectStandardRunFinishedDetails,
getNonEmptyString,
isRecord,
} from "./converters/usage";
import type { AgentRunFinishedDetails } from "./converters/usage";
import { createStateEventNormalizer } from "./state-delta";
import { describeEndpoint } from "../v1-deprecated/lib/runtime/mcp-client-cache";
import type { StreamableHTTPClientTransportOptions } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { randomUUID } from "@copilotkit/shared";
import { SkillRegistry } from "../v2/runtime/intelligence-platform/skill-registry";
import {
prepareLearnedSkills,
assertNoSkillToolConflicts,
} from "./learned-skills";
import type {
BuiltInAgentLearnedSkills,
BuiltInAgentLearnedSkillsOptions,
} from "./learned-skills";
export type {
BuiltInAgentLearnedSkills,
BuiltInAgentLearnedSkillsOptions,
} from "./learned-skills";
import { mergeMCPTools, toToolNamePrefix } from "./mcp-tool-names";
import type { MCPToolSource } from "./mcp-tool-names";
/**
* Properties that can be overridden by forwardedProps
* These match the exact parameter names in streamText
*/
export type OverridableProperty =
| "model"
| "toolChoice"
| "maxOutputTokens"
| "temperature"
| "topP"
| "topK"
| "presencePenalty"
| "frequencyPenalty"
| "stopSequences"
| "seed"
| "maxRetries"
| "prompt"
| "providerOptions";
/**
* Model identifiers for BuiltInAgent. The named entries are editor
* suggestions, not an allowlist: any provider model id is sent through
* unchanged.
*/
export type BuiltInAgentModel =
// OpenAI models
| "openai/gpt-5.5"
| "openai/gpt-5.4"
| "openai/gpt-5.4-mini"
| "openai/gpt-5"
| "openai/gpt-5-mini"
| "openai/gpt-4.1"
| "openai/gpt-4.1-mini"
| "openai/gpt-4.1-nano"
| "openai/gpt-4o"
| "openai/gpt-4o-mini"
// OpenAI reasoning series
| "openai/o3"
| "openai/o3-mini"
| "openai/o4-mini"
// Anthropic (Claude) models
| "anthropic/claude-sonnet-4-6"
| "anthropic/claude-sonnet-4-5"
| "anthropic/claude-opus-4-8"
| "anthropic/claude-haiku-4-5"
// Google (Gemini) models
| "google/gemini-3.8-flash"
| "google/gemini-3.5-flash"
| "google/gemini-3.5-flash-lite"
// MiniMax models
| "minimax/MiniMax-M3"
| "minimax/MiniMax-M2.7"
// Allow any LanguageModel instance
| (string & {});
/**
* Model specifier - can be a string like "openai/gpt-4o" or a LanguageModel instance
*/
export type ModelSpecifier = string | LanguageModel;
/**
* MCP Client configuration for HTTP transport
*/
export interface MCPClientConfigHTTP {
/** Type of MCP client */
type: "http";
/**
* Optional name for this server. When a tool name collides with another
* MCP server's tool or with an app tool, the MCP tool is exposed as
* `<name>_<tool>`. Without a name, the prefix is `mcp<N>`, where N is the
* server's position among `mcpClients` and then `mcpServers`, from 1.
* Give each server a different name: if a prefixed name is already in use,
* a number is added (`<name>_<tool>_2`).
*/
name?: string;
/** URL of the MCP server */
url: string;
/**
* Optional transport options for the underlying
* `StreamableHTTPClientTransport`. The SDK's documented extension point
* for per-request customization is `options.fetch` — pass a wrapped fetch
* here if you need static + dynamic headers on outbound MCP requests.
*/
options?: StreamableHTTPClientTransportOptions;
}
/**
* MCP Client configuration for SSE transport
*/
export interface MCPClientConfigSSE {
/** Type of MCP client */
type: "sse";
/**
* Optional name for this server. When a tool name collides with another
* MCP server's tool or with an app tool, the MCP tool is exposed as
* `<name>_<tool>`. Without a name, the prefix is `mcp<N>`, where N is the
* server's position among `mcpClients` and then `mcpServers`, from 1.
* Give each server a different name: if a prefixed name is already in use,
* a number is added (`<name>_<tool>_2`).
*/
name?: string;
/** URL of the MCP server */
url: string;
/** Optional HTTP headers (e.g., for authentication) */
headers?: Record<string, string>;
}
/**
* MCP Client configuration
*/
export type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;
/**
* A user-managed MCP client that provides tools to the agent.
* The user is responsible for creating, configuring, and closing the client.
* Compatible with the return type of @ai-sdk/mcp's createMCPClient().
*
* Unlike mcpServers, the agent does NOT create or close these clients.
* This allows persistent connections, custom auth, and tool caching.
*/
export interface MCPClientProvider {
/** Return tools to be merged into the agent's tool set. */
tools(): Promise<ToolSet>;
}
/**
* Resolves a model specifier to a LanguageModel instance
* @param spec - Model string (e.g., "openai/gpt-4o") or LanguageModel instance
* @param apiKey - Optional API key to use instead of environment variables
* @returns LanguageModel instance
*/
/**
* An AG-UI tool result as the AI SDK's tool result output.
*
* Providers hold one response per tool call, and the Google adapter emits one
* functionResponse per text entry of a content list, so all of a result's text
* is collected into a single entry: text parts run together, and a
* URL-referenced part contributes the URL it carries on a line of its own —
* the bytes are not here to hand over, and the reference is the content the
* tool actually returned. A result with no inline media is that text alone.
* One with inline media is a content list: the text entry first, when there is
* any, then each media part with its bytes and media type. A media-only result
* is media alone: a placeholder text would be content the tool never returned.
* Which adapters can place media inside a tool response is theirs to decide.
* A provider file handle (`file` source) is neither bytes nor a URL, and this
* path cannot hand it to the provider, so the part is dropped with a warning.
* A result whose parts were all dropped is the empty string, as AG-UI 1.0
* requires: the call must still be answered.
*/
function warnDroppedFileSource(what: string): void {
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.`,
);
}
function toolResultOutput(
content: ToolMessage["content"],
): ToolResultPart["output"] {
if (typeof content === "string") return { type: "text", value: content };
const segments: string[] = [];
const media: Array<{ type: "media"; data: string; mediaType: string }> = [];
let open = false; // whether the last segment is text still being appended to
for (const part of content) {
if (part.type === "text") {
if (open) segments[segments.length - 1] += part.text;
else segments.push(part.text);
open = true;
} else if (part.source.type === "file") {
warnDroppedFileSource(`${part.type} part in a tool result`);
} else if (part.source.type === "url") {
segments.push(part.source.value);
open = false;
} else {
media.push({
type: "media",
data: part.source.value,
mediaType: part.source.mimeType,
});
open = false;
}
}
const text = segments.join("\n");
if (media.length === 0) return { type: "text", value: text };
return {
type: "content",
value: [
...(text.length > 0 ? [{ type: "text" as const, text }] : []),
...media,
],
};
}
/**
* Split a model string into provider and model id. The provider is the text
* before the FIRST ":" or "/"; everything after it is the model id, unchanged.
* So "openai:meta-llama/llama-3.3-70b" keeps the slash in its model id, and
* "openai/ft:gpt-4o-mini:org::id" keeps its colons. Empty strings mean the
* part is missing.
*/
function parseModelSpec(spec: string): { provider: string; model: string } {
const trimmed = spec.trim();
const separator = trimmed.search(/[:/]/);
if (separator === -1) {
return { provider: trimmed.toLowerCase(), model: "" };
}
return {
provider: trimmed.slice(0, separator).toLowerCase(),
model: trimmed.slice(separator + 1).trim(),
};
}
/**
* Whether an `OPENAI_BASE_URL` should get Chat Completions instead of the
* Responses API. OpenAI's own hosts (including `*.api.openai.com`, such as the
* EU data-residency host) and Azure serve `/responses`, so they keep it, as
* does an unset value. Any other host gets `/chat/completions`, which is what
* most OpenAI-compatible servers implement. The host rule is
* `classifyModelHost`, the same one telemetry uses.
*
* A value `new URL` throws on keeps the Responses route; the request will
* fail on that base URL either way. A schemeless value such as
* `localhost:11434/v1` does not throw (it parses with scheme `localhost:` and
* an empty host), so it classifies as `other` and gets Chat Completions.
*/
function usesChatCompletions(baseURL: string | undefined): boolean {
const trimmed = baseURL?.trim();
if (!trimmed) return false;
try {
new URL(trimmed);
} catch {
return false;
}
const host = classifyModelHost(trimmed, "openai");
return host !== "openai" && host !== "azure";
}
/** Whether the Chat Completions notice below was already logged. */
let loggedChatCompletionsRoute = false;
/**
* Which OpenAI API an `openai/...` model string targets.
*
* `COPILOTKIT_OPENAI_API` (`responses` or `chat`) wins when set, so a proxy in
* front of OpenAI can keep the Responses API, and an OpenAI host can use Chat
* Completions. Unset or blank, `usesChatCompletions` decides from
* `OPENAI_BASE_URL`.
*
* When that rule picks Chat Completions, this logs once per process. Through a
* proxy, Chat Completions drops Responses-only features (such as reasoning
* summaries) without an error, and the notice names the way back.
*/
function openAIApiFor(baseURL: string | undefined): "responses" | "chat" {
const raw = process.env.COPILOTKIT_OPENAI_API;
const override = raw?.trim().toLowerCase();
if (override === "responses" || override === "chat") return override;
if (override) {
throw new Error(
`Invalid COPILOTKIT_OPENAI_API "${raw}". Use "responses" or "chat", or leave it unset.`,
);
}
if (!usesChatCompletions(baseURL)) return "responses";
if (!loggedChatCompletionsRoute) {
loggedChatCompletionsRoute = true;
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.',
);
}
return "chat";
}
export function resolveModel(
spec: ModelSpecifier,
apiKey?: string,
): LanguageModel {
// If already a LanguageModel instance, pass through
if (typeof spec !== "string") {
return spec;
}
const { provider, model } = parseModelSpec(spec);
if (!provider) {
throw new Error(
`Invalid model string "${spec}". Use "openai/gpt-5", "anthropic/claude-sonnet-4.5", or "google/gemini-3.8-flash".`,
);
}
if (!model) {
throw new Error(
`Invalid model string "${spec}". Use "openai/gpt-5", "anthropic/claude-sonnet-4.5", or "google/gemini-3.8-flash".`,
);
}
switch (provider) {
case "openai": {
// Lazily create OpenAI provider
// Use provided apiKey, or fall back to environment variable
const openai = createOpenAI({
apiKey: apiKey || process.env.OPENAI_API_KEY!,
// Honor an OpenAI-COMPATIBLE endpoint (Azure OpenAI, OpenRouter, a gateway,
// vLLM/LM Studio/Ollama, etc.) via the standard OPENAI_BASE_URL env var.
// Undefined when unset, so the provider falls back to its default
// (api.openai.com) — fully backward compatible.
baseURL: process.env.OPENAI_BASE_URL,
});
// Accepts any OpenAI model id, e.g. "gpt-4o", "gpt-4.1-mini", "o3-mini".
// `openai(model)` targets the Responses API (`{base}/responses`), which
// most OpenAI-compatible hosts do not serve. Off OpenAI and Azure hosts,
// use Chat Completions (`{base}/chat/completions`) instead, unless
// COPILOTKIT_OPENAI_API says otherwise.
return openAIApiFor(process.env.OPENAI_BASE_URL) === "chat"
? openai.chat(model)
: openai(model);
}
case "anthropic": {
// Lazily create Anthropic provider
// Use provided apiKey, or fall back to environment variable
const anthropic = createAnthropic({
apiKey: apiKey || process.env.ANTHROPIC_API_KEY!,
// Honor a custom Anthropic-compatible endpoint via ANTHROPIC_BASE_URL (see OpenAI note).
baseURL: process.env.ANTHROPIC_BASE_URL,
});
// Pass model identifiers through unchanged; the provider owns validation.
return anthropic(model);
}
case "google":
case "gemini":
case "google-gemini": {
// Lazily create Google provider
// Use provided apiKey, or fall back to environment variable
const google = createGoogleGenerativeAI({
apiKey: apiKey || process.env.GOOGLE_API_KEY!,
// Honor a custom Google-compatible endpoint via GOOGLE_GENERATIVE_AI_BASE_URL (see OpenAI note).
baseURL: process.env.GOOGLE_GENERATIVE_AI_BASE_URL,
});
// Accepts any Gemini id, e.g. "gemini-3.8-flash", "gemini-3.5-flash-lite"
return google(model);
}
case "minimax": {
const minimax = createOpenAI({
name: "minimax",
apiKey: apiKey || process.env.MINIMAX_API_KEY!,
baseURL: process.env.MINIMAX_BASE_URL || "https://api.minimax.io/v1",
});
return minimax(model);
}
case "vertex": {
const vertex = createVertex();
return vertex(model);
}
default:
throw new Error(
`Unknown provider "${provider}" in "${spec}". Supported: openai, anthropic, google (gemini).`,
);
}
}
/**
* Which vendor a model specifier will actually reach, as a closed vocabulary.
*
* `resolveModel` above is the only place this runtime builds a provider, so it
* is the only place that knows the endpoint. Once built, the endpoint is gone:
* an AI SDK model's `provider` names only the wire API (`"openai.responses"`
* on OpenAI and Azure, `"openai.chat"` on any other host), so it cannot tell
* OpenRouter from a laptop, and its base URL survives
* only inside a closure that the public `LanguageModelV3` type does not
* expose. Azure's own migration guide tells customers to use that same OpenAI
* client, so the case we are blindest to is the common one.
*
* A caller who hands us an already-built LanguageModel gets `unknown`. Nobody
* can recover the host from it, and saying so is more useful than guessing
* `openai` from a provider label that means only "speaks the OpenAI wire".
*
* The branches below mirror `resolveModel`'s switch and must change with it.
* `model-host-class.test.ts` walks every provider that switch accepts and
* fails if one lands here as `unknown`.
*/
export function classifyModelSpec(spec: ModelSpecifier): ModelHostClass {
// A pre-built model: the endpoint was decided before it reached us.
if (typeof spec !== "string") return "unknown";
const { provider } = parseModelSpec(spec);
switch (provider) {
case "openai":
return classifyModelHost(process.env.OPENAI_BASE_URL, "openai");
case "anthropic":
return classifyModelHost(process.env.ANTHROPIC_BASE_URL, "anthropic");
case "google":
case "gemini":
case "google-gemini":
return classifyModelHost(
process.env.GOOGLE_GENERATIVE_AI_BASE_URL,
"google",
);
case "minimax":
return classifyModelHost(
process.env.MINIMAX_BASE_URL || "https://api.minimax.io/v1",
"minimax",
);
case "vertex":
// `createVertex()` takes no base URL — the endpoint comes from ambient
// Google credentials, so there is nothing to classify and nothing to leak.
return "vertex";
default:
// `resolveModel` throws on anything else, so the run never starts.
return "unknown";
}
}
/**
* Thrown by `AgentFactoryContext.interrupt()` on a fresh (non-resume) run to
* pause the factory. Caught in `runFactory` and translated into a RUN_FINISHED
* event carrying `outcome:{type:"interrupt",interrupts}`. Not a real error.
*/
export class InterruptSignal extends Error {
constructor(public readonly interrupts: Interrupt[]) {
super("CopilotKit interrupt: run paused awaiting human input");
this.name = "InterruptSignal";
}
}
/**
* Tool definition for BuiltInAgent
*/
export interface ToolDefinition<
TParameters extends StandardSchemaV1 = StandardSchemaV1,
> {
name: string;
description: string;
parameters: TParameters;
/**
* Server-side executor. Optional ONLY for interrupt tools (`interrupt:true`),
* which pause the run instead of executing.
*/
execute?: (args: InferSchemaOutput<TParameters>) => Promise<unknown>;
/**
* When true, calling this tool pauses the run and emits a standard AG-UI
* interrupt (RUN_FINISHED outcome:interrupt) keyed by the tool call's id.
* The human response (resume payload) is injected as this tool call's result
* on the resume run. Interrupt tools must NOT define `execute`. The AI SDK
* pauses when a tool call has no result, even with a multi-step limit.
*/
interrupt?: boolean;
/** Optional categorical reason surfaced on the Interrupt (default: "tool_call"). */
interruptReason?: string;
/** Optional human-readable prompt surfaced on the Interrupt. */
interruptMessage?: string;
}
/**
* Define a tool for use with BuiltInAgent
* @param name - The name of the tool
* @param description - Description of what the tool does
* @param parameters - Schema for the tool's input parameters (any Standard Schema V1 compatible library: Zod, Valibot, ArkType, etc.)
* @param execute - Function to execute the tool server-side
* @returns Tool definition
*/
export function defineTool<TParameters extends StandardSchemaV1>(config: {
name: string;
description: string;
parameters: TParameters;
execute?: (args: InferSchemaOutput<TParameters>) => Promise<unknown>;
interrupt?: boolean;
interruptReason?: string;
interruptMessage?: string;
}): ToolDefinition<TParameters> {
return {
name: config.name,
description: config.description,
parameters: config.parameters,
execute: config.execute,
interrupt: config.interrupt,
interruptReason: config.interruptReason,
interruptMessage: config.interruptMessage,
};
}
type LegacyBinaryInputContent = {
type: "binary";
mimeType?: string;
data?: string;
url?: string;
};
/**
* Converts AG-UI user message content to Vercel AI SDK UserContent format.
* Handles plain strings, new modality-specific parts (image/audio/video/document),
* and legacy BinaryInputContent for backward compatibility.
*/
function convertUserMessageContent(
content: string | Array<ContentPart | LegacyBinaryInputContent>,
): string | Array<TextPart | ImagePart | FilePart> {
if (!content) {
return "";
}
if (typeof content === "string") {
return content;
}
const parts: Array<TextPart | ImagePart | FilePart> = [];
for (const part of content) {
if (!part || typeof part !== "object" || !("type" in part)) {
continue;
}
switch (part.type) {
case "text": {
const text = (part as { text?: string }).text;
if (text) {
parts.push({ type: "text", text });
}
break;
}
case "image": {
const source = (part as { source?: any }).source;
if (!source) break;
if (source.type === "data") {
parts.push({
type: "image",
image: source.value,
mediaType: source.mimeType,
});
} else if (source.type === "file") {
warnDroppedFileSource("image part");
} else if (source.type === "url") {
try {
parts.push({
type: "image",
image: new URL(source.value),
mediaType: source.mimeType,
});
} catch {
console.error(
`[CopilotKit] convertUserMessageContent: invalid URL "${source.value}" in image part — skipping`,
);
}
}
break;
}
case "audio":
case "video":
case "document": {
const source = (part as { source?: any }).source;
if (!source) break;
if (source.type === "data") {
parts.push({
type: "file",
data: source.value,
mediaType: source.mimeType,
});
} else if (source.type === "file") {
warnDroppedFileSource(`${part.type} part`);
} else if (source.type === "url") {
try {
parts.push({
type: "file",
data: new URL(source.value),
mediaType: source.mimeType ?? "application/octet-stream",
});
} catch {
console.error(
`[CopilotKit] convertUserMessageContent: invalid URL "${source.value}" in ${part.type} part — skipping`,
);
}
}
break;
}
// Legacy BinaryInputContent backward compatibility
case "binary": {
const legacy = part;
const mimeType = legacy.mimeType ?? "application/octet-stream";
const isImage = mimeType.startsWith("image/");
if (legacy.data) {
if (isImage) {
parts.push({
type: "image",
image: legacy.data,
mediaType: mimeType,
});
} else {
parts.push({
type: "file",
data: legacy.data,
mediaType: mimeType,
});
}
} else if (legacy.url) {
try {
const url = new URL(legacy.url);
if (isImage) {
parts.push({ type: "image", image: url, mediaType: mimeType });
} else {
parts.push({ type: "file", data: url, mediaType: mimeType });
}
} catch {
console.error(
`[CopilotKit] convertUserMessageContent: invalid URL "${legacy.url}" in binary part — skipping`,
);
}
}
break;
}
default: {
console.error(
`[CopilotKit] convertUserMessageContent: unrecognized content part type "${(part as { type: string }).type}" — skipping`,
);
break;
}
}
}
return parts.length > 0 ? parts : "";
}
/**
* Options for converting AG-UI messages to Vercel AI SDK format
*/
export interface MessageConversionOptions {
forwardSystemMessages?: boolean;
forwardDeveloperMessages?: boolean;
}
/**
* Converts AG-UI messages to Vercel AI SDK ModelMessage format
*/
export function convertMessagesToVercelAISDKMessages(
messages: Message[],
options: MessageConversionOptions = {},
): ModelMessage[] {
const result: ModelMessage[] = [];
for (const message of messages) {
if (message.role === "system" && options.forwardSystemMessages) {
const systemMsg: SystemModelMessage = {
role: "system",
content: message.content ?? "",
};
result.push(systemMsg);
} else if (
message.role === "developer" &&
options.forwardDeveloperMessages
) {
const systemMsg: SystemModelMessage = {
role: "system",
content: message.content ?? "",
};
result.push(systemMsg);
} else if (message.role === "assistant") {
const parts: Array<TextPart | ToolCallPart> = message.content
? [{ type: "text", text: message.content }]
: [];
for (const toolCall of message.toolCalls ?? []) {
const toolCallPart: ToolCallPart = {
type: "tool-call",
toolCallId: toolCall.id,
toolName: toolCall.function.name,
input: safeParseToolArgs(toolCall.function.arguments),
};
parts.push(toolCallPart);
}
const assistantMsg: AssistantModelMessage = {
role: "assistant",
content: parts,
};
result.push(assistantMsg);
} else if (message.role === "user") {
const userMsg: UserModelMessage = {
role: "user",
content: convertUserMessageContent(message.content),
};
result.push(userMsg);
} else if (message.role === "tool") {
let toolName = "unknown";
// Find the tool name from the corresponding tool call
for (const msg of messages) {
if (msg.role === "assistant") {
for (const toolCall of msg.toolCalls ?? []) {
if (toolCall.id === message.toolCallId) {
toolName = toolCall.function.name;
break;
}
}
}
}
const toolResultPart: ToolResultPart = {
type: "tool-result",
toolCallId: message.toolCallId,
toolName: toolName,
output: toolResultOutput(message.content),
};
const toolMsg: ToolModelMessage = {
role: "tool",
content: [toolResultPart],
};
result.push(toolMsg);
}
}
return result;
}
/**
* JSON Schema type definition
*/
interface JsonSchema {
type?:
| "object"
| "string"
| "number"
| "integer"
| "boolean"
| "array"
| "null";
description?: string;
properties?: Record<string, JsonSchema>;
required?: string[];
items?: JsonSchema;
enum?: string[];
// Union combinators. A frontend tool authored with `z.discriminatedUnion`
// (or any `z.union`) serializes to a node carrying `anyOf` / `oneOf` and
// usually NO top-level `type`.
anyOf?: JsonSchema[];
oneOf?: JsonSchema[];
}
/**
* Converts JSON Schema to Zod schema
*/
export function convertJsonSchemaToZodSchema(
jsonSchema: JsonSchema,
required: boolean,
): z.ZodSchema {
if (jsonSchema.type === "null") {
const schema = z.null().describe(jsonSchema.description ?? "");
return required ? schema : schema.optional();
}
// Handle `anyOf` / `oneOf` unions (e.g. `z.discriminatedUnion` or `z.union`
// on a frontend tool) as `z.union`. These nodes usually carry no top-level
// `type`, so they MUST be handled before the empty-schema guard below —
// otherwise the union collapses to an empty object (`z.object({})`), the
// reconstructed tool schema loses the union-typed field entirely, and the
// model can never emit it. This is especially load-bearing for a union
// nested inside array `items`, which OpenAI otherwise silently drops.
const unionVariants = jsonSchema.anyOf ?? jsonSchema.oneOf;
if (Array.isArray(unionVariants) && unionVariants.length > 0) {
// A single-variant union is just that variant.
if (unionVariants.length === 1) {
return convertJsonSchemaToZodSchema(unionVariants[0], required);
}
const variantSchemas = unionVariants.map((variant) =>
convertJsonSchemaToZodSchema(variant, true),
);
const schema = z
.union(variantSchemas as [z.ZodSchema, z.ZodSchema, ...z.ZodSchema[]])
.describe(jsonSchema.description ?? "");
return required ? schema : schema.optional();
}
// Handle empty schemas {} (no input required) - treat as empty object
if (!jsonSchema.type) {
return required ? z.object({}) : z.object({}).optional();
}
if (jsonSchema.type === "object") {
const spec: { [key: string]: z.ZodSchema } = {};
if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {
return !required ? z.object(spec).optional() : z.object(spec);
}
for (const [key, value] of Object.entries(jsonSchema.properties)) {
spec[key] = convertJsonSchemaToZodSchema(
value,
jsonSchema.required ? jsonSchema.required.includes(key) : false,
);
}
const schema = z.object(spec).describe(jsonSchema.description ?? "");
return required ? schema : schema.optional();
} else if (jsonSchema.type === "string") {
if (jsonSchema.enum && jsonSchema.enum.length > 0) {
const schema = z
.enum(jsonSchema.enum as [string, ...string[]])
.describe(jsonSchema.description ?? "");
return required ? schema : schema.optional();
}
const schema = z.string().describe(jsonSchema.description ?? "");
return required ? schema : schema.optional();
} else if (jsonSchema.type === "number" || jsonSchema.type === "integer") {
const schema = z.number().describe(jsonSchema.description ?? "");
return required ? schema : schema.optional();
} else if (jsonSchema.type === "boolean") {
const schema = z.boolean().describe(jsonSchema.description ?? "");
return required ? schema : schema.optional();
} else if (jsonSchema.type === "array") {
if (!jsonSchema.items) {
throw new Error("Array type must have items property");
}
const itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);
const schema = z.array(itemSchema).describe(jsonSchema.description ?? "");
return required ? schema : schema.optional();
}
console.error("Invalid JSON schema:", JSON.stringify(jsonSchema, null, 2));
throw new Error("Invalid JSON schema");
}
/**
* Converts AG-UI tools to Vercel AI SDK ToolSet
*/
function isJsonSchema(obj: unknown): obj is JsonSchema {
if (typeof obj !== "object" || obj === null) return false;
const schema = obj as Record<string, unknown>;
// Empty objects {} are valid JSON schemas (no input required)
if (Object.keys(schema).length === 0) return true;
return (
typeof schema.type === "string" &&
["object", "string", "number", "integer", "boolean", "array"].includes(
schema.type,
)
);
}
/**
* Type-only pass-through for handing a Zod schema to the AI SDK's `tool()`.
* The raw Zod schema is returned unchanged at runtime — the SDK's `asSchema()`
* converts and validates it internally exactly as before.
*
* The Zod type is erased through `unknown` deliberately: letting tsc relate
* Zod schema types to the AI SDK's `FlexibleSchema` union (conditional types
* spanning zod v3/v4) makes type instantiation explode (TS2589 / compiler
* OOM) under this package's `moduleResolution: node`.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function toLanguageModelSchema(schema: z.ZodSchema): Schema<any> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return schema as unknown as Schema<any>;
}
/** Preserve AG-UI tool schemas when passing them to the model provider. */
export function convertToolsToVercelAITools(
tools: RunAgentInput["tools"],
): ToolSet {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result: Record<string, any> = {};
for (const tool of tools) {
if (!isJsonSchema(tool.parameters)) {
throw new Error(`Invalid JSON schema for tool ${tool.name}`);
}
const validator = new Validator(tool.parameters, "7");
result[tool.name] = createVercelAISDKTool({
description: tool.description,
// AG-UI already supplies JSON Schema. A Zod round trip loses open object
// fields (including A2UI components), references, and other constraints.
inputSchema: aiJsonSchema(tool.parameters, {
validate: (value) => {
const result = validator.validate(value);
return result.valid
? { success: true, value }
: {
success: false,
error: new Error(`Invalid arguments for tool ${tool.name}`),
};
},
}),
// A2UI components require open objects. Other tools keep the provider's
// existing strictness default instead of opting every tool out.
...(tool.name === RENDER_A2UI_TOOL.name ? { strict: false } : {}),
});
}
return result;
}
/**
* Check whether a schema is a Zod schema by inspecting its Standard Schema vendor.
*/
function isZodSchema(schema: StandardSchemaV1): boolean {
return schema["~standard"]?.vendor === "zod";
}
/**
* Converts ToolDefinition array to Vercel AI SDK ToolSet.
*
* For Zod schemas, passes them directly to the AI SDK (Zod satisfies FlexibleSchema).
* For non-Zod schemas, converts to JSON Schema via schemaToJsonSchema() and wraps
* with the AI SDK's jsonSchema() helper.
*/
export function convertToolDefinitionsToVercelAITools(
You can’t perform that action at this time.
