@copilotkitnext/agent 0.0.31 → 0.0.32

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.
@@ -1,23 +1,23 @@
1
1
 
2
2
  
3
- > @copilotkitnext/agent@0.0.31 build /Users/mikeryan/Repos/cpk/vnext_experimental/packages/agent
3
+ > @copilotkitnext/agent@0.0.31 build /Users/ran/Desktop/vnext_experimental/packages/agent
4
4
  > tsup
5
5
 
6
6
  CLI Building entry: src/index.ts
7
7
  CLI Using tsconfig: tsconfig.json
8
8
  CLI tsup v8.5.0
9
- CLI Using tsup config: /Users/mikeryan/Repos/cpk/vnext_experimental/packages/agent/tsup.config.ts
9
+ CLI Using tsup config: /Users/ran/Desktop/vnext_experimental/packages/agent/tsup.config.ts
10
10
  CLI Target: es2022
11
11
  CLI Cleaning output folder
12
12
  CJS Build start
13
13
  ESM Build start
14
- ESM dist/index.mjs 21.50 KB
15
- ESM dist/index.mjs.map 44.85 KB
16
- ESM ⚡️ Build success in 18ms
17
- CJS dist/index.js 23.31 KB
18
- CJS dist/index.js.map 44.89 KB
19
- CJS ⚡️ Build success in 19ms
14
+ ESM dist/index.mjs 21.68 KB
15
+ ESM dist/index.mjs.map 45.21 KB
16
+ ESM ⚡️ Build success in 16ms
17
+ CJS dist/index.js 23.53 KB
18
+ CJS dist/index.js.map 45.26 KB
19
+ CJS ⚡️ Build success in 18ms
20
20
  DTS Build start
21
- DTS ⚡️ Build success in 1078ms
22
- DTS dist/index.d.ts 6.07 KB
23
- DTS dist/index.d.mts 6.07 KB
21
+ DTS ⚡️ Build success in 2032ms
22
+ DTS dist/index.d.ts 6.25 KB
23
+ DTS dist/index.d.mts 6.25 KB
package/dist/index.d.mts CHANGED
@@ -10,9 +10,9 @@ import { StreamableHTTPClientTransportOptions } from '@modelcontextprotocol/sdk/
10
10
  */
11
11
  type OverridableProperty = "model" | "toolChoice" | "maxOutputTokens" | "temperature" | "topP" | "topK" | "presencePenalty" | "frequencyPenalty" | "stopSequences" | "seed" | "maxRetries" | "prompt";
12
12
  /**
13
- * Supported model identifiers for BasicAgent
13
+ * Supported model identifiers for BuiltInAgent
14
14
  */
15
- type BasicAgentModel = "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/o3" | "openai/o3-mini" | "openai/o4-mini" | "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-2.5-pro" | "google/gemini-2.5-flash" | "google/gemini-2.5-flash-lite" | (string & {});
15
+ type BuiltInAgentModel = "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/o3" | "openai/o3-mini" | "openai/o4-mini" | "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-2.5-pro" | "google/gemini-2.5-flash" | "google/gemini-2.5-flash-lite" | (string & {});
16
16
  /**
17
17
  * Model specifier - can be a string like "openai/gpt-4o" or a LanguageModel instance
18
18
  */
@@ -62,7 +62,7 @@ type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;
62
62
  */
63
63
  declare function resolveModel(spec: ModelSpecifier): LanguageModel;
64
64
  /**
65
- * Tool definition for BasicAgent
65
+ * Tool definition for BuiltInAgent
66
66
  */
