@copilotkit/runtime 1.56.5-canary.1777972218 → 1.57.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/index.cjs +8 -41
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +27 -54
- package/dist/agent/index.d.cts.map +1 -1
- package/dist/agent/index.d.mts +27 -54
- package/dist/agent/index.d.mts.map +1 -1
- package/dist/agent/index.mjs +10 -43
- package/dist/agent/index.mjs.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.mjs +1 -1
- package/dist/v2/index.cjs +0 -2
- package/dist/v2/index.d.cts +5 -6
- package/dist/v2/index.d.mts +5 -6
- package/dist/v2/index.mjs +1 -2
- package/dist/v2/runtime/core/runtime.d.cts +0 -1
- package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
- package/dist/v2/runtime/core/runtime.d.mts +0 -1
- package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/run.cjs +0 -4
- package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/run.mjs +0 -4
- package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
- package/dist/v2/runtime/index.d.cts +1 -3
- package/dist/v2/runtime/index.d.cts.map +1 -1
- package/dist/v2/runtime/index.d.mts +1 -3
- package/dist/v2/runtime/index.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs +0 -53
- package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts +0 -41
- package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +0 -41
- package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs +0 -53
- package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
- package/package.json +2 -2
- package/src/agent/__tests__/mcp-clients.test.ts +25 -11
- package/src/agent/__tests__/mcp-servers-integration.test.ts +1 -485
- package/src/agent/index.ts +62 -139
- package/src/v2/runtime/handlers/intelligence/run.ts +0 -9
- package/src/v2/runtime/handlers/shared/agent-utils.ts +0 -1
- package/src/v2/runtime/index.ts +0 -5
- package/src/v2/runtime/intelligence-platform/client.ts +0 -68
- package/dist/agent/mcp-transport.cjs +0 -94
- package/dist/agent/mcp-transport.cjs.map +0 -1
- package/dist/agent/mcp-transport.d.cts +0 -51
- package/dist/agent/mcp-transport.d.cts.map +0 -1
- package/dist/agent/mcp-transport.d.mts +0 -52
- package/dist/agent/mcp-transport.d.mts.map +0 -1
- package/dist/agent/mcp-transport.mjs +0 -92
- package/dist/agent/mcp-transport.mjs.map +0 -1
- package/dist/v2/runtime/intelligence-platform/index.d.cts +0 -2
- package/dist/v2/runtime/intelligence-platform/index.d.mts +0 -2
- package/src/agent/mcp-transport.ts +0 -190
- package/src/v2/runtime/intelligence-platform/__tests__/intelligence-mcp-helper.test.ts +0 -190
package/dist/agent/index.cjs
CHANGED
|
@@ -2,7 +2,6 @@ require("reflect-metadata");
|
|
|
2
2
|
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
3
|
const require_aisdk = require('./converters/aisdk.cjs');
|
|
4
4
|
const require_tanstack = require('./converters/tanstack.cjs');
|
|
5
|
-
const require_mcp_transport = require('./mcp-transport.cjs');
|
|
6
5
|
let _ai_sdk_openai = require("@ai-sdk/openai");
|
|
7
6
|
let _copilotkit_shared = require("@copilotkit/shared");
|
|
8
7
|
let rxjs = require("rxjs");
|
|
@@ -13,35 +12,11 @@ let _ai_sdk_anthropic = require("@ai-sdk/anthropic");
|
|
|
13
12
|
let _ai_sdk_google = require("@ai-sdk/google");
|
|
14
13
|
let _ai_sdk_google_vertex = require("@ai-sdk/google-vertex");
|
|
15
14
|
let zod = require("zod");
|
|
15
|
+
let _modelcontextprotocol_sdk_client_streamableHttp_js = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
|
|
16
|
+
let _modelcontextprotocol_sdk_client_sse_js = require("@modelcontextprotocol/sdk/client/sse.js");
|
|
16
17
|
|
|
17
18
|
//#region src/agent/index.ts
|
|
18
19
|
/**
|
|
19
|
-
* Open an MCP client for the given server config.
|
|
20
|
-
*
|
|
21
|
-
* - HTTP always goes through {@link CopilotKitMCPTransport} (preserves the
|
|
22
|
-
* pre-existing `options` escape hatch and adds per-call `getHeaders`
|
|
23
|
-
* resolution).
|
|
24
|
-
* - SSE goes through `@ai-sdk/mcp`'s `createMCPClient`, whose built-in
|
|
25
|
-
* `SseMCPTransport` correctly applies static `headers` on every outbound
|
|
26
|
-
* request.
|
|
27
|
-
*/
|
|
28
|
-
async function openMcpClient(config, context) {
|
|
29
|
-
if (config.type === "http") return (0, _ai_sdk_mcp.createMCPClient)({ transport: new require_mcp_transport.CopilotKitMCPTransport({
|
|
30
|
-
url: config.url,
|
|
31
|
-
headers: config.headers,
|
|
32
|
-
getHeaders: config.getHeaders,
|
|
33
|
-
options: config.options,
|
|
34
|
-
requestHeaders: context.requestHeaders,
|
|
35
|
-
input: context.input,
|
|
36
|
-
user: context.user
|
|
37
|
-
}) });
|
|
38
|
-
return (0, _ai_sdk_mcp.createMCPClient)({ transport: {
|
|
39
|
-
type: "sse",
|
|
40
|
-
url: config.url,
|
|
41
|
-
headers: config.headers
|
|
42
|
-
} });
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
20
|
* Resolves a model specifier to a LanguageModel instance
|
|
46
21
|
* @param spec - Model string (e.g., "openai/gpt-4o") or LanguageModel instance
|
|
47
22
|
* @param apiKey - Optional API key to use instead of environment variables
|
|
@@ -347,7 +322,6 @@ var BuiltInAgent = class BuiltInAgent extends _ag_ui_client.AbstractAgent {
|
|
|
347
322
|
constructor(config) {
|
|
348
323
|
super();
|
|
349
324
|
this.config = config;
|
|
350
|
-
this.headers = {};
|
|
351
325
|
}
|
|
352
326
|
/**
|
|
353
327
|
* Check if a property can be overridden by forwardedProps
|
|
@@ -516,19 +490,12 @@ This is state from the application that you can edit by calling AGUISendStateSna
|
|
|
516
490
|
...mcpTools
|
|
517
491
|
};
|
|
518
492
|
}
|
|
519
|
-
if (this.config.mcpServers && this.config.mcpServers.length > 0) {
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
continue;
|
|
526
|
-
}
|
|
527
|
-
const mcpClient = await openMcpClient(serverConfig, {
|
|
528
|
-
requestHeaders,
|
|
529
|
-
input,
|
|
530
|
-
user
|
|
531
|
-
});
|
|
493
|
+
if (this.config.mcpServers && this.config.mcpServers.length > 0) for (const serverConfig of this.config.mcpServers) {
|
|
494
|
+
let transport;
|
|
495
|
+
if (serverConfig.type === "http") transport = new _modelcontextprotocol_sdk_client_streamableHttp_js.StreamableHTTPClientTransport(new URL(serverConfig.url), serverConfig.options);
|
|
496
|
+
else if (serverConfig.type === "sse") transport = new _modelcontextprotocol_sdk_client_sse_js.SSEClientTransport(new URL(serverConfig.url), serverConfig.headers);
|
|
497
|
+
if (transport) {
|
|
498
|
+
const mcpClient = await (0, _ai_sdk_mcp.experimental_createMCPClient)({ transport });
|
|
532
499
|
mcpClients.push(mcpClient);
|
|
533
500
|
const mcpTools = await mcpClient.tools();
|
|
534
501
|
streamTextParams.tools = {
|
package/dist/agent/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["CopilotKitMCPTransport","z","AbstractAgent","Observable","EventType","convertAISDKStream","convertTanStackStream"],"sources":["../../src/agent/index.ts"],"sourcesContent":["import type {\n BaseEvent,\n RunAgentInput,\n Message,\n ReasoningEndEvent,\n ReasoningMessageContentEvent,\n ReasoningMessageEndEvent,\n ReasoningMessageStartEvent,\n ReasoningStartEvent,\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 { AbstractAgent, EventType } from \"@ag-ui/client\";\nimport type { AgentCapabilities } from \"@ag-ui/core\";\nimport type {\n LanguageModel,\n ModelMessage,\n AssistantModelMessage,\n UserModelMessage,\n ToolModelMessage,\n SystemModelMessage,\n ToolCallPart,\n ToolResultPart,\n TextPart,\n ImagePart,\n FilePart,\n ToolChoice,\n ToolSet,\n} from \"ai\";\nimport { streamText, tool as createVercelAISDKTool, stepCountIs } from \"ai\";\nimport { createMCPClient } from \"@ai-sdk/mcp\";\nimport type { MCPClient } 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 { createVertex } from \"@ai-sdk/google-vertex\";\nimport { logger, safeParseToolArgs } from \"@copilotkit/shared\";\nimport { z } from \"zod\";\nimport type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport { schemaToJsonSchema } from \"@copilotkit/shared\";\nimport { jsonSchema as aiJsonSchema } from \"ai\";\nimport { convertAISDKStream } from \"./converters/aisdk\";\nimport { convertTanStackStream } from \"./converters/tanstack\";\nimport type { StreamableHTTPClientTransportOptions } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport {\n CopilotKitMCPTransport,\n MCPHeaderResolverError,\n type MCPRequestContext,\n type MCPRuntimeUser,\n} from \"./mcp-transport\";\nimport { randomUUID } from \"@copilotkit/shared\";\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 | \"providerOptions\";\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// MCPRequestContext and MCPHeaderResolverError now live in mcp-transport.ts.\n// Re-export so existing imports of these symbols from agent/index continue to\n// work.\nexport { MCPHeaderResolverError, type MCPRequestContext };\n\n/**\n * MCP Client configuration for HTTP transport.\n */\nexport interface MCPClientConfigHTTP {\n /** Type of MCP client */\n type: \"http\";\n /** URL of the MCP server */\n url: string;\n /**\n * Optional transport options for the underlying\n * `StreamableHTTPClientTransport`. Pre-existing escape hatch for advanced\n * use cases (custom `fetch`, `requestInit`, OAuth `authProvider`, etc.).\n */\n options?: StreamableHTTPClientTransportOptions;\n /**\n * Static HTTP headers, merged into every outbound request to this server.\n * For per-call values, use {@link MCPClientConfigHTTP.getHeaders} instead.\n */\n headers?: Record<string, string>;\n /**\n * Per-call header resolver. Invoked on **every** outbound HTTP request to\n * this server (initialize, tools/list, tools/call, SSE reconnects). The\n * returned headers are merged on top of `headers` and any\n * `options.requestInit.headers`, so a resolver can override either.\n *\n * Throwing from the resolver causes the agent run to emit `RUN_ERROR`\n * carrying a {@link MCPHeaderResolverError}.\n */\n getHeaders?: (\n ctx: MCPRequestContext,\n ) => Record<string, string> | Promise<Record<string, string>>;\n /** If true, the server is skipped at run-start when `agent.user` is unset. */\n requiresUser?: boolean;\n}\n\n/**\n * MCP Client configuration for SSE transport.\n */\nexport interface MCPClientConfigSSE {\n /** Type of MCP client */\n type: \"sse\";\n /** URL of the MCP server */\n url: string;\n /** Optional HTTP headers (e.g., for authentication). */\n headers?: Record<string, string>;\n}\n\n/**\n * MCP Client configuration.\n */\nexport type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;\n\n/**\n * A user-managed MCP client that provides tools to the agent. Structural\n * alias for `@ai-sdk/mcp`'s `MCPClient.tools` slice — pass any value built by\n * `createMCPClient()` directly, or supply a custom `{ tools(): ... }` object\n * for tests/caching layers.\n *\n * Unlike `mcpServers`, the agent does NOT create or close these clients. The\n * user controls the full lifecycle.\n */\nexport type MCPClientProvider = Pick<MCPClient, \"tools\">;\n\n/**\n * Open an MCP client for the given server config.\n *\n * - HTTP always goes through {@link CopilotKitMCPTransport} (preserves the\n * pre-existing `options` escape hatch and adds per-call `getHeaders`\n * resolution).\n * - SSE goes through `@ai-sdk/mcp`'s `createMCPClient`, whose built-in\n * `SseMCPTransport` correctly applies static `headers` on every outbound\n * request.\n */\nasync function openMcpClient(\n config: MCPClientConfig,\n context: {\n requestHeaders: Record<string, string>;\n input: RunAgentInput;\n user?: MCPRuntimeUser;\n },\n): Promise<MCPClient> {\n if (config.type === \"http\") {\n const transport = new CopilotKitMCPTransport({\n url: config.url,\n headers: config.headers,\n getHeaders: config.getHeaders,\n options: config.options,\n requestHeaders: context.requestHeaders,\n input: context.input,\n user: context.user,\n });\n return createMCPClient({ transport });\n }\n\n // SSE: hand to Vercel's transport. Static `headers` are applied via the\n // SseMCPTransport's common-header pipeline.\n return createMCPClient({\n transport: {\n type: \"sse\",\n url: config.url,\n headers: config.headers,\n },\n });\n}\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 * @param apiKey - Optional API key to use instead of environment variables\n * @returns LanguageModel instance\n */\nexport function resolveModel(\n spec: ModelSpecifier,\n apiKey?: string,\n): 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 // Use provided apiKey, or fall back to environment variable\n const openai = createOpenAI({\n apiKey: 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 // Use provided apiKey, or fall back to environment variable\n const anthropic = createAnthropic({\n apiKey: 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 // Use provided apiKey, or fall back to environment variable\n const google = createGoogleGenerativeAI({\n apiKey: 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 case \"vertex\": {\n const vertex = createVertex();\n return vertex(model);\n }\n\n default:\n throw new Error(\n `Unknown provider \"${provider}\" in \"${spec}\". Supported: openai, anthropic, google (gemini).`,\n );\n }\n}\n\n/**\n * Tool definition for BuiltInAgent\n */\nexport interface ToolDefinition<\n TParameters extends StandardSchemaV1 = StandardSchemaV1,\n> {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: InferSchemaOutput<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 - Schema for the tool's input parameters (any Standard Schema V1 compatible library: Zod, Valibot, ArkType, etc.)\n * @param execute - Function to execute the tool server-side\n * @returns Tool definition\n */\nexport function defineTool<TParameters extends StandardSchemaV1>(config: {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: InferSchemaOutput<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\n/**\n * Converts AG-UI user message content to Vercel AI SDK UserContent format.\n * Handles plain strings, new modality-specific parts (image/audio/video/document),\n * and legacy BinaryInputContent for backward compatibility.\n */\nfunction convertUserMessageContent(\n content: AGUIUserMessage[\"content\"],\n): string | Array<TextPart | ImagePart | FilePart> {\n if (!content) {\n return \"\";\n }\n\n if (typeof content === \"string\") {\n return content;\n }\n\n const parts: Array<TextPart | ImagePart | FilePart> = [];\n\n for (const part of content) {\n if (!part || typeof part !== \"object\" || !(\"type\" in part)) {\n continue;\n }\n\n switch (part.type) {\n case \"text\": {\n const text = (part as { text?: string }).text;\n if (text) {\n parts.push({ type: \"text\", text });\n }\n break;\n }\n\n case \"image\": {\n const source = (part as { source?: any }).source;\n if (!source) break;\n if (source.type === \"data\") {\n parts.push({\n type: \"image\",\n image: source.value,\n mediaType: source.mimeType,\n });\n } else if (source.type === \"url\") {\n try {\n parts.push({\n type: \"image\",\n image: new URL(source.value),\n mediaType: source.mimeType,\n });\n } catch {\n console.error(\n `[CopilotKit] convertUserMessageContent: invalid URL \"${source.value}\" in image part — skipping`,\n );\n }\n }\n break;\n }\n\n case \"audio\":\n case \"video\":\n case \"document\": {\n const source = (part as { source?: any }).source;\n if (!source) break;\n if (source.type === \"data\") {\n parts.push({\n type: \"file\",\n data: source.value,\n mediaType: source.mimeType,\n });\n } else if (source.type === \"url\") {\n try {\n parts.push({\n type: \"file\",\n data: new URL(source.value),\n mediaType: source.mimeType ?? \"application/octet-stream\",\n });\n } catch {\n console.error(\n `[CopilotKit] convertUserMessageContent: invalid URL \"${source.value}\" in ${part.type} part — skipping`,\n );\n }\n }\n break;\n }\n\n // Legacy BinaryInputContent backward compatibility\n case \"binary\": {\n const legacy = part as {\n mimeType?: string;\n data?: string;\n url?: string;\n };\n const mimeType = legacy.mimeType ?? \"application/octet-stream\";\n const isImage = mimeType.startsWith(\"image/\");\n\n if (legacy.data) {\n if (isImage) {\n parts.push({\n type: \"image\",\n image: legacy.data,\n mediaType: mimeType,\n });\n } else {\n parts.push({\n type: \"file\",\n data: legacy.data,\n mediaType: mimeType,\n });\n }\n } else if (legacy.url) {\n try {\n const url = new URL(legacy.url);\n if (isImage) {\n parts.push({ type: \"image\", image: url, mediaType: mimeType });\n } else {\n parts.push({ type: \"file\", data: url, mediaType: mimeType });\n }\n } catch {\n console.error(\n `[CopilotKit] convertUserMessageContent: invalid URL \"${legacy.url}\" in binary part — skipping`,\n );\n }\n }\n break;\n }\n\n default: {\n console.error(\n `[CopilotKit] convertUserMessageContent: unrecognized content part type \"${(part as { type: string }).type}\" — skipping`,\n );\n break;\n }\n }\n }\n\n return parts.length > 0 ? parts : \"\";\n}\n\n/**\n * Options for converting AG-UI messages to Vercel AI SDK format\n */\nexport interface MessageConversionOptions {\n forwardSystemMessages?: boolean;\n forwardDeveloperMessages?: boolean;\n}\n\n/**\n * Converts AG-UI messages to Vercel AI SDK ModelMessage format\n */\nexport function convertMessagesToVercelAISDKMessages(\n messages: Message[],\n options: MessageConversionOptions = {},\n): ModelMessage[] {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\" && options.forwardSystemMessages) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (\n message.role === \"developer\" &&\n options.forwardDeveloperMessages\n ) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content\n ? [{ type: \"text\", text: message.content }]\n : [];\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: safeParseToolArgs(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: convertUserMessageContent(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\" | \"integer\" | \"boolean\" | \"array\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n enum?: string[];\n}\n\n/**\n * Converts JSON Schema to Zod schema\n */\nexport function convertJsonSchemaToZodSchema(\n jsonSchema: JsonSchema,\n required: boolean,\n): z.ZodSchema {\n // Handle empty schemas {} (no input required) - treat as empty object\n if (!jsonSchema.type) {\n return required ? z.object({}) : z.object({}).optional();\n }\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(\n value,\n jsonSchema.required ? jsonSchema.required.includes(key) : false,\n );\n }\n const schema = z.object(spec).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n if (jsonSchema.enum && jsonSchema.enum.length > 0) {\n const schema = z\n .enum(jsonSchema.enum as [string, ...string[]])\n .describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n const schema = z.string().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\" || jsonSchema.type === \"integer\") {\n const schema = z.number().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n const 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 const itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n const schema = z.array(itemSchema).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n console.error(\"Invalid JSON schema:\", JSON.stringify(jsonSchema, null, 2));\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 // Empty objects {} are valid JSON schemas (no input required)\n if (Object.keys(schema).length === 0) return true;\n return (\n typeof schema.type === \"string\" &&\n [\"object\", \"string\", \"number\", \"integer\", \"boolean\", \"array\"].includes(\n schema.type,\n )\n );\n}\n\nexport function convertToolsToVercelAITools(\n tools: RunAgentInput[\"tools\"],\n): 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 * Check whether a schema is a Zod schema by inspecting its Standard Schema vendor.\n */\nfunction isZodSchema(schema: StandardSchemaV1): boolean {\n return schema[\"~standard\"]?.vendor === \"zod\";\n}\n\n/**\n * Converts ToolDefinition array to Vercel AI SDK ToolSet.\n *\n * For Zod schemas, passes them directly to the AI SDK (Zod satisfies FlexibleSchema).\n * For non-Zod schemas, converts to JSON Schema via schemaToJsonSchema() and wraps\n * with the AI SDK's jsonSchema() helper.\n */\nexport function convertToolDefinitionsToVercelAITools(\n tools: ToolDefinition[],\n): 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 (isZodSchema(tool.parameters)) {\n // Zod schemas can be passed directly to AI SDK (satisfies FlexibleSchema)\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: tool.parameters as any,\n execute: tool.execute,\n });\n } else {\n // Non-Zod: convert to JSON Schema and wrap with AI SDK's jsonSchema()\n const jsonSchemaObj = schemaToJsonSchema(tool.parameters);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: aiJsonSchema(jsonSchemaObj),\n execute: tool.execute,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Context passed to the user-supplied factory function in factory mode.\n */\nexport interface AgentFactoryContext {\n input: RunAgentInput;\n /**\n * Prefer `abortSignal` for most use cases (AI SDK, fetch, custom backends).\n * Provided for backends like TanStack AI that require the full AbortController.\n * Do NOT call `.abort()` on this controller — use `abortRun()` on the agent instead.\n */\n abortController: AbortController;\n abortSignal: AbortSignal;\n}\n\n/**\n * Factory config for AI SDK backend.\n * The factory must return an object with a `fullStream` async iterable\n * (compatible with the result of `streamText()` — only `fullStream` is consumed).\n */\nexport interface BuiltInAgentAISDKFactoryConfig {\n type: \"aisdk\";\n factory: (\n ctx: AgentFactoryContext,\n ) =>\n | { fullStream: AsyncIterable<unknown> }\n | Promise<{ fullStream: AsyncIterable<unknown> }>;\n}\n\n/**\n * Factory config for TanStack AI backend.\n * The factory must return an async iterable of TanStack AI stream chunks.\n */\nexport interface BuiltInAgentTanStackFactoryConfig {\n type: \"tanstack\";\n factory: (\n ctx: AgentFactoryContext,\n ) => AsyncIterable<unknown> | Promise<AsyncIterable<unknown>>;\n}\n\n/**\n * Factory config for a custom backend that directly yields AG-UI events.\n */\nexport interface BuiltInAgentCustomFactoryConfig {\n type: \"custom\";\n factory: (\n ctx: AgentFactoryContext,\n ) => AsyncIterable<BaseEvent> | Promise<AsyncIterable<BaseEvent>>;\n}\n\n/**\n * Union of all factory-mode configurations.\n */\nexport type BuiltInAgentFactoryConfig =\n | BuiltInAgentAISDKFactoryConfig\n | BuiltInAgentTanStackFactoryConfig\n | BuiltInAgentCustomFactoryConfig;\n\n/**\n * Classic config — BuiltInAgent handles streamText, tools, MCP, state tools, prompt building.\n */\nexport interface BuiltInAgentClassicConfig {\n /**\n * The model to use\n */\n model: BuiltInAgentModel | LanguageModel;\n /**\n * API key for the model provider (OpenAI, Anthropic, Google)\n * If not provided, falls back to environment variables:\n * - OPENAI_API_KEY for OpenAI models\n * - ANTHROPIC_API_KEY for Anthropic models\n * - GOOGLE_API_KEY for Google models\n */\n apiKey?: string;\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 list of user-managed MCP clients.\n * Unlike mcpServers, the agent does NOT create or close these clients.\n * The user controls the lifecycle, persistence, auth, and caching.\n *\n * Compatible with @ai-sdk/mcp's createMCPClient() return type:\n * ```typescript\n * const client = await createMCPClient({ transport });\n * const agent = new BuiltInAgent({ model: \"...\", mcpClients: [client] });\n * ```\n */\n mcpClients?: MCPClientProvider[];\n /**\n * Optional tools available to the agent\n */\n tools?: ToolDefinition[];\n /**\n * Forward system-role messages from input to the LLM.\n * Default: false\n */\n forwardSystemMessages?: boolean;\n /**\n * Forward developer-role messages from input to the LLM (as system messages).\n * Default: false\n */\n forwardDeveloperMessages?: boolean;\n /**\n * Provider-specific options passed to the model (e.g., OpenAI reasoningEffort).\n * Example: `{ openai: { reasoningEffort: \"high\" } }`\n */\n providerOptions?: Record<string, any>;\n /**\n * Explicit agent capabilities. **Shallow-merged** at the category level on\n * top of auto-inferred defaults — providing a category (e.g. `tools`)\n * replaces that entire category, not individual fields within it.\n *\n * For example, `{ tools: { supported: true } }` will drop the inferred\n * `clientProvided` value. Include all fields for any category you override.\n */\n capabilities?: Partial<AgentCapabilities>;\n}\n\n/**\n * Configuration for BuiltInAgent.\n *\n * Two modes:\n * - **Classic** (model + params): BuiltInAgent handles everything — streamText, tools, MCP, state tools.\n * - **Factory** (type + factory): You own the LLM call. BuiltInAgent handles lifecycle only.\n */\nexport type BuiltInAgentConfiguration =\n | BuiltInAgentClassicConfig\n | BuiltInAgentFactoryConfig;\n\n/**\n * Type guard: returns true if this is a factory-mode config.\n */\nfunction isFactoryConfig(\n config: BuiltInAgentConfiguration,\n): config is BuiltInAgentFactoryConfig {\n return \"factory\" in config;\n}\n\nexport class BuiltInAgent extends AbstractAgent {\n private abortController?: AbortController;\n /**\n * Headers populated per-request by the runtime's\n * `extractForwardableHeaders` (the incoming request's `Authorization` +\n * every `x-*` header, lower-cased). Available to MCP header resolvers via\n * {@link MCPRequestContext.requestHeaders}; kept here as a plain field so\n * the runtime's `configureAgentForRequest` feature-detect activates.\n */\n public headers: Record<string, string> = {};\n /**\n * End-user identity for the current request, populated by the runtime by\n * invoking `identifyUser(request)` (Intelligence mode). Surfaced to MCP\n * header resolvers via {@link MCPRequestContext.user}; remains undefined\n * for runs that aren't going through a runtime with `identifyUser` set.\n */\n public user?: { id: string; name: string };\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 if (isFactoryConfig(this.config)) return false;\n return this.config?.overridableProperties?.includes(property) ?? false;\n }\n\n async getCapabilities(): Promise<AgentCapabilities> {\n const inferred: AgentCapabilities = {\n tools: {\n supported: true,\n clientProvided: true,\n },\n transport: {\n streaming: true,\n },\n };\n\n if (!this.config.capabilities) {\n return inferred;\n }\n\n // Shallow merge at the category level — explicit overrides replace\n // entire categories when provided, inferred defaults fill the rest.\n return {\n ...inferred,\n ...this.config.capabilities,\n };\n }\n\n run(input: RunAgentInput): Observable<BaseEvent> {\n if (isFactoryConfig(this.config)) {\n return this.runFactory(input, this.config);\n }\n\n if (this.abortController) {\n throw new Error(\n \"Agent is already running. Call abortRun() first or create a new instance.\",\n );\n }\n\n // Set synchronously before Observable creation to close TOCTOU window\n this.abortController = new AbortController();\n const abortController = this.abortController;\n\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, passing API key if provided\n const model = resolveModel(this.config.model, this.config.apiKey);\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 !(\n typeof input.state === \"object\" &&\n Object.keys(input.state).length === 0\n );\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 forwardSystemMessages: this.config.forwardSystemMessages,\n forwardDeveloperMessages: this.config.forwardDeveloperMessages,\n });\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(\n this.config.tools,\n );\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\n ? stepCountIs(this.config.maxSteps)\n : 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 providerOptions: this.config.providerOptions,\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 (\n typeof props.model === \"string\" ||\n typeof props.model === \"object\"\n ) {\n // Accept any string or LanguageModel instance for model override\n // Use the configured API key when resolving overridden models\n streamTextParams.model = resolveModel(\n props.model as string | LanguageModel,\n this.config.apiKey,\n );\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<\n Record<string, unknown>\n >;\n }\n }\n if (\n typeof props.maxOutputTokens === \"number\" &&\n this.canOverride(\"maxOutputTokens\")\n ) {\n streamTextParams.maxOutputTokens = props.maxOutputTokens;\n }\n if (\n typeof props.temperature === \"number\" &&\n this.canOverride(\"temperature\")\n ) {\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 (\n typeof props.presencePenalty === \"number\" &&\n this.canOverride(\"presencePenalty\")\n ) {\n streamTextParams.presencePenalty = props.presencePenalty;\n }\n if (\n typeof props.frequencyPenalty === \"number\" &&\n this.canOverride(\"frequencyPenalty\")\n ) {\n streamTextParams.frequencyPenalty = props.frequencyPenalty;\n }\n if (\n Array.isArray(props.stopSequences) &&\n this.canOverride(\"stopSequences\")\n ) {\n // Validate all elements are strings\n if (\n props.stopSequences.every(\n (item): item is string => typeof item === \"string\",\n )\n ) {\n streamTextParams.stopSequences = props.stopSequences;\n }\n }\n if (typeof props.seed === \"number\" && this.canOverride(\"seed\")) {\n streamTextParams.seed = props.seed;\n }\n if (\n typeof props.maxRetries === \"number\" &&\n this.canOverride(\"maxRetries\")\n ) {\n streamTextParams.maxRetries = props.maxRetries;\n }\n if (\n props.providerOptions !== undefined &&\n this.canOverride(\"providerOptions\")\n ) {\n if (\n typeof props.providerOptions === \"object\" &&\n props.providerOptions !== null\n ) {\n streamTextParams.providerOptions = props.providerOptions as Record<\n string,\n any\n >;\n }\n }\n }\n\n // Set up MCP clients if configured and process the stream\n const mcpClients: MCPClient[] = [];\n\n (async () => {\n let terminalEventEmitted = false;\n let messageId = randomUUID();\n let reasoningMessageId = randomUUID();\n let isInReasoning = false;\n\n // Auto-close an open reasoning lifecycle.\n // Some AI SDK providers (notably @ai-sdk/anthropic) never emit \"reasoning-end\",\n // which leaves downstream state machines stuck. This helper emits the\n // missing REASONING_MESSAGE_END + REASONING_END events so the stream\n // can transition to text, tool-call, or finish phases.\n // Declared before try/catch so it is accessible in the catch block.\n const closeReasoningIfOpen = () => {\n if (!isInReasoning) return;\n isInReasoning = false;\n const reasoningMsgEnd: ReasoningMessageEndEvent = {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningMsgEnd);\n const reasoningEnd: ReasoningEndEvent = {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningEnd);\n };\n\n try {\n // Add AG-UI state update tools\n streamTextParams.tools = {\n ...streamTextParams.tools,\n AGUISendStateSnapshot: createVercelAISDKTool({\n description:\n \"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:\n \"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\n .enum([\"add\", \"replace\", \"remove\"])\n .describe(\"The operation to perform\"),\n path: z\n .string()\n .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 // Merge tools from user-managed MCP clients (user controls lifecycle)\n if (this.config.mcpClients && this.config.mcpClients.length > 0) {\n for (const client of this.config.mcpClients) {\n const mcpTools = await client.tools();\n streamTextParams.tools = {\n ...streamTextParams.tools,\n ...mcpTools,\n } as ToolSet;\n }\n }\n\n // Initialize MCP clients and get their tools\n if (this.config.mcpServers && this.config.mcpServers.length > 0) {\n // Snapshot the agent's per-run state (forwarded headers + user)\n // once at run-start. Resolvers see this immutable snapshot for the\n // lifetime of the run, including any reconnections fired after the\n // initial run completes.\n const requestHeaders: Record<string, string> = { ...this.headers };\n const user = this.user ? { ...this.user } : undefined;\n\n for (const serverConfig of this.config.mcpServers) {\n if (\n serverConfig.type === \"http\" &&\n serverConfig.requiresUser &&\n !user\n ) {\n logger.warn(\n { url: serverConfig.url },\n \"Skipping MCP server: requiresUser is set but no user is resolved for this run\",\n );\n continue;\n }\n\n const mcpClient = await openMcpClient(serverConfig, {\n requestHeaders,\n input,\n user,\n });\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 = {\n ...streamTextParams.tools,\n ...mcpTools,\n } as ToolSet;\n }\n }\n\n // Call streamText and process the stream\n const response = streamText({\n ...streamTextParams,\n abortSignal: abortController.signal,\n });\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 // Close any open reasoning lifecycle on every event except\n // reasoning-delta, which arrives mid-block and must not interrupt it.\n if (part.type !== \"reasoning-delta\") {\n closeReasoningIfOpen();\n }\n\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 \"reasoning-start\": {\n // Use SDK-provided id, or generate a fresh UUID if the id is falsy,\n // \"0\", or matches the non-unique pattern emitted by @ai-sdk/openai-compatible\n // (e.g. \"txt-0\", \"reasoning-0\", \"msg-0\").\n const providedId = \"id\" in part ? part.id : undefined;\n const isNonUniqueId =\n !providedId ||\n providedId === \"0\" ||\n /^(txt|reasoning|msg)-0$/.test(providedId);\n reasoningMessageId = isNonUniqueId\n ? randomUUID()\n : (providedId as typeof reasoningMessageId);\n const reasoningStartEvent: ReasoningStartEvent = {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningStartEvent);\n const reasoningMessageStart: ReasoningMessageStartEvent = {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: \"reasoning\",\n };\n subscriber.next(reasoningMessageStart);\n isInReasoning = true;\n break;\n }\n case \"reasoning-delta\": {\n const delta = part.text ?? \"\";\n if (!delta) break; // skip — @ag-ui/core schema requires delta to be non-empty\n const reasoningDeltaEvent: ReasoningMessageContentEvent = {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta,\n };\n subscriber.next(reasoningDeltaEvent);\n break;\n }\n case \"reasoning-end\": {\n // closeReasoningIfOpen() already called before the switch — no-op here\n // if the SDK never emits this event (e.g. @ai-sdk/anthropic).\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 // Use randomUUID() if part.id is falsy, \"0\", or matches the non-unique\n // pattern emitted by @ai-sdk/openai-compatible (e.g. \"txt-0\", \"msg-0\").\n const providedId = \"id\" in part ? part.id : undefined;\n const isNonUniqueTextId =\n !providedId ||\n providedId === \"0\" ||\n /^(txt|reasoning|msg)-0$/.test(providedId);\n messageId = isNonUniqueTextId\n ? randomUUID()\n : (providedId as typeof messageId);\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 (\n !state.hasArgsDelta &&\n \"input\" in part &&\n part.input !== undefined\n ) {\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 =\n \"output\" in part\n ? part.output\n : \"result\" in part\n ? part.result\n : 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 (\n toolName === \"AGUISendStateSnapshot\" &&\n toolResult &&\n typeof toolResult === \"object\"\n ) {\n const snapshot = toolResult.snapshot;\n if (snapshot !== undefined) {\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot,\n };\n subscriber.next(stateSnapshotEvent);\n }\n } else if (\n toolName === \"AGUISendStateDelta\" &&\n toolResult &&\n typeof toolResult === \"object\"\n ) {\n const delta = toolResult.delta;\n if (delta !== undefined) {\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta,\n };\n subscriber.next(stateDeltaEvent);\n }\n }\n\n // Always emit the tool result event for the LLM\n let serializedResult: string;\n try {\n serializedResult = JSON.stringify(toolResult);\n } catch {\n serializedResult = `[Unserializable tool result from ${toolName || part.toolCallId}]`;\n }\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId: part.toolCallId,\n content: serializedResult,\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\n case \"error\": {\n if (abortController.signal.aborted) {\n break;\n }\n const err = part.error ?? part.message ?? part.cause;\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message:\n err instanceof Error\n ? err.message\n : typeof err === \"string\"\n ? err\n : `AI SDK stream error: ${JSON.stringify(part)}`,\n threadId: input.threadId,\n runId: input.runId,\n } as RunErrorEvent;\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n\n // Handle error\n if (err instanceof Error) subscriber.error(err);\n else\n subscriber.error(\n new Error(\n typeof err === \"string\" ? err : `AI SDK stream error`,\n ),\n );\n break;\n }\n }\n }\n\n if (!terminalEventEmitted) {\n closeReasoningIfOpen();\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 closeReasoningIfOpen();\n if (abortController.signal.aborted) {\n subscriber.complete();\n } else {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error instanceof Error ? error.message : String(error),\n threadId: input.threadId,\n runId: input.runId,\n } as RunErrorEvent;\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 private runFactory(\n input: RunAgentInput,\n config: BuiltInAgentFactoryConfig,\n ): Observable<BaseEvent> {\n if (this.abortController) {\n throw new Error(\n \"Agent is already running. Call abortRun() first or create a new instance.\",\n );\n }\n\n // Set synchronously before Observable creation to close TOCTOU window\n this.abortController = new AbortController();\n const controller = this.abortController;\n\n return new Observable<BaseEvent>((subscriber) => {\n const startEvent: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(startEvent);\n\n const ctx: AgentFactoryContext = {\n input,\n abortController: controller,\n abortSignal: controller.signal,\n };\n\n (async () => {\n try {\n let events: AsyncIterable<BaseEvent>;\n\n switch (config.type) {\n case \"aisdk\": {\n const result = await config.factory(ctx);\n events = convertAISDKStream(result.fullStream, controller.signal);\n break;\n }\n case \"tanstack\": {\n const stream = await config.factory(ctx);\n events = convertTanStackStream(stream, controller.signal);\n break;\n }\n case \"custom\": {\n events = await config.factory(ctx);\n break;\n }\n default: {\n const _exhaustive: never = config;\n throw new Error(\n `Unknown agent config type: ${(_exhaustive as BuiltInAgentFactoryConfig).type}`,\n );\n }\n }\n\n for await (const event of events) {\n subscriber.next(event);\n }\n\n if (!controller.signal.aborted) {\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n }\n subscriber.complete();\n } catch (error) {\n if (controller.signal.aborted) {\n subscriber.complete();\n } else {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error instanceof Error ? error.message : String(error),\n threadId: input.threadId,\n runId: input.runId,\n } as RunErrorEvent;\n subscriber.next(runErrorEvent);\n subscriber.error(error);\n }\n } finally {\n this.abortController = undefined;\n }\n })();\n\n return () => {\n controller.abort();\n };\n });\n }\n\n clone() {\n const cloned = new BuiltInAgent(this.config);\n // AbstractAgent.middlewares is private in @ag-ui/client — no public accessor exists.\n // This coupling is intentional: clone() must preserve middleware chains.\n // @ts-expect-error accessing private AbstractAgent.middlewares\n cloned.middlewares = [...this.middlewares];\n return cloned;\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\n/** @deprecated Use BuiltInAgentClassicConfig instead */\nexport type BasicAgentConfiguration = BuiltInAgentClassicConfig;\n\nexport * from \"./converters\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiMA,eAAe,cACb,QACA,SAKoB;AACpB,KAAI,OAAO,SAAS,OAUlB,yCAAuB,EAAE,WATP,IAAIA,6CAAuB;EAC3C,KAAK,OAAO;EACZ,SAAS,OAAO;EAChB,YAAY,OAAO;EACnB,SAAS,OAAO;EAChB,gBAAgB,QAAQ;EACxB,OAAO,QAAQ;EACf,MAAM,QAAQ;EACf,CAAC,EACkC,CAAC;AAKvC,yCAAuB,EACrB,WAAW;EACT,MAAM;EACN,KAAK,OAAO;EACZ,SAAS,OAAO;EACjB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AAW,KAAK,cAAc;;AAEhC,gBAAW,UAAU;aACd,OAAO;AACd,SAAI,WAAW,OAAO,QACpB,YAAW,UAAU;UAChB;MACL,MAAM,gBAA+B;OACnC,MAAMA,wBAAU;OAChB,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;OAC/D,UAAU,MAAM;OAChB,OAAO,MAAM;OACd;AACD,iBAAW,KAAK,cAAc;AAC9B,iBAAW,MAAM,MAAM;;cAEjB;AACR,UAAK,kBAAkB;;OAEvB;AAEJ,gBAAa;AACX,eAAW,OAAO;;IAEpB;;CAGJ,QAAQ;EACN,MAAM,SAAS,IAAI,aAAa,KAAK,OAAO;AAI5C,SAAO,cAAc,CAAC,GAAG,KAAK,YAAY;AAC1C,SAAO;;CAGT,WAAiB;AACf,OAAK,iBAAiB,OAAO;;;;;;AAOjC,IAAa,aAAb,cAAgC,aAAa;CAC3C,YAAY,QAAmC;AAC7C,QAAM,OAAO;AACb,UAAQ,KAAK,qDAAqD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["z","AbstractAgent","Observable","EventType","StreamableHTTPClientTransport","SSEClientTransport","convertAISDKStream","convertTanStackStream"],"sources":["../../src/agent/index.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n RunAgentInput,\n EventType,\n Message,\n ReasoningEndEvent,\n ReasoningMessageContentEvent,\n ReasoningMessageEndEvent,\n ReasoningMessageStartEvent,\n ReasoningStartEvent,\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 type { AgentCapabilities } from \"@ag-ui/core\";\nimport {\n streamText,\n LanguageModel,\n ModelMessage,\n AssistantModelMessage,\n UserModelMessage,\n ToolModelMessage,\n SystemModelMessage,\n ToolCallPart,\n ToolResultPart,\n TextPart,\n ImagePart,\n FilePart,\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 { createVertex } from \"@ai-sdk/google-vertex\";\nimport { safeParseToolArgs } from \"@copilotkit/shared\";\nimport { z } from \"zod\";\nimport type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport { schemaToJsonSchema } from \"@copilotkit/shared\";\nimport { jsonSchema as aiJsonSchema } from \"ai\";\nimport { convertAISDKStream } from \"./converters/aisdk\";\nimport { convertTanStackStream } from \"./converters/tanstack\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { randomUUID } from \"@copilotkit/shared\";\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 | \"providerOptions\";\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 * A user-managed MCP client that provides tools to the agent.\n * The user is responsible for creating, configuring, and closing the client.\n * Compatible with the return type of @ai-sdk/mcp's createMCPClient().\n *\n * Unlike mcpServers, the agent does NOT create or close these clients.\n * This allows persistent connections, custom auth, and tool caching.\n */\nexport interface MCPClientProvider {\n /** Return tools to be merged into the agent's tool set. */\n tools(): Promise<ToolSet>;\n}\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 * @param apiKey - Optional API key to use instead of environment variables\n * @returns LanguageModel instance\n */\nexport function resolveModel(\n spec: ModelSpecifier,\n apiKey?: string,\n): 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 // Use provided apiKey, or fall back to environment variable\n const openai = createOpenAI({\n apiKey: 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 // Use provided apiKey, or fall back to environment variable\n const anthropic = createAnthropic({\n apiKey: 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 // Use provided apiKey, or fall back to environment variable\n const google = createGoogleGenerativeAI({\n apiKey: 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 case \"vertex\": {\n const vertex = createVertex();\n return vertex(model);\n }\n\n default:\n throw new Error(\n `Unknown provider \"${provider}\" in \"${spec}\". Supported: openai, anthropic, google (gemini).`,\n );\n }\n}\n\n/**\n * Tool definition for BuiltInAgent\n */\nexport interface ToolDefinition<\n TParameters extends StandardSchemaV1 = StandardSchemaV1,\n> {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: InferSchemaOutput<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 - Schema for the tool's input parameters (any Standard Schema V1 compatible library: Zod, Valibot, ArkType, etc.)\n * @param execute - Function to execute the tool server-side\n * @returns Tool definition\n */\nexport function defineTool<TParameters extends StandardSchemaV1>(config: {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: InferSchemaOutput<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\n/**\n * Converts AG-UI user message content to Vercel AI SDK UserContent format.\n * Handles plain strings, new modality-specific parts (image/audio/video/document),\n * and legacy BinaryInputContent for backward compatibility.\n */\nfunction convertUserMessageContent(\n content: AGUIUserMessage[\"content\"],\n): string | Array<TextPart | ImagePart | FilePart> {\n if (!content) {\n return \"\";\n }\n\n if (typeof content === \"string\") {\n return content;\n }\n\n const parts: Array<TextPart | ImagePart | FilePart> = [];\n\n for (const part of content) {\n if (!part || typeof part !== \"object\" || !(\"type\" in part)) {\n continue;\n }\n\n switch (part.type) {\n case \"text\": {\n const text = (part as { text?: string }).text;\n if (text) {\n parts.push({ type: \"text\", text });\n }\n break;\n }\n\n case \"image\": {\n const source = (part as { source?: any }).source;\n if (!source) break;\n if (source.type === \"data\") {\n parts.push({\n type: \"image\",\n image: source.value,\n mediaType: source.mimeType,\n });\n } else if (source.type === \"url\") {\n try {\n parts.push({\n type: \"image\",\n image: new URL(source.value),\n mediaType: source.mimeType,\n });\n } catch {\n console.error(\n `[CopilotKit] convertUserMessageContent: invalid URL \"${source.value}\" in image part — skipping`,\n );\n }\n }\n break;\n }\n\n case \"audio\":\n case \"video\":\n case \"document\": {\n const source = (part as { source?: any }).source;\n if (!source) break;\n if (source.type === \"data\") {\n parts.push({\n type: \"file\",\n data: source.value,\n mediaType: source.mimeType,\n });\n } else if (source.type === \"url\") {\n try {\n parts.push({\n type: \"file\",\n data: new URL(source.value),\n mediaType: source.mimeType ?? \"application/octet-stream\",\n });\n } catch {\n console.error(\n `[CopilotKit] convertUserMessageContent: invalid URL \"${source.value}\" in ${part.type} part — skipping`,\n );\n }\n }\n break;\n }\n\n // Legacy BinaryInputContent backward compatibility\n case \"binary\": {\n const legacy = part as {\n mimeType?: string;\n data?: string;\n url?: string;\n };\n const mimeType = legacy.mimeType ?? \"application/octet-stream\";\n const isImage = mimeType.startsWith(\"image/\");\n\n if (legacy.data) {\n if (isImage) {\n parts.push({\n type: \"image\",\n image: legacy.data,\n mediaType: mimeType,\n });\n } else {\n parts.push({\n type: \"file\",\n data: legacy.data,\n mediaType: mimeType,\n });\n }\n } else if (legacy.url) {\n try {\n const url = new URL(legacy.url);\n if (isImage) {\n parts.push({ type: \"image\", image: url, mediaType: mimeType });\n } else {\n parts.push({ type: \"file\", data: url, mediaType: mimeType });\n }\n } catch {\n console.error(\n `[CopilotKit] convertUserMessageContent: invalid URL \"${legacy.url}\" in binary part — skipping`,\n );\n }\n }\n break;\n }\n\n default: {\n console.error(\n `[CopilotKit] convertUserMessageContent: unrecognized content part type \"${(part as { type: string }).type}\" — skipping`,\n );\n break;\n }\n }\n }\n\n return parts.length > 0 ? parts : \"\";\n}\n\n/**\n * Options for converting AG-UI messages to Vercel AI SDK format\n */\nexport interface MessageConversionOptions {\n forwardSystemMessages?: boolean;\n forwardDeveloperMessages?: boolean;\n}\n\n/**\n * Converts AG-UI messages to Vercel AI SDK ModelMessage format\n */\nexport function convertMessagesToVercelAISDKMessages(\n messages: Message[],\n options: MessageConversionOptions = {},\n): ModelMessage[] {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\" && options.forwardSystemMessages) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (\n message.role === \"developer\" &&\n options.forwardDeveloperMessages\n ) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content\n ? [{ type: \"text\", text: message.content }]\n : [];\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: safeParseToolArgs(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: convertUserMessageContent(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\" | \"integer\" | \"boolean\" | \"array\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n enum?: string[];\n}\n\n/**\n * Converts JSON Schema to Zod schema\n */\nexport function convertJsonSchemaToZodSchema(\n jsonSchema: JsonSchema,\n required: boolean,\n): z.ZodSchema {\n // Handle empty schemas {} (no input required) - treat as empty object\n if (!jsonSchema.type) {\n return required ? z.object({}) : z.object({}).optional();\n }\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(\n value,\n jsonSchema.required ? jsonSchema.required.includes(key) : false,\n );\n }\n const schema = z.object(spec).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n if (jsonSchema.enum && jsonSchema.enum.length > 0) {\n const schema = z\n .enum(jsonSchema.enum as [string, ...string[]])\n .describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n const schema = z.string().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\" || jsonSchema.type === \"integer\") {\n const schema = z.number().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n const 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 const itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n const schema = z.array(itemSchema).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n console.error(\"Invalid JSON schema:\", JSON.stringify(jsonSchema, null, 2));\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 // Empty objects {} are valid JSON schemas (no input required)\n if (Object.keys(schema).length === 0) return true;\n return (\n typeof schema.type === \"string\" &&\n [\"object\", \"string\", \"number\", \"integer\", \"boolean\", \"array\"].includes(\n schema.type,\n )\n );\n}\n\nexport function convertToolsToVercelAITools(\n tools: RunAgentInput[\"tools\"],\n): 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 * Check whether a schema is a Zod schema by inspecting its Standard Schema vendor.\n */\nfunction isZodSchema(schema: StandardSchemaV1): boolean {\n return schema[\"~standard\"]?.vendor === \"zod\";\n}\n\n/**\n * Converts ToolDefinition array to Vercel AI SDK ToolSet.\n *\n * For Zod schemas, passes them directly to the AI SDK (Zod satisfies FlexibleSchema).\n * For non-Zod schemas, converts to JSON Schema via schemaToJsonSchema() and wraps\n * with the AI SDK's jsonSchema() helper.\n */\nexport function convertToolDefinitionsToVercelAITools(\n tools: ToolDefinition[],\n): 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 (isZodSchema(tool.parameters)) {\n // Zod schemas can be passed directly to AI SDK (satisfies FlexibleSchema)\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: tool.parameters as any,\n execute: tool.execute,\n });\n } else {\n // Non-Zod: convert to JSON Schema and wrap with AI SDK's jsonSchema()\n const jsonSchemaObj = schemaToJsonSchema(tool.parameters);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: aiJsonSchema(jsonSchemaObj),\n execute: tool.execute,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Context passed to the user-supplied factory function in factory mode.\n */\nexport interface AgentFactoryContext {\n input: RunAgentInput;\n /**\n * Prefer `abortSignal` for most use cases (AI SDK, fetch, custom backends).\n * Provided for backends like TanStack AI that require the full AbortController.\n * Do NOT call `.abort()` on this controller — use `abortRun()` on the agent instead.\n */\n abortController: AbortController;\n abortSignal: AbortSignal;\n}\n\n/**\n * Factory config for AI SDK backend.\n * The factory must return an object with a `fullStream` async iterable\n * (compatible with the result of `streamText()` — only `fullStream` is consumed).\n */\nexport interface BuiltInAgentAISDKFactoryConfig {\n type: \"aisdk\";\n factory: (\n ctx: AgentFactoryContext,\n ) =>\n | { fullStream: AsyncIterable<unknown> }\n | Promise<{ fullStream: AsyncIterable<unknown> }>;\n}\n\n/**\n * Factory config for TanStack AI backend.\n * The factory must return an async iterable of TanStack AI stream chunks.\n */\nexport interface BuiltInAgentTanStackFactoryConfig {\n type: \"tanstack\";\n factory: (\n ctx: AgentFactoryContext,\n ) => AsyncIterable<unknown> | Promise<AsyncIterable<unknown>>;\n}\n\n/**\n * Factory config for a custom backend that directly yields AG-UI events.\n */\nexport interface BuiltInAgentCustomFactoryConfig {\n type: \"custom\";\n factory: (\n ctx: AgentFactoryContext,\n ) => AsyncIterable<BaseEvent> | Promise<AsyncIterable<BaseEvent>>;\n}\n\n/**\n * Union of all factory-mode configurations.\n */\nexport type BuiltInAgentFactoryConfig =\n | BuiltInAgentAISDKFactoryConfig\n | BuiltInAgentTanStackFactoryConfig\n | BuiltInAgentCustomFactoryConfig;\n\n/**\n * Classic config — BuiltInAgent handles streamText, tools, MCP, state tools, prompt building.\n */\nexport interface BuiltInAgentClassicConfig {\n /**\n * The model to use\n */\n model: BuiltInAgentModel | LanguageModel;\n /**\n * API key for the model provider (OpenAI, Anthropic, Google)\n * If not provided, falls back to environment variables:\n * - OPENAI_API_KEY for OpenAI models\n * - ANTHROPIC_API_KEY for Anthropic models\n * - GOOGLE_API_KEY for Google models\n */\n apiKey?: string;\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 list of user-managed MCP clients.\n * Unlike mcpServers, the agent does NOT create or close these clients.\n * The user controls the lifecycle, persistence, auth, and caching.\n *\n * Compatible with @ai-sdk/mcp's createMCPClient() return type:\n * ```typescript\n * const client = await createMCPClient({ transport });\n * const agent = new BuiltInAgent({ model: \"...\", mcpClients: [client] });\n * ```\n */\n mcpClients?: MCPClientProvider[];\n /**\n * Optional tools available to the agent\n */\n tools?: ToolDefinition[];\n /**\n * Forward system-role messages from input to the LLM.\n * Default: false\n */\n forwardSystemMessages?: boolean;\n /**\n * Forward developer-role messages from input to the LLM (as system messages).\n * Default: false\n */\n forwardDeveloperMessages?: boolean;\n /**\n * Provider-specific options passed to the model (e.g., OpenAI reasoningEffort).\n * Example: `{ openai: { reasoningEffort: \"high\" } }`\n */\n providerOptions?: Record<string, any>;\n /**\n * Explicit agent capabilities. **Shallow-merged** at the category level on\n * top of auto-inferred defaults — providing a category (e.g. `tools`)\n * replaces that entire category, not individual fields within it.\n *\n * For example, `{ tools: { supported: true } }` will drop the inferred\n * `clientProvided` value. Include all fields for any category you override.\n */\n capabilities?: Partial<AgentCapabilities>;\n}\n\n/**\n * Configuration for BuiltInAgent.\n *\n * Two modes:\n * - **Classic** (model + params): BuiltInAgent handles everything — streamText, tools, MCP, state tools.\n * - **Factory** (type + factory): You own the LLM call. BuiltInAgent handles lifecycle only.\n */\nexport type BuiltInAgentConfiguration =\n | BuiltInAgentClassicConfig\n | BuiltInAgentFactoryConfig;\n\n/**\n * Type guard: returns true if this is a factory-mode config.\n */\nfunction isFactoryConfig(\n config: BuiltInAgentConfiguration,\n): config is BuiltInAgentFactoryConfig {\n return \"factory\" in config;\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 if (isFactoryConfig(this.config)) return false;\n return this.config?.overridableProperties?.includes(property) ?? false;\n }\n\n async getCapabilities(): Promise<AgentCapabilities> {\n const inferred: AgentCapabilities = {\n tools: {\n supported: true,\n clientProvided: true,\n },\n transport: {\n streaming: true,\n },\n };\n\n if (!this.config.capabilities) {\n return inferred;\n }\n\n // Shallow merge at the category level — explicit overrides replace\n // entire categories when provided, inferred defaults fill the rest.\n return {\n ...inferred,\n ...this.config.capabilities,\n };\n }\n\n run(input: RunAgentInput): Observable<BaseEvent> {\n if (isFactoryConfig(this.config)) {\n return this.runFactory(input, this.config);\n }\n\n if (this.abortController) {\n throw new Error(\n \"Agent is already running. Call abortRun() first or create a new instance.\",\n );\n }\n\n // Set synchronously before Observable creation to close TOCTOU window\n this.abortController = new AbortController();\n const abortController = this.abortController;\n\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, passing API key if provided\n const model = resolveModel(this.config.model, this.config.apiKey);\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 !(\n typeof input.state === \"object\" &&\n Object.keys(input.state).length === 0\n );\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 forwardSystemMessages: this.config.forwardSystemMessages,\n forwardDeveloperMessages: this.config.forwardDeveloperMessages,\n });\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(\n this.config.tools,\n );\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\n ? stepCountIs(this.config.maxSteps)\n : 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 providerOptions: this.config.providerOptions,\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 (\n typeof props.model === \"string\" ||\n typeof props.model === \"object\"\n ) {\n // Accept any string or LanguageModel instance for model override\n // Use the configured API key when resolving overridden models\n streamTextParams.model = resolveModel(\n props.model as string | LanguageModel,\n this.config.apiKey,\n );\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<\n Record<string, unknown>\n >;\n }\n }\n if (\n typeof props.maxOutputTokens === \"number\" &&\n this.canOverride(\"maxOutputTokens\")\n ) {\n streamTextParams.maxOutputTokens = props.maxOutputTokens;\n }\n if (\n typeof props.temperature === \"number\" &&\n this.canOverride(\"temperature\")\n ) {\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 (\n typeof props.presencePenalty === \"number\" &&\n this.canOverride(\"presencePenalty\")\n ) {\n streamTextParams.presencePenalty = props.presencePenalty;\n }\n if (\n typeof props.frequencyPenalty === \"number\" &&\n this.canOverride(\"frequencyPenalty\")\n ) {\n streamTextParams.frequencyPenalty = props.frequencyPenalty;\n }\n if (\n Array.isArray(props.stopSequences) &&\n this.canOverride(\"stopSequences\")\n ) {\n // Validate all elements are strings\n if (\n props.stopSequences.every(\n (item): item is string => typeof item === \"string\",\n )\n ) {\n streamTextParams.stopSequences = props.stopSequences;\n }\n }\n if (typeof props.seed === \"number\" && this.canOverride(\"seed\")) {\n streamTextParams.seed = props.seed;\n }\n if (\n typeof props.maxRetries === \"number\" &&\n this.canOverride(\"maxRetries\")\n ) {\n streamTextParams.maxRetries = props.maxRetries;\n }\n if (\n props.providerOptions !== undefined &&\n this.canOverride(\"providerOptions\")\n ) {\n if (\n typeof props.providerOptions === \"object\" &&\n props.providerOptions !== null\n ) {\n streamTextParams.providerOptions = props.providerOptions as Record<\n string,\n any\n >;\n }\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 let terminalEventEmitted = false;\n let messageId = randomUUID();\n let reasoningMessageId = randomUUID();\n let isInReasoning = false;\n\n // Auto-close an open reasoning lifecycle.\n // Some AI SDK providers (notably @ai-sdk/anthropic) never emit \"reasoning-end\",\n // which leaves downstream state machines stuck. This helper emits the\n // missing REASONING_MESSAGE_END + REASONING_END events so the stream\n // can transition to text, tool-call, or finish phases.\n // Declared before try/catch so it is accessible in the catch block.\n const closeReasoningIfOpen = () => {\n if (!isInReasoning) return;\n isInReasoning = false;\n const reasoningMsgEnd: ReasoningMessageEndEvent = {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningMsgEnd);\n const reasoningEnd: ReasoningEndEvent = {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningEnd);\n };\n\n try {\n // Add AG-UI state update tools\n streamTextParams.tools = {\n ...streamTextParams.tools,\n AGUISendStateSnapshot: createVercelAISDKTool({\n description:\n \"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:\n \"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\n .enum([\"add\", \"replace\", \"remove\"])\n .describe(\"The operation to perform\"),\n path: z\n .string()\n .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 // Merge tools from user-managed MCP clients (user controls lifecycle)\n if (this.config.mcpClients && this.config.mcpClients.length > 0) {\n for (const client of this.config.mcpClients) {\n const mcpTools = await client.tools();\n streamTextParams.tools = {\n ...streamTextParams.tools,\n ...mcpTools,\n } as ToolSet;\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(\n url,\n serverConfig.options,\n );\n } else if (serverConfig.type === \"sse\") {\n transport = new SSEClientTransport(\n new URL(serverConfig.url),\n serverConfig.headers,\n );\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 = {\n ...streamTextParams.tools,\n ...mcpTools,\n } as ToolSet;\n }\n }\n }\n\n // Call streamText and process the stream\n const response = streamText({\n ...streamTextParams,\n abortSignal: abortController.signal,\n });\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 // Close any open reasoning lifecycle on every event except\n // reasoning-delta, which arrives mid-block and must not interrupt it.\n if (part.type !== \"reasoning-delta\") {\n closeReasoningIfOpen();\n }\n\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 \"reasoning-start\": {\n // Use SDK-provided id, or generate a fresh UUID if the id is falsy,\n // \"0\", or matches the non-unique pattern emitted by @ai-sdk/openai-compatible\n // (e.g. \"txt-0\", \"reasoning-0\", \"msg-0\").\n const providedId = \"id\" in part ? part.id : undefined;\n const isNonUniqueId =\n !providedId ||\n providedId === \"0\" ||\n /^(txt|reasoning|msg)-0$/.test(providedId);\n reasoningMessageId = isNonUniqueId\n ? randomUUID()\n : (providedId as typeof reasoningMessageId);\n const reasoningStartEvent: ReasoningStartEvent = {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningStartEvent);\n const reasoningMessageStart: ReasoningMessageStartEvent = {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: \"reasoning\",\n };\n subscriber.next(reasoningMessageStart);\n isInReasoning = true;\n break;\n }\n case \"reasoning-delta\": {\n const delta = part.text ?? \"\";\n if (!delta) break; // skip — @ag-ui/core schema requires delta to be non-empty\n const reasoningDeltaEvent: ReasoningMessageContentEvent = {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta,\n };\n subscriber.next(reasoningDeltaEvent);\n break;\n }\n case \"reasoning-end\": {\n // closeReasoningIfOpen() already called before the switch — no-op here\n // if the SDK never emits this event (e.g. @ai-sdk/anthropic).\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 // Use randomUUID() if part.id is falsy, \"0\", or matches the non-unique\n // pattern emitted by @ai-sdk/openai-compatible (e.g. \"txt-0\", \"msg-0\").\n const providedId = \"id\" in part ? part.id : undefined;\n const isNonUniqueTextId =\n !providedId ||\n providedId === \"0\" ||\n /^(txt|reasoning|msg)-0$/.test(providedId);\n messageId = isNonUniqueTextId\n ? randomUUID()\n : (providedId as typeof messageId);\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 (\n !state.hasArgsDelta &&\n \"input\" in part &&\n part.input !== undefined\n ) {\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 =\n \"output\" in part\n ? part.output\n : \"result\" in part\n ? part.result\n : 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 (\n toolName === \"AGUISendStateSnapshot\" &&\n toolResult &&\n typeof toolResult === \"object\"\n ) {\n const snapshot = toolResult.snapshot;\n if (snapshot !== undefined) {\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot,\n };\n subscriber.next(stateSnapshotEvent);\n }\n } else if (\n toolName === \"AGUISendStateDelta\" &&\n toolResult &&\n typeof toolResult === \"object\"\n ) {\n const delta = toolResult.delta;\n if (delta !== undefined) {\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta,\n };\n subscriber.next(stateDeltaEvent);\n }\n }\n\n // Always emit the tool result event for the LLM\n let serializedResult: string;\n try {\n serializedResult = JSON.stringify(toolResult);\n } catch {\n serializedResult = `[Unserializable tool result from ${toolName || part.toolCallId}]`;\n }\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId: part.toolCallId,\n content: serializedResult,\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\n case \"error\": {\n if (abortController.signal.aborted) {\n break;\n }\n const err = part.error ?? part.message ?? part.cause;\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message:\n err instanceof Error\n ? err.message\n : typeof err === \"string\"\n ? err\n : `AI SDK stream error: ${JSON.stringify(part)}`,\n threadId: input.threadId,\n runId: input.runId,\n } as RunErrorEvent;\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n\n // Handle error\n if (err instanceof Error) subscriber.error(err);\n else\n subscriber.error(\n new Error(\n typeof err === \"string\" ? err : `AI SDK stream error`,\n ),\n );\n break;\n }\n }\n }\n\n if (!terminalEventEmitted) {\n closeReasoningIfOpen();\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 closeReasoningIfOpen();\n if (abortController.signal.aborted) {\n subscriber.complete();\n } else {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error instanceof Error ? error.message : String(error),\n threadId: input.threadId,\n runId: input.runId,\n } as RunErrorEvent;\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 private runFactory(\n input: RunAgentInput,\n config: BuiltInAgentFactoryConfig,\n ): Observable<BaseEvent> {\n if (this.abortController) {\n throw new Error(\n \"Agent is already running. Call abortRun() first or create a new instance.\",\n );\n }\n\n // Set synchronously before Observable creation to close TOCTOU window\n this.abortController = new AbortController();\n const controller = this.abortController;\n\n return new Observable<BaseEvent>((subscriber) => {\n const startEvent: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(startEvent);\n\n const ctx: AgentFactoryContext = {\n input,\n abortController: controller,\n abortSignal: controller.signal,\n };\n\n (async () => {\n try {\n let events: AsyncIterable<BaseEvent>;\n\n switch (config.type) {\n case \"aisdk\": {\n const result = await config.factory(ctx);\n events = convertAISDKStream(result.fullStream, controller.signal);\n break;\n }\n case \"tanstack\": {\n const stream = await config.factory(ctx);\n events = convertTanStackStream(stream, controller.signal);\n break;\n }\n case \"custom\": {\n events = await config.factory(ctx);\n break;\n }\n default: {\n const _exhaustive: never = config;\n throw new Error(\n `Unknown agent config type: ${(_exhaustive as BuiltInAgentFactoryConfig).type}`,\n );\n }\n }\n\n for await (const event of events) {\n subscriber.next(event);\n }\n\n if (!controller.signal.aborted) {\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n }\n subscriber.complete();\n } catch (error) {\n if (controller.signal.aborted) {\n subscriber.complete();\n } else {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error instanceof Error ? error.message : String(error),\n threadId: input.threadId,\n runId: input.runId,\n } as RunErrorEvent;\n subscriber.next(runErrorEvent);\n subscriber.error(error);\n }\n } finally {\n this.abortController = undefined;\n }\n })();\n\n return () => {\n controller.abort();\n };\n });\n }\n\n clone() {\n const cloned = new BuiltInAgent(this.config);\n // AbstractAgent.middlewares is private in @ag-ui/client — no public accessor exists.\n // This coupling is intentional: clone() must preserve middleware chains.\n // @ts-expect-error accessing private AbstractAgent.middlewares\n cloned.middlewares = [...this.middlewares];\n return cloned;\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\n/** @deprecated Use BuiltInAgentClassicConfig instead */\nexport type BasicAgentConfiguration =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ACd;AACD,iBAAW,KAAK,cAAc;;AAEhC,gBAAW,UAAU;aACd,OAAO;AACd,SAAI,WAAW,OAAO,QACpB,YAAW,UAAU;UAChB;MACL,MAAM,gBAA+B;OACnC,MAAMA,wBAAU;OAChB,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;OAC/D,UAAU,MAAM;OAChB,OAAO,MAAM;OACd;AACD,iBAAW,KAAK,cAAc;AAC9B,iBAAW,MAAM,MAAM;;cAEjB;AACR,UAAK,kBAAkB;;OAEvB;AAEJ,gBAAa;AACX,eAAW,OAAO;;IAEpB;;CAGJ,QAAQ;EACN,MAAM,SAAS,IAAI,aAAa,KAAK,OAAO;AAI5C,SAAO,cAAc,CAAC,GAAG,KAAK,YAAY;AAC1C,SAAO;;CAGT,WAAiB;AACf,OAAK,iBAAiB,OAAO;;;;;;AAOjC,IAAa,aAAb,cAAgC,aAAa;CAC3C,YAAY,QAAmC;AAC7C,QAAM,OAAO;AACb,UAAQ,KAAK,qDAAqD"}
|
package/dist/agent/index.d.cts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
|
|
2
|
-
import { MCPHeaderResolverError, MCPRequestContext } from "./mcp-transport.cjs";
|
|
3
2
|
import { convertAISDKStream } from "./converters/aisdk.cjs";
|
|
4
3
|
import { TanStackChatMessage, TanStackInputResult, convertInputToTanStackAI, convertTanStackStream } from "./converters/tanstack.cjs";
|
|
5
4
|
import { LanguageModel, ModelMessage, ToolChoice, ToolSet } from "ai";
|
|
@@ -7,7 +6,6 @@ import { Observable } from "rxjs";
|
|
|
7
6
|
import { InferSchemaOutput, StandardSchemaV1 } from "@copilotkit/shared";
|
|
8
7
|
import { AbstractAgent, BaseEvent, Message, RunAgentInput } from "@ag-ui/client";
|
|
9
8
|
import { AgentCapabilities } from "@ag-ui/core";
|
|
10
|
-
import { MCPClient } from "@ai-sdk/mcp";
|
|
11
9
|
import { z } from "zod";
|
|
12
10
|
import { StreamableHTTPClientTransportOptions } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
13
11
|
|
|
@@ -26,62 +24,55 @@ type BuiltInAgentModel = "openai/gpt-5" | "openai/gpt-5-mini" | "openai/gpt-4.1"
|
|
|
26
24
|
*/
|
|
27
25
|
type ModelSpecifier = string | LanguageModel;
|
|
28
26
|
/**
|
|
29
|
-
* MCP Client configuration for HTTP transport
|
|
27
|
+
* MCP Client configuration for HTTP transport
|
|
30
28
|
*/
|
|
31
29
|
interface MCPClientConfigHTTP {
|
|
32
|
-
/** Type of MCP client */
|
|
33
|
-
type: "http";
|
|
34
|
-
/** URL of the MCP server */
|
|
35
|
-
url: string;
|
|
36
30
|
/**
|
|
37
|
-
*
|
|
38
|
-
* `StreamableHTTPClientTransport`. Pre-existing escape hatch for advanced
|
|
39
|
-
* use cases (custom `fetch`, `requestInit`, OAuth `authProvider`, etc.).
|
|
31
|
+
* Type of MCP client
|
|
40
32
|
*/
|
|
41
|
-
|
|
33
|
+
type: "http";
|
|
42
34
|
/**
|
|
43
|
-
*
|
|
44
|
-
* For per-call values, use {@link MCPClientConfigHTTP.getHeaders} instead.
|
|
35
|
+
* URL of the MCP server
|
|
45
36
|
*/
|
|
46
|
-
|
|
37
|
+
url: string;
|
|
47
38
|
/**
|
|
48
|
-
*
|
|
49
|
-
* this server (initialize, tools/list, tools/call, SSE reconnects). The
|
|
50
|
-
* returned headers are merged on top of `headers` and any
|
|
51
|
-
* `options.requestInit.headers`, so a resolver can override either.
|
|
52
|
-
*
|
|
53
|
-
* Throwing from the resolver causes the agent run to emit `RUN_ERROR`
|
|
54
|
-
* carrying a {@link MCPHeaderResolverError}.
|
|
39
|
+
* Optional transport options for HTTP client
|
|
55
40
|
*/
|
|
56
|
-
|
|
57
|
-
/** If true, the server is skipped at run-start when `agent.user` is unset. */
|
|
58
|
-
requiresUser?: boolean;
|
|
41
|
+
options?: StreamableHTTPClientTransportOptions;
|
|
59
42
|
}
|
|
60
43
|
/**
|
|
61
|
-
* MCP Client configuration for SSE transport
|
|
44
|
+
* MCP Client configuration for SSE transport
|
|
62
45
|
*/
|
|
63
46
|
interface MCPClientConfigSSE {
|
|
64
|
-
/**
|
|
47
|
+
/**
|
|
48
|
+
* Type of MCP client
|
|
49
|
+
*/
|
|
65
50
|
type: "sse";
|
|
66
|
-
/**
|
|
51
|
+
/**
|
|
52
|
+
* URL of the MCP server
|
|
53
|
+
*/
|
|
67
54
|
url: string;
|
|
68
|
-
/**
|
|
55
|
+
/**
|
|
56
|
+
* Optional HTTP headers (e.g., for authentication)
|
|
57
|
+
*/
|
|
69
58
|
headers?: Record<string, string>;
|
|
70
59
|
}
|
|
71
60
|
/**
|
|
72
|
-
* MCP Client configuration
|
|
61
|
+
* MCP Client configuration
|
|
73
62
|
*/
|
|
74
63
|
type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;
|
|
75
64
|
/**
|
|
76
|
-
* A user-managed MCP client that provides tools to the agent.
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
* for tests/caching layers.
|
|
65
|
+
* A user-managed MCP client that provides tools to the agent.
|
|
66
|
+
* The user is responsible for creating, configuring, and closing the client.
|
|
67
|
+
* Compatible with the return type of @ai-sdk/mcp's createMCPClient().
|
|
80
68
|
*
|
|
81
|
-
* Unlike
|
|
82
|
-
*
|
|
69
|
+
* Unlike mcpServers, the agent does NOT create or close these clients.
|
|
70
|
+
* This allows persistent connections, custom auth, and tool caching.
|
|
83
71
|
*/
|
|
84
|
-
|
|
72
|
+
interface MCPClientProvider {
|
|
73
|
+
/** Return tools to be merged into the agent's tool set. */
|
|
74
|
+
tools(): Promise<ToolSet>;
|
|
75
|
+
}
|
|
85
76
|
/**
|
|
86
77
|
* Resolves a model specifier to a LanguageModel instance
|
|
87
78
|
* @param spec - Model string (e.g., "openai/gpt-4o") or LanguageModel instance
|
|
@@ -316,24 +307,6 @@ type BuiltInAgentConfiguration = BuiltInAgentClassicConfig | BuiltInAgentFactory
|
|
|
316
307
|
declare class BuiltInAgent extends AbstractAgent {
|
|
317
308
|
private config;
|
|
318
309
|
private abortController?;
|
|
319
|
-
/**
|
|
320
|
-
* Headers populated per-request by the runtime's
|
|
321
|
-
* `extractForwardableHeaders` (the incoming request's `Authorization` +
|
|
322
|
-
* every `x-*` header, lower-cased). Available to MCP header resolvers via
|
|
323
|
-
* {@link MCPRequestContext.requestHeaders}; kept here as a plain field so
|
|
324
|
-
* the runtime's `configureAgentForRequest` feature-detect activates.
|
|
325
|
-
*/
|
|
326
|
-
headers: Record<string, string>;
|
|
327
|
-
/**
|
|
328
|
-
* End-user identity for the current request, populated by the runtime by
|
|
329
|
-
* invoking `identifyUser(request)` (Intelligence mode). Surfaced to MCP
|
|
330
|
-
* header resolvers via {@link MCPRequestContext.user}; remains undefined
|
|
331
|
-
* for runs that aren't going through a runtime with `identifyUser` set.
|
|
332
|
-
*/
|
|
333
|
-
user?: {
|
|
334
|
-
id: string;
|
|
335
|
-
name: string;
|
|
336
|
-
};
|
|
337
310
|
constructor(config: BuiltInAgentConfiguration);
|
|
338
311
|
/**
|
|
339
312
|
* Check if a property can be overridden by forwardedProps
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/agent/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/agent/index.ts"],"mappings":";;;;;;;;;;;;;;;;KAiEY,mBAAA;;;;KAkBA,iBAAA;AAAZ;;;AAAA,KA8BY,cAAA,YAA0B,aAAA;;AAAtC;;UAKiB,mBAAA;EALqB;;AAKtC;EAIE,IAAA;;;;EAIA,GAAA;EAIA;;;EAAA,OAAA,GAAU,oCAAA;AAAA;;;;UAMK,kBAAA;EAQf;;;EAJA,IAAA;EAQgB;AAMlB;;EAVE,GAAA;EAU4B;;AAU9B;EAhBE,OAAA,GAAU,MAAA;AAAA;;;;KAMA,eAAA,GAAkB,mBAAA,GAAsB,kBAAA;;;AAqBpD;;;;;;UAXiB,iBAAA;EAcd;EAZ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