forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
1693 lines (1563 loc) · 54 KB
/
Copy pathindex.ts
File metadata and controls
1693 lines (1563 loc) · 54 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 type {
BaseEvent,
RunAgentInput,
Message,
ReasoningEndEvent,
ReasoningMessageContentEvent,
ReasoningMessageEndEvent,
ReasoningMessageStartEvent,
ReasoningStartEvent,
RunFinishedEvent,
RunStartedEvent,
TextMessageChunkEvent,
ToolCallArgsEvent,
ToolCallEndEvent,
ToolCallStartEvent,
ToolCallResultEvent,
RunErrorEvent,
StateSnapshotEvent,
StateDeltaEvent,
} from "@ag-ui/client";
import { AbstractAgent, EventType } from "@ag-ui/client";
import type { AgentCapabilities } from "@ag-ui/core";
import type {
LanguageModel,
ModelMessage,
AssistantModelMessage,
UserModelMessage,
ToolModelMessage,
SystemModelMessage,
ToolCallPart,
ToolResultPart,
TextPart,
ImagePart,
FilePart,
ToolChoice,
ToolSet,
} from "ai";
import { streamText, tool as createVercelAISDKTool, stepCountIs } from "ai";
import { createMCPClient } from "@ai-sdk/mcp";
import type { MCPClient } 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 } 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 { convertAISDKStream } from "./converters/aisdk";
import { convertTanStackStream } from "./converters/tanstack";
import type { StreamableHTTPClientTransportOptions } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import { randomUUID } from "@copilotkit/shared";
/**
* 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";
/**
* Supported model identifiers for BuiltInAgent
*/
export type BuiltInAgentModel =
// OpenAI models
| "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.5"
| "anthropic/claude-sonnet-4"
| "anthropic/claude-3.7-sonnet"
| "anthropic/claude-opus-4.1"
| "anthropic/claude-opus-4"
| "anthropic/claude-3.5-haiku"
// Google (Gemini) models
| "google/gemini-2.5-pro"
| "google/gemini-2.5-flash"
| "google/gemini-2.5-flash-lite"
// 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";
/** 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";
/** 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
*/
export function resolveModel(
spec: ModelSpecifier,
apiKey?: string,
): LanguageModel {
// If already a LanguageModel instance, pass through
if (typeof spec !== "string") {
return spec;
}
// Normalize "provider/model" or "provider:model" format
const normalized = spec.replace("/", ":").trim();
const parts = normalized.split(":");
const rawProvider = parts[0];
const rest = parts.slice(1);
if (!rawProvider) {
throw new Error(
`Invalid model string "${spec}". Use "openai/gpt-5", "anthropic/claude-sonnet-4.5", or "google/gemini-2.5-pro".`,
);
}
const provider = rawProvider.toLowerCase();
const model = rest.join(":").trim();
if (!model) {
throw new Error(
`Invalid model string "${spec}". Use "openai/gpt-5", "anthropic/claude-sonnet-4.5", or "google/gemini-2.5-pro".`,
);
}
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!,
});
// Accepts any OpenAI model id, e.g. "gpt-4o", "gpt-4.1-mini", "o3-mini"
return 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!,
});
// Accepts any Claude id, e.g. "claude-3.7-sonnet", "claude-3.5-haiku"
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!,
});
// Accepts any Gemini id, e.g. "gemini-2.5-pro", "gemini-2.5-flash"
return google(model);
}
case "vertex": {
const vertex = createVertex();
return vertex(model);
}
default:
throw new Error(
`Unknown provider "${provider}" in "${spec}". Supported: openai, anthropic, google (gemini).`,
);
}
}
/**
* Tool definition for BuiltInAgent
*/
export interface ToolDefinition<
TParameters extends StandardSchemaV1 = StandardSchemaV1,
> {
name: string;
description: string;
parameters: TParameters;
execute: (args: InferSchemaOutput<TParameters>) => Promise<unknown>;
}
/**
* 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>;
}): ToolDefinition<TParameters> {
return {
name: config.name,
description: config.description,
parameters: config.parameters,
execute: config.execute,
};
}
type AGUIUserMessage = Extract<Message, { role: "user" }>;
/**
* 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: AGUIUserMessage["content"],
): 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 === "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 === "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 as {
mimeType?: string;
data?: string;
url?: string;
};
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: {
type: "text",
value: 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";
description?: string;
properties?: Record<string, JsonSchema>;
required?: string[];
items?: JsonSchema;
enum?: string[];
}
/**
* Converts JSON Schema to Zod schema
*/
export function convertJsonSchemaToZodSchema(
jsonSchema: JsonSchema,
required: boolean,
): z.ZodSchema {
// 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,
)
);
}
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 zodSchema = convertJsonSchemaToZodSchema(tool.parameters, true);
result[tool.name] = createVercelAISDKTool({
description: tool.description,
inputSchema: zodSchema,
});
}
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(
tools: ToolDefinition[],
): ToolSet {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result: Record<string, any> = {};
for (const tool of tools) {
if (isZodSchema(tool.parameters)) {
// Zod schemas can be passed directly to AI SDK (satisfies FlexibleSchema)
result[tool.name] = createVercelAISDKTool({
description: tool.description,
inputSchema: tool.parameters as any,
execute: tool.execute,
});
} else {
// Non-Zod: convert to JSON Schema and wrap with AI SDK's jsonSchema()
const jsonSchemaObj = schemaToJsonSchema(tool.parameters);
result[tool.name] = createVercelAISDKTool({
description: tool.description,
inputSchema: aiJsonSchema(jsonSchemaObj),
execute: tool.execute,
});
}
}
return result;
}
/**
* Context passed to the user-supplied factory function in factory mode.
*/
export interface AgentFactoryContext {
input: RunAgentInput;
/**
* Prefer `abortSignal` for most use cases (AI SDK, fetch, custom backends).
* Provided for backends like TanStack AI that require the full AbortController.
* Do NOT call `.abort()` on this controller — use `abortRun()` on the agent instead.
*/
abortController: AbortController;
abortSignal: AbortSignal;
}
/**
* Factory config for AI SDK backend.
* The factory must return an object with a `fullStream` async iterable
* (compatible with the result of `streamText()` — only `fullStream` is consumed).
*/
export interface BuiltInAgentAISDKFactoryConfig {
type: "aisdk";
factory: (
ctx: AgentFactoryContext,
) =>
| { fullStream: AsyncIterable<unknown> }
| Promise<{ fullStream: AsyncIterable<unknown> }>;
}
/**
* Factory config for TanStack AI backend.
* The factory must return an async iterable of TanStack AI stream chunks.
*/
export interface BuiltInAgentTanStackFactoryConfig {
type: "tanstack";
factory: (
ctx: AgentFactoryContext,
) => AsyncIterable<unknown> | Promise<AsyncIterable<unknown>>;
}
/**
* Factory config for a custom backend that directly yields AG-UI events.
*/
export interface BuiltInAgentCustomFactoryConfig {
type: "custom";
factory: (
ctx: AgentFactoryContext,
) => AsyncIterable<BaseEvent> | Promise<AsyncIterable<BaseEvent>>;
}
/**
* Union of all factory-mode configurations.
*/
export type BuiltInAgentFactoryConfig =
| BuiltInAgentAISDKFactoryConfig
| BuiltInAgentTanStackFactoryConfig
| BuiltInAgentCustomFactoryConfig;
/**
* Classic config — BuiltInAgent handles streamText, tools, MCP, state tools, prompt building.
*/
export interface BuiltInAgentClassicConfig {
/**
* The model to use
*/
model: BuiltInAgentModel | LanguageModel;
/**
* API key for the model provider (OpenAI, Anthropic, Google)
* If not provided, falls back to environment variables:
* - OPENAI_API_KEY for OpenAI models
* - ANTHROPIC_API_KEY for Anthropic models
* - GOOGLE_API_KEY for Google models
*/
apiKey?: string;
/**
* Maximum number of steps/iterations for tool calling (default: 1)
*/
maxSteps?: number;
/**
* Tool choice setting - how tools are selected for execution (default: "auto")
*/
toolChoice?: ToolChoice<Record<string, unknown>>;
/**
* Maximum number of tokens to generate
*/
maxOutputTokens?: number;
/**
* Temperature setting (range depends on provider)
*/
temperature?: number;
/**
* Nucleus sampling (topP)
*/
topP?: number;
/**
* Top K sampling
*/
topK?: number;
/**
* Presence penalty
*/
presencePenalty?: number;
/**
* Frequency penalty
*/
frequencyPenalty?: number;
/**
* Sequences that will stop the generation
*/
stopSequences?: string[];
/**
* Seed for deterministic results
*/
seed?: number;
/**
* Maximum number of retries
*/
maxRetries?: number;
/**
* Prompt for the agent
*/
prompt?: string;
/**
* List of properties that can be overridden by forwardedProps.
*/
overridableProperties?: OverridableProperty[];
/**
* Optional list of MCP server configurations
*/
mcpServers?: MCPClientConfig[];
/**
* Optional list of user-managed MCP clients.
* Unlike mcpServers, the agent does NOT create or close these clients.
* The user controls the lifecycle, persistence, auth, and caching.
*
* Compatible with @ai-sdk/mcp's createMCPClient() return type:
* ```typescript
* const client = await createMCPClient({ transport });
* const agent = new BuiltInAgent({ model: "...", mcpClients: [client] });
* ```
*/
mcpClients?: MCPClientProvider[];
/**
* Optional tools available to the agent
*/
tools?: ToolDefinition[];
/**
* Forward system-role messages from input to the LLM.
* Default: false
*/
forwardSystemMessages?: boolean;
/**
* Forward developer-role messages from input to the LLM (as system messages).
* Default: false
*/
forwardDeveloperMessages?: boolean;
/**
* Provider-specific options passed to the model (e.g., OpenAI reasoningEffort).
* Example: `{ openai: { reasoningEffort: "high" } }`
*/
providerOptions?: Record<string, any>;
/**
* Explicit agent capabilities. **Shallow-merged** at the category level on
* top of auto-inferred defaults — providing a category (e.g. `tools`)
* replaces that entire category, not individual fields within it.
*
* For example, `{ tools: { supported: true } }` will drop the inferred
* `clientProvided` value. Include all fields for any category you override.
*/
capabilities?: Partial<AgentCapabilities>;
}
/**
* Configuration for BuiltInAgent.
*
* Two modes:
* - **Classic** (model + params): BuiltInAgent handles everything — streamText, tools, MCP, state tools.
* - **Factory** (type + factory): You own the LLM call. BuiltInAgent handles lifecycle only.
*/
export type BuiltInAgentConfiguration =
| BuiltInAgentClassicConfig
| BuiltInAgentFactoryConfig;
/**
* Type guard: returns true if this is a factory-mode config.
*/
function isFactoryConfig(
config: BuiltInAgentConfiguration,
): config is BuiltInAgentFactoryConfig {
return "factory" in config;
}
export class BuiltInAgent extends AbstractAgent {
private abortController?: AbortController;
constructor(private config: BuiltInAgentConfiguration) {
super();
}
/**
* Check if a property can be overridden by forwardedProps
*/
canOverride(property: OverridableProperty): boolean {
if (isFactoryConfig(this.config)) return false;
return this.config?.overridableProperties?.includes(property) ?? false;
}
async getCapabilities(): Promise<AgentCapabilities> {
const inferred: AgentCapabilities = {
tools: {
supported: true,
clientProvided: true,
},
transport: {
streaming: true,
},
};
if (!this.config.capabilities) {
return inferred;
}
// Shallow merge at the category level — explicit overrides replace
// entire categories when provided, inferred defaults fill the rest.
return {
...inferred,
...this.config.capabilities,
};
}
run(input: RunAgentInput): Observable<BaseEvent> {
if (isFactoryConfig(this.config)) {
return this.runFactory(input, this.config);
}
if (this.abortController) {
throw new Error(
"Agent is already running. Call abortRun() first or create a new instance.",
);
}
// Set synchronously before Observable creation to close TOCTOU window
this.abortController = new AbortController();
const abortController = this.abortController;
return new Observable<BaseEvent>((subscriber) => {
// Emit RUN_STARTED event
const startEvent: RunStartedEvent = {
type: EventType.RUN_STARTED,
threadId: input.threadId,
runId: input.runId,
};
subscriber.next(startEvent);
// Resolve the model, passing API key if provided
const model = resolveModel(this.config.model, this.config.apiKey);
// Build prompt based on conditions
let systemPrompt: string | undefined = undefined;
// Check if we should build a prompt:
// - config.prompt is set, OR
// - input.context is non-empty, OR
// - input.state is non-empty and not an empty object
const hasPrompt = !!this.config.prompt;
const hasContext = input.context && input.context.length > 0;
const hasState =
input.state !== undefined &&
input.state !== null &&
!(
typeof input.state === "object" &&
Object.keys(input.state).length === 0
);
if (hasPrompt || hasContext || hasState) {
const parts: string[] = [];
// First: the prompt if any
if (hasPrompt) {
parts.push(this.config.prompt!);
}
// Second: context from the application
if (hasContext) {
parts.push("\n## Context from the application\n");
for (const ctx of input.context) {
parts.push(`${ctx.description}:\n${ctx.value}\n`);
}
}
// Third: state from the application that can be edited
if (hasState) {
parts.push(
"\n## Application State\n" +
"This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.\n" +
`\`\`\`json\n${JSON.stringify(input.state, null, 2)}\n\`\`\`\n`,
);
}
systemPrompt = parts.join("");
}
// Convert messages and prepend system message if we have a prompt
const messages = convertMessagesToVercelAISDKMessages(input.messages, {
forwardSystemMessages: this.config.forwardSystemMessages,
forwardDeveloperMessages: this.config.forwardDeveloperMessages,
});
if (systemPrompt) {
messages.unshift({
role: "system",
content: systemPrompt,
});
}
// Merge tools from input and config
let allTools: ToolSet = convertToolsToVercelAITools(input.tools);
if (this.config.tools && this.config.tools.length > 0) {
const configTools = convertToolDefinitionsToVercelAITools(
this.config.tools,
);
allTools = { ...allTools, ...configTools };
}
const streamTextParams: Parameters<typeof streamText>[0] = {
model,
messages,
tools: allTools,
toolChoice: this.config.toolChoice,
stopWhen: this.config.maxSteps
? stepCountIs(this.config.maxSteps)
: undefined,
maxOutputTokens: this.config.maxOutputTokens,
temperature: this.config.temperature,
topP: this.config.topP,
topK: this.config.topK,
presencePenalty: this.config.presencePenalty,
frequencyPenalty: this.config.frequencyPenalty,
stopSequences: this.config.stopSequences,
seed: this.config.seed,
providerOptions: this.config.providerOptions,
maxRetries: this.config.maxRetries,
};
// Apply forwardedProps overrides (if allowed)
if (input.forwardedProps && typeof input.forwardedProps === "object") {
const props = input.forwardedProps as Record<string, unknown>;
// Check and apply each overridable property
if (props.model !== undefined && this.canOverride("model")) {
if (
typeof props.model === "string" ||
typeof props.model === "object"