67
67
  interface ToolDefinition<TParameters extends z.ZodTypeAny = z.ZodTypeAny> {
68
68
  name: string;
@@ -71,7 +71,7 @@ interface ToolDefinition<TParameters extends z.ZodTypeAny = z.ZodTypeAny> {
71
71
  execute: (args: z.infer<TParameters>) => Promise<unknown>;
72
72
  }
73
73
  /**
74
- * Define a tool for use with BasicAgent
74
+ * Define a tool for use with BuiltInAgent
75
75
  * @param name - The name of the tool
76
76
  * @param description - Description of what the tool does
77
77
  * @param parameters - Zod schema for the tool's input parameters
@@ -108,13 +108,13 @@ declare function convertToolsToVercelAITools(tools: RunAgentInput["tools"]): Too
108
108
  */
109
109
  declare function convertToolDefinitionsToVercelAITools(tools: ToolDefinition[]): ToolSet;
110
110
  /**
111
- * Configuration for BasicAgent
111
+ * Configuration for BuiltInAgent
112
112
  */
113
- interface BasicAgentConfiguration {
113
+ interface BuiltInAgentConfiguration {
114
114
  /**
115
115
  * The model to use
116
116
  */
117
- model: BasicAgentModel | LanguageModel;
117
+ model: BuiltInAgentModel | LanguageModel;
118
118
  /**
119
119
  * Maximum number of steps/iterations for tool calling (default: 1)
120
120
  */
@@ -176,17 +176,23 @@ interface BasicAgentConfiguration {
176
176
  */
177
177
  tools?: ToolDefinition[];
178
178
  }
179
- declare class BasicAgent extends AbstractAgent {
179
+ declare class BuiltInAgent extends AbstractAgent {
180
180
  private config;
181
181
  private abortController?;
182
- constructor(config: BasicAgentConfiguration);
182
+ constructor(config: BuiltInAgentConfiguration);
183
183
  /**
184
184
  * Check if a property can be overridden by forwardedProps
185
185
  */
186
186
  canOverride(property: OverridableProperty): boolean;
187
187
  run(input: RunAgentInput): Observable<BaseEvent>;
188
- clone(): BasicAgent;
188
+ clone(): BuiltInAgent;
189
189
  abortRun(): void;
190
190
  }
191
+ /**
192
+ * @deprecated Use BuiltInAgent instead
193
+ */
194
+ declare class BasicAgent extends BuiltInAgent {
195
+ constructor(config: BuiltInAgentConfiguration);
196
+ }
191
197
 
192
- export { BasicAgent, type BasicAgentConfiguration, type BasicAgentModel, type MCPClientConfig, type MCPClientConfigHTTP, type MCPClientConfigSSE, type ModelSpecifier, type OverridableProperty, type ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel };
198
+ export { BasicAgent, BuiltInAgent, type BuiltInAgentConfiguration, type BuiltInAgentModel, type MCPClientConfig, type MCPClientConfigHTTP, type MCPClientConfigSSE, type ModelSpecifier, type OverridableProperty, type ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel };
package/dist/index.d.ts CHANGED
@@ -10,9 +10,9 @@ import { StreamableHTTPClientTransportOptions } from '@modelcontextprotocol/sdk/
10
10
  */
11
11
  type OverridableProperty = "model" | "toolChoice" | "maxOutputTokens" | "temperature" | "topP" | "topK" | "presencePenalty" | "frequencyPenalty" | "stopSequences" | "seed" | "maxRetries" | "prompt";
12
12
  /**
13
- * Supported model identifiers for BasicAgent
13
+ * Supported model identifiers for BuiltInAgent
14
14
  */
15
- type BasicAgentModel = "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/o3" | "openai/o3-mini" | "openai/o4-mini" | "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-2.5-pro" | "google/gemini-2.5-flash" | "google/gemini-2.5-flash-lite" | (string & {});
15
+ type BuiltInAgentModel = "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/o3" | "openai/o3-mini" | "openai/o4-mini" | "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-2.5-pro" | "google/gemini-2.5-flash" | "google/gemini-2.5-flash-lite" | (string & {});
16
16
  /**
17
17
  * Model specifier - can be a string like "openai/gpt-4o" or a LanguageModel instance
18
18
  */
@@ -62,7 +62,7 @@ type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;
62
62
  */
63
63
  declare function resolveModel(spec: ModelSpecifier): LanguageModel;
64
64
  /**
65
- * Tool definition for BasicAgent
65
+ * Tool definition for BuiltInAgent
66
66
  */
67
67
  interface ToolDefinition<TParameters extends z.ZodTypeAny = z.ZodTypeAny> {
68
68
  name: string;
@@ -71,7 +71,7 @@ interface ToolDefinition<TParameters extends z.ZodTypeAny = z.ZodTypeAny> {
71
71
  execute: (args: z.infer<TParameters>) => Promise<unknown>;
72
72
  }
73
73
  /**
74
- * Define a tool for use with BasicAgent
74
+ * Define a tool for use with BuiltInAgent
75
75
  * @param name - The name of the tool
76
76
  * @param description - Description of what the tool does
77
77
  * @param parameters - Zod schema for the tool's input parameters
@@ -108,13 +108,13 @@ declare function convertToolsToVercelAITools(tools: RunAgentInput["tools"]): Too
108
108
  */
109
109
  declare function convertToolDefinitionsToVercelAITools(tools: ToolDefinition[]): ToolSet;
110
110
  /**
111
- * Configuration for BasicAgent
111
+ * Configuration for BuiltInAgent
112
112
  */
113
- interface BasicAgentConfiguration {
113
+ interface BuiltInAgentConfiguration {
114
114
  /**
115
115
  * The model to use
116
116
  */
117
- model: BasicAgentModel | LanguageModel;
117
+ model: BuiltInAgentModel | LanguageModel;
118
118
  /**
119
119
  * Maximum number of steps/iterations for tool calling (default: 1)
120
120
  */
@@ -176,17 +176,23 @@ interface BasicAgentConfiguration {
176
176
  */
177
177
  tools?: ToolDefinition[];
178
178
  }
179
- declare class BasicAgent extends AbstractAgent {
179
+ declare class BuiltInAgent extends AbstractAgent {
180
180
  private config;
181
181
  private abortController?;
182
- constructor(config: BasicAgentConfiguration);
182
+ constructor(config: BuiltInAgentConfiguration);
183
183
  /**
184
184
  * Check if a property can be overridden by forwardedProps
185
185
  */
186
186
  canOverride(property: OverridableProperty): boolean;
187
187
  run(input: RunAgentInput): Observable<BaseEvent>;
188
- clone(): BasicAgent;
188
+ clone(): BuiltInAgent;
189
189
  abortRun(): void;
190
190
  }
191
+ /**
192
+ * @deprecated Use BuiltInAgent instead
193
+ */
194
+ declare class BasicAgent extends BuiltInAgent {
195
+ constructor(config: BuiltInAgentConfiguration);
196
+ }
191
197
 
192
- export { BasicAgent, type BasicAgentConfiguration, type BasicAgentModel, type MCPClientConfig, type MCPClientConfigHTTP, type MCPClientConfigSSE, type ModelSpecifier, type OverridableProperty, type ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel };
198
+ export { BasicAgent, BuiltInAgent, type BuiltInAgentConfiguration, type BuiltInAgentModel, type MCPClientConfig, type MCPClientConfigHTTP, type MCPClientConfigSSE, type ModelSpecifier, type OverridableProperty, type ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel };
package/dist/index.js CHANGED
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  BasicAgent: () => BasicAgent,
24
+ BuiltInAgent: () => BuiltInAgent,
24
25
  convertJsonSchemaToZodSchema: () => convertJsonSchemaToZodSchema,
25
26
  convertMessagesToVercelAISDKMessages: () => convertMessagesToVercelAISDKMessages,
26
27
  convertToolDefinitionsToVercelAITools: () => convertToolDefinitionsToVercelAITools,
@@ -222,7 +223,7 @@ function convertToolDefinitionsToVercelAITools(tools) {
222
223
  }
223
224
  return result;
224
225
  }
225
- var BasicAgent = class _BasicAgent extends import_client.AbstractAgent {
226
+ var BuiltInAgent = class _BuiltInAgent extends import_client.AbstractAgent {
226
227
  constructor(config) {
227
228
  super();
228
229
  this.config = config;
@@ -599,15 +600,22 @@ ${JSON.stringify(input.state, null, 2)}
599
600
  });
600
601
  }
601
602
  clone() {
602
- return new _BasicAgent(this.config);
603
+ return new _BuiltInAgent(this.config);
603
604
  }
604
605
  abortRun() {
605
606
  this.abortController?.abort();
606
607
  }
607
608
  };
609
+ var BasicAgent = class extends BuiltInAgent {
610
+ constructor(config) {
611
+ super(config);
612
+ console.warn("BasicAgent is deprecated, use BuiltInAgent instead");
613
+ }
614
+ };
608
615
  // Annotate the CommonJS export names for ESM import in node:
609
616
  0 && (module.exports = {
610
617
  BasicAgent,
618
+ BuiltInAgent,
611
619
  convertJsonSchemaToZodSchema,
612
620
  convertMessagesToVercelAISDKMessages,
613
621
  convertToolDefinitionsToVercelAITools,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n RunAgentInput,\n EventType,\n Message,\n RunFinishedEvent,\n RunStartedEvent,\n TextMessageChunkEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolCallResultEvent,\n RunErrorEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n} from \"@ag-ui/client\";\nimport {\n streamText,\n LanguageModel,\n ModelMessage,\n AssistantModelMessage,\n UserModelMessage,\n ToolModelMessage,\n ToolCallPart,\n ToolResultPart,\n TextPart,\n tool as createVercelAISDKTool,\n ToolChoice,\n ToolSet,\n stepCountIs,\n} from \"ai\";\nimport { experimental_createMCPClient as createMCPClient } from \"@ai-sdk/mcp\";\nimport { Observable } from \"rxjs\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createGoogleGenerativeAI } from \"@ai-sdk/google\";\nimport { randomUUID } from \"crypto\";\nimport { z } from \"zod\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\n/**\n * Properties that can be overridden by forwardedProps\n * These match the exact parameter names in streamText\n */\nexport type OverridableProperty =\n | \"model\"\n | \"toolChoice\"\n | \"maxOutputTokens\"\n | \"temperature\"\n | \"topP\"\n | \"topK\"\n | \"presencePenalty\"\n | \"frequencyPenalty\"\n | \"stopSequences\"\n | \"seed\"\n | \"maxRetries\"\n | \"prompt\";\n\n/**\n * Supported model identifiers for BasicAgent\n */\nexport type BasicAgentModel =\n // OpenAI models\n | \"openai/gpt-5\"\n | \"openai/gpt-5-mini\"\n | \"openai/gpt-4.1\"\n | \"openai/gpt-4.1-mini\"\n | \"openai/gpt-4.1-nano\"\n | \"openai/gpt-4o\"\n | \"openai/gpt-4o-mini\"\n // OpenAI reasoning series\n | \"openai/o3\"\n | \"openai/o3-mini\"\n | \"openai/o4-mini\"\n // Anthropic (Claude) models\n | \"anthropic/claude-sonnet-4.5\"\n | \"anthropic/claude-sonnet-4\"\n | \"anthropic/claude-3.7-sonnet\"\n | \"anthropic/claude-opus-4.1\"\n | \"anthropic/claude-opus-4\"\n | \"anthropic/claude-3.5-haiku\"\n // Google (Gemini) models\n | \"google/gemini-2.5-pro\"\n | \"google/gemini-2.5-flash\"\n | \"google/gemini-2.5-flash-lite\"\n // Allow any LanguageModel instance\n | (string & {});\n\n/**\n * Model specifier - can be a string like \"openai/gpt-4o\" or a LanguageModel instance\n */\nexport type ModelSpecifier = string | LanguageModel;\n\n/**\n * MCP Client configuration for HTTP transport\n */\nexport interface MCPClientConfigHTTP {\n /**\n * Type of MCP client\n */\n type: \"http\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional transport options for HTTP client\n */\n options?: StreamableHTTPClientTransportOptions;\n}\n\n/**\n * MCP Client configuration for SSE transport\n */\nexport interface MCPClientConfigSSE {\n /**\n * Type of MCP client\n */\n type: \"sse\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional HTTP headers (e.g., for authentication)\n */\n headers?: Record<string, string>;\n}\n\n/**\n * MCP Client configuration\n */\nexport type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;\n\n/**\n * Resolves a model specifier to a LanguageModel instance\n * @param spec - Model string (e.g., \"openai/gpt-4o\") or LanguageModel instance\n * @returns LanguageModel instance\n */\nexport function resolveModel(spec: ModelSpecifier): LanguageModel {\n // If already a LanguageModel instance, pass through\n if (typeof spec !== \"string\") {\n return spec;\n }\n\n // Normalize \"provider/model\" or \"provider:model\" format\n const normalized = spec.replace(\"/\", \":\").trim();\n const parts = normalized.split(\":\");\n const rawProvider = parts[0];\n const rest = parts.slice(1);\n\n if (!rawProvider) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n const provider = rawProvider.toLowerCase();\n const model = rest.join(\":\").trim();\n\n if (!model) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n switch (provider) {\n case \"openai\": {\n // Lazily create OpenAI provider\n const openai = createOpenAI({\n apiKey: process.env.OPENAI_API_KEY!,\n });\n // Accepts any OpenAI model id, e.g. \"gpt-4o\", \"gpt-4.1-mini\", \"o3-mini\"\n return openai(model);\n }\n\n case \"anthropic\": {\n // Lazily create Anthropic provider\n const anthropic = createAnthropic({\n apiKey: process.env.ANTHROPIC_API_KEY!,\n });\n // Accepts any Claude id, e.g. \"claude-3.7-sonnet\", \"claude-3.5-haiku\"\n return anthropic(model);\n }\n\n case \"google\":\n case \"gemini\":\n case \"google-gemini\": {\n // Lazily create Google provider\n const google = createGoogleGenerativeAI({\n apiKey: process.env.GOOGLE_API_KEY!,\n });\n // Accepts any Gemini id, e.g. \"gemini-2.5-pro\", \"gemini-2.5-flash\"\n return google(model);\n }\n\n default:\n throw new Error(`Unknown provider \"${provider}\" in \"${spec}\". Supported: openai, anthropic, google (gemini).`);\n }\n}\n\n/**\n * Tool definition for BasicAgent\n */\nexport interface ToolDefinition<TParameters extends z.ZodTypeAny = z.ZodTypeAny> {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: z.infer<TParameters>) => Promise<unknown>;\n}\n\n/**\n * Define a tool for use with BasicAgent\n * @param name - The name of the tool\n * @param description - Description of what the tool does\n * @param parameters - Zod schema for the tool's input parameters\n * @param execute - Function to execute the tool server-side\n * @returns Tool definition\n */\nexport function defineTool<TParameters extends z.ZodTypeAny>(config: {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: z.infer<TParameters>) => Promise<unknown>;\n}): ToolDefinition<TParameters> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n execute: config.execute,\n };\n}\n\ntype AGUIUserMessage = Extract<Message, { role: \"user\" }>;\n\nfunction flattenUserMessageContent(content?: AGUIUserMessage[\"content\"]): string {\n if (!content) {\n return \"\";\n }\n\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .map((part) => {\n if (\n part &&\n typeof part === \"object\" &&\n \"type\" in part &&\n (part as { type?: unknown }).type === \"text\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n return (part as { text: string }).text;\n }\n return \"\";\n })\n .filter((text) => text.length > 0)\n .join(\"\\n\");\n}\n\n/**\n * Converts AG-UI messages to Vercel AI SDK ModelMessage format\n */\nexport function convertMessagesToVercelAISDKMessages(messages: Message[]): ModelMessage[] {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content ? [{ type: \"text\", text: message.content }] : [];\n\n for (const toolCall of message.toolCalls ?? []) {\n const toolCallPart: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: JSON.parse(toolCall.function.arguments),\n };\n parts.push(toolCallPart);\n }\n\n const assistantMsg: AssistantModelMessage = {\n role: \"assistant\",\n content: parts,\n };\n result.push(assistantMsg);\n } else if (message.role === \"user\") {\n const userMsg: UserModelMessage = {\n role: \"user\",\n content: flattenUserMessageContent(message.content),\n };\n result.push(userMsg);\n } else if (message.role === \"tool\") {\n let toolName = \"unknown\";\n // Find the tool name from the corresponding tool call\n for (const msg of messages) {\n if (msg.role === \"assistant\") {\n for (const toolCall of msg.toolCalls ?? []) {\n if (toolCall.id === message.toolCallId) {\n toolName = toolCall.function.name;\n break;\n }\n }\n }\n }\n\n const toolResultPart: ToolResultPart = {\n type: \"tool-result\",\n toolCallId: message.toolCallId,\n toolName: toolName,\n output: {\n type: \"text\",\n value: message.content,\n },\n };\n\n const toolMsg: ToolModelMessage = {\n role: \"tool\",\n content: [toolResultPart],\n };\n result.push(toolMsg);\n }\n }\n\n return result;\n}\n\n/**\n * JSON Schema type definition\n */\ninterface JsonSchema {\n type: \"object\" | \"string\" | \"number\" | \"boolean\" | \"array\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n}\n\n/**\n * Converts JSON Schema to Zod schema\n */\nexport function convertJsonSchemaToZodSchema(jsonSchema: JsonSchema, required: boolean): z.ZodSchema {\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false);\n }\n let schema = z.object(spec).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n let schema = z.string().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\") {\n let schema = z.number().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n let schema = z.boolean().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n if (!jsonSchema.items) {\n throw new Error(\"Array type must have items property\");\n }\n let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n let schema = z.array(itemSchema).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n throw new Error(\"Invalid JSON schema\");\n}\n\n/**\n * Converts AG-UI tools to Vercel AI SDK ToolSet\n */\nfunction isJsonSchema(obj: unknown): obj is JsonSchema {\n if (typeof obj !== \"object\" || obj === null) return false;\n const schema = obj as Record<string, unknown>;\n return typeof schema.type === \"string\" && [\"object\", \"string\", \"number\", \"boolean\", \"array\"].includes(schema.type);\n}\n\nexport function convertToolsToVercelAITools(tools: RunAgentInput[\"tools\"]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n const zodSchema = convertJsonSchemaToZodSchema(tool.parameters, true);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: zodSchema,\n });\n }\n\n return result;\n}\n\n/**\n * Converts ToolDefinition array to Vercel AI SDK ToolSet\n */\nexport function convertToolDefinitionsToVercelAITools(tools: ToolDefinition[]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: tool.parameters,\n execute: tool.execute,\n });\n }\n\n return result;\n}\n\n/**\n * Configuration for BasicAgent\n */\nexport interface BasicAgentConfiguration {\n /**\n * The model to use\n */\n model: BasicAgentModel | LanguageModel;\n /**\n * Maximum number of steps/iterations for tool calling (default: 1)\n */\n maxSteps?: number;\n /**\n * Tool choice setting - how tools are selected for execution (default: \"auto\")\n */\n toolChoice?: ToolChoice<Record<string, unknown>>;\n /**\n * Maximum number of tokens to generate\n */\n maxOutputTokens?: number;\n /**\n * Temperature setting (range depends on provider)\n */\n temperature?: number;\n /**\n * Nucleus sampling (topP)\n */\n topP?: number;\n /**\n * Top K sampling\n */\n topK?: number;\n /**\n * Presence penalty\n */\n presencePenalty?: number;\n /**\n * Frequency penalty\n */\n frequencyPenalty?: number;\n /**\n * Sequences that will stop the generation\n */\n stopSequences?: string[];\n /**\n * Seed for deterministic results\n */\n seed?: number;\n /**\n * Maximum number of retries\n */\n maxRetries?: number;\n /**\n * Prompt for the agent\n */\n prompt?: string;\n /**\n * List of properties that can be overridden by forwardedProps.\n */\n overridableProperties?: OverridableProperty[];\n /**\n * Optional list of MCP server configurations\n */\n mcpServers?: MCPClientConfig[];\n /**\n * Optional tools available to the agent\n */\n tools?: ToolDefinition[];\n}\n\nexport class BasicAgent extends AbstractAgent {\n private abortController?: AbortController;\n\n constructor(private config: BasicAgentConfiguration) {\n super();\n }\n\n /**\n * Check if a property can be overridden by forwardedProps\n */\n canOverride(property: OverridableProperty): boolean {\n return this.config?.overridableProperties?.includes(property) ?? false;\n }\n\n run(input: RunAgentInput): Observable<BaseEvent> {\n return new Observable<BaseEvent>((subscriber) => {\n // Emit RUN_STARTED event\n const startEvent: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(startEvent);\n\n // Resolve the model\n const model = resolveModel(this.config.model);\n\n // Build prompt based on conditions\n let systemPrompt: string | undefined = undefined;\n\n // Check if we should build a prompt:\n // - config.prompt is set, OR\n // - input.context is non-empty, OR\n // - input.state is non-empty and not an empty object\n const hasPrompt = !!this.config.prompt;\n const hasContext = input.context && input.context.length > 0;\n const hasState =\n input.state !== undefined &&\n input.state !== null &&\n !(typeof input.state === \"object\" && Object.keys(input.state).length === 0);\n\n if (hasPrompt || hasContext || hasState) {\n const parts: string[] = [];\n\n // First: the prompt if any\n if (hasPrompt) {\n parts.push(this.config.prompt!);\n }\n\n // Second: context from the application\n if (hasContext) {\n parts.push(\"\\n## Context from the application\\n\");\n for (const ctx of input.context) {\n parts.push(`${ctx.description}:\\n${ctx.value}\\n`);\n }\n }\n\n // Third: state from the application that can be edited\n if (hasState) {\n parts.push(\n \"\\n## Application State\\n\" +\n \"This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.\\n\" +\n `\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\`\\n`,\n );\n }\n\n systemPrompt = parts.join(\"\");\n }\n\n // Convert messages and prepend system message if we have a prompt\n const messages = convertMessagesToVercelAISDKMessages(input.messages);\n if (systemPrompt) {\n messages.unshift({\n role: \"system\",\n content: systemPrompt,\n });\n }\n\n // Merge tools from input and config\n let allTools: ToolSet = convertToolsToVercelAITools(input.tools);\n if (this.config.tools && this.config.tools.length > 0) {\n const configTools = convertToolDefinitionsToVercelAITools(this.config.tools);\n allTools = { ...allTools, ...configTools };\n }\n\n const streamTextParams: Parameters<typeof streamText>[0] = {\n model,\n messages,\n tools: allTools,\n toolChoice: this.config.toolChoice,\n stopWhen: this.config.maxSteps ? stepCountIs(this.config.maxSteps) : undefined,\n maxOutputTokens: this.config.maxOutputTokens,\n temperature: this.config.temperature,\n topP: this.config.topP,\n topK: this.config.topK,\n presencePenalty: this.config.presencePenalty,\n frequencyPenalty: this.config.frequencyPenalty,\n stopSequences: this.config.stopSequences,\n seed: this.config.seed,\n maxRetries: this.config.maxRetries,\n };\n\n // Apply forwardedProps overrides (if allowed)\n if (input.forwardedProps && typeof input.forwardedProps === \"object\") {\n const props = input.forwardedProps as Record<string, unknown>;\n\n // Check and apply each overridable property\n if (props.model !== undefined && this.canOverride(\"model\")) {\n if (typeof props.model === \"string\" || typeof props.model === \"object\") {\n // Accept any string or LanguageModel instance for model override\n streamTextParams.model = resolveModel(props.model as string | LanguageModel);\n }\n }\n if (props.toolChoice !== undefined && this.canOverride(\"toolChoice\")) {\n // ToolChoice can be 'auto', 'required', 'none', or { type: 'tool', toolName: string }\n const toolChoice = props.toolChoice;\n if (\n toolChoice === \"auto\" ||\n toolChoice === \"required\" ||\n toolChoice === \"none\" ||\n (typeof toolChoice === \"object\" &&\n toolChoice !== null &&\n \"type\" in toolChoice &&\n toolChoice.type === \"tool\")\n ) {\n streamTextParams.toolChoice = toolChoice as ToolChoice<Record<string, unknown>>;\n }\n }\n if (typeof props.maxOutputTokens === \"number\" && this.canOverride(\"maxOutputTokens\")) {\n streamTextParams.maxOutputTokens = props.maxOutputTokens;\n }\n if (typeof props.temperature === \"number\" && this.canOverride(\"temperature\")) {\n streamTextParams.temperature = props.temperature;\n }\n if (typeof props.topP === \"number\" && this.canOverride(\"topP\")) {\n streamTextParams.topP = props.topP;\n }\n if (typeof props.topK === \"number\" && this.canOverride(\"topK\")) {\n streamTextParams.topK = props.topK;\n }\n if (typeof props.presencePenalty === \"number\" && this.canOverride(\"presencePenalty\")) {\n streamTextParams.presencePenalty = props.presencePenalty;\n }\n if (typeof props.frequencyPenalty === \"number\" && this.canOverride(\"frequencyPenalty\")) {\n streamTextParams.frequencyPenalty = props.frequencyPenalty;\n }\n if (Array.isArray(props.stopSequences) && this.canOverride(\"stopSequences\")) {\n // Validate all elements are strings\n if (props.stopSequences.every((item): item is string => typeof item === \"string\")) {\n streamTextParams.stopSequences = props.stopSequences;\n }\n }\n if (typeof props.seed === \"number\" && this.canOverride(\"seed\")) {\n streamTextParams.seed = props.seed;\n }\n if (typeof props.maxRetries === \"number\" && this.canOverride(\"maxRetries\")) {\n streamTextParams.maxRetries = props.maxRetries;\n }\n }\n\n // Set up MCP clients if configured and process the stream\n const mcpClients: Array<{ close: () => Promise<void> }> = [];\n\n (async () => {\n const abortController = new AbortController();\n this.abortController = abortController;\n let terminalEventEmitted = false;\n\n try {\n // Add AG-UI state update tools\n streamTextParams.tools = {\n ...streamTextParams.tools,\n AGUISendStateSnapshot: createVercelAISDKTool({\n description: \"Replace the entire application state with a new snapshot\",\n inputSchema: z.object({\n snapshot: z.any().describe(\"The complete new state object\"),\n }),\n execute: async ({ snapshot }) => {\n return { success: true, snapshot };\n },\n }),\n AGUISendStateDelta: createVercelAISDKTool({\n description: \"Apply incremental updates to application state using JSON Patch operations\",\n inputSchema: z.object({\n delta: z\n .array(\n z.object({\n op: z.enum([\"add\", \"replace\", \"remove\"]).describe(\"The operation to perform\"),\n path: z.string().describe(\"JSON Pointer path (e.g., '/foo/bar')\"),\n value: z\n .any()\n .optional()\n .describe(\n \"The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.\",\n ),\n }),\n )\n .describe(\"Array of JSON Patch operations\"),\n }),\n execute: async ({ delta }) => {\n return { success: true, delta };\n },\n }),\n };\n\n // Initialize MCP clients and get their tools\n if (this.config.mcpServers && this.config.mcpServers.length > 0) {\n for (const serverConfig of this.config.mcpServers) {\n let transport;\n\n if (serverConfig.type === \"http\") {\n const url = new URL(serverConfig.url);\n transport = new StreamableHTTPClientTransport(url, serverConfig.options);\n } else if (serverConfig.type === \"sse\") {\n transport = new SSEClientTransport(new URL(serverConfig.url), serverConfig.headers);\n }\n\n if (transport) {\n const mcpClient = await createMCPClient({ transport });\n mcpClients.push(mcpClient);\n\n // Get tools from this MCP server and merge with existing tools\n const mcpTools = await mcpClient.tools();\n streamTextParams.tools = { ...streamTextParams.tools, ...mcpTools };\n }\n }\n }\n\n // Call streamText and process the stream\n const response = streamText({ ...streamTextParams, abortSignal: abortController.signal });\n\n let messageId = randomUUID();\n\n const toolCallStates = new Map<\n string,\n {\n started: boolean;\n hasArgsDelta: boolean;\n ended: boolean;\n toolName?: string;\n }\n >();\n\n const ensureToolCallState = (toolCallId: string) => {\n let state = toolCallStates.get(toolCallId);\n if (!state) {\n state = { started: false, hasArgsDelta: false, ended: false };\n toolCallStates.set(toolCallId, state);\n }\n return state;\n };\n\n // Process fullStream events\n for await (const part of response.fullStream) {\n switch (part.type) {\n case 'abort':\n const abortEndEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(abortEndEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n\n case \"tool-input-start\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName;\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n break;\n }\n\n case \"tool-input-delta\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.hasArgsDelta = true;\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: part.delta,\n };\n subscriber.next(argsEvent);\n break;\n }\n\n case \"tool-input-end\": {\n // No direct event – the subsequent \"tool-call\" part marks completion.\n break;\n }\n\n case \"text-start\": {\n // New text message starting - use the SDK-provided id\n messageId = \"id\" in part ? (part.id as typeof messageId) : randomUUID();\n break;\n }\n\n case \"text-delta\": {\n // Accumulate text content - in AI SDK 5.0, the property is 'text'\n const textDelta = \"text\" in part ? part.text : \"\";\n // Emit text chunk event\n const textEvent: TextMessageChunkEvent = {\n type: EventType.TEXT_MESSAGE_CHUNK,\n role: \"assistant\",\n messageId,\n delta: textDelta,\n };\n subscriber.next(textEvent);\n break;\n }\n\n case \"tool-call\": {\n const toolCallId = part.toolCallId;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName ?? state.toolName;\n\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n\n if (!state.hasArgsDelta && \"input\" in part && part.input !== undefined) {\n let serializedInput = \"\";\n if (typeof part.input === \"string\") {\n serializedInput = part.input;\n } else {\n try {\n serializedInput = JSON.stringify(part.input);\n } catch {\n serializedInput = String(part.input);\n }\n }\n\n if (serializedInput.length > 0) {\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: serializedInput,\n };\n subscriber.next(argsEvent);\n state.hasArgsDelta = true;\n }\n }\n\n if (!state.ended) {\n state.ended = true;\n const endEvent: ToolCallEndEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n subscriber.next(endEvent);\n }\n break;\n }\n\n case \"tool-result\": {\n const toolResult = \"output\" in part ? part.output : null;\n const toolName = \"toolName\" in part ? part.toolName : \"\";\n toolCallStates.delete(part.toolCallId);\n\n // Check if this is a state update tool\n if (toolName === \"AGUISendStateSnapshot\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateSnapshotEvent\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: toolResult.snapshot,\n };\n subscriber.next(stateSnapshotEvent);\n } else if (toolName === \"AGUISendStateDelta\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateDeltaEvent\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta: toolResult.delta,\n };\n subscriber.next(stateDeltaEvent);\n }\n\n // Always emit the tool result event for the LLM\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId: part.toolCallId,\n content: JSON.stringify(toolResult),\n };\n subscriber.next(resultEvent);\n break;\n }\n\n case \"finish\":\n // Emit run finished event\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n\n case \"error\": {\n if (abortController.signal.aborted) {\n break;\n }\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: part.error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n\n // Handle error\n subscriber.error(part.error);\n break;\n }\n }\n }\n\n if (!terminalEventEmitted) {\n if (abortController.signal.aborted) {\n // Let the runner finalize the stream on stop requests so it can\n // inject consistent closing events and a RUN_FINISHED marker.\n } else {\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n }\n\n terminalEventEmitted = true;\n subscriber.complete();\n }\n } catch (error) {\n if (abortController.signal.aborted) {\n subscriber.complete();\n } else {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n subscriber.error(error);\n }\n } finally {\n this.abortController = undefined;\n await Promise.all(mcpClients.map((client) => client.close()));\n }\n })();\n\n // Cleanup function\n return () => {\n // Cleanup MCP clients if stream is unsubscribed\n Promise.all(mcpClients.map((client) => client.close())).catch(() => {\n // Ignore cleanup errors\n });\n };\n });\n }\n\n clone() {\n return new BasicAgent(this.config);\n }\n\n abortRun(): void {\n this.abortController?.abort();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAgBO;AACP,gBAcO;AACP,iBAAgE;AAChE,kBAA2B;AAC3B,oBAA6B;AAC7B,uBAAgC;AAChC,oBAAyC;AACzC,oBAA2B;AAC3B,iBAAkB;AAClB,4BAGO;AACP,iBAAmC;AAqG5B,SAAS,aAAa,MAAqC;AAEhE,MAAI,OAAO,SAAS,UAAU;AAC5B,WAAO;AAAA,EACT;AAGA,QAAM,aAAa,KAAK,QAAQ,KAAK,GAAG,EAAE,KAAK;AAC/C,QAAM,QAAQ,WAAW,MAAM,GAAG;AAClC,QAAM,cAAc,MAAM,CAAC;AAC3B,QAAM,OAAO,MAAM,MAAM,CAAC;AAE1B,MAAI,CAAC,aAAa;AAChB,UAAM,IAAI;AAAA,MACR,yBAAyB,IAAI;AAAA,IAC/B;AAAA,EACF;AAEA,QAAM,WAAW,YAAY,YAAY;AACzC,QAAM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AACd,cAAI,gBAAgB,OAAO,SAAS;AAClC,uBAAW,SAAS;AAAA,UACtB,OAAO;AACL,kBAAM,gBAA+B;AAAA,cACnC,MAAM,wBAAU;AAAA,cAChB,SAAS,QAAQ;AAAA,YACnB;AACA,uBAAW,KAAK,aAAa;AAC7B,mCAAuB;AACvB,uBAAW,MAAM,KAAK;AAAA,UACxB;AAAA,QACF,UAAE;AACA,eAAK,kBAAkB;AACvB,gBAAM,QAAQ,IAAI,WAAW,IAAI,CAAC,WAAW,OAAO,MAAM,CAAC,CAAC;AAAA,QAC9D;AAAA,MACF,GAAG;AAGH,aAAO,MAAM;AAEX,gBAAQ,IAAI,WAAW,IAAI,CAAC,WAAW,OAAO,MAAM,CAAC,CAAC,EAAE,MAAM,MAAM;AAAA,QAEpE,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,QAAQ;AACN,WAAO,IAAI,YAAW,KAAK,MAAM;AAAA,EACnC;AAAA,EAEA,WAAiB;AACf,SAAK,iBAAiB,MAAM;AAAA,EAC9B;AACF;","names":["createVercelAISDKTool","createMCPClient","startEvent"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n RunAgentInput,\n EventType,\n Message,\n RunFinishedEvent,\n RunStartedEvent,\n TextMessageChunkEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolCallResultEvent,\n RunErrorEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n} from \"@ag-ui/client\";\nimport {\n streamText,\n LanguageModel,\n ModelMessage,\n AssistantModelMessage,\n UserModelMessage,\n ToolModelMessage,\n ToolCallPart,\n ToolResultPart,\n TextPart,\n tool as createVercelAISDKTool,\n ToolChoice,\n ToolSet,\n stepCountIs,\n} from \"ai\";\nimport { experimental_createMCPClient as createMCPClient } from \"@ai-sdk/mcp\";\nimport { Observable } from \"rxjs\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createGoogleGenerativeAI } from \"@ai-sdk/google\";\nimport { randomUUID } from \"crypto\";\nimport { z } from \"zod\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\n/**\n * Properties that can be overridden by forwardedProps\n * These match the exact parameter names in streamText\n */\nexport type OverridableProperty =\n | \"model\"\n | \"toolChoice\"\n | \"maxOutputTokens\"\n | \"temperature\"\n | \"topP\"\n | \"topK\"\n | \"presencePenalty\"\n | \"frequencyPenalty\"\n | \"stopSequences\"\n | \"seed\"\n | \"maxRetries\"\n | \"prompt\";\n\n/**\n * Supported model identifiers for BuiltInAgent\n */\nexport type BuiltInAgentModel =\n // OpenAI models\n | \"openai/gpt-5\"\n | \"openai/gpt-5-mini\"\n | \"openai/gpt-4.1\"\n | \"openai/gpt-4.1-mini\"\n | \"openai/gpt-4.1-nano\"\n | \"openai/gpt-4o\"\n | \"openai/gpt-4o-mini\"\n // OpenAI reasoning series\n | \"openai/o3\"\n | \"openai/o3-mini\"\n | \"openai/o4-mini\"\n // Anthropic (Claude) models\n | \"anthropic/claude-sonnet-4.5\"\n | \"anthropic/claude-sonnet-4\"\n | \"anthropic/claude-3.7-sonnet\"\n | \"anthropic/claude-opus-4.1\"\n | \"anthropic/claude-opus-4\"\n | \"anthropic/claude-3.5-haiku\"\n // Google (Gemini) models\n | \"google/gemini-2.5-pro\"\n | \"google/gemini-2.5-flash\"\n | \"google/gemini-2.5-flash-lite\"\n // Allow any LanguageModel instance\n | (string & {});\n\n/**\n * Model specifier - can be a string like \"openai/gpt-4o\" or a LanguageModel instance\n */\nexport type ModelSpecifier = string | LanguageModel;\n\n/**\n * MCP Client configuration for HTTP transport\n */\nexport interface MCPClientConfigHTTP {\n /**\n * Type of MCP client\n */\n type: \"http\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional transport options for HTTP client\n */\n options?: StreamableHTTPClientTransportOptions;\n}\n\n/**\n * MCP Client configuration for SSE transport\n */\nexport interface MCPClientConfigSSE {\n /**\n * Type of MCP client\n */\n type: \"sse\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional HTTP headers (e.g., for authentication)\n */\n headers?: Record<string, string>;\n}\n\n/**\n * MCP Client configuration\n */\nexport type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;\n\n/**\n * Resolves a model specifier to a LanguageModel instance\n * @param spec - Model string (e.g., \"openai/gpt-4o\") or LanguageModel instance\n * @returns LanguageModel instance\n */\nexport function resolveModel(spec: ModelSpecifier): LanguageModel {\n // If already a LanguageModel instance, pass through\n if (typeof spec !== \"string\") {\n return spec;\n }\n\n // Normalize \"provider/model\" or \"provider:model\" format\n const normalized = spec.replace(\"/\", \":\").trim();\n const parts = normalized.split(\":\");\n const rawProvider = parts[0];\n const rest = parts.slice(1);\n\n if (!rawProvider) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n const provider = rawProvider.toLowerCase();\n const model = rest.join(\":\").trim();\n\n if (!model) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n switch (provider) {\n case \"openai\": {\n // Lazily create OpenAI provider\n const openai = createOpenAI({\n apiKey: process.env.OPENAI_API_KEY!,\n });\n // Accepts any OpenAI model id, e.g. \"gpt-4o\", \"gpt-4.1-mini\", \"o3-mini\"\n return openai(model);\n }\n\n case \"anthropic\": {\n // Lazily create Anthropic provider\n const anthropic = createAnthropic({\n apiKey: process.env.ANTHROPIC_API_KEY!,\n });\n // Accepts any Claude id, e.g. \"claude-3.7-sonnet\", \"claude-3.5-haiku\"\n return anthropic(model);\n }\n\n case \"google\":\n case \"gemini\":\n case \"google-gemini\": {\n // Lazily create Google provider\n const google = createGoogleGenerativeAI({\n apiKey: process.env.GOOGLE_API_KEY!,\n });\n // Accepts any Gemini id, e.g. \"gemini-2.5-pro\", \"gemini-2.5-flash\"\n return google(model);\n }\n\n default:\n throw new Error(`Unknown provider \"${provider}\" in \"${spec}\". Supported: openai, anthropic, google (gemini).`);\n }\n}\n\n/**\n * Tool definition for BuiltInAgent\n */\nexport interface ToolDefinition<TParameters extends z.ZodTypeAny = z.ZodTypeAny> {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: z.infer<TParameters>) => Promise<unknown>;\n}\n\n/**\n * Define a tool for use with BuiltInAgent\n * @param name - The name of the tool\n * @param description - Description of what the tool does\n * @param parameters - Zod schema for the tool's input parameters\n * @param execute - Function to execute the tool server-side\n * @returns Tool definition\n */\nexport function defineTool<TParameters extends z.ZodTypeAny>(config: {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: z.infer<TParameters>) => Promise<unknown>;\n}): ToolDefinition<TParameters> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n execute: config.execute,\n };\n}\n\ntype AGUIUserMessage = Extract<Message, { role: \"user\" }>;\n\nfunction flattenUserMessageContent(content?: AGUIUserMessage[\"content\"]): string {\n if (!content) {\n return \"\";\n }\n\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .map((part) => {\n if (\n part &&\n typeof part === \"object\" &&\n \"type\" in part &&\n (part as { type?: unknown }).type === \"text\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n return (part as { text: string }).text;\n }\n return \"\";\n })\n .filter((text) => text.length > 0)\n .join(\"\\n\");\n}\n\n/**\n * Converts AG-UI messages to Vercel AI SDK ModelMessage format\n */\nexport function convertMessagesToVercelAISDKMessages(messages: Message[]): ModelMessage[] {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content ? [{ type: \"text\", text: message.content }] : [];\n\n for (const toolCall of message.toolCalls ?? []) {\n const toolCallPart: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: JSON.parse(toolCall.function.arguments),\n };\n parts.push(toolCallPart);\n }\n\n const assistantMsg: AssistantModelMessage = {\n role: \"assistant\",\n content: parts,\n };\n result.push(assistantMsg);\n } else if (message.role === \"user\") {\n const userMsg: UserModelMessage = {\n role: \"user\",\n content: flattenUserMessageContent(message.content),\n };\n result.push(userMsg);\n } else if (message.role === \"tool\") {\n let toolName = \"unknown\";\n // Find the tool name from the corresponding tool call\n for (const msg of messages) {\n if (msg.role === \"assistant\") {\n for (const toolCall of msg.toolCalls ?? []) {\n if (toolCall.id === message.toolCallId) {\n toolName = toolCall.function.name;\n break;\n }\n }\n }\n }\n\n const toolResultPart: ToolResultPart = {\n type: \"tool-result\",\n toolCallId: message.toolCallId,\n toolName: toolName,\n output: {\n type: \"text\",\n value: message.content,\n },\n };\n\n const toolMsg: ToolModelMessage = {\n role: \"tool\",\n content: [toolResultPart],\n };\n result.push(toolMsg);\n }\n }\n\n return result;\n}\n\n/**\n * JSON Schema type definition\n */\ninterface JsonSchema {\n type: \"object\" | \"string\" | \"number\" | \"boolean\" | \"array\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n}\n\n/**\n * Converts JSON Schema to Zod schema\n */\nexport function convertJsonSchemaToZodSchema(jsonSchema: JsonSchema, required: boolean): z.ZodSchema {\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false);\n }\n let schema = z.object(spec).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n let schema = z.string().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\") {\n let schema = z.number().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n let schema = z.boolean().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n if (!jsonSchema.items) {\n throw new Error(\"Array type must have items property\");\n }\n let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n let schema = z.array(itemSchema).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n throw new Error(\"Invalid JSON schema\");\n}\n\n/**\n * Converts AG-UI tools to Vercel AI SDK ToolSet\n */\nfunction isJsonSchema(obj: unknown): obj is JsonSchema {\n if (typeof obj !== \"object\" || obj === null) return false;\n const schema = obj as Record<string, unknown>;\n return typeof schema.type === \"string\" && [\"object\", \"string\", \"number\", \"boolean\", \"array\"].includes(schema.type);\n}\n\nexport function convertToolsToVercelAITools(tools: RunAgentInput[\"tools\"]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n const zodSchema = convertJsonSchemaToZodSchema(tool.parameters, true);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: zodSchema,\n });\n }\n\n return result;\n}\n\n/**\n * Converts ToolDefinition array to Vercel AI SDK ToolSet\n */\nexport function convertToolDefinitionsToVercelAITools(tools: ToolDefinition[]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: tool.parameters,\n execute: tool.execute,\n });\n }\n\n return result;\n}\n\n/**\n * Configuration for BuiltInAgent\n */\nexport interface BuiltInAgentConfiguration {\n /**\n * The model to use\n */\n model: BuiltInAgentModel | LanguageModel;\n /**\n * Maximum number of steps/iterations for tool calling (default: 1)\n */\n maxSteps?: number;\n /**\n * Tool choice setting - how tools are selected for execution (default: \"auto\")\n */\n toolChoice?: ToolChoice<Record<string, unknown>>;\n /**\n * Maximum number of tokens to generate\n */\n maxOutputTokens?: number;\n /**\n * Temperature setting (range depends on provider)\n */\n temperature?: number;\n /**\n * Nucleus sampling (topP)\n */\n topP?: number;\n /**\n * Top K sampling\n */\n topK?: number;\n /**\n * Presence penalty\n */\n presencePenalty?: number;\n /**\n * Frequency penalty\n */\n frequencyPenalty?: number;\n /**\n * Sequences that will stop the generation\n */\n stopSequences?: string[];\n /**\n * Seed for deterministic results\n */\n seed?: number;\n /**\n * Maximum number of retries\n */\n maxRetries?: number;\n /**\n * Prompt for the agent\n */\n prompt?: string;\n /**\n * List of properties that can be overridden by forwardedProps.\n */\n overridableProperties?: OverridableProperty[];\n /**\n * Optional list of MCP server configurations\n */\n mcpServers?: MCPClientConfig[];\n /**\n * Optional tools available to the agent\n */\n tools?: ToolDefinition[];\n}\n\nexport class BuiltInAgent extends AbstractAgent {\n private abortController?: AbortController;\n\n constructor(private config: BuiltInAgentConfiguration) {\n super();\n }\n\n /**\n * Check if a property can be overridden by forwardedProps\n */\n canOverride(property: OverridableProperty): boolean {\n return this.config?.overridableProperties?.includes(property) ?? false;\n }\n\n run(input: RunAgentInput): Observable<BaseEvent> {\n return new Observable<BaseEvent>((subscriber) => {\n // Emit RUN_STARTED event\n const startEvent: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(startEvent);\n\n // Resolve the model\n const model = resolveModel(this.config.model);\n\n // Build prompt based on conditions\n let systemPrompt: string | undefined = undefined;\n\n // Check if we should build a prompt:\n // - config.prompt is set, OR\n // - input.context is non-empty, OR\n // - input.state is non-empty and not an empty object\n const hasPrompt = !!this.config.prompt;\n const hasContext = input.context && input.context.length > 0;\n const hasState =\n input.state !== undefined &&\n input.state !== null &&\n !(typeof input.state === \"object\" && Object.keys(input.state).length === 0);\n\n if (hasPrompt || hasContext || hasState) {\n const parts: string[] = [];\n\n // First: the prompt if any\n if (hasPrompt) {\n parts.push(this.config.prompt!);\n }\n\n // Second: context from the application\n if (hasContext) {\n parts.push(\"\\n## Context from the application\\n\");\n for (const ctx of input.context) {\n parts.push(`${ctx.description}:\\n${ctx.value}\\n`);\n }\n }\n\n // Third: state from the application that can be edited\n if (hasState) {\n parts.push(\n \"\\n## Application State\\n\" +\n \"This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.\\n\" +\n `\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\`\\n`,\n );\n }\n\n systemPrompt = parts.join(\"\");\n }\n\n // Convert messages and prepend system message if we have a prompt\n const messages = convertMessagesToVercelAISDKMessages(input.messages);\n if (systemPrompt) {\n messages.unshift({\n role: \"system\",\n content: systemPrompt,\n });\n }\n\n // Merge tools from input and config\n let allTools: ToolSet = convertToolsToVercelAITools(input.tools);\n if (this.config.tools && this.config.tools.length > 0) {\n const configTools = convertToolDefinitionsToVercelAITools(this.config.tools);\n allTools = { ...allTools, ...configTools };\n }\n\n const streamTextParams: Parameters<typeof streamText>[0] = {\n model,\n messages,\n tools: allTools,\n toolChoice: this.config.toolChoice,\n stopWhen: this.config.maxSteps ? stepCountIs(this.config.maxSteps) : undefined,\n maxOutputTokens: this.config.maxOutputTokens,\n temperature: this.config.temperature,\n topP: this.config.topP,\n topK: this.config.topK,\n presencePenalty: this.config.presencePenalty,\n frequencyPenalty: this.config.frequencyPenalty,\n stopSequences: this.config.stopSequences,\n seed: this.config.seed,\n maxRetries: this.config.maxRetries,\n };\n\n // Apply forwardedProps overrides (if allowed)\n if (input.forwardedProps && typeof input.forwardedProps === \"object\") {\n const props = input.forwardedProps as Record<string, unknown>;\n\n // Check and apply each overridable property\n if (props.model !== undefined && this.canOverride(\"model\")) {\n if (typeof props.model === \"string\" || typeof props.model === \"object\") {\n // Accept any string or LanguageModel instance for model override\n streamTextParams.model = resolveModel(props.model as string | LanguageModel);\n }\n }\n if (props.toolChoice !== undefined && this.canOverride(\"toolChoice\")) {\n // ToolChoice can be 'auto', 'required', 'none', or { type: 'tool', toolName: string }\n const toolChoice = props.toolChoice;\n if (\n toolChoice === \"auto\" ||\n toolChoice === \"required\" ||\n toolChoice === \"none\" ||\n (typeof toolChoice === \"object\" &&\n toolChoice !== null &&\n \"type\" in toolChoice &&\n toolChoice.type === \"tool\")\n ) {\n streamTextParams.toolChoice = toolChoice as ToolChoice<Record<string, unknown>>;\n }\n }\n if (typeof props.maxOutputTokens === \"number\" && this.canOverride(\"maxOutputTokens\")) {\n streamTextParams.maxOutputTokens = props.maxOutputTokens;\n }\n if (typeof props.temperature === \"number\" && this.canOverride(\"temperature\")) {\n streamTextParams.temperature = props.temperature;\n }\n if (typeof props.topP === \"number\" && this.canOverride(\"topP\")) {\n streamTextParams.topP = props.topP;\n }\n if (typeof props.topK === \"number\" && this.canOverride(\"topK\")) {\n streamTextParams.topK = props.topK;\n }\n if (typeof props.presencePenalty === \"number\" && this.canOverride(\"presencePenalty\")) {\n streamTextParams.presencePenalty = props.presencePenalty;\n }\n if (typeof props.frequencyPenalty === \"number\" && this.canOverride(\"frequencyPenalty\")) {\n streamTextParams.frequencyPenalty = props.frequencyPenalty;\n }\n if (Array.isArray(props.stopSequences) && this.canOverride(\"stopSequences\")) {\n // Validate all elements are strings\n if (props.stopSequences.every((item): item is string => typeof item === \"string\")) {\n streamTextParams.stopSequences = props.stopSequences;\n }\n }\n if (typeof props.seed === \"number\" && this.canOverride(\"seed\")) {\n streamTextParams.seed = props.seed;\n }\n if (typeof props.maxRetries === \"number\" && this.canOverride(\"maxRetries\")) {\n streamTextParams.maxRetries = props.maxRetries;\n }\n }\n\n // Set up MCP clients if configured and process the stream\n const mcpClients: Array<{ close: () => Promise<void> }> = [];\n\n (async () => {\n const abortController = new AbortController();\n this.abortController = abortController;\n let terminalEventEmitted = false;\n\n try {\n // Add AG-UI state update tools\n streamTextParams.tools = {\n ...streamTextParams.tools,\n AGUISendStateSnapshot: createVercelAISDKTool({\n description: \"Replace the entire application state with a new snapshot\",\n inputSchema: z.object({\n snapshot: z.any().describe(\"The complete new state object\"),\n }),\n execute: async ({ snapshot }) => {\n return { success: true, snapshot };\n },\n }),\n AGUISendStateDelta: createVercelAISDKTool({\n description: \"Apply incremental updates to application state using JSON Patch operations\",\n inputSchema: z.object({\n delta: z\n .array(\n z.object({\n op: z.enum([\"add\", \"replace\", \"remove\"]).describe(\"The operation to perform\"),\n path: z.string().describe(\"JSON Pointer path (e.g., '/foo/bar')\"),\n value: z\n .any()\n .optional()\n .describe(\n \"The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.\",\n ),\n }),\n )\n .describe(\"Array of JSON Patch operations\"),\n }),\n execute: async ({ delta }) => {\n return { success: true, delta };\n },\n }),\n };\n\n // Initialize MCP clients and get their tools\n if (this.config.mcpServers && this.config.mcpServers.length > 0) {\n for (const serverConfig of this.config.mcpServers) {\n let transport;\n\n if (serverConfig.type === \"http\") {\n const url = new URL(serverConfig.url);\n transport = new StreamableHTTPClientTransport(url, serverConfig.options);\n } else if (serverConfig.type === \"sse\") {\n transport = new SSEClientTransport(new URL(serverConfig.url), serverConfig.headers);\n }\n\n if (transport) {\n const mcpClient = await createMCPClient({ transport });\n mcpClients.push(mcpClient);\n\n // Get tools from this MCP server and merge with existing tools\n const mcpTools = await mcpClient.tools();\n streamTextParams.tools = { ...streamTextParams.tools, ...mcpTools };\n }\n }\n }\n\n // Call streamText and process the stream\n const response = streamText({ ...streamTextParams, abortSignal: abortController.signal });\n\n let messageId = randomUUID();\n\n const toolCallStates = new Map<\n string,\n {\n started: boolean;\n hasArgsDelta: boolean;\n ended: boolean;\n toolName?: string;\n }\n >();\n\n const ensureToolCallState = (toolCallId: string) => {\n let state = toolCallStates.get(toolCallId);\n if (!state) {\n state = { started: false, hasArgsDelta: false, ended: false };\n toolCallStates.set(toolCallId, state);\n }\n return state;\n };\n\n // Process fullStream events\n for await (const part of response.fullStream) {\n switch (part.type) {\n case 'abort':\n const abortEndEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(abortEndEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n\n case \"tool-input-start\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName;\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n break;\n }\n\n case \"tool-input-delta\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.hasArgsDelta = true;\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: part.delta,\n };\n subscriber.next(argsEvent);\n break;\n }\n\n case \"tool-input-end\": {\n // No direct event – the subsequent \"tool-call\" part marks completion.\n break;\n }\n\n case \"text-start\": {\n // New text message starting - use the SDK-provided id\n messageId = \"id\" in part ? (part.id as typeof messageId) : randomUUID();\n break;\n }\n\n case \"text-delta\": {\n // Accumulate text content - in AI SDK 5.0, the property is 'text'\n const textDelta = \"text\" in part ? part.text : \"\";\n // Emit text chunk event\n const textEvent: TextMessageChunkEvent = {\n type: EventType.TEXT_MESSAGE_CHUNK,\n role: \"assistant\",\n messageId,\n delta: textDelta,\n };\n subscriber.next(textEvent);\n break;\n }\n\n case \"tool-call\": {\n const toolCallId = part.toolCallId;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName ?? state.toolName;\n\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n\n if (!state.hasArgsDelta && \"input\" in part && part.input !== undefined) {\n let serializedInput = \"\";\n if (typeof part.input === \"string\") {\n serializedInput = part.input;\n } else {\n try {\n serializedInput = JSON.stringify(part.input);\n } catch {\n serializedInput = String(part.input);\n }\n }\n\n if (serializedInput.length > 0) {\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: serializedInput,\n };\n subscriber.next(argsEvent);\n state.hasArgsDelta = true;\n }\n }\n\n if (!state.ended) {\n state.ended = true;\n const endEvent: ToolCallEndEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n subscriber.next(endEvent);\n }\n break;\n }\n\n case \"tool-result\": {\n const toolResult = \"output\" in part ? part.output : null;\n const toolName = \"toolName\" in part ? part.toolName : \"\";\n toolCallStates.delete(part.toolCallId);\n\n // Check if this is a state update tool\n if (toolName === \"AGUISendStateSnapshot\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateSnapshotEvent\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: toolResult.snapshot,\n };\n subscriber.next(stateSnapshotEvent);\n } else if (toolName === \"AGUISendStateDelta\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateDeltaEvent\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta: toolResult.delta,\n };\n subscriber.next(stateDeltaEvent);\n }\n\n // Always emit the tool result event for the LLM\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId: part.toolCallId,\n content: JSON.stringify(toolResult),\n };\n subscriber.next(resultEvent);\n break;\n }\n\n case \"finish\":\n // Emit run finished event\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n\n case \"error\": {\n if (abortController.signal.aborted) {\n break;\n }\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: part.error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n\n // Handle error\n subscriber.error(part.error);\n break;\n }\n }\n }\n\n if (!terminalEventEmitted) {\n if (abortController.signal.aborted) {\n // Let the runner finalize the stream on stop requests so it can\n // inject consistent closing events and a RUN_FINISHED marker.\n } else {\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n }\n\n terminalEventEmitted = true;\n subscriber.complete();\n }\n } catch (error) {\n if (abortController.signal.aborted) {\n subscriber.complete();\n } else {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n subscriber.error(error);\n }\n } finally {\n this.abortController = undefined;\n await Promise.all(mcpClients.map((client) => client.close()));\n }\n })();\n\n // Cleanup function\n return () => {\n // Cleanup MCP clients if stream is unsubscribed\n Promise.all(mcpClients.map((client) => client.close())).catch(() => {\n // Ignore cleanup errors\n });\n };\n });\n }\n\n clone() {\n return new BuiltInAgent(this.config);\n }\n\n abortRun(): void {\n this.abortController?.abort();\n }\n}\n\n/**\n * @deprecated Use BuiltInAgent instead\n */\nexport class BasicAgent extends BuiltInAgent {\n constructor(config: BuiltInAgentConfiguration) {\n super(config);\n console.warn(\"BasicAgent is deprecated, use BuiltInAgent instead\");\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAgBO;AACP,gBAcO;AACP,iBAAgE;AAChE,kBAA2B;AAC3B,oBAA6B;AAC7B,uBAAgC;AAChC,oBAAyC;AACzC,oBAA2B;AAC3B,iBAAkB;AAClB,4BA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@@ -201,7 +201,7 @@ function convertToolDefinitionsToVercelAITools(tools) {
201
201
  }
202
202
  return result;
203
203
  }
204
- var BasicAgent = class _BasicAgent extends AbstractAgent {
204
+ var BuiltInAgent = class _BuiltInAgent extends AbstractAgent {
205
205
  constructor(config) {
206
206
  super();
207
207
  this.config = config;
@@ -578,14 +578,21 @@ ${JSON.stringify(input.state, null, 2)}
578
578
  });
579
579
  }
580
580
  clone() {
581
- return new _BasicAgent(this.config);
581
+ return new _BuiltInAgent(this.config);
582
582
  }
583
583
  abortRun() {
584
584
  this.abortController?.abort();
585
585
  }
586
586
  };
587
+ var BasicAgent = class extends BuiltInAgent {
588
+ constructor(config) {
589
+ super(config);
590
+ console.warn("BasicAgent is deprecated, use BuiltInAgent instead");
591
+ }
592
+ };
587
593
  export {
588
594
  BasicAgent,
595
+ BuiltInAgent,
589
596
  convertJsonSchemaToZodSchema,
590
597
  convertMessagesToVercelAISDKMessages,
591
598
  convertToolDefinitionsToVercelAITools,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n RunAgentInput,\n EventType,\n Message,\n RunFinishedEvent,\n RunStartedEvent,\n TextMessageChunkEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolCallResultEvent,\n RunErrorEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n} from \"@ag-ui/client\";\nimport {\n streamText,\n LanguageModel,\n ModelMessage,\n AssistantModelMessage,\n UserModelMessage,\n ToolModelMessage,\n ToolCallPart,\n ToolResultPart,\n TextPart,\n tool as createVercelAISDKTool,\n ToolChoice,\n ToolSet,\n stepCountIs,\n} from \"ai\";\nimport { experimental_createMCPClient as createMCPClient } from \"@ai-sdk/mcp\";\nimport { Observable } from \"rxjs\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createGoogleGenerativeAI } from \"@ai-sdk/google\";\nimport { randomUUID } from \"crypto\";\nimport { z } from \"zod\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\n/**\n * Properties that can be overridden by forwardedProps\n * These match the exact parameter names in streamText\n */\nexport type OverridableProperty =\n | \"model\"\n | \"toolChoice\"\n | \"maxOutputTokens\"\n | \"temperature\"\n | \"topP\"\n | \"topK\"\n | \"presencePenalty\"\n | \"frequencyPenalty\"\n | \"stopSequences\"\n | \"seed\"\n | \"maxRetries\"\n | \"prompt\";\n\n/**\n * Supported model identifiers for BasicAgent\n */\nexport type BasicAgentModel =\n // OpenAI models\n | \"openai/gpt-5\"\n | \"openai/gpt-5-mini\"\n | \"openai/gpt-4.1\"\n | \"openai/gpt-4.1-mini\"\n | \"openai/gpt-4.1-nano\"\n | \"openai/gpt-4o\"\n | \"openai/gpt-4o-mini\"\n // OpenAI reasoning series\n | \"openai/o3\"\n | \"openai/o3-mini\"\n | \"openai/o4-mini\"\n // Anthropic (Claude) models\n | \"anthropic/claude-sonnet-4.5\"\n | \"anthropic/claude-sonnet-4\"\n | \"anthropic/claude-3.7-sonnet\"\n | \"anthropic/claude-opus-4.1\"\n | \"anthropic/claude-opus-4\"\n | \"anthropic/claude-3.5-haiku\"\n // Google (Gemini) models\n | \"google/gemini-2.5-pro\"\n | \"google/gemini-2.5-flash\"\n | \"google/gemini-2.5-flash-lite\"\n // Allow any LanguageModel instance\n | (string & {});\n\n/**\n * Model specifier - can be a string like \"openai/gpt-4o\" or a LanguageModel instance\n */\nexport type ModelSpecifier = string | LanguageModel;\n\n/**\n * MCP Client configuration for HTTP transport\n */\nexport interface MCPClientConfigHTTP {\n /**\n * Type of MCP client\n */\n type: \"http\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional transport options for HTTP client\n */\n options?: StreamableHTTPClientTransportOptions;\n}\n\n/**\n * MCP Client configuration for SSE transport\n */\nexport interface MCPClientConfigSSE {\n /**\n * Type of MCP client\n */\n type: \"sse\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional HTTP headers (e.g., for authentication)\n */\n headers?: Record<string, string>;\n}\n\n/**\n * MCP Client configuration\n */\nexport type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;\n\n/**\n * Resolves a model specifier to a LanguageModel instance\n * @param spec - Model string (e.g., \"openai/gpt-4o\") or LanguageModel instance\n * @returns LanguageModel instance\n */\nexport function resolveModel(spec: ModelSpecifier): LanguageModel {\n // If already a LanguageModel instance, pass through\n if (typeof spec !== \"string\") {\n return spec;\n }\n\n // Normalize \"provider/model\" or \"provider:model\" format\n const normalized = spec.replace(\"/\", \":\").trim();\n const parts = normalized.split(\":\");\n const rawProvider = parts[0];\n const rest = parts.slice(1);\n\n if (!rawProvider) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n const provider = rawProvider.toLowerCase();\n const model = rest.join(\":\").trim();\n\n if (!model) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n switch (provider) {\n case \"openai\": {\n // Lazily create OpenAI provider\n const openai = createOpenAI({\n apiKey: process.env.OPENAI_API_KEY!,\n });\n // Accepts any OpenAI model id, e.g. \"gpt-4o\", \"gpt-4.1-mini\", \"o3-mini\"\n return openai(model);\n }\n\n case \"anthropic\": {\n // Lazily create Anthropic provider\n const anthropic = createAnthropic({\n apiKey: process.env.ANTHROPIC_API_KEY!,\n });\n // Accepts any Claude id, e.g. \"claude-3.7-sonnet\", \"claude-3.5-haiku\"\n return anthropic(model);\n }\n\n case \"google\":\n case \"gemini\":\n case \"google-gemini\": {\n // Lazily create Google provider\n const google = createGoogleGenerativeAI({\n apiKey: process.env.GOOGLE_API_KEY!,\n });\n // Accepts any Gemini id, e.g. \"gemini-2.5-pro\", \"gemini-2.5-flash\"\n return google(model);\n }\n\n default:\n throw new Error(`Unknown provider \"${provider}\" in \"${spec}\". Supported: openai, anthropic, google (gemini).`);\n }\n}\n\n/**\n * Tool definition for BasicAgent\n */\nexport interface ToolDefinition<TParameters extends z.ZodTypeAny = z.ZodTypeAny> {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: z.infer<TParameters>) => Promise<unknown>;\n}\n\n/**\n * Define a tool for use with BasicAgent\n * @param name - The name of the tool\n * @param description - Description of what the tool does\n * @param parameters - Zod schema for the tool's input parameters\n * @param execute - Function to execute the tool server-side\n * @returns Tool definition\n */\nexport function defineTool<TParameters extends z.ZodTypeAny>(config: {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: z.infer<TParameters>) => Promise<unknown>;\n}): ToolDefinition<TParameters> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n execute: config.execute,\n };\n}\n\ntype AGUIUserMessage = Extract<Message, { role: \"user\" }>;\n\nfunction flattenUserMessageContent(content?: AGUIUserMessage[\"content\"]): string {\n if (!content) {\n return \"\";\n }\n\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .map((part) => {\n if (\n part &&\n typeof part === \"object\" &&\n \"type\" in part &&\n (part as { type?: unknown }).type === \"text\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n return (part as { text: string }).text;\n }\n return \"\";\n })\n .filter((text) => text.length > 0)\n .join(\"\\n\");\n}\n\n/**\n * Converts AG-UI messages to Vercel AI SDK ModelMessage format\n */\nexport function convertMessagesToVercelAISDKMessages(messages: Message[]): ModelMessage[] {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content ? [{ type: \"text\", text: message.content }] : [];\n\n for (const toolCall of message.toolCalls ?? []) {\n const toolCallPart: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: JSON.parse(toolCall.function.arguments),\n };\n parts.push(toolCallPart);\n }\n\n const assistantMsg: AssistantModelMessage = {\n role: \"assistant\",\n content: parts,\n };\n result.push(assistantMsg);\n } else if (message.role === \"user\") {\n const userMsg: UserModelMessage = {\n role: \"user\",\n content: flattenUserMessageContent(message.content),\n };\n result.push(userMsg);\n } else if (message.role === \"tool\") {\n let toolName = \"unknown\";\n // Find the tool name from the corresponding tool call\n for (const msg of messages) {\n if (msg.role === \"assistant\") {\n for (const toolCall of msg.toolCalls ?? []) {\n if (toolCall.id === message.toolCallId) {\n toolName = toolCall.function.name;\n break;\n }\n }\n }\n }\n\n const toolResultPart: ToolResultPart = {\n type: \"tool-result\",\n toolCallId: message.toolCallId,\n toolName: toolName,\n output: {\n type: \"text\",\n value: message.content,\n },\n };\n\n const toolMsg: ToolModelMessage = {\n role: \"tool\",\n content: [toolResultPart],\n };\n result.push(toolMsg);\n }\n }\n\n return result;\n}\n\n/**\n * JSON Schema type definition\n */\ninterface JsonSchema {\n type: \"object\" | \"string\" | \"number\" | \"boolean\" | \"array\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n}\n\n/**\n * Converts JSON Schema to Zod schema\n */\nexport function convertJsonSchemaToZodSchema(jsonSchema: JsonSchema, required: boolean): z.ZodSchema {\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false);\n }\n let schema = z.object(spec).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n let schema = z.string().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\") {\n let schema = z.number().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n let schema = z.boolean().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n if (!jsonSchema.items) {\n throw new Error(\"Array type must have items property\");\n }\n let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n let schema = z.array(itemSchema).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n throw new Error(\"Invalid JSON schema\");\n}\n\n/**\n * Converts AG-UI tools to Vercel AI SDK ToolSet\n */\nfunction isJsonSchema(obj: unknown): obj is JsonSchema {\n if (typeof obj !== \"object\" || obj === null) return false;\n const schema = obj as Record<string, unknown>;\n return typeof schema.type === \"string\" && [\"object\", \"string\", \"number\", \"boolean\", \"array\"].includes(schema.type);\n}\n\nexport function convertToolsToVercelAITools(tools: RunAgentInput[\"tools\"]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n const zodSchema = convertJsonSchemaToZodSchema(tool.parameters, true);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: zodSchema,\n });\n }\n\n return result;\n}\n\n/**\n * Converts ToolDefinition array to Vercel AI SDK ToolSet\n */\nexport function convertToolDefinitionsToVercelAITools(tools: ToolDefinition[]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: tool.parameters,\n execute: tool.execute,\n });\n }\n\n return result;\n}\n\n/**\n * Configuration for BasicAgent\n */\nexport interface BasicAgentConfiguration {\n /**\n * The model to use\n */\n model: BasicAgentModel | LanguageModel;\n /**\n * Maximum number of steps/iterations for tool calling (default: 1)\n */\n maxSteps?: number;\n /**\n * Tool choice setting - how tools are selected for execution (default: \"auto\")\n */\n toolChoice?: ToolChoice<Record<string, unknown>>;\n /**\n * Maximum number of tokens to generate\n */\n maxOutputTokens?: number;\n /**\n * Temperature setting (range depends on provider)\n */\n temperature?: number;\n /**\n * Nucleus sampling (topP)\n */\n topP?: number;\n /**\n * Top K sampling\n */\n topK?: number;\n /**\n * Presence penalty\n */\n presencePenalty?: number;\n /**\n * Frequency penalty\n */\n frequencyPenalty?: number;\n /**\n * Sequences that will stop the generation\n */\n stopSequences?: string[];\n /**\n * Seed for deterministic results\n */\n seed?: number;\n /**\n * Maximum number of retries\n */\n maxRetries?: number;\n /**\n * Prompt for the agent\n */\n prompt?: string;\n /**\n * List of properties that can be overridden by forwardedProps.\n */\n overridableProperties?: OverridableProperty[];\n /**\n * Optional list of MCP server configurations\n */\n mcpServers?: MCPClientConfig[];\n /**\n * Optional tools available to the agent\n */\n tools?: ToolDefinition[];\n}\n\nexport class BasicAgent extends AbstractAgent {\n private abortController?: AbortController;\n\n constructor(private config: BasicAgentConfiguration) {\n super();\n }\n\n /**\n * Check if a property can be overridden by forwardedProps\n */\n canOverride(property: OverridableProperty): boolean {\n return this.config?.overridableProperties?.includes(property) ?? false;\n }\n\n run(input: RunAgentInput): Observable<BaseEvent> {\n return new Observable<BaseEvent>((subscriber) => {\n // Emit RUN_STARTED event\n const startEvent: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(startEvent);\n\n // Resolve the model\n const model = resolveModel(this.config.model);\n\n // Build prompt based on conditions\n let systemPrompt: string | undefined = undefined;\n\n // Check if we should build a prompt:\n // - config.prompt is set, OR\n // - input.context is non-empty, OR\n // - input.state is non-empty and not an empty object\n const hasPrompt = !!this.config.prompt;\n const hasContext = input.context && input.context.length > 0;\n const hasState =\n input.state !== undefined &&\n input.state !== null &&\n !(typeof input.state === \"object\" && Object.keys(input.state).length === 0);\n\n if (hasPrompt || hasContext || hasState) {\n const parts: string[] = [];\n\n // First: the prompt if any\n if (hasPrompt) {\n parts.push(this.config.prompt!);\n }\n\n // Second: context from the application\n if (hasContext) {\n parts.push(\"\\n## Context from the application\\n\");\n for (const ctx of input.context) {\n parts.push(`${ctx.description}:\\n${ctx.value}\\n`);\n }\n }\n\n // Third: state from the application that can be edited\n if (hasState) {\n parts.push(\n \"\\n## Application State\\n\" +\n \"This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.\\n\" +\n `\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\`\\n`,\n );\n }\n\n systemPrompt = parts.join(\"\");\n }\n\n // Convert messages and prepend system message if we have a prompt\n const messages = convertMessagesToVercelAISDKMessages(input.messages);\n if (systemPrompt) {\n messages.unshift({\n role: \"system\",\n content: systemPrompt,\n });\n }\n\n // Merge tools from input and config\n let allTools: ToolSet = convertToolsToVercelAITools(input.tools);\n if (this.config.tools && this.config.tools.length > 0) {\n const configTools = convertToolDefinitionsToVercelAITools(this.config.tools);\n allTools = { ...allTools, ...configTools };\n }\n\n const streamTextParams: Parameters<typeof streamText>[0] = {\n model,\n messages,\n tools: allTools,\n toolChoice: this.config.toolChoice,\n stopWhen: this.config.maxSteps ? stepCountIs(this.config.maxSteps) : undefined,\n maxOutputTokens: this.config.maxOutputTokens,\n temperature: this.config.temperature,\n topP: this.config.topP,\n topK: this.config.topK,\n presencePenalty: this.config.presencePenalty,\n frequencyPenalty: this.config.frequencyPenalty,\n stopSequences: this.config.stopSequences,\n seed: this.config.seed,\n maxRetries: this.config.maxRetries,\n };\n\n // Apply forwardedProps overrides (if allowed)\n if (input.forwardedProps && typeof input.forwardedProps === \"object\") {\n const props = input.forwardedProps as Record<string, unknown>;\n\n // Check and apply each overridable property\n if (props.model !== undefined && this.canOverride(\"model\")) {\n if (typeof props.model === \"string\" || typeof props.model === \"object\") {\n // Accept any string or LanguageModel instance for model override\n streamTextParams.model = resolveModel(props.model as string | LanguageModel);\n }\n }\n if (props.toolChoice !== undefined && this.canOverride(\"toolChoice\")) {\n // ToolChoice can be 'auto', 'required', 'none', or { type: 'tool', toolName: string }\n const toolChoice = props.toolChoice;\n if (\n toolChoice === \"auto\" ||\n toolChoice === \"required\" ||\n toolChoice === \"none\" ||\n (typeof toolChoice === \"object\" &&\n toolChoice !== null &&\n \"type\" in toolChoice &&\n toolChoice.type === \"tool\")\n ) {\n streamTextParams.toolChoice = toolChoice as ToolChoice<Record<string, unknown>>;\n }\n }\n if (typeof props.maxOutputTokens === \"number\" && this.canOverride(\"maxOutputTokens\")) {\n streamTextParams.maxOutputTokens = props.maxOutputTokens;\n }\n if (typeof props.temperature === \"number\" && this.canOverride(\"temperature\")) {\n streamTextParams.temperature = props.temperature;\n }\n if (typeof props.topP === \"number\" && this.canOverride(\"topP\")) {\n streamTextParams.topP = props.topP;\n }\n if (typeof props.topK === \"number\" && this.canOverride(\"topK\")) {\n streamTextParams.topK = props.topK;\n }\n if (typeof props.presencePenalty === \"number\" && this.canOverride(\"presencePenalty\")) {\n streamTextParams.presencePenalty = props.presencePenalty;\n }\n if (typeof props.frequencyPenalty === \"number\" && this.canOverride(\"frequencyPenalty\")) {\n streamTextParams.frequencyPenalty = props.frequencyPenalty;\n }\n if (Array.isArray(props.stopSequences) && this.canOverride(\"stopSequences\")) {\n // Validate all elements are strings\n if (props.stopSequences.every((item): item is string => typeof item === \"string\")) {\n streamTextParams.stopSequences = props.stopSequences;\n }\n }\n if (typeof props.seed === \"number\" && this.canOverride(\"seed\")) {\n streamTextParams.seed = props.seed;\n }\n if (typeof props.maxRetries === \"number\" && this.canOverride(\"maxRetries\")) {\n streamTextParams.maxRetries = props.maxRetries;\n }\n }\n\n // Set up MCP clients if configured and process the stream\n const mcpClients: Array<{ close: () => Promise<void> }> = [];\n\n (async () => {\n const abortController = new AbortController();\n this.abortController = abortController;\n let terminalEventEmitted = false;\n\n try {\n // Add AG-UI state update tools\n streamTextParams.tools = {\n ...streamTextParams.tools,\n AGUISendStateSnapshot: createVercelAISDKTool({\n description: \"Replace the entire application state with a new snapshot\",\n inputSchema: z.object({\n snapshot: z.any().describe(\"The complete new state object\"),\n }),\n execute: async ({ snapshot }) => {\n return { success: true, snapshot };\n },\n }),\n AGUISendStateDelta: createVercelAISDKTool({\n description: \"Apply incremental updates to application state using JSON Patch operations\",\n inputSchema: z.object({\n delta: z\n .array(\n z.object({\n op: z.enum([\"add\", \"replace\", \"remove\"]).describe(\"The operation to perform\"),\n path: z.string().describe(\"JSON Pointer path (e.g., '/foo/bar')\"),\n value: z\n .any()\n .optional()\n .describe(\n \"The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.\",\n ),\n }),\n )\n .describe(\"Array of JSON Patch operations\"),\n }),\n execute: async ({ delta }) => {\n return { success: true, delta };\n },\n }),\n };\n\n // Initialize MCP clients and get their tools\n if (this.config.mcpServers && this.config.mcpServers.length > 0) {\n for (const serverConfig of this.config.mcpServers) {\n let transport;\n\n if (serverConfig.type === \"http\") {\n const url = new URL(serverConfig.url);\n transport = new StreamableHTTPClientTransport(url, serverConfig.options);\n } else if (serverConfig.type === \"sse\") {\n transport = new SSEClientTransport(new URL(serverConfig.url), serverConfig.headers);\n }\n\n if (transport) {\n const mcpClient = await createMCPClient({ transport });\n mcpClients.push(mcpClient);\n\n // Get tools from this MCP server and merge with existing tools\n const mcpTools = await mcpClient.tools();\n streamTextParams.tools = { ...streamTextParams.tools, ...mcpTools };\n }\n }\n }\n\n // Call streamText and process the stream\n const response = streamText({ ...streamTextParams, abortSignal: abortController.signal });\n\n let messageId = randomUUID();\n\n const toolCallStates = new Map<\n string,\n {\n started: boolean;\n hasArgsDelta: boolean;\n ended: boolean;\n toolName?: string;\n }\n >();\n\n const ensureToolCallState = (toolCallId: string) => {\n let state = toolCallStates.get(toolCallId);\n if (!state) {\n state = { started: false, hasArgsDelta: false, ended: false };\n toolCallStates.set(toolCallId, state);\n }\n return state;\n };\n\n // Process fullStream events\n for await (const part of response.fullStream) {\n switch (part.type) {\n case 'abort':\n const abortEndEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(abortEndEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n\n case \"tool-input-start\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName;\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n break;\n }\n\n case \"tool-input-delta\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.hasArgsDelta = true;\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: part.delta,\n };\n subscriber.next(argsEvent);\n break;\n }\n\n case \"tool-input-end\": {\n // No direct event – the subsequent \"tool-call\" part marks completion.\n break;\n }\n\n case \"text-start\": {\n // New text message starting - use the SDK-provided id\n messageId = \"id\" in part ? (part.id as typeof messageId) : randomUUID();\n break;\n }\n\n case \"text-delta\": {\n // Accumulate text content - in AI SDK 5.0, the property is 'text'\n const textDelta = \"text\" in part ? part.text : \"\";\n // Emit text chunk event\n const textEvent: TextMessageChunkEvent = {\n type: EventType.TEXT_MESSAGE_CHUNK,\n role: \"assistant\",\n messageId,\n delta: textDelta,\n };\n subscriber.next(textEvent);\n break;\n }\n\n case \"tool-call\": {\n const toolCallId = part.toolCallId;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName ?? state.toolName;\n\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n\n if (!state.hasArgsDelta && \"input\" in part && part.input !== undefined) {\n let serializedInput = \"\";\n if (typeof part.input === \"string\") {\n serializedInput = part.input;\n } else {\n try {\n serializedInput = JSON.stringify(part.input);\n } catch {\n serializedInput = String(part.input);\n }\n }\n\n if (serializedInput.length > 0) {\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: serializedInput,\n };\n subscriber.next(argsEvent);\n state.hasArgsDelta = true;\n }\n }\n\n if (!state.ended) {\n state.ended = true;\n const endEvent: ToolCallEndEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n subscriber.next(endEvent);\n }\n break;\n }\n\n case \"tool-result\": {\n const toolResult = \"output\" in part ? part.output : null;\n const toolName = \"toolName\" in part ? part.toolName : \"\";\n toolCallStates.delete(part.toolCallId);\n\n // Check if this is a state update tool\n if (toolName === \"AGUISendStateSnapshot\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateSnapshotEvent\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: toolResult.snapshot,\n };\n subscriber.next(stateSnapshotEvent);\n } else if (toolName === \"AGUISendStateDelta\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateDeltaEvent\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta: toolResult.delta,\n };\n subscriber.next(stateDeltaEvent);\n }\n\n // Always emit the tool result event for the LLM\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId: part.toolCallId,\n content: JSON.stringify(toolResult),\n };\n subscriber.next(resultEvent);\n break;\n }\n\n case \"finish\":\n // Emit run finished event\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n\n case \"error\": {\n if (abortController.signal.aborted) {\n break;\n }\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: part.error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n\n // Handle error\n subscriber.error(part.error);\n break;\n }\n }\n }\n\n if (!terminalEventEmitted) {\n if (abortController.signal.aborted) {\n // Let the runner finalize the stream on stop requests so it can\n // inject consistent closing events and a RUN_FINISHED marker.\n } else {\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n }\n\n terminalEventEmitted = true;\n subscriber.complete();\n }\n } catch (error) {\n if (abortController.signal.aborted) {\n subscriber.complete();\n } else {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n subscriber.error(error);\n }\n } finally {\n this.abortController = undefined;\n await Promise.all(mcpClients.map((client) => client.close()));\n }\n })();\n\n // Cleanup function\n return () => {\n // Cleanup MCP clients if stream is unsubscribed\n Promise.all(mcpClients.map((client) => client.close())).catch(() => {\n // Ignore cleanup errors\n });\n };\n });\n }\n\n clone() {\n return new BasicAgent(this.config);\n }\n\n abortRun(): void {\n this.abortController?.abort();\n }\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EAGA;AAAA,OAYK;AACP;AAAA,EACE;AAAA,EASA,QAAQ;AAAA,EAGR;AAAA,OACK;AACP,SAAS,gCAAgC,uBAAuB;AAChE,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB;AAChC,SAAS,gCAAgC;AACzC,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAClB;AAAA,EACE;AAAA,OAEK;AACP,SAAS,0BAA0B;AAqG5B,SAAS,aAAa,MAAqC;AAEhE,MAAI,OAAO,SAAS,UAAU;AAC5B,WAAO;AAAA,EACT;AAGA,QAAM,aAAa,KAAK,QAAQ,KAAK,GAAG,EAAE,KAAK;AAC/C,QAAM,QAAQ,WAAW,MAAM,GAAG;AA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A,gBAChB,OAAO,MAAM;AAAA,cACf;AACA,yBAAW,KAAK,aAAa;AAAA,YAC/B;AAEA,mCAAuB;AACvB,uBAAW,SAAS;AAAA,UACtB;AAAA,QACF,SAAS,OAAO;AACd,cAAI,gBAAgB,OAAO,SAAS;AAClC,uBAAW,SAAS;AAAA,UACtB,OAAO;AACL,kBAAM,gBAA+B;AAAA,cACnC,MAAM,UAAU;AAAA,cAChB,SAAS,QAAQ;AAAA,YACnB;AACA,uBAAW,KAAK,aAAa;AAC7B,mCAAuB;AACvB,uBAAW,MAAM,KAAK;AAAA,UACxB;AAAA,QACF,UAAE;AACA,eAAK,kBAAkB;AACvB,gBAAM,QAAQ,IAAI,WAAW,IAAI,CAAC,WAAW,OAAO,MAAM,CAAC,CAAC;AAAA,QAC9D;AAAA,MACF,GAAG;AAGH,aAAO,MAAM;AAEX,gBAAQ,IAAI,WAAW,IAAI,CAAC,WAAW,OAAO,MAAM,CAAC,CAAC,EAAE,MAAM,MAAM;AAAA,QAEpE,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,QAAQ;AACN,WAAO,IAAI,YAAW,KAAK,MAAM;AAAA,EACnC;AAAA,EAEA,WAAiB;AACf,SAAK,iBAAiB,MAAM;AAAA,EAC9B;AACF;","names":["startEvent"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n RunAgentInput,\n EventType,\n Message,\n RunFinishedEvent,\n RunStartedEvent,\n TextMessageChunkEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolCallResultEvent,\n RunErrorEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n} from \"@ag-ui/client\";\nimport {\n streamText,\n LanguageModel,\n ModelMessage,\n AssistantModelMessage,\n UserModelMessage,\n ToolModelMessage,\n ToolCallPart,\n ToolResultPart,\n TextPart,\n tool as createVercelAISDKTool,\n ToolChoice,\n ToolSet,\n stepCountIs,\n} from \"ai\";\nimport { experimental_createMCPClient as createMCPClient } from \"@ai-sdk/mcp\";\nimport { Observable } from \"rxjs\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createGoogleGenerativeAI } from \"@ai-sdk/google\";\nimport { randomUUID } from \"crypto\";\nimport { z } from \"zod\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\n/**\n * Properties that can be overridden by forwardedProps\n * These match the exact parameter names in streamText\n */\nexport type OverridableProperty =\n | \"model\"\n | \"toolChoice\"\n | \"maxOutputTokens\"\n | \"temperature\"\n | \"topP\"\n | \"topK\"\n | \"presencePenalty\"\n | \"frequencyPenalty\"\n | \"stopSequences\"\n | \"seed\"\n | \"maxRetries\"\n | \"prompt\";\n\n/**\n * Supported model identifiers for BuiltInAgent\n */\nexport type BuiltInAgentModel =\n // OpenAI models\n | \"openai/gpt-5\"\n | \"openai/gpt-5-mini\"\n | \"openai/gpt-4.1\"\n | \"openai/gpt-4.1-mini\"\n | \"openai/gpt-4.1-nano\"\n | \"openai/gpt-4o\"\n | \"openai/gpt-4o-mini\"\n // OpenAI reasoning series\n | \"openai/o3\"\n | \"openai/o3-mini\"\n | \"openai/o4-mini\"\n // Anthropic (Claude) models\n | \"anthropic/claude-sonnet-4.5\"\n | \"anthropic/claude-sonnet-4\"\n | \"anthropic/claude-3.7-sonnet\"\n | \"anthropic/claude-opus-4.1\"\n | \"anthropic/claude-opus-4\"\n | \"anthropic/claude-3.5-haiku\"\n // Google (Gemini) models\n | \"google/gemini-2.5-pro\"\n | \"google/gemini-2.5-flash\"\n | \"google/gemini-2.5-flash-lite\"\n // Allow any LanguageModel instance\n | (string & {});\n\n/**\n * Model specifier - can be a string like \"openai/gpt-4o\" or a LanguageModel instance\n */\nexport type ModelSpecifier = string | LanguageModel;\n\n/**\n * MCP Client configuration for HTTP transport\n */\nexport interface MCPClientConfigHTTP {\n /**\n * Type of MCP client\n */\n type: \"http\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional transport options for HTTP client\n */\n options?: StreamableHTTPClientTransportOptions;\n}\n\n/**\n * MCP Client configuration for SSE transport\n */\nexport interface MCPClientConfigSSE {\n /**\n * Type of MCP client\n */\n type: \"sse\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional HTTP headers (e.g., for authentication)\n */\n headers?: Record<string, string>;\n}\n\n/**\n * MCP Client configuration\n */\nexport type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;\n\n/**\n * Resolves a model specifier to a LanguageModel instance\n * @param spec - Model string (e.g., \"openai/gpt-4o\") or LanguageModel instance\n * @returns LanguageModel instance\n */\nexport function resolveModel(spec: ModelSpecifier): LanguageModel {\n // If already a LanguageModel instance, pass through\n if (typeof spec !== \"string\") {\n return spec;\n }\n\n // Normalize \"provider/model\" or \"provider:model\" format\n const normalized = spec.replace(\"/\", \":\").trim();\n const parts = normalized.split(\":\");\n const rawProvider = parts[0];\n const rest = parts.slice(1);\n\n if (!rawProvider) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n const provider = rawProvider.toLowerCase();\n const model = rest.join(\":\").trim();\n\n if (!model) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n switch (provider) {\n case \"openai\": {\n // Lazily create OpenAI provider\n const openai = createOpenAI({\n apiKey: process.env.OPENAI_API_KEY!,\n });\n // Accepts any OpenAI model id, e.g. \"gpt-4o\", \"gpt-4.1-mini\", \"o3-mini\"\n return openai(model);\n }\n\n case \"anthropic\": {\n // Lazily create Anthropic provider\n const anthropic = createAnthropic({\n apiKey: process.env.ANTHROPIC_API_KEY!,\n });\n // Accepts any Claude id, e.g. \"claude-3.7-sonnet\", \"claude-3.5-haiku\"\n return anthropic(model);\n }\n\n case \"google\":\n case \"gemini\":\n case \"google-gemini\": {\n // Lazily create Google provider\n const google = createGoogleGenerativeAI({\n apiKey: process.env.GOOGLE_API_KEY!,\n });\n // Accepts any Gemini id, e.g. \"gemini-2.5-pro\", \"gemini-2.5-flash\"\n return google(model);\n }\n\n default:\n throw new Error(`Unknown provider \"${provider}\" in \"${spec}\". Supported: openai, anthropic, google (gemini).`);\n }\n}\n\n/**\n * Tool definition for BuiltInAgent\n */\nexport interface ToolDefinition<TParameters extends z.ZodTypeAny = z.ZodTypeAny> {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: z.infer<TParameters>) => Promise<unknown>;\n}\n\n/**\n * Define a tool for use with BuiltInAgent\n * @param name - The name of the tool\n * @param description - Description of what the tool does\n * @param parameters - Zod schema for the tool's input parameters\n * @param execute - Function to execute the tool server-side\n * @returns Tool definition\n */\nexport function defineTool<TParameters extends z.ZodTypeAny>(config: {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: z.infer<TParameters>) => Promise<unknown>;\n}): ToolDefinition<TParameters> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n execute: config.execute,\n };\n}\n\ntype AGUIUserMessage = Extract<Message, { role: \"user\" }>;\n\nfunction flattenUserMessageContent(content?: AGUIUserMessage[\"content\"]): string {\n if (!content) {\n return \"\";\n }\n\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .map((part) => {\n if (\n part &&\n typeof part === \"object\" &&\n \"type\" in part &&\n (part as { type?: unknown }).type === \"text\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n return (part as { text: string }).text;\n }\n return \"\";\n })\n .filter((text) => text.length > 0)\n .join(\"\\n\");\n}\n\n/**\n * Converts AG-UI messages to Vercel AI SDK ModelMessage format\n */\nexport function convertMessagesToVercelAISDKMessages(messages: Message[]): ModelMessage[] {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content ? [{ type: \"text\", text: message.content }] : [];\n\n for (const toolCall of message.toolCalls ?? []) {\n const toolCallPart: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: JSON.parse(toolCall.function.arguments),\n };\n parts.push(toolCallPart);\n }\n\n const assistantMsg: AssistantModelMessage = {\n role: \"assistant\",\n content: parts,\n };\n result.push(assistantMsg);\n } else if (message.role === \"user\") {\n const userMsg: UserModelMessage = {\n role: \"user\",\n content: flattenUserMessageContent(message.content),\n };\n result.push(userMsg);\n } else if (message.role === \"tool\") {\n let toolName = \"unknown\";\n // Find the tool name from the corresponding tool call\n for (const msg of messages) {\n if (msg.role === \"assistant\") {\n for (const toolCall of msg.toolCalls ?? []) {\n if (toolCall.id === message.toolCallId) {\n toolName = toolCall.function.name;\n break;\n }\n }\n }\n }\n\n const toolResultPart: ToolResultPart = {\n type: \"tool-result\",\n toolCallId: message.toolCallId,\n toolName: toolName,\n output: {\n type: \"text\",\n value: message.content,\n },\n };\n\n const toolMsg: ToolModelMessage = {\n role: \"tool\",\n content: [toolResultPart],\n };\n result.push(toolMsg);\n }\n }\n\n return result;\n}\n\n/**\n * JSON Schema type definition\n */\ninterface JsonSchema {\n type: \"object\" | \"string\" | \"number\" | \"boolean\" | \"array\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n}\n\n/**\n * Converts JSON Schema to Zod schema\n */\nexport function convertJsonSchemaToZodSchema(jsonSchema: JsonSchema, required: boolean): z.ZodSchema {\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false);\n }\n let schema = z.object(spec).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n let schema = z.string().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\") {\n let schema = z.number().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n let schema = z.boolean().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n if (!jsonSchema.items) {\n throw new Error(\"Array type must have items property\");\n }\n let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n let schema = z.array(itemSchema).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n throw new Error(\"Invalid JSON schema\");\n}\n\n/**\n * Converts AG-UI tools to Vercel AI SDK ToolSet\n */\nfunction isJsonSchema(obj: unknown): obj is JsonSchema {\n if (typeof obj !== \"object\" || obj === null) return false;\n const schema = obj as Record<string, unknown>;\n return typeof schema.type === \"string\" && [\"object\", \"string\", \"number\", \"boolean\", \"array\"].includes(schema.type);\n}\n\nexport function convertToolsToVercelAITools(tools: RunAgentInput[\"tools\"]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n const zodSchema = convertJsonSchemaToZodSchema(tool.parameters, true);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: zodSchema,\n });\n }\n\n return result;\n}\n\n/**\n * Converts ToolDefinition array to Vercel AI SDK ToolSet\n */\nexport function convertToolDefinitionsToVercelAITools(tools: ToolDefinition[]): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: tool.parameters,\n execute: tool.execute,\n });\n }\n\n return result;\n}\n\n/**\n * Configuration for BuiltInAgent\n */\nexport interface BuiltInAgentConfiguration {\n /**\n * The model to use\n */\n model: BuiltInAgentModel | LanguageModel;\n /**\n * Maximum number of steps/iterations for tool calling (default: 1)\n */\n maxSteps?: number;\n /**\n * Tool choice setting - how tools are selected for execution (default: \"auto\")\n */\n toolChoice?: ToolChoice<Record<string, unknown>>;\n /**\n * Maximum number of tokens to generate\n */\n maxOutputTokens?: number;\n /**\n * Temperature setting (range depends on provider)\n */\n temperature?: number;\n /**\n * Nucleus sampling (topP)\n */\n topP?: number;\n /**\n * Top K sampling\n */\n topK?: number;\n /**\n * Presence penalty\n */\n presencePenalty?: number;\n /**\n * Frequency penalty\n */\n frequencyPenalty?: number;\n /**\n * Sequences that will stop the generation\n */\n stopSequences?: string[];\n /**\n * Seed for deterministic results\n */\n seed?: number;\n /**\n * Maximum number of retries\n */\n maxRetries?: number;\n /**\n * Prompt for the agent\n */\n prompt?: string;\n /**\n * List of properties that can be overridden by forwardedProps.\n */\n overridableProperties?: OverridableProperty[];\n /**\n * Optional list of MCP server configurations\n */\n mcpServers?: MCPClientConfig[];\n /**\n * Optional tools available to the agent\n */\n tools?: ToolDefinition[];\n}\n\nexport class BuiltInAgent extends AbstractAgent {\n private abortController?: AbortController;\n\n constructor(private config: BuiltInAgentConfiguration) {\n super();\n }\n\n /**\n * Check if a property can be overridden by forwardedProps\n */\n canOverride(property: OverridableProperty): boolean {\n return this.config?.overridableProperties?.includes(property) ?? false;\n }\n\n run(input: RunAgentInput): Observable<BaseEvent> {\n return new Observable<BaseEvent>((subscriber) => {\n // Emit RUN_STARTED event\n const startEvent: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(startEvent);\n\n // Resolve the model\n const model = resolveModel(this.config.model);\n\n // Build prompt based on conditions\n let systemPrompt: string | undefined = undefined;\n\n // Check if we should build a prompt:\n // - config.prompt is set, OR\n // - input.context is non-empty, OR\n // - input.state is non-empty and not an empty object\n const hasPrompt = !!this.config.prompt;\n const hasContext = input.context && input.context.length > 0;\n const hasState =\n input.state !== undefined &&\n input.state !== null &&\n !(typeof input.state === \"object\" && Object.keys(input.state).length === 0);\n\n if (hasPrompt || hasContext || hasState) {\n const parts: string[] = [];\n\n // First: the prompt if any\n if (hasPrompt) {\n parts.push(this.config.prompt!);\n }\n\n // Second: context from the application\n if (hasContext) {\n parts.push(\"\\n## Context from the application\\n\");\n for (const ctx of input.context) {\n parts.push(`${ctx.description}:\\n${ctx.value}\\n`);\n }\n }\n\n // Third: state from the application that can be edited\n if (hasState) {\n parts.push(\n \"\\n## Application State\\n\" +\n \"This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.\\n\" +\n `\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\`\\n`,\n );\n }\n\n systemPrompt = parts.join(\"\");\n }\n\n // Convert messages and prepend system message if we have a prompt\n const messages = convertMessagesToVercelAISDKMessages(input.messages);\n if (systemPrompt) {\n messages.unshift({\n role: \"system\",\n content: systemPrompt,\n });\n }\n\n // Merge tools from input and config\n let allTools: ToolSet = convertToolsToVercelAITools(input.tools);\n if (this.config.tools && this.config.tools.length > 0) {\n const configTools = convertToolDefinitionsToVercelAITools(this.config.tools);\n allTools = { ...allTools, ...configTools };\n }\n\n const streamTextParams: Parameters<typeof streamText>[0] = {\n model,\n messages,\n tools: allTools,\n toolChoice: this.config.toolChoice,\n stopWhen: this.config.maxSteps ? stepCountIs(this.config.maxSteps) : undefined,\n maxOutputTokens: this.config.maxOutputTokens,\n temperature: this.config.temperature,\n topP: this.config.topP,\n topK: this.config.topK,\n presencePenalty: this.config.presencePenalty,\n frequencyPenalty: this.config.frequencyPenalty,\n stopSequences: this.config.stopSequences,\n seed: this.config.seed,\n maxRetries: this.config.maxRetries,\n };\n\n // Apply forwardedProps overrides (if allowed)\n if (input.forwardedProps && typeof input.forwardedProps === \"object\") {\n const props = input.forwardedProps as Record<string, unknown>;\n\n // Check and apply each overridable property\n if (props.model !== undefined && this.canOverride(\"model\")) {\n if (typeof props.model === \"string\" || typeof props.model === \"object\") {\n // Accept any string or LanguageModel instance for model override\n streamTextParams.model = resolveModel(props.model as string | LanguageModel);\n }\n }\n if (props.toolChoice !== undefined && this.canOverride(\"toolChoice\")) {\n // ToolChoice can be 'auto', 'required', 'none', or { type: 'tool', toolName: string }\n const toolChoice = props.toolChoice;\n if (\n toolChoice === \"auto\" ||\n toolChoice === \"required\" ||\n toolChoice === \"none\" ||\n (typeof toolChoice === \"object\" &&\n toolChoice !== null &&\n \"type\" in toolChoice &&\n toolChoice.type === \"tool\")\n ) {\n streamTextParams.toolChoice = toolChoice as ToolChoice<Record<string, unknown>>;\n }\n }\n if (typeof props.maxOutputTokens === \"number\" && this.canOverride(\"maxOutputTokens\")) {\n streamTextParams.maxOutputTokens = props.maxOutputTokens;\n }\n if (typeof props.temperature === \"number\" && this.canOverride(\"temperature\")) {\n streamTextParams.temperature = props.temperature;\n }\n if (typeof props.topP === \"number\" && this.canOverride(\"topP\")) {\n streamTextParams.topP = props.topP;\n }\n if (typeof props.topK === \"number\" && this.canOverride(\"topK\")) {\n streamTextParams.topK = props.topK;\n }\n if (typeof props.presencePenalty === \"number\" && this.canOverride(\"presencePenalty\")) {\n streamTextParams.presencePenalty = props.presencePenalty;\n }\n if (typeof props.frequencyPenalty === \"number\" && this.canOverride(\"frequencyPenalty\")) {\n streamTextParams.frequencyPenalty = props.frequencyPenalty;\n }\n if (Array.isArray(props.stopSequences) && this.canOverride(\"stopSequences\")) {\n // Validate all elements are strings\n if (props.stopSequences.every((item): item is string => typeof item === \"string\")) {\n streamTextParams.stopSequences = props.stopSequences;\n }\n }\n if (typeof props.seed === \"number\" && this.canOverride(\"seed\")) {\n streamTextParams.seed = props.seed;\n }\n if (typeof props.maxRetries === \"number\" && this.canOverride(\"maxRetries\")) {\n streamTextParams.maxRetries = props.maxRetries;\n }\n }\n\n // Set up MCP clients if configured and process the stream\n const mcpClients: Array<{ close: () => Promise<void> }> = [];\n\n (async () => {\n const abortController = new AbortController();\n this.abortController = abortController;\n let terminalEventEmitted = false;\n\n try {\n // Add AG-UI state update tools\n streamTextParams.tools = {\n ...streamTextParams.tools,\n AGUISendStateSnapshot: createVercelAISDKTool({\n description: \"Replace the entire application state with a new snapshot\",\n inputSchema: z.object({\n snapshot: z.any().describe(\"The complete new state object\"),\n }),\n execute: async ({ snapshot }) => {\n return { success: true, snapshot };\n },\n }),\n AGUISendStateDelta: createVercelAISDKTool({\n description: \"Apply incremental updates to application state using JSON Patch operations\",\n inputSchema: z.object({\n delta: z\n .array(\n z.object({\n op: z.enum([\"add\", \"replace\", \"remove\"]).describe(\"The operation to perform\"),\n path: z.string().describe(\"JSON Pointer path (e.g., '/foo/bar')\"),\n value: z\n .any()\n .optional()\n .describe(\n \"The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.\",\n ),\n }),\n )\n .describe(\"Array of JSON Patch operations\"),\n }),\n execute: async ({ delta }) => {\n return { success: true, delta };\n },\n }),\n };\n\n // Initialize MCP clients and get their tools\n if (this.config.mcpServers && this.config.mcpServers.length > 0) {\n for (const serverConfig of this.config.mcpServers) {\n let transport;\n\n if (serverConfig.type === \"http\") {\n const url = new URL(serverConfig.url);\n transport = new StreamableHTTPClientTransport(url, serverConfig.options);\n } else if (serverConfig.type === \"sse\") {\n transport = new SSEClientTransport(new URL(serverConfig.url), serverConfig.headers);\n }\n\n if (transport) {\n const mcpClient = await createMCPClient({ transport });\n mcpClients.push(mcpClient);\n\n // Get tools from this MCP server and merge with existing tools\n const mcpTools = await mcpClient.tools();\n streamTextParams.tools = { ...streamTextParams.tools, ...mcpTools };\n }\n }\n }\n\n // Call streamText and process the stream\n const response = streamText({ ...streamTextParams, abortSignal: abortController.signal });\n\n let messageId = randomUUID();\n\n const toolCallStates = new Map<\n string,\n {\n started: boolean;\n hasArgsDelta: boolean;\n ended: boolean;\n toolName?: string;\n }\n >();\n\n const ensureToolCallState = (toolCallId: string) => {\n let state = toolCallStates.get(toolCallId);\n if (!state) {\n state = { started: false, hasArgsDelta: false, ended: false };\n toolCallStates.set(toolCallId, state);\n }\n return state;\n };\n\n // Process fullStream events\n for await (const part of response.fullStream) {\n switch (part.type) {\n case 'abort':\n const abortEndEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(abortEndEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n\n case \"tool-input-start\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName;\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n break;\n }\n\n case \"tool-input-delta\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.hasArgsDelta = true;\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: part.delta,\n };\n subscriber.next(argsEvent);\n break;\n }\n\n case \"tool-input-end\": {\n // No direct event – the subsequent \"tool-call\" part marks completion.\n break;\n }\n\n case \"text-start\": {\n // New text message starting - use the SDK-provided id\n messageId = \"id\" in part ? (part.id as typeof messageId) : randomUUID();\n break;\n }\n\n case \"text-delta\": {\n // Accumulate text content - in AI SDK 5.0, the property is 'text'\n const textDelta = \"text\" in part ? part.text : \"\";\n // Emit text chunk event\n const textEvent: TextMessageChunkEvent = {\n type: EventType.TEXT_MESSAGE_CHUNK,\n role: \"assistant\",\n messageId,\n delta: textDelta,\n };\n subscriber.next(textEvent);\n break;\n }\n\n case \"tool-call\": {\n const toolCallId = part.toolCallId;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName ?? state.toolName;\n\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n\n if (!state.hasArgsDelta && \"input\" in part && part.input !== undefined) {\n let serializedInput = \"\";\n if (typeof part.input === \"string\") {\n serializedInput = part.input;\n } else {\n try {\n serializedInput = JSON.stringify(part.input);\n } catch {\n serializedInput = String(part.input);\n }\n }\n\n if (serializedInput.length > 0) {\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: serializedInput,\n };\n subscriber.next(argsEvent);\n state.hasArgsDelta = true;\n }\n }\n\n if (!state.ended) {\n state.ended = true;\n const endEvent: ToolCallEndEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n subscriber.next(endEvent);\n }\n break;\n }\n\n case \"tool-result\": {\n const toolResult = \"output\" in part ? part.output : null;\n const toolName = \"toolName\" in part ? part.toolName : \"\";\n toolCallStates.delete(part.toolCallId);\n\n // Check if this is a state update tool\n if (toolName === \"AGUISendStateSnapshot\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateSnapshotEvent\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: toolResult.snapshot,\n };\n subscriber.next(stateSnapshotEvent);\n } else if (toolName === \"AGUISendStateDelta\" && toolResult && typeof toolResult === \"object\") {\n // Emit StateDeltaEvent\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta: toolResult.delta,\n };\n subscriber.next(stateDeltaEvent);\n }\n\n // Always emit the tool result event for the LLM\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId: part.toolCallId,\n content: JSON.stringify(toolResult),\n };\n subscriber.next(resultEvent);\n break;\n }\n\n case \"finish\":\n // Emit run finished event\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n\n case \"error\": {\n if (abortController.signal.aborted) {\n break;\n }\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: part.error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n\n // Handle error\n subscriber.error(part.error);\n break;\n }\n }\n }\n\n if (!terminalEventEmitted) {\n if (abortController.signal.aborted) {\n // Let the runner finalize the stream on stop requests so it can\n // inject consistent closing events and a RUN_FINISHED marker.\n } else {\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n }\n\n terminalEventEmitted = true;\n subscriber.complete();\n }\n } catch (error) {\n if (abortController.signal.aborted) {\n subscriber.complete();\n } else {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n subscriber.error(error);\n }\n } finally {\n this.abortController = undefined;\n await Promise.all(mcpClients.map((client) => client.close()));\n }\n })();\n\n // Cleanup function\n return () => {\n // Cleanup MCP clients if stream is unsubscribed\n Promise.all(mcpClients.map((client) => client.close())).catch(() => {\n // Ignore cleanup errors\n });\n };\n });\n }\n\n clone() {\n return new BuiltInAgent(this.config);\n }\n\n abortRun(): void {\n this.abortController?.abort();\n }\n}\n\n/**\n * @deprecated Use BuiltInAgent instead\n */\nexport class BasicAgent extends BuiltInAgent {\n constructor(config: BuiltInAgentConfiguration) {\n super(config);\n console.warn(\"BasicAgent is deprecated, use BuiltInAgent instead\");\n }\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EAGA;AAAA,OAYK;AACP;AAAA,EACE;AAAA,EASA,QAAQ;AAAA,EAGR;AAAA,OACK;AACP,SAAS,gCAAgC,uB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AACZ,YAAQ,KAAK,oDAAoD;AAAA,EACnE;AACF;","names":["startEvent"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copilotkitnext/agent",
3
- "version": "0.0.31",
3
+ "version": "0.0.32",
4
4
  "description": "Basic Agent for CopilotKit",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/src/index.ts CHANGED
@@ -62,9 +62,9 @@ export type OverridableProperty =
62
62
  | "prompt";
63
63
 
64
64
  /**
65
- * Supported model identifiers for BasicAgent
65
+ * Supported model identifiers for BuiltInAgent
66
66
  */
67
- export type BasicAgentModel =
67
+ export type BuiltInAgentModel =
68
68
  // OpenAI models
69
69
  | "openai/gpt-5"
70
70
  | "openai/gpt-5-mini"
@@ -205,7 +205,7 @@ export function resolveModel(spec: ModelSpecifier): LanguageModel {
205
205
  }
206
206
 
207
207
  /**
208
- * Tool definition for BasicAgent
208
+ * Tool definition for BuiltInAgent
209
209
  */
210
210
  export interface ToolDefinition<TParameters extends z.ZodTypeAny = z.ZodTypeAny> {
211
211
  name: string;
@@ -215,7 +215,7 @@ export interface ToolDefinition<TParameters extends z.ZodTypeAny = z.ZodTypeAny>
215
215
  }
216
216
 
217
217
  /**
218
- * Define a tool for use with BasicAgent
218
+ * Define a tool for use with BuiltInAgent
219
219
  * @param name - The name of the tool
220
220
  * @param description - Description of what the tool does
221
221
  * @param parameters - Zod schema for the tool's input parameters
@@ -423,13 +423,13 @@ export function convertToolDefinitionsToVercelAITools(tools: ToolDefinition[]):
423
423
  }
424
424
 
425
425
  /**
426
- * Configuration for BasicAgent
426
+ * Configuration for BuiltInAgent
427
427
  */
428
- export interface BasicAgentConfiguration {
428
+ export interface BuiltInAgentConfiguration {
429
429
  /**
430
430
  * The model to use
431
431
  */
432
- model: BasicAgentModel | LanguageModel;
432
+ model: BuiltInAgentModel | LanguageModel;
433
433
  /**
434
434
  * Maximum number of steps/iterations for tool calling (default: 1)
435
435
  */
@@ -492,10 +492,10 @@ export interface BasicAgentConfiguration {
492
492
  tools?: ToolDefinition[];
493
493
  }
494
494
 
495
- export class BasicAgent extends AbstractAgent {
495
+ export class BuiltInAgent extends AbstractAgent {
496
496
  private abortController?: AbortController;
497
497
 
498
- constructor(private config: BasicAgentConfiguration) {
498
+ constructor(private config: BuiltInAgentConfiguration) {
499
499
  super();
500
500
  }
501
501
 
@@ -976,10 +976,20 @@ export class BasicAgent extends AbstractAgent {
976
976
  }
977
977
 
978
978
  clone() {
979
- return new BasicAgent(this.config);
979
+ return new BuiltInAgent(this.config);
980
980
  }
981
981
 
982
982
  abortRun(): void {
983
983
  this.abortController?.abort();
984
984
  }
985
985
  }
986
+
987
+ /**
988
+ * @deprecated Use BuiltInAgent instead
989
+ */
990
+ export class BasicAgent extends BuiltInAgent {
991
+ constructor(config: BuiltInAgentConfiguration) {
992
+ super(config);
993
+ console.warn("BasicAgent is deprecated, use BuiltInAgent instead");
994
+ }
995
+ }
@@ -1,38 +0,0 @@
1
-
2
- 
3
- > @copilotkitnext/agent@0.0.28 test /Users/mikeryan/Repos/cpk/vnext_experimental/packages/agent
4
- > vitest run
5
-
6
- [?25l
7
-  RUN  v3.2.4 /Users/mikeryan/Repos/cpk/vnext_experimental/packages/agent
8
-
9
- [?2026h
10
-  ❯ src/__tests__/config-tools-execution.test.ts [queued]
11
-
12
-  Test Files 0 passed (5)
13
-  Tests 0 passed (0)
14
-  Start at 13:18:38
15
-  Duration 201ms
16
- [?2026l[?2026h
17
-  ❯ src/__tests__/basic-agent.test.ts 0/14
18
-  ❯ src/__tests__/config-tools-execution.test.ts [queued]
19
-  ❯ src/__tests__/property-overrides.test.ts [queued]
20
-  ❯ src/__tests__/state-tools.test.ts [queued]
21
-  ❯ src/__tests__/utils.test.ts [queued]
22
-
23
-  Test Files 0 passed (5)
24
-  Tests 0 passed (14)
25
-  Start at 13:18:38
26
-  Duration 404ms
27
- [?2026l ✓ src/__tests__/property-overrides.test.ts (21 tests) 8ms
28
- ✓ src/__tests__/basic-agent.test.ts (14 tests) 9ms
29
- ✓ src/__tests__/state-tools.test.ts (10 tests) 7ms
30
- ✓ src/__tests__/config-tools-execution.test.ts (11 tests) 8ms
31
- ✓ src/__tests__/utils.test.ts (27 tests) 7ms
32
-
33
-  Test Files  5 passed (5)
34
-  Tests  83 passed (83)
35
-  Start at  13:18:38
36
-  Duration  534ms (transform 239ms, setup 0ms, collect 1.25s, tests 39ms, environment 0ms, prepare 299ms)
37
-
38
- [?25h