@copilotkitnext/core 0.0.9-alpha.3 → 0.0.11

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/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { AbstractAgent, Message, Context, RunAgentResult, HttpAgentConfig, HttpAgent, RunAgentInput, BaseEvent } from '@ag-ui/client';
1
+ import { ToolCall, AbstractAgent, Message, Context, RunAgentResult, HttpAgentConfig, HttpAgent, RunAgentInput, BaseEvent } from '@ag-ui/client';
2
2
  import { z } from 'zod';
3
3
  import { Observable } from 'rxjs';
4
4
 
@@ -14,7 +14,7 @@ type FrontendTool<T extends Record<string, unknown> = Record<string, unknown>> =
14
14
  name: string;
15
15
  description?: string;
16
16
  parameters?: z.ZodType<T>;
17
- handler?: (args: T) => Promise<unknown>;
17
+ handler?: (args: T, toolCall: ToolCall) => Promise<unknown>;
18
18
  followUp?: boolean;
19
19
  /**
20
20
  * Optional agent ID to constrain this tool to a specific agent.
@@ -124,6 +124,8 @@ declare class CopilotKitCore {
124
124
  private _runtimeVersion?;
125
125
  private _runtimeConnectionStatus;
126
126
  constructor({ runtimeUrl, headers, properties, agents, tools, }: CopilotKitCoreConfig);
127
+ private applyHeadersToAgent;
128
+ private applyHeadersToAgents;
127
129
  private assignAgentIds;
128
130
  private notifySubscribers;
129
131
  private emitError;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AbstractAgent, Message, Context, RunAgentResult, HttpAgentConfig, HttpAgent, RunAgentInput, BaseEvent } from '@ag-ui/client';
1
+ import { ToolCall, AbstractAgent, Message, Context, RunAgentResult, HttpAgentConfig, HttpAgent, RunAgentInput, BaseEvent } from '@ag-ui/client';
2
2
  import { z } from 'zod';
3
3
  import { Observable } from 'rxjs';
4
4
 
@@ -14,7 +14,7 @@ type FrontendTool<T extends Record<string, unknown> = Record<string, unknown>> =
14
14
  name: string;
15
15
  description?: string;
16
16
  parameters?: z.ZodType<T>;
17
- handler?: (args: T) => Promise<unknown>;
17
+ handler?: (args: T, toolCall: ToolCall) => Promise<unknown>;
18
18
  followUp?: boolean;
19
19
  /**
20
20
  * Optional agent ID to constrain this tool to a specific agent.
@@ -124,6 +124,8 @@ declare class CopilotKitCore {
124
124
  private _runtimeVersion?;
125
125
  private _runtimeConnectionStatus;
126
126
  constructor({ runtimeUrl, headers, properties, agents, tools, }: CopilotKitCoreConfig);
127
+ private applyHeadersToAgent;
128
+ private applyHeadersToAgents;
127
129
  private assignAgentIds;
128
130
  private notifySubscribers;
129
131
  private emitError;
package/dist/index.js CHANGED
@@ -95,10 +95,21 @@ var CopilotKitCore = class {
95
95
  this.headers = headers;
96
96
  this.properties = properties;
97
97
  this.localAgents = this.assignAgentIds(agents);
98
+ this.applyHeadersToAgents(this.localAgents);
98
99
  this._agents = this.localAgents;
99
100
  this._tools = tools;
100
101
  this.setRuntimeUrl(runtimeUrl);
101
102
  }
103
+ applyHeadersToAgent(agent) {
104
+ if (agent instanceof import_client2.HttpAgent) {
105
+ agent.headers = { ...this.headers };
106
+ }
107
+ }
108
+ applyHeadersToAgents(agents) {
109
+ Object.values(agents).forEach((agent) => {
110
+ this.applyHeadersToAgent(agent);
111
+ });
112
+ }
102
113
  assignAgentIds(agents) {
103
114
  Object.entries(agents).forEach(([id, agent]) => {
104
115
  if (agent && !agent.agentId) {
@@ -227,6 +238,7 @@ var CopilotKitCore = class {
227
238
  agentId: id,
228
239
  description
229
240
  });
241
+ this.applyHeadersToAgent(agent);
230
242
  return [id, agent];
231
243
  })
232
244
  );
@@ -286,6 +298,7 @@ var CopilotKitCore = class {
286
298
  */
287
299
  setHeaders(headers) {
288
300
  this.headers = headers;
301
+ this.applyHeadersToAgents(this._agents);
289
302
  void this.notifySubscribers(
290
303
  (subscriber) => subscriber.onHeadersChanged?.({
291
304
  copilotkit: this,
@@ -307,6 +320,7 @@ var CopilotKitCore = class {
307
320
  setAgents(agents) {
308
321
  this.localAgents = this.assignAgentIds(agents);
309
322
  this._agents = { ...this.localAgents, ...this.remoteAgents };
323
+ this.applyHeadersToAgents(this._agents);
310
324
  void this.notifySubscribers(
311
325
  (subscriber) => subscriber.onAgentsChanged?.({
312
326
  copilotkit: this,
@@ -320,6 +334,7 @@ var CopilotKitCore = class {
320
334
  if (!agent.agentId) {
321
335
  agent.agentId = id;
322
336
  }
337
+ this.applyHeadersToAgent(agent);
323
338
  this._agents = { ...this.localAgents, ...this.remoteAgents };
324
339
  void this.notifySubscribers(
325
340
  (subscriber) => subscriber.onAgentsChanged?.({
@@ -562,7 +577,10 @@ var CopilotKitCore = class {
562
577
  );
563
578
  if (!errorMessage) {
564
579
  try {
565
- const result = await tool.handler(parsedArgs);
580
+ const result = await tool.handler(
581
+ parsedArgs,
582
+ toolCall
583
+ );
566
584
  if (result === void 0 || result === null) {
567
585
  toolCallResult = "";
568
586
  } else if (typeof result === "string") {
@@ -667,7 +685,8 @@ var CopilotKitCore = class {
667
685
  if (!errorMessage) {
668
686
  try {
669
687
  const result = await wildcardTool.handler(
670
- wildcardArgs
688
+ wildcardArgs,
689
+ toolCall
671
690
  );
672
691
  if (result === void 0 || result === null) {
673
692
  toolCallResult = "";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/core.ts","../src/agent.ts","../src/types.ts","../src/utils/markdown.ts"],"sourcesContent":["export * from \"./core\";\nexport * from \"./types\";\nexport * from \"./agent\";\nexport * from \"./utils/markdown\";\n","import {\n AgentDescription,\n DEFAULT_AGENT_ID,\n randomUUID,\n RuntimeInfo,\n logger,\n} from \"@copilotkitnext/shared\";\nimport {\n AbstractAgent,\n AgentSubscriber,\n Context,\n HttpAgent,\n Message,\n RunAgentResult,\n} from \"@ag-ui/client\";\nimport { FrontendTool } from \"./types\";\nimport { ProxiedCopilotRuntimeAgent } from \"./agent\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\n\n/** Configuration options for `CopilotKitCore`. */\nexport interface CopilotKitCoreConfig {\n /** The endpoint of the CopilotRuntime. */\n runtimeUrl?: string;\n /** Mapping from agent name to its `AbstractAgent` instance. */\n agents?: Record<string, AbstractAgent>;\n /** Headers appended to every HTTP request made by `CopilotKitCore`. */\n headers?: Record<string, string>;\n /** Properties sent as `forwardedProps` to the AG-UI agent. */\n properties?: Record<string, unknown>;\n /** Ordered collection of frontend tools available to the core. */\n tools?: FrontendTool<any>[];\n}\n\nexport interface CopilotKitCoreAddAgentParams {\n id: string;\n agent: AbstractAgent;\n}\n\nexport interface CopilotKitCoreRunAgentParams {\n agent: AbstractAgent;\n withMessages?: Message[];\n agentId?: string;\n}\n\nexport interface CopilotKitCoreConnectAgentParams {\n agent: AbstractAgent;\n agentId?: string;\n}\n\nexport interface CopilotKitCoreGetToolParams {\n toolName: string;\n agentId?: string;\n}\n\nexport enum CopilotKitCoreErrorCode {\n RUNTIME_INFO_FETCH_FAILED = \"runtime_info_fetch_failed\",\n AGENT_CONNECT_FAILED = \"agent_connect_failed\",\n AGENT_RUN_FAILED = \"agent_run_failed\",\n AGENT_RUN_FAILED_EVENT = \"agent_run_failed_event\",\n AGENT_RUN_ERROR_EVENT = \"agent_run_error_event\",\n TOOL_ARGUMENT_PARSE_FAILED = \"tool_argument_parse_failed\",\n TOOL_HANDLER_FAILED = \"tool_handler_failed\",\n}\n\nexport interface CopilotKitCoreSubscriber {\n onRuntimeConnectionStatusChanged?: (event: {\n copilotkit: CopilotKitCore;\n status: CopilotKitCoreRuntimeConnectionStatus;\n }) => void | Promise<void>;\n onToolExecutionStart?: (event: {\n copilotkit: CopilotKitCore;\n toolCallId: string;\n agentId: string;\n toolName: string;\n args: unknown;\n }) => void | Promise<void>;\n onToolExecutionEnd?: (event: {\n copilotkit: CopilotKitCore;\n toolCallId: string;\n agentId: string;\n toolName: string;\n result: string;\n error?: string;\n }) => void | Promise<void>;\n onAgentsChanged?: (event: {\n copilotkit: CopilotKitCore;\n agents: Readonly<Record<string, AbstractAgent>>;\n }) => void | Promise<void>;\n onContextChanged?: (event: {\n copilotkit: CopilotKitCore;\n context: Readonly<Record<string, Context>>;\n }) => void | Promise<void>;\n onPropertiesChanged?: (event: {\n copilotkit: CopilotKitCore;\n properties: Readonly<Record<string, unknown>>;\n }) => void | Promise<void>;\n onHeadersChanged?: (event: {\n copilotkit: CopilotKitCore;\n headers: Readonly<Record<string, string>>;\n }) => void | Promise<void>;\n onError?: (event: {\n copilotkit: CopilotKitCore;\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n}\n\nexport enum CopilotKitCoreRuntimeConnectionStatus {\n Disconnected = \"disconnected\",\n Connected = \"connected\",\n Connecting = \"connecting\",\n Error = \"error\",\n}\n\nexport class CopilotKitCore {\n headers: Record<string, string>;\n properties: Record<string, unknown>;\n\n private _context: Record<string, Context> = {};\n private _agents: Record<string, AbstractAgent> = {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _tools: FrontendTool<any>[] = [];\n\n private localAgents: Record<string, AbstractAgent> = {};\n private remoteAgents: Record<string, AbstractAgent> = {};\n private subscribers: Set<CopilotKitCoreSubscriber> = new Set();\n\n private _runtimeUrl?: string;\n private _runtimeVersion?: string;\n private _runtimeConnectionStatus: CopilotKitCoreRuntimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Disconnected;\n\n constructor({\n runtimeUrl,\n headers = {},\n properties = {},\n agents = {},\n tools = [],\n }: CopilotKitCoreConfig) {\n this.headers = headers;\n this.properties = properties;\n this.localAgents = this.assignAgentIds(agents);\n this._agents = this.localAgents;\n this._tools = tools;\n this.setRuntimeUrl(runtimeUrl);\n }\n\n private assignAgentIds(agents: Record<string, AbstractAgent>) {\n Object.entries(agents).forEach(([id, agent]) => {\n if (agent && !agent.agentId) {\n agent.agentId = id;\n }\n });\n return agents;\n }\n\n private async notifySubscribers(\n handler: (subscriber: CopilotKitCoreSubscriber) => void | Promise<void>,\n errorMessage: string\n ) {\n await Promise.all(\n Array.from(this.subscribers).map(async (subscriber) => {\n try {\n await handler(subscriber);\n } catch (error) {\n logger.error(errorMessage, error);\n }\n })\n );\n }\n\n private async emitError({\n error,\n code,\n context = {},\n }: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context?: Record<string, any>;\n }) {\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onError?.({\n copilotkit: this,\n error,\n code,\n context,\n }),\n \"Subscriber onError error:\"\n );\n }\n\n private resolveAgentId(\n agent: AbstractAgent,\n providedAgentId?: string\n ): string {\n if (providedAgentId) {\n return providedAgentId;\n }\n if (agent.agentId) {\n return agent.agentId;\n }\n const found = Object.entries(this._agents).find(([, storedAgent]) => {\n return storedAgent === agent;\n });\n if (found) {\n agent.agentId = found[0];\n return found[0];\n }\n agent.agentId = DEFAULT_AGENT_ID;\n return DEFAULT_AGENT_ID;\n }\n\n /**\n * Snapshot accessors\n */\n get context(): Readonly<Record<string, Context>> {\n return this._context;\n }\n\n get agents(): Readonly<Record<string, AbstractAgent>> {\n return this._agents;\n }\n\n get tools(): Readonly<FrontendTool<any>[]> {\n return this._tools;\n }\n\n get runtimeUrl(): string | undefined {\n return this._runtimeUrl;\n }\n\n setRuntimeUrl(runtimeUrl: string | undefined) {\n const normalizedRuntimeUrl = runtimeUrl\n ? runtimeUrl.replace(/\\/$/, \"\")\n : undefined;\n\n if (this._runtimeUrl === normalizedRuntimeUrl) {\n return;\n }\n\n this._runtimeUrl = normalizedRuntimeUrl;\n void this.updateRuntimeConnection();\n }\n\n get runtimeVersion(): string | undefined {\n return this._runtimeVersion;\n }\n\n get runtimeConnectionStatus(): CopilotKitCoreRuntimeConnectionStatus {\n return this._runtimeConnectionStatus;\n }\n\n /**\n * Runtime connection\n */\n private async updateRuntimeConnection() {\n if (!this.runtimeUrl) {\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Disconnected;\n this._runtimeVersion = undefined;\n this.remoteAgents = {};\n this._agents = this.localAgents;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Disconnected,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n return;\n }\n\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Connecting;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Connecting,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n try {\n const response = await fetch(`${this.runtimeUrl}/info`, {\n headers: this.headers,\n });\n const {\n version,\n ...runtimeInfo\n }: {\n agents: Record<string, AgentDescription>;\n version: string;\n } = (await response.json()) as RuntimeInfo;\n\n const agents: Record<string, AbstractAgent> = Object.fromEntries(\n Object.entries(runtimeInfo.agents).map(([id, { description }]) => {\n const agent = new ProxiedCopilotRuntimeAgent({\n runtimeUrl: this.runtimeUrl,\n agentId: id,\n description: description,\n });\n return [id, agent];\n })\n );\n\n this.remoteAgents = agents;\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Connected;\n this._runtimeVersion = version;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Connected,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n } catch (error) {\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Error;\n this._runtimeVersion = undefined;\n this.remoteAgents = {};\n this._agents = this.localAgents;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Error,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n const message =\n error instanceof Error ? error.message : JSON.stringify(error);\n logger.warn(\n `Failed to load runtime info (${this.runtimeUrl}/info): ${message}`\n );\n const runtimeError =\n error instanceof Error ? error : new Error(String(error));\n await this.emitError({\n error: runtimeError,\n code: CopilotKitCoreErrorCode.RUNTIME_INFO_FETCH_FAILED,\n context: {\n runtimeUrl: this.runtimeUrl,\n },\n });\n }\n }\n\n /**\n * Configuration updates\n */\n setHeaders(headers: Record<string, string>) {\n this.headers = headers;\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onHeadersChanged?.({\n copilotkit: this,\n headers: this.headers,\n }),\n \"Subscriber onHeadersChanged error:\"\n );\n }\n\n setProperties(properties: Record<string, unknown>) {\n this.properties = properties;\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onPropertiesChanged?.({\n copilotkit: this,\n properties: this.properties,\n }),\n \"Subscriber onPropertiesChanged error:\"\n );\n }\n\n setAgents(agents: Record<string, AbstractAgent>) {\n this.localAgents = this.assignAgentIds(agents);\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n }\n\n addAgent({ id, agent }: CopilotKitCoreAddAgentParams) {\n this.localAgents[id] = agent;\n if (!agent.agentId) {\n agent.agentId = id;\n }\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n }\n\n removeAgent(id: string) {\n delete this.localAgents[id];\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n }\n\n getAgent(id: string): AbstractAgent | undefined {\n if (id in this._agents) {\n return this._agents[id] as AbstractAgent;\n }\n\n if (\n this.runtimeUrl !== undefined &&\n (this.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Disconnected ||\n this.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connecting)\n ) {\n return undefined;\n } else {\n console.warn(`Agent ${id} not found`);\n return undefined;\n }\n }\n\n /**\n * Context management\n */\n addContext({ description, value }: Context): string {\n const id = randomUUID();\n this._context[id] = { description, value };\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onContextChanged?.({\n copilotkit: this,\n context: this._context,\n }),\n \"Subscriber onContextChanged error:\"\n );\n return id;\n }\n\n removeContext(id: string) {\n delete this._context[id];\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onContextChanged?.({\n copilotkit: this,\n context: this._context,\n }),\n \"Subscriber onContextChanged error:\"\n );\n }\n\n /**\n * Tool management\n */\n addTool<T extends Record<string, unknown> = Record<string, unknown>>(\n tool: FrontendTool<T>\n ) {\n // Check if a tool with the same name and agentId already exists\n const existingToolIndex = this._tools.findIndex(\n (t) => t.name === tool.name && t.agentId === tool.agentId\n );\n\n if (existingToolIndex !== -1) {\n logger.warn(\n `Tool already exists: '${tool.name}' for agent '${tool.agentId || \"global\"}', skipping.`\n );\n return;\n }\n\n this._tools.push(tool);\n }\n\n removeTool(id: string, agentId?: string) {\n this._tools = this._tools.filter((tool) => {\n // Remove tool if both name and agentId match\n if (agentId !== undefined) {\n return !(tool.name === id && tool.agentId === agentId);\n }\n // If no agentId specified, only remove global tools with matching name\n return !(tool.name === id && !tool.agentId);\n });\n }\n\n /**\n * Get a tool by name and optionally by agentId.\n * If agentId is provided, it will first look for an agent-specific tool,\n * then fall back to a global tool with the same name.\n */\n getTool(params: CopilotKitCoreGetToolParams): FrontendTool<any> | undefined {\n const { toolName, agentId } = params;\n\n // If agentId is provided, first look for agent-specific tool\n if (agentId) {\n const agentTool = this._tools.find(\n (tool) => tool.name === toolName && tool.agentId === agentId\n );\n if (agentTool) {\n return agentTool;\n }\n }\n\n // Fall back to global tool (no agentId)\n return this._tools.find((tool) => tool.name === toolName && !tool.agentId);\n }\n\n /**\n * Set all tools at once. Replaces existing tools.\n */\n setTools(tools: FrontendTool<any>[]) {\n this._tools = [...tools];\n }\n\n /**\n * Subscription lifecycle\n */\n subscribe(subscriber: CopilotKitCoreSubscriber): () => void {\n this.subscribers.add(subscriber);\n\n // Return unsubscribe function\n return () => {\n this.unsubscribe(subscriber);\n };\n }\n\n unsubscribe(subscriber: CopilotKitCoreSubscriber) {\n this.subscribers.delete(subscriber);\n }\n\n /**\n * Agent connectivity\n */\n async connectAgent({\n agent,\n agentId,\n }: CopilotKitCoreConnectAgentParams): Promise<RunAgentResult> {\n try {\n if (agent instanceof HttpAgent) {\n agent.headers = { ...this.headers };\n }\n\n const runAgentResult = await agent.connectAgent(\n {\n forwardedProps: this.properties,\n tools: this.buildFrontendTools(agentId),\n },\n this.createAgentErrorSubscriber(agent, agentId)\n );\n\n return this.processAgentResult({ runAgentResult, agent, agentId });\n } catch (error) {\n const connectError =\n error instanceof Error ? error : new Error(String(error));\n const context: Record<string, any> = {};\n if (agentId ?? agent.agentId) {\n context.agentId = agentId ?? agent.agentId;\n }\n await this.emitError({\n error: connectError,\n code: CopilotKitCoreErrorCode.AGENT_CONNECT_FAILED,\n context,\n });\n throw error;\n }\n }\n\n async runAgent({\n agent,\n withMessages,\n agentId,\n }: CopilotKitCoreRunAgentParams): Promise<RunAgentResult> {\n if (agent instanceof HttpAgent) {\n agent.headers = { ...this.headers };\n }\n\n if (withMessages) {\n agent.addMessages(withMessages);\n }\n try {\n const runAgentResult = await agent.runAgent(\n {\n forwardedProps: this.properties,\n tools: this.buildFrontendTools(agentId),\n },\n this.createAgentErrorSubscriber(agent, agentId)\n );\n return this.processAgentResult({ runAgentResult, agent, agentId });\n } catch (error) {\n const runError =\n error instanceof Error ? error : new Error(String(error));\n const context: Record<string, any> = {};\n if (agentId ?? agent.agentId) {\n context.agentId = agentId ?? agent.agentId;\n }\n if (withMessages) {\n context.messageCount = withMessages.length;\n }\n await this.emitError({\n error: runError,\n code: CopilotKitCoreErrorCode.AGENT_RUN_FAILED,\n context,\n });\n throw error;\n }\n }\n\n private async processAgentResult({\n runAgentResult,\n agent,\n agentId,\n }: {\n runAgentResult: RunAgentResult;\n agent: AbstractAgent;\n agentId: string | undefined;\n }): Promise<RunAgentResult> {\n const { newMessages } = runAgentResult;\n const effectiveAgentId = this.resolveAgentId(agent, agentId);\n\n let needsFollowUp = false;\n\n for (const message of newMessages) {\n if (message.role === \"assistant\") {\n for (const toolCall of message.toolCalls || []) {\n if (\n newMessages.findIndex(\n (m) => m.role === \"tool\" && m.toolCallId === toolCall.id\n ) === -1\n ) {\n const tool = this.getTool({\n toolName: toolCall.function.name,\n agentId,\n });\n if (tool) {\n // Check if tool is constrained to a specific agent\n if (tool?.agentId && tool.agentId !== agentId) {\n // Tool is not available for this agent, skip it\n continue;\n }\n\n let toolCallResult = \"\";\n let errorMessage: string | undefined;\n let isArgumentError = false;\n if (tool?.handler) {\n let parsedArgs: unknown;\n try {\n parsedArgs = JSON.parse(toolCall.function.arguments);\n } catch (error) {\n const parseError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = parseError.message;\n isArgumentError = true;\n await this.emitError({\n error: parseError,\n code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n rawArguments: toolCall.function.arguments,\n toolType: \"specific\",\n messageId: message.id,\n },\n });\n }\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionStart?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n args: parsedArgs,\n }),\n \"Subscriber onToolExecutionStart error:\"\n );\n\n if (!errorMessage) {\n try {\n const result = await tool.handler(parsedArgs as any);\n if (result === undefined || result === null) {\n toolCallResult = \"\";\n } else if (typeof result === \"string\") {\n toolCallResult = result;\n } else {\n toolCallResult = JSON.stringify(result);\n }\n } catch (error) {\n const handlerError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = handlerError.message;\n await this.emitError({\n error: handlerError,\n code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n parsedArgs,\n toolType: \"specific\",\n messageId: message.id,\n },\n });\n }\n }\n\n if (errorMessage) {\n toolCallResult = `Error: ${errorMessage}`;\n }\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionEnd?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n result: errorMessage ? \"\" : toolCallResult,\n error: errorMessage,\n }),\n \"Subscriber onToolExecutionEnd error:\"\n );\n\n if (isArgumentError) {\n throw new Error(errorMessage ?? \"Tool execution failed\");\n }\n }\n\n if (!errorMessage || !isArgumentError) {\n const messageIndex = agent.messages.findIndex(\n (m) => m.id === message.id\n );\n const toolMessage = {\n id: randomUUID(),\n role: \"tool\" as const,\n toolCallId: toolCall.id,\n content: toolCallResult,\n };\n agent.messages.splice(messageIndex + 1, 0, toolMessage);\n\n if (!errorMessage && tool?.followUp !== false) {\n needsFollowUp = true;\n }\n }\n } else {\n // Wildcard fallback for undefined tools\n const wildcardTool = this.getTool({ toolName: \"*\", agentId });\n if (wildcardTool) {\n // Check if wildcard tool is constrained to a specific agent\n if (wildcardTool?.agentId && wildcardTool.agentId !== agentId) {\n // Wildcard tool is not available for this agent, skip it\n continue;\n }\n\n let toolCallResult = \"\";\n let errorMessage: string | undefined;\n let isArgumentError = false;\n if (wildcardTool?.handler) {\n let parsedArgs: unknown;\n try {\n parsedArgs = JSON.parse(toolCall.function.arguments);\n } catch (error) {\n const parseError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = parseError.message;\n isArgumentError = true;\n await this.emitError({\n error: parseError,\n code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n rawArguments: toolCall.function.arguments,\n toolType: \"wildcard\",\n messageId: message.id,\n },\n });\n }\n\n const wildcardArgs = {\n toolName: toolCall.function.name,\n args: parsedArgs,\n };\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionStart?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n args: wildcardArgs,\n }),\n \"Subscriber onToolExecutionStart error:\"\n );\n\n if (!errorMessage) {\n try {\n const result = await wildcardTool.handler(\n wildcardArgs as any\n );\n if (result === undefined || result === null) {\n toolCallResult = \"\";\n } else if (typeof result === \"string\") {\n toolCallResult = result;\n } else {\n toolCallResult = JSON.stringify(result);\n }\n } catch (error) {\n const handlerError =\n error instanceof Error\n ? error\n : new Error(String(error));\n errorMessage = handlerError.message;\n await this.emitError({\n error: handlerError,\n code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n parsedArgs: wildcardArgs,\n toolType: \"wildcard\",\n messageId: message.id,\n },\n });\n }\n }\n\n if (errorMessage) {\n toolCallResult = `Error: ${errorMessage}`;\n }\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionEnd?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n result: errorMessage ? \"\" : toolCallResult,\n error: errorMessage,\n }),\n \"Subscriber onToolExecutionEnd error:\"\n );\n\n if (isArgumentError) {\n throw new Error(errorMessage ?? \"Tool execution failed\");\n }\n }\n\n if (!errorMessage || !isArgumentError) {\n const messageIndex = agent.messages.findIndex(\n (m) => m.id === message.id\n );\n const toolMessage = {\n id: randomUUID(),\n role: \"tool\" as const,\n toolCallId: toolCall.id,\n content: toolCallResult,\n };\n agent.messages.splice(messageIndex + 1, 0, toolMessage);\n\n if (!errorMessage && wildcardTool?.followUp !== false) {\n needsFollowUp = true;\n }\n }\n }\n }\n }\n }\n }\n }\n\n if (needsFollowUp) {\n return await this.runAgent({ agent, agentId });\n }\n\n return runAgentResult;\n }\n\n private buildFrontendTools(agentId?: string) {\n return this._tools\n .filter((tool) => !tool.agentId || tool.agentId === agentId)\n .map((tool) => ({\n name: tool.name,\n description: tool.description ?? \"\",\n parameters: createToolSchema(tool),\n }));\n }\n\n private createAgentErrorSubscriber(\n agent: AbstractAgent,\n agentId?: string\n ): AgentSubscriber {\n const emitAgentError = async (\n error: Error,\n code: CopilotKitCoreErrorCode,\n extraContext: Record<string, any> = {}\n ) => {\n const context: Record<string, any> = { ...extraContext };\n if (agentId ?? agent.agentId) {\n context.agentId = agentId ?? agent.agentId;\n }\n await this.emitError({\n error,\n code,\n context,\n });\n };\n\n return {\n onRunFailed: async ({ error }: { error: Error }) => {\n await emitAgentError(\n error,\n CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT,\n {\n source: \"onRunFailed\",\n }\n );\n },\n onRunErrorEvent: async ({ event }) => {\n const eventError =\n event?.rawEvent instanceof Error\n ? event.rawEvent\n : event?.rawEvent?.error instanceof Error\n ? event.rawEvent.error\n : undefined;\n\n const errorMessage =\n typeof event?.rawEvent?.error === \"string\"\n ? event.rawEvent.error\n : (event?.message ?? \"Agent run error\");\n\n const rawError = eventError ?? new Error(errorMessage);\n\n if (event?.code && !(rawError as any).code) {\n (rawError as any).code = event.code;\n }\n\n await emitAgentError(\n rawError,\n CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT,\n {\n source: \"onRunErrorEvent\",\n event,\n runtimeErrorCode: event?.code,\n }\n );\n },\n };\n }\n}\n\nconst EMPTY_TOOL_SCHEMA = {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n} as const satisfies Record<string, unknown>;\n\nfunction createToolSchema(tool: FrontendTool<any>): Record<string, unknown> {\n if (!tool.parameters) {\n return EMPTY_TOOL_SCHEMA;\n }\n\n const rawSchema = zodToJsonSchema(tool.parameters, {\n $refStrategy: \"none\",\n });\n\n if (!rawSchema || typeof rawSchema !== \"object\") {\n return { ...EMPTY_TOOL_SCHEMA };\n }\n\n const { $schema, ...schema } = rawSchema as Record<string, unknown>;\n\n if (typeof schema.type !== \"string\") {\n schema.type = \"object\";\n }\n if (typeof schema.properties !== \"object\" || schema.properties === null) {\n schema.properties = {};\n }\n if (schema.additionalProperties === undefined) {\n schema.additionalProperties = false;\n }\n\n return schema;\n}\n","import {\n BaseEvent,\n HttpAgent,\n HttpAgentConfig,\n RunAgentInput,\n runHttpRequest,\n transformHttpEventStream,\n} from \"@ag-ui/client\";\nimport { Observable } from \"rxjs\";\n\nexport interface ProxiedCopilotRuntimeAgentConfig\n extends Omit<HttpAgentConfig, \"url\"> {\n runtimeUrl?: string;\n}\n\nexport class ProxiedCopilotRuntimeAgent extends HttpAgent {\n runtimeUrl?: string;\n\n constructor(config: ProxiedCopilotRuntimeAgentConfig) {\n super({\n ...config,\n url: `${config.runtimeUrl}/agent/${config.agentId}/run`,\n });\n this.runtimeUrl = config.runtimeUrl;\n }\n\n connect(input: RunAgentInput): Observable<BaseEvent> {\n const httpEvents = runHttpRequest(\n `${this.runtimeUrl}/agent/${this.agentId}/connect`,\n this.requestInit(input)\n );\n return transformHttpEventStream(httpEvents);\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Status of a tool call execution\n */\nexport enum ToolCallStatus {\n InProgress = \"inProgress\",\n Executing = \"executing\",\n Complete = \"complete\"\n}\n\nexport type FrontendTool<T extends Record<string, unknown> = Record<string, unknown>> = {\n name: string;\n description?: string;\n parameters?: z.ZodType<T>;\n handler?: (args: T) => Promise<unknown>;\n followUp?: boolean;\n /**\n * Optional agent ID to constrain this tool to a specific agent.\n * If specified, this tool will only be available to the specified agent.\n */\n agentId?: string;\n};\n","export function completePartialMarkdown(input: string): string {\n let s = input;\n\n // Handle code fences first - use FIRST unmatched fence for proper nesting\n const fenceMatches = Array.from(s.matchAll(/^(\\s*)(`{3,}|~{3,})/gm));\n if (fenceMatches.length % 2 === 1) {\n const [, indent, fence] = fenceMatches[0]!;\n s += `\\n${indent}${fence}`;\n }\n\n // Identify incomplete links at the end and close them\n const incompleteLinkMatch = s.match(/\\[([^\\]]*)\\]\\(([^)]*)$/);\n if (incompleteLinkMatch) {\n s += \")\";\n }\n\n // State-based parsing\n interface OpenElement {\n type: string;\n marker: string;\n position: number;\n }\n\n const openElements: OpenElement[] = [];\n const chars = Array.from(s);\n\n // First pass: identify code block boundaries and inline code to avoid processing their content\n const codeBlockRanges: Array<{ start: number; end: number }> = [];\n const inlineCodeRanges: Array<{ start: number; end: number }> = [];\n\n // Find code block ranges\n let tempCodeFenceCount = 0;\n let currentCodeBlockStart = -1;\n\n for (let i = 0; i < chars.length; i++) {\n if (i === 0 || chars[i - 1] === \"\\n\") {\n const lineMatch = s.substring(i).match(/^(\\s*)(`{3,}|~{3,})/);\n if (lineMatch) {\n tempCodeFenceCount++;\n if (tempCodeFenceCount % 2 === 1) {\n currentCodeBlockStart = i;\n } else if (currentCodeBlockStart !== -1) {\n codeBlockRanges.push({\n start: currentCodeBlockStart,\n end: i + lineMatch[0].length,\n });\n currentCodeBlockStart = -1;\n }\n i += lineMatch[0].length - 1;\n }\n }\n }\n\n // Find inline code ranges\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] === \"`\") {\n // Check if escaped\n let backslashCount = 0;\n for (let j = i - 1; j >= 0 && chars[j] === \"\\\\\"; j--) {\n backslashCount++;\n }\n if (backslashCount % 2 === 0) {\n // Not escaped - find the closing backtick\n for (let j = i + 1; j < chars.length; j++) {\n if (chars[j] === \"`\") {\n let closingBackslashCount = 0;\n for (let k = j - 1; k >= 0 && chars[k] === \"\\\\\"; k--) {\n closingBackslashCount++;\n }\n if (closingBackslashCount % 2 === 0) {\n inlineCodeRanges.push({ start: i, end: j + 1 });\n i = j;\n break;\n }\n }\n }\n }\n }\n }\n\n // Helper function to check if position is in code\n const isInCode = (pos: number): boolean => {\n return (\n codeBlockRanges.some((range) => pos >= range.start && pos < range.end) ||\n inlineCodeRanges.some((range) => pos >= range.start && pos < range.end)\n );\n };\n\n // Second pass: process markdown elements, skipping code regions\n for (let i = 0; i < chars.length; i++) {\n const char = chars[i];\n const nextChar = chars[i + 1];\n const prevChar = chars[i - 1];\n\n if (isInCode(i)) {\n continue;\n }\n\n // Handle brackets (but not if they're part of already-complete links)\n if (char === \"[\") {\n // Check if this is part of a complete link [text](url)\n let isCompleteLink = false;\n let bracketDepth = 1;\n let j = i + 1;\n\n // Find the matching ]\n while (j < chars.length && bracketDepth > 0) {\n if (chars[j] === \"[\" && !isInCode(j)) bracketDepth++;\n if (chars[j] === \"]\" && !isInCode(j)) bracketDepth--;\n j++;\n }\n\n // Check if followed by (\n if (bracketDepth === 0 && chars[j] === \"(\") {\n // Find the closing )\n let parenDepth = 1;\n j++;\n while (j < chars.length && parenDepth > 0) {\n if (chars[j] === \"(\" && !isInCode(j)) parenDepth++;\n if (chars[j] === \")\" && !isInCode(j)) parenDepth--;\n j++;\n }\n if (parenDepth === 0) {\n isCompleteLink = true;\n i = j - 1;\n continue;\n }\n }\n\n // This is a standalone bracket, treat as markdown\n if (!isCompleteLink) {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bracket\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"bracket\", marker: \"[\", position: i });\n }\n }\n }\n\n // Handle double emphasis first (**, __, ~~) - these take precedence\n else if (char === \"*\" && nextChar === \"*\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bold_star\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"bold_star\", marker: \"**\", position: i });\n }\n i++; // Skip next character\n } else if (char === \"_\" && nextChar === \"_\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bold_underscore\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({\n type: \"bold_underscore\",\n marker: \"__\",\n position: i,\n });\n }\n i++; // Skip next character\n } else if (char === \"~\" && nextChar === \"~\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"strike\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"strike\", marker: \"~~\", position: i });\n }\n i++; // Skip next character\n }\n\n // Handle single emphasis (*, _) - only if not part of double\n else if (char === \"*\" && prevChar !== \"*\" && nextChar !== \"*\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"italic_star\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"italic_star\", marker: \"*\", position: i });\n }\n } else if (char === \"_\" && prevChar !== \"_\" && nextChar !== \"_\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"italic_underscore\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({\n type: \"italic_underscore\",\n marker: \"_\",\n position: i,\n });\n }\n }\n }\n\n // Handle remaining unmatched backticks (outside of inline code ranges)\n let backtickCount = 0;\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] === \"`\" && !isInCode(i)) {\n backtickCount++;\n }\n }\n if (backtickCount % 2 === 1) {\n s += \"`\";\n }\n\n // Close remaining open elements in reverse order (LIFO stack semantics)\n openElements.sort((a, b) => b.position - a.position);\n\n const closers = openElements.map((el) => {\n switch (el.type) {\n case \"bracket\":\n return \"]\";\n case \"bold_star\":\n return \"**\";\n case \"bold_underscore\":\n return \"__\";\n case \"strike\":\n return \"~~\";\n case \"italic_star\":\n return \"*\";\n case \"italic_underscore\":\n return \"_\";\n default:\n return \"\";\n }\n });\n\n let result = s + closers.join(\"\");\n\n // Handle parentheses ONLY if not inside code\n const finalFenceMatches = Array.from(\n result.matchAll(/^(\\s*)(`{3,}|~{3,})/gm)\n );\n const hasUnclosedBacktick = (result.match(/`/g) || []).length % 2 === 1;\n const hasUnclosedCodeFence = finalFenceMatches.length % 2 === 1;\n\n let shouldCloseParens = !hasUnclosedBacktick && !hasUnclosedCodeFence;\n\n if (shouldCloseParens) {\n const lastOpenParen = result.lastIndexOf(\"(\");\n if (lastOpenParen !== -1) {\n // Check if this paren is inside a backtick pair\n const beforeParen = result.substring(0, lastOpenParen);\n const backticksBeforeParen = (beforeParen.match(/`/g) || []).length;\n if (backticksBeforeParen % 2 === 1) {\n shouldCloseParens = false;\n }\n }\n }\n\n if (shouldCloseParens) {\n const openParens = (result.match(/\\(/g) || []).length;\n const closeParens = (result.match(/\\)/g) || []).length;\n if (openParens > closeParens) {\n result += \")\".repeat(openParens - closeParens);\n }\n }\n\n return result;\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAMO;AACP,IAAAA,iBAOO;;;ACdP,oBAOO;AAQA,IAAM,6BAAN,cAAyC,wBAAU;AAAA,EACxD;AAAA,EAEA,YAAY,QAA0C;AACpD,UAAM;AAAA,MACJ,GAAG;AAAA,MACH,KAAK,GAAG,OAAO,UAAU,UAAU,OAAO,OAAO;AAAA,IACnD,CAAC;AACD,SAAK,aAAa,OAAO;AAAA,EAC3B;AAAA,EAEA,QAAQ,OAA6C;AACnD,UAAM,iBAAa;AAAA,MACjB,GAAG,KA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IAAI;AAExB,YAAM,cAAc,OAAO,UAAU,GAAG,aAAa;AACrD,YAAM,wBAAwB,YAAY,MAAM,IAAI,KAAK,CAAC,GAAG;AAC7D,UAAI,uBAAuB,MAAM,GAAG;AAClC,4BAAoB;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AAEA,MAAI,mBAAmB;AACrB,UAAM,cAAc,OAAO,MAAM,KAAK,KAAK,CAAC,GAAG;AAC/C,UAAM,eAAe,OAAO,MAAM,KAAK,KAAK,CAAC,GAAG;AAChD,QAAI,aAAa,aAAa;AAC5B,gBAAU,IAAI,OAAO,aAAa,WAAW;AAAA,IAC/C;AAAA,EACF;AAEA,SAAO;AACT;","names":["import_client","CopilotKitCoreErrorCode","CopilotKitCoreRuntimeConnectionStatus","ToolCallStatus"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/core.ts","../src/agent.ts","../src/types.ts","../src/utils/markdown.ts"],"sourcesContent":["export * from \"./core\";\nexport * from \"./types\";\nexport * from \"./agent\";\nexport * from \"./utils/markdown\";\n","import {\n AgentDescription,\n DEFAULT_AGENT_ID,\n randomUUID,\n RuntimeInfo,\n logger,\n} from \"@copilotkitnext/shared\";\nimport {\n AbstractAgent,\n AgentSubscriber,\n Context,\n HttpAgent,\n Message,\n RunAgentResult,\n} from \"@ag-ui/client\";\nimport { FrontendTool } from \"./types\";\nimport { ProxiedCopilotRuntimeAgent } from \"./agent\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\n\n/** Configuration options for `CopilotKitCore`. */\nexport interface CopilotKitCoreConfig {\n /** The endpoint of the CopilotRuntime. */\n runtimeUrl?: string;\n /** Mapping from agent name to its `AbstractAgent` instance. */\n agents?: Record<string, AbstractAgent>;\n /** Headers appended to every HTTP request made by `CopilotKitCore`. */\n headers?: Record<string, string>;\n /** Properties sent as `forwardedProps` to the AG-UI agent. */\n properties?: Record<string, unknown>;\n /** Ordered collection of frontend tools available to the core. */\n tools?: FrontendTool<any>[];\n}\n\nexport interface CopilotKitCoreAddAgentParams {\n id: string;\n agent: AbstractAgent;\n}\n\nexport interface CopilotKitCoreRunAgentParams {\n agent: AbstractAgent;\n withMessages?: Message[];\n agentId?: string;\n}\n\nexport interface CopilotKitCoreConnectAgentParams {\n agent: AbstractAgent;\n agentId?: string;\n}\n\nexport interface CopilotKitCoreGetToolParams {\n toolName: string;\n agentId?: string;\n}\n\nexport enum CopilotKitCoreErrorCode {\n RUNTIME_INFO_FETCH_FAILED = \"runtime_info_fetch_failed\",\n AGENT_CONNECT_FAILED = \"agent_connect_failed\",\n AGENT_RUN_FAILED = \"agent_run_failed\",\n AGENT_RUN_FAILED_EVENT = \"agent_run_failed_event\",\n AGENT_RUN_ERROR_EVENT = \"agent_run_error_event\",\n TOOL_ARGUMENT_PARSE_FAILED = \"tool_argument_parse_failed\",\n TOOL_HANDLER_FAILED = \"tool_handler_failed\",\n}\n\nexport interface CopilotKitCoreSubscriber {\n onRuntimeConnectionStatusChanged?: (event: {\n copilotkit: CopilotKitCore;\n status: CopilotKitCoreRuntimeConnectionStatus;\n }) => void | Promise<void>;\n onToolExecutionStart?: (event: {\n copilotkit: CopilotKitCore;\n toolCallId: string;\n agentId: string;\n toolName: string;\n args: unknown;\n }) => void | Promise<void>;\n onToolExecutionEnd?: (event: {\n copilotkit: CopilotKitCore;\n toolCallId: string;\n agentId: string;\n toolName: string;\n result: string;\n error?: string;\n }) => void | Promise<void>;\n onAgentsChanged?: (event: {\n copilotkit: CopilotKitCore;\n agents: Readonly<Record<string, AbstractAgent>>;\n }) => void | Promise<void>;\n onContextChanged?: (event: {\n copilotkit: CopilotKitCore;\n context: Readonly<Record<string, Context>>;\n }) => void | Promise<void>;\n onPropertiesChanged?: (event: {\n copilotkit: CopilotKitCore;\n properties: Readonly<Record<string, unknown>>;\n }) => void | Promise<void>;\n onHeadersChanged?: (event: {\n copilotkit: CopilotKitCore;\n headers: Readonly<Record<string, string>>;\n }) => void | Promise<void>;\n onError?: (event: {\n copilotkit: CopilotKitCore;\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n}\n\nexport enum CopilotKitCoreRuntimeConnectionStatus {\n Disconnected = \"disconnected\",\n Connected = \"connected\",\n Connecting = \"connecting\",\n Error = \"error\",\n}\n\nexport class CopilotKitCore {\n headers: Record<string, string>;\n properties: Record<string, unknown>;\n\n private _context: Record<string, Context> = {};\n private _agents: Record<string, AbstractAgent> = {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _tools: FrontendTool<any>[] = [];\n\n private localAgents: Record<string, AbstractAgent> = {};\n private remoteAgents: Record<string, AbstractAgent> = {};\n private subscribers: Set<CopilotKitCoreSubscriber> = new Set();\n\n private _runtimeUrl?: string;\n private _runtimeVersion?: string;\n private _runtimeConnectionStatus: CopilotKitCoreRuntimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Disconnected;\n\n constructor({\n runtimeUrl,\n headers = {},\n properties = {},\n agents = {},\n tools = [],\n }: CopilotKitCoreConfig) {\n this.headers = headers;\n this.properties = properties;\n this.localAgents = this.assignAgentIds(agents);\n this.applyHeadersToAgents(this.localAgents);\n this._agents = this.localAgents;\n this._tools = tools;\n this.setRuntimeUrl(runtimeUrl);\n }\n\n private applyHeadersToAgent(agent: AbstractAgent) {\n if (agent instanceof HttpAgent) {\n agent.headers = { ...this.headers };\n }\n }\n\n private applyHeadersToAgents(agents: Record<string, AbstractAgent>) {\n Object.values(agents).forEach((agent) => {\n this.applyHeadersToAgent(agent);\n });\n }\n\n private assignAgentIds(agents: Record<string, AbstractAgent>) {\n Object.entries(agents).forEach(([id, agent]) => {\n if (agent && !agent.agentId) {\n agent.agentId = id;\n }\n });\n return agents;\n }\n\n private async notifySubscribers(\n handler: (subscriber: CopilotKitCoreSubscriber) => void | Promise<void>,\n errorMessage: string\n ) {\n await Promise.all(\n Array.from(this.subscribers).map(async (subscriber) => {\n try {\n await handler(subscriber);\n } catch (error) {\n logger.error(errorMessage, error);\n }\n })\n );\n }\n\n private async emitError({\n error,\n code,\n context = {},\n }: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context?: Record<string, any>;\n }) {\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onError?.({\n copilotkit: this,\n error,\n code,\n context,\n }),\n \"Subscriber onError error:\"\n );\n }\n\n private resolveAgentId(\n agent: AbstractAgent,\n providedAgentId?: string\n ): string {\n if (providedAgentId) {\n return providedAgentId;\n }\n if (agent.agentId) {\n return agent.agentId;\n }\n const found = Object.entries(this._agents).find(([, storedAgent]) => {\n return storedAgent === agent;\n });\n if (found) {\n agent.agentId = found[0];\n return found[0];\n }\n agent.agentId = DEFAULT_AGENT_ID;\n return DEFAULT_AGENT_ID;\n }\n\n /**\n * Snapshot accessors\n */\n get context(): Readonly<Record<string, Context>> {\n return this._context;\n }\n\n get agents(): Readonly<Record<string, AbstractAgent>> {\n return this._agents;\n }\n\n get tools(): Readonly<FrontendTool<any>[]> {\n return this._tools;\n }\n\n get runtimeUrl(): string | undefined {\n return this._runtimeUrl;\n }\n\n setRuntimeUrl(runtimeUrl: string | undefined) {\n const normalizedRuntimeUrl = runtimeUrl\n ? runtimeUrl.replace(/\\/$/, \"\")\n : undefined;\n\n if (this._runtimeUrl === normalizedRuntimeUrl) {\n return;\n }\n\n this._runtimeUrl = normalizedRuntimeUrl;\n void this.updateRuntimeConnection();\n }\n\n get runtimeVersion(): string | undefined {\n return this._runtimeVersion;\n }\n\n get runtimeConnectionStatus(): CopilotKitCoreRuntimeConnectionStatus {\n return this._runtimeConnectionStatus;\n }\n\n /**\n * Runtime connection\n */\n private async updateRuntimeConnection() {\n if (!this.runtimeUrl) {\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Disconnected;\n this._runtimeVersion = undefined;\n this.remoteAgents = {};\n this._agents = this.localAgents;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Disconnected,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n return;\n }\n\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Connecting;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Connecting,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n try {\n const response = await fetch(`${this.runtimeUrl}/info`, {\n headers: this.headers,\n });\n const {\n version,\n ...runtimeInfo\n }: {\n agents: Record<string, AgentDescription>;\n version: string;\n } = (await response.json()) as RuntimeInfo;\n\n const agents: Record<string, AbstractAgent> = Object.fromEntries(\n Object.entries(runtimeInfo.agents).map(([id, { description }]) => {\n const agent = new ProxiedCopilotRuntimeAgent({\n runtimeUrl: this.runtimeUrl,\n agentId: id,\n description: description,\n });\n this.applyHeadersToAgent(agent);\n return [id, agent];\n })\n );\n\n this.remoteAgents = agents;\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Connected;\n this._runtimeVersion = version;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Connected,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n } catch (error) {\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Error;\n this._runtimeVersion = undefined;\n this.remoteAgents = {};\n this._agents = this.localAgents;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Error,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n const message =\n error instanceof Error ? error.message : JSON.stringify(error);\n logger.warn(\n `Failed to load runtime info (${this.runtimeUrl}/info): ${message}`\n );\n const runtimeError =\n error instanceof Error ? error : new Error(String(error));\n await this.emitError({\n error: runtimeError,\n code: CopilotKitCoreErrorCode.RUNTIME_INFO_FETCH_FAILED,\n context: {\n runtimeUrl: this.runtimeUrl,\n },\n });\n }\n }\n\n /**\n * Configuration updates\n */\n setHeaders(headers: Record<string, string>) {\n this.headers = headers;\n this.applyHeadersToAgents(this._agents);\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onHeadersChanged?.({\n copilotkit: this,\n headers: this.headers,\n }),\n \"Subscriber onHeadersChanged error:\"\n );\n }\n\n setProperties(properties: Record<string, unknown>) {\n this.properties = properties;\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onPropertiesChanged?.({\n copilotkit: this,\n properties: this.properties,\n }),\n \"Subscriber onPropertiesChanged error:\"\n );\n }\n\n setAgents(agents: Record<string, AbstractAgent>) {\n this.localAgents = this.assignAgentIds(agents);\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n this.applyHeadersToAgents(this._agents);\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n }\n\n addAgent({ id, agent }: CopilotKitCoreAddAgentParams) {\n this.localAgents[id] = agent;\n if (!agent.agentId) {\n agent.agentId = id;\n }\n this.applyHeadersToAgent(agent);\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n }\n\n removeAgent(id: string) {\n delete this.localAgents[id];\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n }\n\n getAgent(id: string): AbstractAgent | undefined {\n if (id in this._agents) {\n return this._agents[id] as AbstractAgent;\n }\n\n if (\n this.runtimeUrl !== undefined &&\n (this.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Disconnected ||\n this.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connecting)\n ) {\n return undefined;\n } else {\n console.warn(`Agent ${id} not found`);\n return undefined;\n }\n }\n\n /**\n * Context management\n */\n addContext({ description, value }: Context): string {\n const id = randomUUID();\n this._context[id] = { description, value };\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onContextChanged?.({\n copilotkit: this,\n context: this._context,\n }),\n \"Subscriber onContextChanged error:\"\n );\n return id;\n }\n\n removeContext(id: string) {\n delete this._context[id];\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onContextChanged?.({\n copilotkit: this,\n context: this._context,\n }),\n \"Subscriber onContextChanged error:\"\n );\n }\n\n /**\n * Tool management\n */\n addTool<T extends Record<string, unknown> = Record<string, unknown>>(\n tool: FrontendTool<T>\n ) {\n // Check if a tool with the same name and agentId already exists\n const existingToolIndex = this._tools.findIndex(\n (t) => t.name === tool.name && t.agentId === tool.agentId\n );\n\n if (existingToolIndex !== -1) {\n logger.warn(\n `Tool already exists: '${tool.name}' for agent '${tool.agentId || \"global\"}', skipping.`\n );\n return;\n }\n\n this._tools.push(tool);\n }\n\n removeTool(id: string, agentId?: string) {\n this._tools = this._tools.filter((tool) => {\n // Remove tool if both name and agentId match\n if (agentId !== undefined) {\n return !(tool.name === id && tool.agentId === agentId);\n }\n // If no agentId specified, only remove global tools with matching name\n return !(tool.name === id && !tool.agentId);\n });\n }\n\n /**\n * Get a tool by name and optionally by agentId.\n * If agentId is provided, it will first look for an agent-specific tool,\n * then fall back to a global tool with the same name.\n */\n getTool(params: CopilotKitCoreGetToolParams): FrontendTool<any> | undefined {\n const { toolName, agentId } = params;\n\n // If agentId is provided, first look for agent-specific tool\n if (agentId) {\n const agentTool = this._tools.find(\n (tool) => tool.name === toolName && tool.agentId === agentId\n );\n if (agentTool) {\n return agentTool;\n }\n }\n\n // Fall back to global tool (no agentId)\n return this._tools.find((tool) => tool.name === toolName && !tool.agentId);\n }\n\n /**\n * Set all tools at once. Replaces existing tools.\n */\n setTools(tools: FrontendTool<any>[]) {\n this._tools = [...tools];\n }\n\n /**\n * Subscription lifecycle\n */\n subscribe(subscriber: CopilotKitCoreSubscriber): () => void {\n this.subscribers.add(subscriber);\n\n // Return unsubscribe function\n return () => {\n this.unsubscribe(subscriber);\n };\n }\n\n unsubscribe(subscriber: CopilotKitCoreSubscriber) {\n this.subscribers.delete(subscriber);\n }\n\n /**\n * Agent connectivity\n */\n async connectAgent({\n agent,\n agentId,\n }: CopilotKitCoreConnectAgentParams): Promise<RunAgentResult> {\n try {\n if (agent instanceof HttpAgent) {\n agent.headers = { ...this.headers };\n }\n\n const runAgentResult = await agent.connectAgent(\n {\n forwardedProps: this.properties,\n tools: this.buildFrontendTools(agentId),\n },\n this.createAgentErrorSubscriber(agent, agentId)\n );\n\n return this.processAgentResult({ runAgentResult, agent, agentId });\n } catch (error) {\n const connectError =\n error instanceof Error ? error : new Error(String(error));\n const context: Record<string, any> = {};\n if (agentId ?? agent.agentId) {\n context.agentId = agentId ?? agent.agentId;\n }\n await this.emitError({\n error: connectError,\n code: CopilotKitCoreErrorCode.AGENT_CONNECT_FAILED,\n context,\n });\n throw error;\n }\n }\n\n async runAgent({\n agent,\n withMessages,\n agentId,\n }: CopilotKitCoreRunAgentParams): Promise<RunAgentResult> {\n if (agent instanceof HttpAgent) {\n agent.headers = { ...this.headers };\n }\n\n if (withMessages) {\n agent.addMessages(withMessages);\n }\n try {\n const runAgentResult = await agent.runAgent(\n {\n forwardedProps: this.properties,\n tools: this.buildFrontendTools(agentId),\n },\n this.createAgentErrorSubscriber(agent, agentId)\n );\n return this.processAgentResult({ runAgentResult, agent, agentId });\n } catch (error) {\n const runError =\n error instanceof Error ? error : new Error(String(error));\n const context: Record<string, any> = {};\n if (agentId ?? agent.agentId) {\n context.agentId = agentId ?? agent.agentId;\n }\n if (withMessages) {\n context.messageCount = withMessages.length;\n }\n await this.emitError({\n error: runError,\n code: CopilotKitCoreErrorCode.AGENT_RUN_FAILED,\n context,\n });\n throw error;\n }\n }\n\n private async processAgentResult({\n runAgentResult,\n agent,\n agentId,\n }: {\n runAgentResult: RunAgentResult;\n agent: AbstractAgent;\n agentId: string | undefined;\n }): Promise<RunAgentResult> {\n const { newMessages } = runAgentResult;\n const effectiveAgentId = this.resolveAgentId(agent, agentId);\n\n let needsFollowUp = false;\n\n for (const message of newMessages) {\n if (message.role === \"assistant\") {\n for (const toolCall of message.toolCalls || []) {\n if (\n newMessages.findIndex(\n (m) => m.role === \"tool\" && m.toolCallId === toolCall.id\n ) === -1\n ) {\n const tool = this.getTool({\n toolName: toolCall.function.name,\n agentId,\n });\n if (tool) {\n // Check if tool is constrained to a specific agent\n if (tool?.agentId && tool.agentId !== agentId) {\n // Tool is not available for this agent, skip it\n continue;\n }\n\n let toolCallResult = \"\";\n let errorMessage: string | undefined;\n let isArgumentError = false;\n if (tool?.handler) {\n let parsedArgs: unknown;\n try {\n parsedArgs = JSON.parse(toolCall.function.arguments);\n } catch (error) {\n const parseError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = parseError.message;\n isArgumentError = true;\n await this.emitError({\n error: parseError,\n code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n rawArguments: toolCall.function.arguments,\n toolType: \"specific\",\n messageId: message.id,\n },\n });\n }\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionStart?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n args: parsedArgs,\n }),\n \"Subscriber onToolExecutionStart error:\"\n );\n\n if (!errorMessage) {\n try {\n const result = await tool.handler(\n parsedArgs as any,\n toolCall\n );\n if (result === undefined || result === null) {\n toolCallResult = \"\";\n } else if (typeof result === \"string\") {\n toolCallResult = result;\n } else {\n toolCallResult = JSON.stringify(result);\n }\n } catch (error) {\n const handlerError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = handlerError.message;\n await this.emitError({\n error: handlerError,\n code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n parsedArgs,\n toolType: \"specific\",\n messageId: message.id,\n },\n });\n }\n }\n\n if (errorMessage) {\n toolCallResult = `Error: ${errorMessage}`;\n }\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionEnd?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n result: errorMessage ? \"\" : toolCallResult,\n error: errorMessage,\n }),\n \"Subscriber onToolExecutionEnd error:\"\n );\n\n if (isArgumentError) {\n throw new Error(errorMessage ?? \"Tool execution failed\");\n }\n }\n\n if (!errorMessage || !isArgumentError) {\n const messageIndex = agent.messages.findIndex(\n (m) => m.id === message.id\n );\n const toolMessage = {\n id: randomUUID(),\n role: \"tool\" as const,\n toolCallId: toolCall.id,\n content: toolCallResult,\n };\n agent.messages.splice(messageIndex + 1, 0, toolMessage);\n\n if (!errorMessage && tool?.followUp !== false) {\n needsFollowUp = true;\n }\n }\n } else {\n // Wildcard fallback for undefined tools\n const wildcardTool = this.getTool({ toolName: \"*\", agentId });\n if (wildcardTool) {\n // Check if wildcard tool is constrained to a specific agent\n if (wildcardTool?.agentId && wildcardTool.agentId !== agentId) {\n // Wildcard tool is not available for this agent, skip it\n continue;\n }\n\n let toolCallResult = \"\";\n let errorMessage: string | undefined;\n let isArgumentError = false;\n if (wildcardTool?.handler) {\n let parsedArgs: unknown;\n try {\n parsedArgs = JSON.parse(toolCall.function.arguments);\n } catch (error) {\n const parseError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = parseError.message;\n isArgumentError = true;\n await this.emitError({\n error: parseError,\n code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n rawArguments: toolCall.function.arguments,\n toolType: \"wildcard\",\n messageId: message.id,\n },\n });\n }\n\n const wildcardArgs = {\n toolName: toolCall.function.name,\n args: parsedArgs,\n };\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionStart?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n args: wildcardArgs,\n }),\n \"Subscriber onToolExecutionStart error:\"\n );\n\n if (!errorMessage) {\n try {\n const result = await wildcardTool.handler(\n wildcardArgs as any,\n toolCall\n );\n if (result === undefined || result === null) {\n toolCallResult = \"\";\n } else if (typeof result === \"string\") {\n toolCallResult = result;\n } else {\n toolCallResult = JSON.stringify(result);\n }\n } catch (error) {\n const handlerError =\n error instanceof Error\n ? error\n : new Error(String(error));\n errorMessage = handlerError.message;\n await this.emitError({\n error: handlerError,\n code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n parsedArgs: wildcardArgs,\n toolType: \"wildcard\",\n messageId: message.id,\n },\n });\n }\n }\n\n if (errorMessage) {\n toolCallResult = `Error: ${errorMessage}`;\n }\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionEnd?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n result: errorMessage ? \"\" : toolCallResult,\n error: errorMessage,\n }),\n \"Subscriber onToolExecutionEnd error:\"\n );\n\n if (isArgumentError) {\n throw new Error(errorMessage ?? \"Tool execution failed\");\n }\n }\n\n if (!errorMessage || !isArgumentError) {\n const messageIndex = agent.messages.findIndex(\n (m) => m.id === message.id\n );\n const toolMessage = {\n id: randomUUID(),\n role: \"tool\" as const,\n toolCallId: toolCall.id,\n content: toolCallResult,\n };\n agent.messages.splice(messageIndex + 1, 0, toolMessage);\n\n if (!errorMessage && wildcardTool?.followUp !== false) {\n needsFollowUp = true;\n }\n }\n }\n }\n }\n }\n }\n }\n\n if (needsFollowUp) {\n return await this.runAgent({ agent, agentId });\n }\n\n return runAgentResult;\n }\n\n private buildFrontendTools(agentId?: string) {\n return this._tools\n .filter((tool) => !tool.agentId || tool.agentId === agentId)\n .map((tool) => ({\n name: tool.name,\n description: tool.description ?? \"\",\n parameters: createToolSchema(tool),\n }));\n }\n\n private createAgentErrorSubscriber(\n agent: AbstractAgent,\n agentId?: string\n ): AgentSubscriber {\n const emitAgentError = async (\n error: Error,\n code: CopilotKitCoreErrorCode,\n extraContext: Record<string, any> = {}\n ) => {\n const context: Record<string, any> = { ...extraContext };\n if (agentId ?? agent.agentId) {\n context.agentId = agentId ?? agent.agentId;\n }\n await this.emitError({\n error,\n code,\n context,\n });\n };\n\n return {\n onRunFailed: async ({ error }: { error: Error }) => {\n await emitAgentError(\n error,\n CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT,\n {\n source: \"onRunFailed\",\n }\n );\n },\n onRunErrorEvent: async ({ event }) => {\n const eventError =\n event?.rawEvent instanceof Error\n ? event.rawEvent\n : event?.rawEvent?.error instanceof Error\n ? event.rawEvent.error\n : undefined;\n\n const errorMessage =\n typeof event?.rawEvent?.error === \"string\"\n ? event.rawEvent.error\n : (event?.message ?? \"Agent run error\");\n\n const rawError = eventError ?? new Error(errorMessage);\n\n if (event?.code && !(rawError as any).code) {\n (rawError as any).code = event.code;\n }\n\n await emitAgentError(\n rawError,\n CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT,\n {\n source: \"onRunErrorEvent\",\n event,\n runtimeErrorCode: event?.code,\n }\n );\n },\n };\n }\n}\n\nconst EMPTY_TOOL_SCHEMA = {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n} as const satisfies Record<string, unknown>;\n\nfunction createToolSchema(tool: FrontendTool<any>): Record<string, unknown> {\n if (!tool.parameters) {\n return EMPTY_TOOL_SCHEMA;\n }\n\n const rawSchema = zodToJsonSchema(tool.parameters, {\n $refStrategy: \"none\",\n });\n\n if (!rawSchema || typeof rawSchema !== \"object\") {\n return { ...EMPTY_TOOL_SCHEMA };\n }\n\n const { $schema, ...schema } = rawSchema as Record<string, unknown>;\n\n if (typeof schema.type !== \"string\") {\n schema.type = \"object\";\n }\n if (typeof schema.properties !== \"object\" || schema.properties === null) {\n schema.properties = {};\n }\n if (schema.additionalProperties === undefined) {\n schema.additionalProperties = false;\n }\n\n return schema;\n}\n","import {\n BaseEvent,\n HttpAgent,\n HttpAgentConfig,\n RunAgentInput,\n runHttpRequest,\n transformHttpEventStream,\n} from \"@ag-ui/client\";\nimport { Observable } from \"rxjs\";\n\nexport interface ProxiedCopilotRuntimeAgentConfig\n extends Omit<HttpAgentConfig, \"url\"> {\n runtimeUrl?: string;\n}\n\nexport class ProxiedCopilotRuntimeAgent extends HttpAgent {\n runtimeUrl?: string;\n\n constructor(config: ProxiedCopilotRuntimeAgentConfig) {\n super({\n ...config,\n url: `${config.runtimeUrl}/agent/${config.agentId}/run`,\n });\n this.runtimeUrl = config.runtimeUrl;\n }\n\n connect(input: RunAgentInput): Observable<BaseEvent> {\n const httpEvents = runHttpRequest(\n `${this.runtimeUrl}/agent/${this.agentId}/connect`,\n this.requestInit(input)\n );\n return transformHttpEventStream(httpEvents);\n }\n}\n","import { ToolCall } from \"@ag-ui/client\";\nimport { z } from \"zod\";\n\n/**\n * Status of a tool call execution\n */\nexport enum ToolCallStatus {\n InProgress = \"inProgress\",\n Executing = \"executing\",\n Complete = \"complete\",\n}\n\nexport type FrontendTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n> = {\n name: string;\n description?: string;\n parameters?: z.ZodType<T>;\n handler?: (args: T, toolCall: ToolCall) => Promise<unknown>;\n followUp?: boolean;\n /**\n * Optional agent ID to constrain this tool to a specific agent.\n * If specified, this tool will only be available to the specified agent.\n */\n agentId?: string;\n};\n","export function completePartialMarkdown(input: string): string {\n let s = input;\n\n // Handle code fences first - use FIRST unmatched fence for proper nesting\n const fenceMatches = Array.from(s.matchAll(/^(\\s*)(`{3,}|~{3,})/gm));\n if (fenceMatches.length % 2 === 1) {\n const [, indent, fence] = fenceMatches[0]!;\n s += `\\n${indent}${fence}`;\n }\n\n // Identify incomplete links at the end and close them\n const incompleteLinkMatch = s.match(/\\[([^\\]]*)\\]\\(([^)]*)$/);\n if (incompleteLinkMatch) {\n s += \")\";\n }\n\n // State-based parsing\n interface OpenElement {\n type: string;\n marker: string;\n position: number;\n }\n\n const openElements: OpenElement[] = [];\n const chars = Array.from(s);\n\n // First pass: identify code block boundaries and inline code to avoid processing their content\n const codeBlockRanges: Array<{ start: number; end: number }> = [];\n const inlineCodeRanges: Array<{ start: number; end: number }> = [];\n\n // Find code block ranges\n let tempCodeFenceCount = 0;\n let currentCodeBlockStart = -1;\n\n for (let i = 0; i < chars.length; i++) {\n if (i === 0 || chars[i - 1] === \"\\n\") {\n const lineMatch = s.substring(i).match(/^(\\s*)(`{3,}|~{3,})/);\n if (lineMatch) {\n tempCodeFenceCount++;\n if (tempCodeFenceCount % 2 === 1) {\n currentCodeBlockStart = i;\n } else if (currentCodeBlockStart !== -1) {\n codeBlockRanges.push({\n start: currentCodeBlockStart,\n end: i + lineMatch[0].length,\n });\n currentCodeBlockStart = -1;\n }\n i += lineMatch[0].length - 1;\n }\n }\n }\n\n // Find inline code ranges\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] === \"`\") {\n // Check if escaped\n let backslashCount = 0;\n for (let j = i - 1; j >= 0 && chars[j] === \"\\\\\"; j--) {\n backslashCount++;\n }\n if (backslashCount % 2 === 0) {\n // Not escaped - find the closing backtick\n for (let j = i + 1; j < chars.length; j++) {\n if (chars[j] === \"`\") {\n let closingBackslashCount = 0;\n for (let k = j - 1; k >= 0 && chars[k] === \"\\\\\"; k--) {\n closingBackslashCount++;\n }\n if (closingBackslashCount % 2 === 0) {\n inlineCodeRanges.push({ start: i, end: j + 1 });\n i = j;\n break;\n }\n }\n }\n }\n }\n }\n\n // Helper function to check if position is in code\n const isInCode = (pos: number): boolean => {\n return (\n codeBlockRanges.some((range) => pos >= range.start && pos < range.end) ||\n inlineCodeRanges.some((range) => pos >= range.start && pos < range.end)\n );\n };\n\n // Second pass: process markdown elements, skipping code regions\n for (let i = 0; i < chars.length; i++) {\n const char = chars[i];\n const nextChar = chars[i + 1];\n const prevChar = chars[i - 1];\n\n if (isInCode(i)) {\n continue;\n }\n\n // Handle brackets (but not if they're part of already-complete links)\n if (char === \"[\") {\n // Check if this is part of a complete link [text](url)\n let isCompleteLink = false;\n let bracketDepth = 1;\n let j = i + 1;\n\n // Find the matching ]\n while (j < chars.length && bracketDepth > 0) {\n if (chars[j] === \"[\" && !isInCode(j)) bracketDepth++;\n if (chars[j] === \"]\" && !isInCode(j)) bracketDepth--;\n j++;\n }\n\n // Check if followed by (\n if (bracketDepth === 0 && chars[j] === \"(\") {\n // Find the closing )\n let parenDepth = 1;\n j++;\n while (j < chars.length && parenDepth > 0) {\n if (chars[j] === \"(\" && !isInCode(j)) parenDepth++;\n if (chars[j] === \")\" && !isInCode(j)) parenDepth--;\n j++;\n }\n if (parenDepth === 0) {\n isCompleteLink = true;\n i = j - 1;\n continue;\n }\n }\n\n // This is a standalone bracket, treat as markdown\n if (!isCompleteLink) {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bracket\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"bracket\", marker: \"[\", position: i });\n }\n }\n }\n\n // Handle double emphasis first (**, __, ~~) - these take precedence\n else if (char === \"*\" && nextChar === \"*\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bold_star\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"bold_star\", marker: \"**\", position: i });\n }\n i++; // Skip next character\n } else if (char === \"_\" && nextChar === \"_\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bold_underscore\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({\n type: \"bold_underscore\",\n marker: \"__\",\n position: i,\n });\n }\n i++; // Skip next character\n } else if (char === \"~\" && nextChar === \"~\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"strike\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"strike\", marker: \"~~\", position: i });\n }\n i++; // Skip next character\n }\n\n // Handle single emphasis (*, _) - only if not part of double\n else if (char === \"*\" && prevChar !== \"*\" && nextChar !== \"*\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"italic_star\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"italic_star\", marker: \"*\", position: i });\n }\n } else if (char === \"_\" && prevChar !== \"_\" && nextChar !== \"_\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"italic_underscore\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({\n type: \"italic_underscore\",\n marker: \"_\",\n position: i,\n });\n }\n }\n }\n\n // Handle remaining unmatched backticks (outside of inline code ranges)\n let backtickCount = 0;\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] === \"`\" && !isInCode(i)) {\n backtickCount++;\n }\n }\n if (backtickCount % 2 === 1) {\n s += \"`\";\n }\n\n // Close remaining open elements in reverse order (LIFO stack semantics)\n openElements.sort((a, b) => b.position - a.position);\n\n const closers = openElements.map((el) => {\n switch (el.type) {\n case \"bracket\":\n return \"]\";\n case \"bold_star\":\n return \"**\";\n case \"bold_underscore\":\n return \"__\";\n case \"strike\":\n return \"~~\";\n case \"italic_star\":\n return \"*\";\n case \"italic_underscore\":\n return \"_\";\n default:\n return \"\";\n }\n });\n\n let result = s + closers.join(\"\");\n\n // Handle parentheses ONLY if not inside code\n const finalFenceMatches = Array.from(\n result.matchAll(/^(\\s*)(`{3,}|~{3,})/gm)\n );\n const hasUnclosedBacktick = (result.match(/`/g) || []).length % 2 === 1;\n const hasUnclosedCodeFence = finalFenceMatches.length % 2 === 1;\n\n let shouldCloseParens = !hasUnclosedBacktick && !hasUnclosedCodeFence;\n\n if (shouldCloseParens) {\n const lastOpenParen = result.lastIndexOf(\"(\");\n if (lastOpenParen !== -1) {\n // Check if this paren is inside a backtick pair\n const beforeParen = result.substring(0, lastOpenParen);\n const backticksBeforeParen = (beforeParen.match(/`/g) || []).length;\n if (backticksBeforeParen % 2 === 1) {\n shouldCloseParens = false;\n }\n }\n }\n\n if (shouldCloseParens) {\n const openParens = (result.match(/\\(/g) || []).length;\n const closeParens = (result.match(/\\)/g) || []).length;\n if (openParens > closeParens) {\n result += \")\".repeat(openParens - closeParens);\n }\n }\n\n return result;\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAMO;AACP,IAAAA,iBAOO;;;ACdP,oBAOO;AAQA,IAAM,6BAAN,cAAyC,wBAAU;AAAA,EACxD;AAAA,EAEA,YAAY,QAA0C;AACpD,UAAM;AAAA,MACJ,GAAG;AAAA,MACH,KAAK,GAAG,OAAO,UAAU,UAAU,OAAO,OAAO;AAAA,IACnD,CAAC;AACD,SAAK,aAAa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A,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT;AACE,eAAO;AAAA,IACX;AAAA,EACF,CAAC;AAED,MAAI,SAAS,IAAI,QAAQ,KAAK,EAAE;AAGhC,QAAM,oBAAoB,MAAM;AAAA,IAC9B,OAAO,SAAS,uBAAuB;AAAA,EACzC;AACA,QAAM,uBAAuB,OAAO,MAAM,IAAI,KAAK,CAAC,GAAG,SAAS,MAAM;AACtE,QAAM,uBAAuB,kBAAkB,SAAS,MAAM;AAE9D,MAAI,oBAAoB,CAAC,uBAAuB,CAAC;AAEjD,MAAI,mBAAmB;AACrB,UAAM,gBAAgB,OAAO,YAAY,GAAG;AAC5C,QAAI,kBAAkB,IAAI;AAExB,YAAM,cAAc,OAAO,UAAU,GAAG,aAAa;AACrD,YAAM,wBAAwB,YAAY,MAAM,IAAI,KAAK,CAAC,GAAG;AAC7D,UAAI,uBAAuB,MAAM,GAAG;AAClC,4BAAoB;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AAEA,MAAI,mBAAmB;AACrB,UAAM,cAAc,OAAO,MAAM,KAAK,KAAK,CAAC,GAAG;AAC/C,UAAM,eAAe,OAAO,MAAM,KAAK,KAAK,CAAC,GAAG;AAChD,QAAI,aAAa,aAAa;AAC5B,gBAAU,IAAI,OAAO,aAAa,WAAW;AAAA,IAC/C;AAAA,EACF;AAEA,SAAO;AACT;","names":["import_client","CopilotKitCoreErrorCode","CopilotKitCoreRuntimeConnectionStatus","ToolCallStatus"]}
package/dist/index.mjs CHANGED
@@ -74,10 +74,21 @@ var CopilotKitCore = class {
74
74
  this.headers = headers;
75
75
  this.properties = properties;
76
76
  this.localAgents = this.assignAgentIds(agents);
77
+ this.applyHeadersToAgents(this.localAgents);
77
78
  this._agents = this.localAgents;
78
79
  this._tools = tools;
79
80
  this.setRuntimeUrl(runtimeUrl);
80
81
  }
82
+ applyHeadersToAgent(agent) {
83
+ if (agent instanceof HttpAgent2) {
84
+ agent.headers = { ...this.headers };
85
+ }
86
+ }
87
+ applyHeadersToAgents(agents) {
88
+ Object.values(agents).forEach((agent) => {
89
+ this.applyHeadersToAgent(agent);
90
+ });
91
+ }
81
92
  assignAgentIds(agents) {
82
93
  Object.entries(agents).forEach(([id, agent]) => {
83
94
  if (agent && !agent.agentId) {
@@ -206,6 +217,7 @@ var CopilotKitCore = class {
206
217
  agentId: id,
207
218
  description
208
219
  });
220
+ this.applyHeadersToAgent(agent);
209
221
  return [id, agent];
210
222
  })
211
223
  );
@@ -265,6 +277,7 @@ var CopilotKitCore = class {
265
277
  */
266
278
  setHeaders(headers) {
267
279
  this.headers = headers;
280
+ this.applyHeadersToAgents(this._agents);
268
281
  void this.notifySubscribers(
269
282
  (subscriber) => subscriber.onHeadersChanged?.({
270
283
  copilotkit: this,
@@ -286,6 +299,7 @@ var CopilotKitCore = class {
286
299
  setAgents(agents) {
287
300
  this.localAgents = this.assignAgentIds(agents);
288
301
  this._agents = { ...this.localAgents, ...this.remoteAgents };
302
+ this.applyHeadersToAgents(this._agents);
289
303
  void this.notifySubscribers(
290
304
  (subscriber) => subscriber.onAgentsChanged?.({
291
305
  copilotkit: this,
@@ -299,6 +313,7 @@ var CopilotKitCore = class {
299
313
  if (!agent.agentId) {
300
314
  agent.agentId = id;
301
315
  }
316
+ this.applyHeadersToAgent(agent);
302
317
  this._agents = { ...this.localAgents, ...this.remoteAgents };
303
318
  void this.notifySubscribers(
304
319
  (subscriber) => subscriber.onAgentsChanged?.({
@@ -541,7 +556,10 @@ var CopilotKitCore = class {
541
556
  );
542
557
  if (!errorMessage) {
543
558
  try {
544
- const result = await tool.handler(parsedArgs);
559
+ const result = await tool.handler(
560
+ parsedArgs,
561
+ toolCall
562
+ );
545
563
  if (result === void 0 || result === null) {
546
564
  toolCallResult = "";
547
565
  } else if (typeof result === "string") {
@@ -646,7 +664,8 @@ var CopilotKitCore = class {
646
664
  if (!errorMessage) {
647
665
  try {
648
666
  const result = await wildcardTool.handler(
649
- wildcardArgs
667
+ wildcardArgs,
668
+ toolCall
650
669
  );
651
670
  if (result === void 0 || result === null) {
652
671
  toolCallResult = "";
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core.ts","../src/agent.ts","../src/types.ts","../src/utils/markdown.ts"],"sourcesContent":["import {\n AgentDescription,\n DEFAULT_AGENT_ID,\n randomUUID,\n RuntimeInfo,\n logger,\n} from \"@copilotkitnext/shared\";\nimport {\n AbstractAgent,\n AgentSubscriber,\n Context,\n HttpAgent,\n Message,\n RunAgentResult,\n} from \"@ag-ui/client\";\nimport { FrontendTool } from \"./types\";\nimport { ProxiedCopilotRuntimeAgent } from \"./agent\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\n\n/** Configuration options for `CopilotKitCore`. */\nexport interface CopilotKitCoreConfig {\n /** The endpoint of the CopilotRuntime. */\n runtimeUrl?: string;\n /** Mapping from agent name to its `AbstractAgent` instance. */\n agents?: Record<string, AbstractAgent>;\n /** Headers appended to every HTTP request made by `CopilotKitCore`. */\n headers?: Record<string, string>;\n /** Properties sent as `forwardedProps` to the AG-UI agent. */\n properties?: Record<string, unknown>;\n /** Ordered collection of frontend tools available to the core. */\n tools?: FrontendTool<any>[];\n}\n\nexport interface CopilotKitCoreAddAgentParams {\n id: string;\n agent: AbstractAgent;\n}\n\nexport interface CopilotKitCoreRunAgentParams {\n agent: AbstractAgent;\n withMessages?: Message[];\n agentId?: string;\n}\n\nexport interface CopilotKitCoreConnectAgentParams {\n agent: AbstractAgent;\n agentId?: string;\n}\n\nexport interface CopilotKitCoreGetToolParams {\n toolName: string;\n agentId?: string;\n}\n\nexport enum CopilotKitCoreErrorCode {\n RUNTIME_INFO_FETCH_FAILED = \"runtime_info_fetch_failed\",\n AGENT_CONNECT_FAILED = \"agent_connect_failed\",\n AGENT_RUN_FAILED = \"agent_run_failed\",\n AGENT_RUN_FAILED_EVENT = \"agent_run_failed_event\",\n AGENT_RUN_ERROR_EVENT = \"agent_run_error_event\",\n TOOL_ARGUMENT_PARSE_FAILED = \"tool_argument_parse_failed\",\n TOOL_HANDLER_FAILED = \"tool_handler_failed\",\n}\n\nexport interface CopilotKitCoreSubscriber {\n onRuntimeConnectionStatusChanged?: (event: {\n copilotkit: CopilotKitCore;\n status: CopilotKitCoreRuntimeConnectionStatus;\n }) => void | Promise<void>;\n onToolExecutionStart?: (event: {\n copilotkit: CopilotKitCore;\n toolCallId: string;\n agentId: string;\n toolName: string;\n args: unknown;\n }) => void | Promise<void>;\n onToolExecutionEnd?: (event: {\n copilotkit: CopilotKitCore;\n toolCallId: string;\n agentId: string;\n toolName: string;\n result: string;\n error?: string;\n }) => void | Promise<void>;\n onAgentsChanged?: (event: {\n copilotkit: CopilotKitCore;\n agents: Readonly<Record<string, AbstractAgent>>;\n }) => void | Promise<void>;\n onContextChanged?: (event: {\n copilotkit: CopilotKitCore;\n context: Readonly<Record<string, Context>>;\n }) => void | Promise<void>;\n onPropertiesChanged?: (event: {\n copilotkit: CopilotKitCore;\n properties: Readonly<Record<string, unknown>>;\n }) => void | Promise<void>;\n onHeadersChanged?: (event: {\n copilotkit: CopilotKitCore;\n headers: Readonly<Record<string, string>>;\n }) => void | Promise<void>;\n onError?: (event: {\n copilotkit: CopilotKitCore;\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n}\n\nexport enum CopilotKitCoreRuntimeConnectionStatus {\n Disconnected = \"disconnected\",\n Connected = \"connected\",\n Connecting = \"connecting\",\n Error = \"error\",\n}\n\nexport class CopilotKitCore {\n headers: Record<string, string>;\n properties: Record<string, unknown>;\n\n private _context: Record<string, Context> = {};\n private _agents: Record<string, AbstractAgent> = {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _tools: FrontendTool<any>[] = [];\n\n private localAgents: Record<string, AbstractAgent> = {};\n private remoteAgents: Record<string, AbstractAgent> = {};\n private subscribers: Set<CopilotKitCoreSubscriber> = new Set();\n\n private _runtimeUrl?: string;\n private _runtimeVersion?: string;\n private _runtimeConnectionStatus: CopilotKitCoreRuntimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Disconnected;\n\n constructor({\n runtimeUrl,\n headers = {},\n properties = {},\n agents = {},\n tools = [],\n }: CopilotKitCoreConfig) {\n this.headers = headers;\n this.properties = properties;\n this.localAgents = this.assignAgentIds(agents);\n this._agents = this.localAgents;\n this._tools = tools;\n this.setRuntimeUrl(runtimeUrl);\n }\n\n private assignAgentIds(agents: Record<string, AbstractAgent>) {\n Object.entries(agents).forEach(([id, agent]) => {\n if (agent && !agent.agentId) {\n agent.agentId = id;\n }\n });\n return agents;\n }\n\n private async notifySubscribers(\n handler: (subscriber: CopilotKitCoreSubscriber) => void | Promise<void>,\n errorMessage: string\n ) {\n await Promise.all(\n Array.from(this.subscribers).map(async (subscriber) => {\n try {\n await handler(subscriber);\n } catch (error) {\n logger.error(errorMessage, error);\n }\n })\n );\n }\n\n private async emitError({\n error,\n code,\n context = {},\n }: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context?: Record<string, any>;\n }) {\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onError?.({\n copilotkit: this,\n error,\n code,\n context,\n }),\n \"Subscriber onError error:\"\n );\n }\n\n private resolveAgentId(\n agent: AbstractAgent,\n providedAgentId?: string\n ): string {\n if (providedAgentId) {\n return providedAgentId;\n }\n if (agent.agentId) {\n return agent.agentId;\n }\n const found = Object.entries(this._agents).find(([, storedAgent]) => {\n return storedAgent === agent;\n });\n if (found) {\n agent.agentId = found[0];\n return found[0];\n }\n agent.agentId = DEFAULT_AGENT_ID;\n return DEFAULT_AGENT_ID;\n }\n\n /**\n * Snapshot accessors\n */\n get context(): Readonly<Record<string, Context>> {\n return this._context;\n }\n\n get agents(): Readonly<Record<string, AbstractAgent>> {\n return this._agents;\n }\n\n get tools(): Readonly<FrontendTool<any>[]> {\n return this._tools;\n }\n\n get runtimeUrl(): string | undefined {\n return this._runtimeUrl;\n }\n\n setRuntimeUrl(runtimeUrl: string | undefined) {\n const normalizedRuntimeUrl = runtimeUrl\n ? runtimeUrl.replace(/\\/$/, \"\")\n : undefined;\n\n if (this._runtimeUrl === normalizedRuntimeUrl) {\n return;\n }\n\n this._runtimeUrl = normalizedRuntimeUrl;\n void this.updateRuntimeConnection();\n }\n\n get runtimeVersion(): string | undefined {\n return this._runtimeVersion;\n }\n\n get runtimeConnectionStatus(): CopilotKitCoreRuntimeConnectionStatus {\n return this._runtimeConnectionStatus;\n }\n\n /**\n * Runtime connection\n */\n private async updateRuntimeConnection() {\n if (!this.runtimeUrl) {\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Disconnected;\n this._runtimeVersion = undefined;\n this.remoteAgents = {};\n this._agents = this.localAgents;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Disconnected,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n return;\n }\n\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Connecting;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Connecting,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n try {\n const response = await fetch(`${this.runtimeUrl}/info`, {\n headers: this.headers,\n });\n const {\n version,\n ...runtimeInfo\n }: {\n agents: Record<string, AgentDescription>;\n version: string;\n } = (await response.json()) as RuntimeInfo;\n\n const agents: Record<string, AbstractAgent> = Object.fromEntries(\n Object.entries(runtimeInfo.agents).map(([id, { description }]) => {\n const agent = new ProxiedCopilotRuntimeAgent({\n runtimeUrl: this.runtimeUrl,\n agentId: id,\n description: description,\n });\n return [id, agent];\n })\n );\n\n this.remoteAgents = agents;\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Connected;\n this._runtimeVersion = version;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Connected,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n } catch (error) {\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Error;\n this._runtimeVersion = undefined;\n this.remoteAgents = {};\n this._agents = this.localAgents;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Error,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n const message =\n error instanceof Error ? error.message : JSON.stringify(error);\n logger.warn(\n `Failed to load runtime info (${this.runtimeUrl}/info): ${message}`\n );\n const runtimeError =\n error instanceof Error ? error : new Error(String(error));\n await this.emitError({\n error: runtimeError,\n code: CopilotKitCoreErrorCode.RUNTIME_INFO_FETCH_FAILED,\n context: {\n runtimeUrl: this.runtimeUrl,\n },\n });\n }\n }\n\n /**\n * Configuration updates\n */\n setHeaders(headers: Record<string, string>) {\n this.headers = headers;\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onHeadersChanged?.({\n copilotkit: this,\n headers: this.headers,\n }),\n \"Subscriber onHeadersChanged error:\"\n );\n }\n\n setProperties(properties: Record<string, unknown>) {\n this.properties = properties;\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onPropertiesChanged?.({\n copilotkit: this,\n properties: this.properties,\n }),\n \"Subscriber onPropertiesChanged error:\"\n );\n }\n\n setAgents(agents: Record<string, AbstractAgent>) {\n this.localAgents = this.assignAgentIds(agents);\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n }\n\n addAgent({ id, agent }: CopilotKitCoreAddAgentParams) {\n this.localAgents[id] = agent;\n if (!agent.agentId) {\n agent.agentId = id;\n }\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n }\n\n removeAgent(id: string) {\n delete this.localAgents[id];\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n }\n\n getAgent(id: string): AbstractAgent | undefined {\n if (id in this._agents) {\n return this._agents[id] as AbstractAgent;\n }\n\n if (\n this.runtimeUrl !== undefined &&\n (this.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Disconnected ||\n this.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connecting)\n ) {\n return undefined;\n } else {\n console.warn(`Agent ${id} not found`);\n return undefined;\n }\n }\n\n /**\n * Context management\n */\n addContext({ description, value }: Context): string {\n const id = randomUUID();\n this._context[id] = { description, value };\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onContextChanged?.({\n copilotkit: this,\n context: this._context,\n }),\n \"Subscriber onContextChanged error:\"\n );\n return id;\n }\n\n removeContext(id: string) {\n delete this._context[id];\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onContextChanged?.({\n copilotkit: this,\n context: this._context,\n }),\n \"Subscriber onContextChanged error:\"\n );\n }\n\n /**\n * Tool management\n */\n addTool<T extends Record<string, unknown> = Record<string, unknown>>(\n tool: FrontendTool<T>\n ) {\n // Check if a tool with the same name and agentId already exists\n const existingToolIndex = this._tools.findIndex(\n (t) => t.name === tool.name && t.agentId === tool.agentId\n );\n\n if (existingToolIndex !== -1) {\n logger.warn(\n `Tool already exists: '${tool.name}' for agent '${tool.agentId || \"global\"}', skipping.`\n );\n return;\n }\n\n this._tools.push(tool);\n }\n\n removeTool(id: string, agentId?: string) {\n this._tools = this._tools.filter((tool) => {\n // Remove tool if both name and agentId match\n if (agentId !== undefined) {\n return !(tool.name === id && tool.agentId === agentId);\n }\n // If no agentId specified, only remove global tools with matching name\n return !(tool.name === id && !tool.agentId);\n });\n }\n\n /**\n * Get a tool by name and optionally by agentId.\n * If agentId is provided, it will first look for an agent-specific tool,\n * then fall back to a global tool with the same name.\n */\n getTool(params: CopilotKitCoreGetToolParams): FrontendTool<any> | undefined {\n const { toolName, agentId } = params;\n\n // If agentId is provided, first look for agent-specific tool\n if (agentId) {\n const agentTool = this._tools.find(\n (tool) => tool.name === toolName && tool.agentId === agentId\n );\n if (agentTool) {\n return agentTool;\n }\n }\n\n // Fall back to global tool (no agentId)\n return this._tools.find((tool) => tool.name === toolName && !tool.agentId);\n }\n\n /**\n * Set all tools at once. Replaces existing tools.\n */\n setTools(tools: FrontendTool<any>[]) {\n this._tools = [...tools];\n }\n\n /**\n * Subscription lifecycle\n */\n subscribe(subscriber: CopilotKitCoreSubscriber): () => void {\n this.subscribers.add(subscriber);\n\n // Return unsubscribe function\n return () => {\n this.unsubscribe(subscriber);\n };\n }\n\n unsubscribe(subscriber: CopilotKitCoreSubscriber) {\n this.subscribers.delete(subscriber);\n }\n\n /**\n * Agent connectivity\n */\n async connectAgent({\n agent,\n agentId,\n }: CopilotKitCoreConnectAgentParams): Promise<RunAgentResult> {\n try {\n if (agent instanceof HttpAgent) {\n agent.headers = { ...this.headers };\n }\n\n const runAgentResult = await agent.connectAgent(\n {\n forwardedProps: this.properties,\n tools: this.buildFrontendTools(agentId),\n },\n this.createAgentErrorSubscriber(agent, agentId)\n );\n\n return this.processAgentResult({ runAgentResult, agent, agentId });\n } catch (error) {\n const connectError =\n error instanceof Error ? error : new Error(String(error));\n const context: Record<string, any> = {};\n if (agentId ?? agent.agentId) {\n context.agentId = agentId ?? agent.agentId;\n }\n await this.emitError({\n error: connectError,\n code: CopilotKitCoreErrorCode.AGENT_CONNECT_FAILED,\n context,\n });\n throw error;\n }\n }\n\n async runAgent({\n agent,\n withMessages,\n agentId,\n }: CopilotKitCoreRunAgentParams): Promise<RunAgentResult> {\n if (agent instanceof HttpAgent) {\n agent.headers = { ...this.headers };\n }\n\n if (withMessages) {\n agent.addMessages(withMessages);\n }\n try {\n const runAgentResult = await agent.runAgent(\n {\n forwardedProps: this.properties,\n tools: this.buildFrontendTools(agentId),\n },\n this.createAgentErrorSubscriber(agent, agentId)\n );\n return this.processAgentResult({ runAgentResult, agent, agentId });\n } catch (error) {\n const runError =\n error instanceof Error ? error : new Error(String(error));\n const context: Record<string, any> = {};\n if (agentId ?? agent.agentId) {\n context.agentId = agentId ?? agent.agentId;\n }\n if (withMessages) {\n context.messageCount = withMessages.length;\n }\n await this.emitError({\n error: runError,\n code: CopilotKitCoreErrorCode.AGENT_RUN_FAILED,\n context,\n });\n throw error;\n }\n }\n\n private async processAgentResult({\n runAgentResult,\n agent,\n agentId,\n }: {\n runAgentResult: RunAgentResult;\n agent: AbstractAgent;\n agentId: string | undefined;\n }): Promise<RunAgentResult> {\n const { newMessages } = runAgentResult;\n const effectiveAgentId = this.resolveAgentId(agent, agentId);\n\n let needsFollowUp = false;\n\n for (const message of newMessages) {\n if (message.role === \"assistant\") {\n for (const toolCall of message.toolCalls || []) {\n if (\n newMessages.findIndex(\n (m) => m.role === \"tool\" && m.toolCallId === toolCall.id\n ) === -1\n ) {\n const tool = this.getTool({\n toolName: toolCall.function.name,\n agentId,\n });\n if (tool) {\n // Check if tool is constrained to a specific agent\n if (tool?.agentId && tool.agentId !== agentId) {\n // Tool is not available for this agent, skip it\n continue;\n }\n\n let toolCallResult = \"\";\n let errorMessage: string | undefined;\n let isArgumentError = false;\n if (tool?.handler) {\n let parsedArgs: unknown;\n try {\n parsedArgs = JSON.parse(toolCall.function.arguments);\n } catch (error) {\n const parseError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = parseError.message;\n isArgumentError = true;\n await this.emitError({\n error: parseError,\n code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n rawArguments: toolCall.function.arguments,\n toolType: \"specific\",\n messageId: message.id,\n },\n });\n }\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionStart?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n args: parsedArgs,\n }),\n \"Subscriber onToolExecutionStart error:\"\n );\n\n if (!errorMessage) {\n try {\n const result = await tool.handler(parsedArgs as any);\n if (result === undefined || result === null) {\n toolCallResult = \"\";\n } else if (typeof result === \"string\") {\n toolCallResult = result;\n } else {\n toolCallResult = JSON.stringify(result);\n }\n } catch (error) {\n const handlerError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = handlerError.message;\n await this.emitError({\n error: handlerError,\n code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n parsedArgs,\n toolType: \"specific\",\n messageId: message.id,\n },\n });\n }\n }\n\n if (errorMessage) {\n toolCallResult = `Error: ${errorMessage}`;\n }\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionEnd?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n result: errorMessage ? \"\" : toolCallResult,\n error: errorMessage,\n }),\n \"Subscriber onToolExecutionEnd error:\"\n );\n\n if (isArgumentError) {\n throw new Error(errorMessage ?? \"Tool execution failed\");\n }\n }\n\n if (!errorMessage || !isArgumentError) {\n const messageIndex = agent.messages.findIndex(\n (m) => m.id === message.id\n );\n const toolMessage = {\n id: randomUUID(),\n role: \"tool\" as const,\n toolCallId: toolCall.id,\n content: toolCallResult,\n };\n agent.messages.splice(messageIndex + 1, 0, toolMessage);\n\n if (!errorMessage && tool?.followUp !== false) {\n needsFollowUp = true;\n }\n }\n } else {\n // Wildcard fallback for undefined tools\n const wildcardTool = this.getTool({ toolName: \"*\", agentId });\n if (wildcardTool) {\n // Check if wildcard tool is constrained to a specific agent\n if (wildcardTool?.agentId && wildcardTool.agentId !== agentId) {\n // Wildcard tool is not available for this agent, skip it\n continue;\n }\n\n let toolCallResult = \"\";\n let errorMessage: string | undefined;\n let isArgumentError = false;\n if (wildcardTool?.handler) {\n let parsedArgs: unknown;\n try {\n parsedArgs = JSON.parse(toolCall.function.arguments);\n } catch (error) {\n const parseError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = parseError.message;\n isArgumentError = true;\n await this.emitError({\n error: parseError,\n code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n rawArguments: toolCall.function.arguments,\n toolType: \"wildcard\",\n messageId: message.id,\n },\n });\n }\n\n const wildcardArgs = {\n toolName: toolCall.function.name,\n args: parsedArgs,\n };\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionStart?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n args: wildcardArgs,\n }),\n \"Subscriber onToolExecutionStart error:\"\n );\n\n if (!errorMessage) {\n try {\n const result = await wildcardTool.handler(\n wildcardArgs as any\n );\n if (result === undefined || result === null) {\n toolCallResult = \"\";\n } else if (typeof result === \"string\") {\n toolCallResult = result;\n } else {\n toolCallResult = JSON.stringify(result);\n }\n } catch (error) {\n const handlerError =\n error instanceof Error\n ? error\n : new Error(String(error));\n errorMessage = handlerError.message;\n await this.emitError({\n error: handlerError,\n code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n parsedArgs: wildcardArgs,\n toolType: \"wildcard\",\n messageId: message.id,\n },\n });\n }\n }\n\n if (errorMessage) {\n toolCallResult = `Error: ${errorMessage}`;\n }\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionEnd?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n result: errorMessage ? \"\" : toolCallResult,\n error: errorMessage,\n }),\n \"Subscriber onToolExecutionEnd error:\"\n );\n\n if (isArgumentError) {\n throw new Error(errorMessage ?? \"Tool execution failed\");\n }\n }\n\n if (!errorMessage || !isArgumentError) {\n const messageIndex = agent.messages.findIndex(\n (m) => m.id === message.id\n );\n const toolMessage = {\n id: randomUUID(),\n role: \"tool\" as const,\n toolCallId: toolCall.id,\n content: toolCallResult,\n };\n agent.messages.splice(messageIndex + 1, 0, toolMessage);\n\n if (!errorMessage && wildcardTool?.followUp !== false) {\n needsFollowUp = true;\n }\n }\n }\n }\n }\n }\n }\n }\n\n if (needsFollowUp) {\n return await this.runAgent({ agent, agentId });\n }\n\n return runAgentResult;\n }\n\n private buildFrontendTools(agentId?: string) {\n return this._tools\n .filter((tool) => !tool.agentId || tool.agentId === agentId)\n .map((tool) => ({\n name: tool.name,\n description: tool.description ?? \"\",\n parameters: createToolSchema(tool),\n }));\n }\n\n private createAgentErrorSubscriber(\n agent: AbstractAgent,\n agentId?: string\n ): AgentSubscriber {\n const emitAgentError = async (\n error: Error,\n code: CopilotKitCoreErrorCode,\n extraContext: Record<string, any> = {}\n ) => {\n const context: Record<string, any> = { ...extraContext };\n if (agentId ?? agent.agentId) {\n context.agentId = agentId ?? agent.agentId;\n }\n await this.emitError({\n error,\n code,\n context,\n });\n };\n\n return {\n onRunFailed: async ({ error }: { error: Error }) => {\n await emitAgentError(\n error,\n CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT,\n {\n source: \"onRunFailed\",\n }\n );\n },\n onRunErrorEvent: async ({ event }) => {\n const eventError =\n event?.rawEvent instanceof Error\n ? event.rawEvent\n : event?.rawEvent?.error instanceof Error\n ? event.rawEvent.error\n : undefined;\n\n const errorMessage =\n typeof event?.rawEvent?.error === \"string\"\n ? event.rawEvent.error\n : (event?.message ?? \"Agent run error\");\n\n const rawError = eventError ?? new Error(errorMessage);\n\n if (event?.code && !(rawError as any).code) {\n (rawError as any).code = event.code;\n }\n\n await emitAgentError(\n rawError,\n CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT,\n {\n source: \"onRunErrorEvent\",\n event,\n runtimeErrorCode: event?.code,\n }\n );\n },\n };\n }\n}\n\nconst EMPTY_TOOL_SCHEMA = {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n} as const satisfies Record<string, unknown>;\n\nfunction createToolSchema(tool: FrontendTool<any>): Record<string, unknown> {\n if (!tool.parameters) {\n return EMPTY_TOOL_SCHEMA;\n }\n\n const rawSchema = zodToJsonSchema(tool.parameters, {\n $refStrategy: \"none\",\n });\n\n if (!rawSchema || typeof rawSchema !== \"object\") {\n return { ...EMPTY_TOOL_SCHEMA };\n }\n\n const { $schema, ...schema } = rawSchema as Record<string, unknown>;\n\n if (typeof schema.type !== \"string\") {\n schema.type = \"object\";\n }\n if (typeof schema.properties !== \"object\" || schema.properties === null) {\n schema.properties = {};\n }\n if (schema.additionalProperties === undefined) {\n schema.additionalProperties = false;\n }\n\n return schema;\n}\n","import {\n BaseEvent,\n HttpAgent,\n HttpAgentConfig,\n RunAgentInput,\n runHttpRequest,\n transformHttpEventStream,\n} from \"@ag-ui/client\";\nimport { Observable } from \"rxjs\";\n\nexport interface ProxiedCopilotRuntimeAgentConfig\n extends Omit<HttpAgentConfig, \"url\"> {\n runtimeUrl?: string;\n}\n\nexport class ProxiedCopilotRuntimeAgent extends HttpAgent {\n runtimeUrl?: string;\n\n constructor(config: ProxiedCopilotRuntimeAgentConfig) {\n super({\n ...config,\n url: `${config.runtimeUrl}/agent/${config.agentId}/run`,\n });\n this.runtimeUrl = config.runtimeUrl;\n }\n\n connect(input: RunAgentInput): Observable<BaseEvent> {\n const httpEvents = runHttpRequest(\n `${this.runtimeUrl}/agent/${this.agentId}/connect`,\n this.requestInit(input)\n );\n return transformHttpEventStream(httpEvents);\n }\n}\n","import { z } from \"zod\";\n\n/**\n * Status of a tool call execution\n */\nexport enum ToolCallStatus {\n InProgress = \"inProgress\",\n Executing = \"executing\",\n Complete = \"complete\"\n}\n\nexport type FrontendTool<T extends Record<string, unknown> = Record<string, unknown>> = {\n name: string;\n description?: string;\n parameters?: z.ZodType<T>;\n handler?: (args: T) => Promise<unknown>;\n followUp?: boolean;\n /**\n * Optional agent ID to constrain this tool to a specific agent.\n * If specified, this tool will only be available to the specified agent.\n */\n agentId?: string;\n};\n","export function completePartialMarkdown(input: string): string {\n let s = input;\n\n // Handle code fences first - use FIRST unmatched fence for proper nesting\n const fenceMatches = Array.from(s.matchAll(/^(\\s*)(`{3,}|~{3,})/gm));\n if (fenceMatches.length % 2 === 1) {\n const [, indent, fence] = fenceMatches[0]!;\n s += `\\n${indent}${fence}`;\n }\n\n // Identify incomplete links at the end and close them\n const incompleteLinkMatch = s.match(/\\[([^\\]]*)\\]\\(([^)]*)$/);\n if (incompleteLinkMatch) {\n s += \")\";\n }\n\n // State-based parsing\n interface OpenElement {\n type: string;\n marker: string;\n position: number;\n }\n\n const openElements: OpenElement[] = [];\n const chars = Array.from(s);\n\n // First pass: identify code block boundaries and inline code to avoid processing their content\n const codeBlockRanges: Array<{ start: number; end: number }> = [];\n const inlineCodeRanges: Array<{ start: number; end: number }> = [];\n\n // Find code block ranges\n let tempCodeFenceCount = 0;\n let currentCodeBlockStart = -1;\n\n for (let i = 0; i < chars.length; i++) {\n if (i === 0 || chars[i - 1] === \"\\n\") {\n const lineMatch = s.substring(i).match(/^(\\s*)(`{3,}|~{3,})/);\n if (lineMatch) {\n tempCodeFenceCount++;\n if (tempCodeFenceCount % 2 === 1) {\n currentCodeBlockStart = i;\n } else if (currentCodeBlockStart !== -1) {\n codeBlockRanges.push({\n start: currentCodeBlockStart,\n end: i + lineMatch[0].length,\n });\n currentCodeBlockStart = -1;\n }\n i += lineMatch[0].length - 1;\n }\n }\n }\n\n // Find inline code ranges\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] === \"`\") {\n // Check if escaped\n let backslashCount = 0;\n for (let j = i - 1; j >= 0 && chars[j] === \"\\\\\"; j--) {\n backslashCount++;\n }\n if (backslashCount % 2 === 0) {\n // Not escaped - find the closing backtick\n for (let j = i + 1; j < chars.length; j++) {\n if (chars[j] === \"`\") {\n let closingBackslashCount = 0;\n for (let k = j - 1; k >= 0 && chars[k] === \"\\\\\"; k--) {\n closingBackslashCount++;\n }\n if (closingBackslashCount % 2 === 0) {\n inlineCodeRanges.push({ start: i, end: j + 1 });\n i = j;\n break;\n }\n }\n }\n }\n }\n }\n\n // Helper function to check if position is in code\n const isInCode = (pos: number): boolean => {\n return (\n codeBlockRanges.some((range) => pos >= range.start && pos < range.end) ||\n inlineCodeRanges.some((range) => pos >= range.start && pos < range.end)\n );\n };\n\n // Second pass: process markdown elements, skipping code regions\n for (let i = 0; i < chars.length; i++) {\n const char = chars[i];\n const nextChar = chars[i + 1];\n const prevChar = chars[i - 1];\n\n if (isInCode(i)) {\n continue;\n }\n\n // Handle brackets (but not if they're part of already-complete links)\n if (char === \"[\") {\n // Check if this is part of a complete link [text](url)\n let isCompleteLink = false;\n let bracketDepth = 1;\n let j = i + 1;\n\n // Find the matching ]\n while (j < chars.length && bracketDepth > 0) {\n if (chars[j] === \"[\" && !isInCode(j)) bracketDepth++;\n if (chars[j] === \"]\" && !isInCode(j)) bracketDepth--;\n j++;\n }\n\n // Check if followed by (\n if (bracketDepth === 0 && chars[j] === \"(\") {\n // Find the closing )\n let parenDepth = 1;\n j++;\n while (j < chars.length && parenDepth > 0) {\n if (chars[j] === \"(\" && !isInCode(j)) parenDepth++;\n if (chars[j] === \")\" && !isInCode(j)) parenDepth--;\n j++;\n }\n if (parenDepth === 0) {\n isCompleteLink = true;\n i = j - 1;\n continue;\n }\n }\n\n // This is a standalone bracket, treat as markdown\n if (!isCompleteLink) {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bracket\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"bracket\", marker: \"[\", position: i });\n }\n }\n }\n\n // Handle double emphasis first (**, __, ~~) - these take precedence\n else if (char === \"*\" && nextChar === \"*\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bold_star\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"bold_star\", marker: \"**\", position: i });\n }\n i++; // Skip next character\n } else if (char === \"_\" && nextChar === \"_\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bold_underscore\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({\n type: \"bold_underscore\",\n marker: \"__\",\n position: i,\n });\n }\n i++; // Skip next character\n } else if (char === \"~\" && nextChar === \"~\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"strike\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"strike\", marker: \"~~\", position: i });\n }\n i++; // Skip next character\n }\n\n // Handle single emphasis (*, _) - only if not part of double\n else if (char === \"*\" && prevChar !== \"*\" && nextChar !== \"*\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"italic_star\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"italic_star\", marker: \"*\", position: i });\n }\n } else if (char === \"_\" && prevChar !== \"_\" && nextChar !== \"_\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"italic_underscore\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({\n type: \"italic_underscore\",\n marker: \"_\",\n position: i,\n });\n }\n }\n }\n\n // Handle remaining unmatched backticks (outside of inline code ranges)\n let backtickCount = 0;\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] === \"`\" && !isInCode(i)) {\n backtickCount++;\n }\n }\n if (backtickCount % 2 === 1) {\n s += \"`\";\n }\n\n // Close remaining open elements in reverse order (LIFO stack semantics)\n openElements.sort((a, b) => b.position - a.position);\n\n const closers = openElements.map((el) => {\n switch (el.type) {\n case \"bracket\":\n return \"]\";\n case \"bold_star\":\n return \"**\";\n case \"bold_underscore\":\n return \"__\";\n case \"strike\":\n return \"~~\";\n case \"italic_star\":\n return \"*\";\n case \"italic_underscore\":\n return \"_\";\n default:\n return \"\";\n }\n });\n\n let result = s + closers.join(\"\");\n\n // Handle parentheses ONLY if not inside code\n const finalFenceMatches = Array.from(\n result.matchAll(/^(\\s*)(`{3,}|~{3,})/gm)\n );\n const hasUnclosedBacktick = (result.match(/`/g) || []).length % 2 === 1;\n const hasUnclosedCodeFence = finalFenceMatches.length % 2 === 1;\n\n let shouldCloseParens = !hasUnclosedBacktick && !hasUnclosedCodeFence;\n\n if (shouldCloseParens) {\n const lastOpenParen = result.lastIndexOf(\"(\");\n if (lastOpenParen !== -1) {\n // Check if this paren is inside a backtick pair\n const beforeParen = result.substring(0, lastOpenParen);\n const backticksBeforeParen = (beforeParen.match(/`/g) || []).length;\n if (backticksBeforeParen % 2 === 1) {\n shouldCloseParens = false;\n }\n }\n }\n\n if (shouldCloseParens) {\n const openParens = (result.match(/\\(/g) || []).length;\n const closeParens = (result.match(/\\)/g) || []).length;\n if (openParens > closeParens) {\n result += \")\".repeat(openParens - closeParens);\n }\n }\n\n return result;\n}"],"mappings":";AAAA;AAAA,EAEE;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP;AAAA,EAIE,aAAAA;AAAA,OAGK;;;ACdP;AAAA,EAEE;AAAA,EAGA;AAAA,EACA;AAAA,OACK;AAQA,IAAM,6BAAN,cAAyC,UAAU;AAAA,EACxD;AAAA,EAEA,YAAY,QAA0C;AACpD,UAAM;AAAA,MACJ,GAAG;AAAA,MACH,KAAK,GAAG,OAAO,UAAU,UAAU,OAAO,OAAO;AAAA,IACnD,CAAC;AACD,SAAK,aAAa,OAAO;AAAA,EAC3B;AAAA,EAEA,QAAQ,OAA6C;AACnD,UAAM,aAAa;AAAA,MACjB,GAAG,KAAK,UAAU,UAAU,KAAK,OAAO;AAAA,MACxC,KAAK,YAAY,KAAK;AAAA,IACxB;AACA,WAAO,yBAAyB,UAAU;AAAA,EAC5C;AACF;;;ADhBA,SAAS,uBAAuB;AAqCzB,IAAK,0BAAL,kBAAKC,6BAAL;AACL,EAAAA,yBAAA,+BAA4B;AAC5B,EAAAA,yBAAA,0BAAuB;AACvB,EAAAA,yBAAA,sBAAmB;AACnB,EAAAA,yBAAA,4BAAyB;AACzB,EAAAA,yBAAA,2BAAwB;AACxB,EAAAA,yBAAA,gCAA6B;AAC7B,EAAAA,yBAAA,yBAAsB;AAPZ,SAAAA;AAAA,GAAA;AAsDL,IAAK,wCAAL,kBAAKC,2CAAL;AACL,EAAAA,uCAAA,kBAAe;AACf,EAAAA,uCAAA,eAAY;AACZ,EAAAA,uCAAA,gBAAa;AACb,EAAAA,uCAAA,WAAQ;AAJE,SAAAA;AAAA,GAAA;AAOL,IAAM,iBAAN,MAAqB;AAAA,EAC1B;AAAA,EACA;AAAA,EAEQ,WAAoC,CAAC;AAAA,EACrC,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,MAAM;AAAA,MACf,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT;AACE,eAAO;AAAA,IACX;AAAA,EACF,CAAC;AAED,MAAI,SAAS,IAAI,QAAQ,KAAK,EAAE;AAGhC,QAAM,oBAAoB,MAAM;AAAA,IAC9B,OAAO,SAAS,uBAAuB;AAAA,EACzC;AACA,QAAM,uBAAuB,OAAO,MAAM,IAAI,KAAK,CAAC,GAAG,SAAS,MAAM;AACtE,QAAM,uBAAuB,kBAAkB,SAAS,MAAM;AAE9D,MAAI,oBAAoB,CAAC,uBAAuB,CAAC;AAEjD,MAAI,mBAAmB;AACrB,UAAM,gBAAgB,OAAO,YAAY,GAAG;AAC5C,QAAI,kBAAkB,IAAI;AAExB,YAAM,cAAc,OAAO,UAAU,GAAG,aAAa;AACrD,YAAM,wBAAwB,YAAY,MAAM,IAAI,KAAK,CAAC,GAAG;AAC7D,UAAI,uBAAuB,MAAM,GAAG;AAClC,4BAAoB;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AAEA,MAAI,mBAAmB;AACrB,UAAM,cAAc,OAAO,MAAM,KAAK,KAAK,CAAC,GAAG;AAC/C,UAAM,eAAe,OAAO,MAAM,KAAK,KAAK,CAAC,GAAG;AAChD,QAAI,aAAa,aAAa;AAC5B,gBAAU,IAAI,OAAO,aAAa,WAAW;AAAA,IAC/C;AAAA,EACF;AAEA,SAAO;AACT;","names":["HttpAgent","CopilotKitCoreErrorCode","CopilotKitCoreRuntimeConnectionStatus","HttpAgent","ToolCallStatus"]}
1
+ {"version":3,"sources":["../src/core.ts","../src/agent.ts","../src/types.ts","../src/utils/markdown.ts"],"sourcesContent":["import {\n AgentDescription,\n DEFAULT_AGENT_ID,\n randomUUID,\n RuntimeInfo,\n logger,\n} from \"@copilotkitnext/shared\";\nimport {\n AbstractAgent,\n AgentSubscriber,\n Context,\n HttpAgent,\n Message,\n RunAgentResult,\n} from \"@ag-ui/client\";\nimport { FrontendTool } from \"./types\";\nimport { ProxiedCopilotRuntimeAgent } from \"./agent\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\n\n/** Configuration options for `CopilotKitCore`. */\nexport interface CopilotKitCoreConfig {\n /** The endpoint of the CopilotRuntime. */\n runtimeUrl?: string;\n /** Mapping from agent name to its `AbstractAgent` instance. */\n agents?: Record<string, AbstractAgent>;\n /** Headers appended to every HTTP request made by `CopilotKitCore`. */\n headers?: Record<string, string>;\n /** Properties sent as `forwardedProps` to the AG-UI agent. */\n properties?: Record<string, unknown>;\n /** Ordered collection of frontend tools available to the core. */\n tools?: FrontendTool<any>[];\n}\n\nexport interface CopilotKitCoreAddAgentParams {\n id: string;\n agent: AbstractAgent;\n}\n\nexport interface CopilotKitCoreRunAgentParams {\n agent: AbstractAgent;\n withMessages?: Message[];\n agentId?: string;\n}\n\nexport interface CopilotKitCoreConnectAgentParams {\n agent: AbstractAgent;\n agentId?: string;\n}\n\nexport interface CopilotKitCoreGetToolParams {\n toolName: string;\n agentId?: string;\n}\n\nexport enum CopilotKitCoreErrorCode {\n RUNTIME_INFO_FETCH_FAILED = \"runtime_info_fetch_failed\",\n AGENT_CONNECT_FAILED = \"agent_connect_failed\",\n AGENT_RUN_FAILED = \"agent_run_failed\",\n AGENT_RUN_FAILED_EVENT = \"agent_run_failed_event\",\n AGENT_RUN_ERROR_EVENT = \"agent_run_error_event\",\n TOOL_ARGUMENT_PARSE_FAILED = \"tool_argument_parse_failed\",\n TOOL_HANDLER_FAILED = \"tool_handler_failed\",\n}\n\nexport interface CopilotKitCoreSubscriber {\n onRuntimeConnectionStatusChanged?: (event: {\n copilotkit: CopilotKitCore;\n status: CopilotKitCoreRuntimeConnectionStatus;\n }) => void | Promise<void>;\n onToolExecutionStart?: (event: {\n copilotkit: CopilotKitCore;\n toolCallId: string;\n agentId: string;\n toolName: string;\n args: unknown;\n }) => void | Promise<void>;\n onToolExecutionEnd?: (event: {\n copilotkit: CopilotKitCore;\n toolCallId: string;\n agentId: string;\n toolName: string;\n result: string;\n error?: string;\n }) => void | Promise<void>;\n onAgentsChanged?: (event: {\n copilotkit: CopilotKitCore;\n agents: Readonly<Record<string, AbstractAgent>>;\n }) => void | Promise<void>;\n onContextChanged?: (event: {\n copilotkit: CopilotKitCore;\n context: Readonly<Record<string, Context>>;\n }) => void | Promise<void>;\n onPropertiesChanged?: (event: {\n copilotkit: CopilotKitCore;\n properties: Readonly<Record<string, unknown>>;\n }) => void | Promise<void>;\n onHeadersChanged?: (event: {\n copilotkit: CopilotKitCore;\n headers: Readonly<Record<string, string>>;\n }) => void | Promise<void>;\n onError?: (event: {\n copilotkit: CopilotKitCore;\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n}\n\nexport enum CopilotKitCoreRuntimeConnectionStatus {\n Disconnected = \"disconnected\",\n Connected = \"connected\",\n Connecting = \"connecting\",\n Error = \"error\",\n}\n\nexport class CopilotKitCore {\n headers: Record<string, string>;\n properties: Record<string, unknown>;\n\n private _context: Record<string, Context> = {};\n private _agents: Record<string, AbstractAgent> = {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _tools: FrontendTool<any>[] = [];\n\n private localAgents: Record<string, AbstractAgent> = {};\n private remoteAgents: Record<string, AbstractAgent> = {};\n private subscribers: Set<CopilotKitCoreSubscriber> = new Set();\n\n private _runtimeUrl?: string;\n private _runtimeVersion?: string;\n private _runtimeConnectionStatus: CopilotKitCoreRuntimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Disconnected;\n\n constructor({\n runtimeUrl,\n headers = {},\n properties = {},\n agents = {},\n tools = [],\n }: CopilotKitCoreConfig) {\n this.headers = headers;\n this.properties = properties;\n this.localAgents = this.assignAgentIds(agents);\n this.applyHeadersToAgents(this.localAgents);\n this._agents = this.localAgents;\n this._tools = tools;\n this.setRuntimeUrl(runtimeUrl);\n }\n\n private applyHeadersToAgent(agent: AbstractAgent) {\n if (agent instanceof HttpAgent) {\n agent.headers = { ...this.headers };\n }\n }\n\n private applyHeadersToAgents(agents: Record<string, AbstractAgent>) {\n Object.values(agents).forEach((agent) => {\n this.applyHeadersToAgent(agent);\n });\n }\n\n private assignAgentIds(agents: Record<string, AbstractAgent>) {\n Object.entries(agents).forEach(([id, agent]) => {\n if (agent && !agent.agentId) {\n agent.agentId = id;\n }\n });\n return agents;\n }\n\n private async notifySubscribers(\n handler: (subscriber: CopilotKitCoreSubscriber) => void | Promise<void>,\n errorMessage: string\n ) {\n await Promise.all(\n Array.from(this.subscribers).map(async (subscriber) => {\n try {\n await handler(subscriber);\n } catch (error) {\n logger.error(errorMessage, error);\n }\n })\n );\n }\n\n private async emitError({\n error,\n code,\n context = {},\n }: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context?: Record<string, any>;\n }) {\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onError?.({\n copilotkit: this,\n error,\n code,\n context,\n }),\n \"Subscriber onError error:\"\n );\n }\n\n private resolveAgentId(\n agent: AbstractAgent,\n providedAgentId?: string\n ): string {\n if (providedAgentId) {\n return providedAgentId;\n }\n if (agent.agentId) {\n return agent.agentId;\n }\n const found = Object.entries(this._agents).find(([, storedAgent]) => {\n return storedAgent === agent;\n });\n if (found) {\n agent.agentId = found[0];\n return found[0];\n }\n agent.agentId = DEFAULT_AGENT_ID;\n return DEFAULT_AGENT_ID;\n }\n\n /**\n * Snapshot accessors\n */\n get context(): Readonly<Record<string, Context>> {\n return this._context;\n }\n\n get agents(): Readonly<Record<string, AbstractAgent>> {\n return this._agents;\n }\n\n get tools(): Readonly<FrontendTool<any>[]> {\n return this._tools;\n }\n\n get runtimeUrl(): string | undefined {\n return this._runtimeUrl;\n }\n\n setRuntimeUrl(runtimeUrl: string | undefined) {\n const normalizedRuntimeUrl = runtimeUrl\n ? runtimeUrl.replace(/\\/$/, \"\")\n : undefined;\n\n if (this._runtimeUrl === normalizedRuntimeUrl) {\n return;\n }\n\n this._runtimeUrl = normalizedRuntimeUrl;\n void this.updateRuntimeConnection();\n }\n\n get runtimeVersion(): string | undefined {\n return this._runtimeVersion;\n }\n\n get runtimeConnectionStatus(): CopilotKitCoreRuntimeConnectionStatus {\n return this._runtimeConnectionStatus;\n }\n\n /**\n * Runtime connection\n */\n private async updateRuntimeConnection() {\n if (!this.runtimeUrl) {\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Disconnected;\n this._runtimeVersion = undefined;\n this.remoteAgents = {};\n this._agents = this.localAgents;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Disconnected,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n return;\n }\n\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Connecting;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Connecting,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n try {\n const response = await fetch(`${this.runtimeUrl}/info`, {\n headers: this.headers,\n });\n const {\n version,\n ...runtimeInfo\n }: {\n agents: Record<string, AgentDescription>;\n version: string;\n } = (await response.json()) as RuntimeInfo;\n\n const agents: Record<string, AbstractAgent> = Object.fromEntries(\n Object.entries(runtimeInfo.agents).map(([id, { description }]) => {\n const agent = new ProxiedCopilotRuntimeAgent({\n runtimeUrl: this.runtimeUrl,\n agentId: id,\n description: description,\n });\n this.applyHeadersToAgent(agent);\n return [id, agent];\n })\n );\n\n this.remoteAgents = agents;\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Connected;\n this._runtimeVersion = version;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Connected,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n } catch (error) {\n this._runtimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Error;\n this._runtimeVersion = undefined;\n this.remoteAgents = {};\n this._agents = this.localAgents;\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this,\n status: CopilotKitCoreRuntimeConnectionStatus.Error,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\"\n );\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n const message =\n error instanceof Error ? error.message : JSON.stringify(error);\n logger.warn(\n `Failed to load runtime info (${this.runtimeUrl}/info): ${message}`\n );\n const runtimeError =\n error instanceof Error ? error : new Error(String(error));\n await this.emitError({\n error: runtimeError,\n code: CopilotKitCoreErrorCode.RUNTIME_INFO_FETCH_FAILED,\n context: {\n runtimeUrl: this.runtimeUrl,\n },\n });\n }\n }\n\n /**\n * Configuration updates\n */\n setHeaders(headers: Record<string, string>) {\n this.headers = headers;\n this.applyHeadersToAgents(this._agents);\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onHeadersChanged?.({\n copilotkit: this,\n headers: this.headers,\n }),\n \"Subscriber onHeadersChanged error:\"\n );\n }\n\n setProperties(properties: Record<string, unknown>) {\n this.properties = properties;\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onPropertiesChanged?.({\n copilotkit: this,\n properties: this.properties,\n }),\n \"Subscriber onPropertiesChanged error:\"\n );\n }\n\n setAgents(agents: Record<string, AbstractAgent>) {\n this.localAgents = this.assignAgentIds(agents);\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n this.applyHeadersToAgents(this._agents);\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n }\n\n addAgent({ id, agent }: CopilotKitCoreAddAgentParams) {\n this.localAgents[id] = agent;\n if (!agent.agentId) {\n agent.agentId = id;\n }\n this.applyHeadersToAgent(agent);\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n }\n\n removeAgent(id: string) {\n delete this.localAgents[id];\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\"\n );\n }\n\n getAgent(id: string): AbstractAgent | undefined {\n if (id in this._agents) {\n return this._agents[id] as AbstractAgent;\n }\n\n if (\n this.runtimeUrl !== undefined &&\n (this.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Disconnected ||\n this.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connecting)\n ) {\n return undefined;\n } else {\n console.warn(`Agent ${id} not found`);\n return undefined;\n }\n }\n\n /**\n * Context management\n */\n addContext({ description, value }: Context): string {\n const id = randomUUID();\n this._context[id] = { description, value };\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onContextChanged?.({\n copilotkit: this,\n context: this._context,\n }),\n \"Subscriber onContextChanged error:\"\n );\n return id;\n }\n\n removeContext(id: string) {\n delete this._context[id];\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onContextChanged?.({\n copilotkit: this,\n context: this._context,\n }),\n \"Subscriber onContextChanged error:\"\n );\n }\n\n /**\n * Tool management\n */\n addTool<T extends Record<string, unknown> = Record<string, unknown>>(\n tool: FrontendTool<T>\n ) {\n // Check if a tool with the same name and agentId already exists\n const existingToolIndex = this._tools.findIndex(\n (t) => t.name === tool.name && t.agentId === tool.agentId\n );\n\n if (existingToolIndex !== -1) {\n logger.warn(\n `Tool already exists: '${tool.name}' for agent '${tool.agentId || \"global\"}', skipping.`\n );\n return;\n }\n\n this._tools.push(tool);\n }\n\n removeTool(id: string, agentId?: string) {\n this._tools = this._tools.filter((tool) => {\n // Remove tool if both name and agentId match\n if (agentId !== undefined) {\n return !(tool.name === id && tool.agentId === agentId);\n }\n // If no agentId specified, only remove global tools with matching name\n return !(tool.name === id && !tool.agentId);\n });\n }\n\n /**\n * Get a tool by name and optionally by agentId.\n * If agentId is provided, it will first look for an agent-specific tool,\n * then fall back to a global tool with the same name.\n */\n getTool(params: CopilotKitCoreGetToolParams): FrontendTool<any> | undefined {\n const { toolName, agentId } = params;\n\n // If agentId is provided, first look for agent-specific tool\n if (agentId) {\n const agentTool = this._tools.find(\n (tool) => tool.name === toolName && tool.agentId === agentId\n );\n if (agentTool) {\n return agentTool;\n }\n }\n\n // Fall back to global tool (no agentId)\n return this._tools.find((tool) => tool.name === toolName && !tool.agentId);\n }\n\n /**\n * Set all tools at once. Replaces existing tools.\n */\n setTools(tools: FrontendTool<any>[]) {\n this._tools = [...tools];\n }\n\n /**\n * Subscription lifecycle\n */\n subscribe(subscriber: CopilotKitCoreSubscriber): () => void {\n this.subscribers.add(subscriber);\n\n // Return unsubscribe function\n return () => {\n this.unsubscribe(subscriber);\n };\n }\n\n unsubscribe(subscriber: CopilotKitCoreSubscriber) {\n this.subscribers.delete(subscriber);\n }\n\n /**\n * Agent connectivity\n */\n async connectAgent({\n agent,\n agentId,\n }: CopilotKitCoreConnectAgentParams): Promise<RunAgentResult> {\n try {\n if (agent instanceof HttpAgent) {\n agent.headers = { ...this.headers };\n }\n\n const runAgentResult = await agent.connectAgent(\n {\n forwardedProps: this.properties,\n tools: this.buildFrontendTools(agentId),\n },\n this.createAgentErrorSubscriber(agent, agentId)\n );\n\n return this.processAgentResult({ runAgentResult, agent, agentId });\n } catch (error) {\n const connectError =\n error instanceof Error ? error : new Error(String(error));\n const context: Record<string, any> = {};\n if (agentId ?? agent.agentId) {\n context.agentId = agentId ?? agent.agentId;\n }\n await this.emitError({\n error: connectError,\n code: CopilotKitCoreErrorCode.AGENT_CONNECT_FAILED,\n context,\n });\n throw error;\n }\n }\n\n async runAgent({\n agent,\n withMessages,\n agentId,\n }: CopilotKitCoreRunAgentParams): Promise<RunAgentResult> {\n if (agent instanceof HttpAgent) {\n agent.headers = { ...this.headers };\n }\n\n if (withMessages) {\n agent.addMessages(withMessages);\n }\n try {\n const runAgentResult = await agent.runAgent(\n {\n forwardedProps: this.properties,\n tools: this.buildFrontendTools(agentId),\n },\n this.createAgentErrorSubscriber(agent, agentId)\n );\n return this.processAgentResult({ runAgentResult, agent, agentId });\n } catch (error) {\n const runError =\n error instanceof Error ? error : new Error(String(error));\n const context: Record<string, any> = {};\n if (agentId ?? agent.agentId) {\n context.agentId = agentId ?? agent.agentId;\n }\n if (withMessages) {\n context.messageCount = withMessages.length;\n }\n await this.emitError({\n error: runError,\n code: CopilotKitCoreErrorCode.AGENT_RUN_FAILED,\n context,\n });\n throw error;\n }\n }\n\n private async processAgentResult({\n runAgentResult,\n agent,\n agentId,\n }: {\n runAgentResult: RunAgentResult;\n agent: AbstractAgent;\n agentId: string | undefined;\n }): Promise<RunAgentResult> {\n const { newMessages } = runAgentResult;\n const effectiveAgentId = this.resolveAgentId(agent, agentId);\n\n let needsFollowUp = false;\n\n for (const message of newMessages) {\n if (message.role === \"assistant\") {\n for (const toolCall of message.toolCalls || []) {\n if (\n newMessages.findIndex(\n (m) => m.role === \"tool\" && m.toolCallId === toolCall.id\n ) === -1\n ) {\n const tool = this.getTool({\n toolName: toolCall.function.name,\n agentId,\n });\n if (tool) {\n // Check if tool is constrained to a specific agent\n if (tool?.agentId && tool.agentId !== agentId) {\n // Tool is not available for this agent, skip it\n continue;\n }\n\n let toolCallResult = \"\";\n let errorMessage: string | undefined;\n let isArgumentError = false;\n if (tool?.handler) {\n let parsedArgs: unknown;\n try {\n parsedArgs = JSON.parse(toolCall.function.arguments);\n } catch (error) {\n const parseError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = parseError.message;\n isArgumentError = true;\n await this.emitError({\n error: parseError,\n code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n rawArguments: toolCall.function.arguments,\n toolType: \"specific\",\n messageId: message.id,\n },\n });\n }\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionStart?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n args: parsedArgs,\n }),\n \"Subscriber onToolExecutionStart error:\"\n );\n\n if (!errorMessage) {\n try {\n const result = await tool.handler(\n parsedArgs as any,\n toolCall\n );\n if (result === undefined || result === null) {\n toolCallResult = \"\";\n } else if (typeof result === \"string\") {\n toolCallResult = result;\n } else {\n toolCallResult = JSON.stringify(result);\n }\n } catch (error) {\n const handlerError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = handlerError.message;\n await this.emitError({\n error: handlerError,\n code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n parsedArgs,\n toolType: \"specific\",\n messageId: message.id,\n },\n });\n }\n }\n\n if (errorMessage) {\n toolCallResult = `Error: ${errorMessage}`;\n }\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionEnd?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n result: errorMessage ? \"\" : toolCallResult,\n error: errorMessage,\n }),\n \"Subscriber onToolExecutionEnd error:\"\n );\n\n if (isArgumentError) {\n throw new Error(errorMessage ?? \"Tool execution failed\");\n }\n }\n\n if (!errorMessage || !isArgumentError) {\n const messageIndex = agent.messages.findIndex(\n (m) => m.id === message.id\n );\n const toolMessage = {\n id: randomUUID(),\n role: \"tool\" as const,\n toolCallId: toolCall.id,\n content: toolCallResult,\n };\n agent.messages.splice(messageIndex + 1, 0, toolMessage);\n\n if (!errorMessage && tool?.followUp !== false) {\n needsFollowUp = true;\n }\n }\n } else {\n // Wildcard fallback for undefined tools\n const wildcardTool = this.getTool({ toolName: \"*\", agentId });\n if (wildcardTool) {\n // Check if wildcard tool is constrained to a specific agent\n if (wildcardTool?.agentId && wildcardTool.agentId !== agentId) {\n // Wildcard tool is not available for this agent, skip it\n continue;\n }\n\n let toolCallResult = \"\";\n let errorMessage: string | undefined;\n let isArgumentError = false;\n if (wildcardTool?.handler) {\n let parsedArgs: unknown;\n try {\n parsedArgs = JSON.parse(toolCall.function.arguments);\n } catch (error) {\n const parseError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = parseError.message;\n isArgumentError = true;\n await this.emitError({\n error: parseError,\n code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n rawArguments: toolCall.function.arguments,\n toolType: \"wildcard\",\n messageId: message.id,\n },\n });\n }\n\n const wildcardArgs = {\n toolName: toolCall.function.name,\n args: parsedArgs,\n };\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionStart?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n args: wildcardArgs,\n }),\n \"Subscriber onToolExecutionStart error:\"\n );\n\n if (!errorMessage) {\n try {\n const result = await wildcardTool.handler(\n wildcardArgs as any,\n toolCall\n );\n if (result === undefined || result === null) {\n toolCallResult = \"\";\n } else if (typeof result === \"string\") {\n toolCallResult = result;\n } else {\n toolCallResult = JSON.stringify(result);\n }\n } catch (error) {\n const handlerError =\n error instanceof Error\n ? error\n : new Error(String(error));\n errorMessage = handlerError.message;\n await this.emitError({\n error: handlerError,\n code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,\n context: {\n agentId: effectiveAgentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n parsedArgs: wildcardArgs,\n toolType: \"wildcard\",\n messageId: message.id,\n },\n });\n }\n }\n\n if (errorMessage) {\n toolCallResult = `Error: ${errorMessage}`;\n }\n\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionEnd?.({\n copilotkit: this,\n toolCallId: toolCall.id,\n agentId: effectiveAgentId,\n toolName: toolCall.function.name,\n result: errorMessage ? \"\" : toolCallResult,\n error: errorMessage,\n }),\n \"Subscriber onToolExecutionEnd error:\"\n );\n\n if (isArgumentError) {\n throw new Error(errorMessage ?? \"Tool execution failed\");\n }\n }\n\n if (!errorMessage || !isArgumentError) {\n const messageIndex = agent.messages.findIndex(\n (m) => m.id === message.id\n );\n const toolMessage = {\n id: randomUUID(),\n role: \"tool\" as const,\n toolCallId: toolCall.id,\n content: toolCallResult,\n };\n agent.messages.splice(messageIndex + 1, 0, toolMessage);\n\n if (!errorMessage && wildcardTool?.followUp !== false) {\n needsFollowUp = true;\n }\n }\n }\n }\n }\n }\n }\n }\n\n if (needsFollowUp) {\n return await this.runAgent({ agent, agentId });\n }\n\n return runAgentResult;\n }\n\n private buildFrontendTools(agentId?: string) {\n return this._tools\n .filter((tool) => !tool.agentId || tool.agentId === agentId)\n .map((tool) => ({\n name: tool.name,\n description: tool.description ?? \"\",\n parameters: createToolSchema(tool),\n }));\n }\n\n private createAgentErrorSubscriber(\n agent: AbstractAgent,\n agentId?: string\n ): AgentSubscriber {\n const emitAgentError = async (\n error: Error,\n code: CopilotKitCoreErrorCode,\n extraContext: Record<string, any> = {}\n ) => {\n const context: Record<string, any> = { ...extraContext };\n if (agentId ?? agent.agentId) {\n context.agentId = agentId ?? agent.agentId;\n }\n await this.emitError({\n error,\n code,\n context,\n });\n };\n\n return {\n onRunFailed: async ({ error }: { error: Error }) => {\n await emitAgentError(\n error,\n CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT,\n {\n source: \"onRunFailed\",\n }\n );\n },\n onRunErrorEvent: async ({ event }) => {\n const eventError =\n event?.rawEvent instanceof Error\n ? event.rawEvent\n : event?.rawEvent?.error instanceof Error\n ? event.rawEvent.error\n : undefined;\n\n const errorMessage =\n typeof event?.rawEvent?.error === \"string\"\n ? event.rawEvent.error\n : (event?.message ?? \"Agent run error\");\n\n const rawError = eventError ?? new Error(errorMessage);\n\n if (event?.code && !(rawError as any).code) {\n (rawError as any).code = event.code;\n }\n\n await emitAgentError(\n rawError,\n CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT,\n {\n source: \"onRunErrorEvent\",\n event,\n runtimeErrorCode: event?.code,\n }\n );\n },\n };\n }\n}\n\nconst EMPTY_TOOL_SCHEMA = {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n} as const satisfies Record<string, unknown>;\n\nfunction createToolSchema(tool: FrontendTool<any>): Record<string, unknown> {\n if (!tool.parameters) {\n return EMPTY_TOOL_SCHEMA;\n }\n\n const rawSchema = zodToJsonSchema(tool.parameters, {\n $refStrategy: \"none\",\n });\n\n if (!rawSchema || typeof rawSchema !== \"object\") {\n return { ...EMPTY_TOOL_SCHEMA };\n }\n\n const { $schema, ...schema } = rawSchema as Record<string, unknown>;\n\n if (typeof schema.type !== \"string\") {\n schema.type = \"object\";\n }\n if (typeof schema.properties !== \"object\" || schema.properties === null) {\n schema.properties = {};\n }\n if (schema.additionalProperties === undefined) {\n schema.additionalProperties = false;\n }\n\n return schema;\n}\n","import {\n BaseEvent,\n HttpAgent,\n HttpAgentConfig,\n RunAgentInput,\n runHttpRequest,\n transformHttpEventStream,\n} from \"@ag-ui/client\";\nimport { Observable } from \"rxjs\";\n\nexport interface ProxiedCopilotRuntimeAgentConfig\n extends Omit<HttpAgentConfig, \"url\"> {\n runtimeUrl?: string;\n}\n\nexport class ProxiedCopilotRuntimeAgent extends HttpAgent {\n runtimeUrl?: string;\n\n constructor(config: ProxiedCopilotRuntimeAgentConfig) {\n super({\n ...config,\n url: `${config.runtimeUrl}/agent/${config.agentId}/run`,\n });\n this.runtimeUrl = config.runtimeUrl;\n }\n\n connect(input: RunAgentInput): Observable<BaseEvent> {\n const httpEvents = runHttpRequest(\n `${this.runtimeUrl}/agent/${this.agentId}/connect`,\n this.requestInit(input)\n );\n return transformHttpEventStream(httpEvents);\n }\n}\n","import { ToolCall } from \"@ag-ui/client\";\nimport { z } from \"zod\";\n\n/**\n * Status of a tool call execution\n */\nexport enum ToolCallStatus {\n InProgress = \"inProgress\",\n Executing = \"executing\",\n Complete = \"complete\",\n}\n\nexport type FrontendTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n> = {\n name: string;\n description?: string;\n parameters?: z.ZodType<T>;\n handler?: (args: T, toolCall: ToolCall) => Promise<unknown>;\n followUp?: boolean;\n /**\n * Optional agent ID to constrain this tool to a specific agent.\n * If specified, this tool will only be available to the specified agent.\n */\n agentId?: string;\n};\n","export function completePartialMarkdown(input: string): string {\n let s = input;\n\n // Handle code fences first - use FIRST unmatched fence for proper nesting\n const fenceMatches = Array.from(s.matchAll(/^(\\s*)(`{3,}|~{3,})/gm));\n if (fenceMatches.length % 2 === 1) {\n const [, indent, fence] = fenceMatches[0]!;\n s += `\\n${indent}${fence}`;\n }\n\n // Identify incomplete links at the end and close them\n const incompleteLinkMatch = s.match(/\\[([^\\]]*)\\]\\(([^)]*)$/);\n if (incompleteLinkMatch) {\n s += \")\";\n }\n\n // State-based parsing\n interface OpenElement {\n type: string;\n marker: string;\n position: number;\n }\n\n const openElements: OpenElement[] = [];\n const chars = Array.from(s);\n\n // First pass: identify code block boundaries and inline code to avoid processing their content\n const codeBlockRanges: Array<{ start: number; end: number }> = [];\n const inlineCodeRanges: Array<{ start: number; end: number }> = [];\n\n // Find code block ranges\n let tempCodeFenceCount = 0;\n let currentCodeBlockStart = -1;\n\n for (let i = 0; i < chars.length; i++) {\n if (i === 0 || chars[i - 1] === \"\\n\") {\n const lineMatch = s.substring(i).match(/^(\\s*)(`{3,}|~{3,})/);\n if (lineMatch) {\n tempCodeFenceCount++;\n if (tempCodeFenceCount % 2 === 1) {\n currentCodeBlockStart = i;\n } else if (currentCodeBlockStart !== -1) {\n codeBlockRanges.push({\n start: currentCodeBlockStart,\n end: i + lineMatch[0].length,\n });\n currentCodeBlockStart = -1;\n }\n i += lineMatch[0].length - 1;\n }\n }\n }\n\n // Find inline code ranges\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] === \"`\") {\n // Check if escaped\n let backslashCount = 0;\n for (let j = i - 1; j >= 0 && chars[j] === \"\\\\\"; j--) {\n backslashCount++;\n }\n if (backslashCount % 2 === 0) {\n // Not escaped - find the closing backtick\n for (let j = i + 1; j < chars.length; j++) {\n if (chars[j] === \"`\") {\n let closingBackslashCount = 0;\n for (let k = j - 1; k >= 0 && chars[k] === \"\\\\\"; k--) {\n closingBackslashCount++;\n }\n if (closingBackslashCount % 2 === 0) {\n inlineCodeRanges.push({ start: i, end: j + 1 });\n i = j;\n break;\n }\n }\n }\n }\n }\n }\n\n // Helper function to check if position is in code\n const isInCode = (pos: number): boolean => {\n return (\n codeBlockRanges.some((range) => pos >= range.start && pos < range.end) ||\n inlineCodeRanges.some((range) => pos >= range.start && pos < range.end)\n );\n };\n\n // Second pass: process markdown elements, skipping code regions\n for (let i = 0; i < chars.length; i++) {\n const char = chars[i];\n const nextChar = chars[i + 1];\n const prevChar = chars[i - 1];\n\n if (isInCode(i)) {\n continue;\n }\n\n // Handle brackets (but not if they're part of already-complete links)\n if (char === \"[\") {\n // Check if this is part of a complete link [text](url)\n let isCompleteLink = false;\n let bracketDepth = 1;\n let j = i + 1;\n\n // Find the matching ]\n while (j < chars.length && bracketDepth > 0) {\n if (chars[j] === \"[\" && !isInCode(j)) bracketDepth++;\n if (chars[j] === \"]\" && !isInCode(j)) bracketDepth--;\n j++;\n }\n\n // Check if followed by (\n if (bracketDepth === 0 && chars[j] === \"(\") {\n // Find the closing )\n let parenDepth = 1;\n j++;\n while (j < chars.length && parenDepth > 0) {\n if (chars[j] === \"(\" && !isInCode(j)) parenDepth++;\n if (chars[j] === \")\" && !isInCode(j)) parenDepth--;\n j++;\n }\n if (parenDepth === 0) {\n isCompleteLink = true;\n i = j - 1;\n continue;\n }\n }\n\n // This is a standalone bracket, treat as markdown\n if (!isCompleteLink) {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bracket\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"bracket\", marker: \"[\", position: i });\n }\n }\n }\n\n // Handle double emphasis first (**, __, ~~) - these take precedence\n else if (char === \"*\" && nextChar === \"*\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bold_star\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"bold_star\", marker: \"**\", position: i });\n }\n i++; // Skip next character\n } else if (char === \"_\" && nextChar === \"_\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bold_underscore\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({\n type: \"bold_underscore\",\n marker: \"__\",\n position: i,\n });\n }\n i++; // Skip next character\n } else if (char === \"~\" && nextChar === \"~\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"strike\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"strike\", marker: \"~~\", position: i });\n }\n i++; // Skip next character\n }\n\n // Handle single emphasis (*, _) - only if not part of double\n else if (char === \"*\" && prevChar !== \"*\" && nextChar !== \"*\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"italic_star\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"italic_star\", marker: \"*\", position: i });\n }\n } else if (char === \"_\" && prevChar !== \"_\" && nextChar !== \"_\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"italic_underscore\"\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({\n type: \"italic_underscore\",\n marker: \"_\",\n position: i,\n });\n }\n }\n }\n\n // Handle remaining unmatched backticks (outside of inline code ranges)\n let backtickCount = 0;\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] === \"`\" && !isInCode(i)) {\n backtickCount++;\n }\n }\n if (backtickCount % 2 === 1) {\n s += \"`\";\n }\n\n // Close remaining open elements in reverse order (LIFO stack semantics)\n openElements.sort((a, b) => b.position - a.position);\n\n const closers = openElements.map((el) => {\n switch (el.type) {\n case \"bracket\":\n return \"]\";\n case \"bold_star\":\n return \"**\";\n case \"bold_underscore\":\n return \"__\";\n case \"strike\":\n return \"~~\";\n case \"italic_star\":\n return \"*\";\n case \"italic_underscore\":\n return \"_\";\n default:\n return \"\";\n }\n });\n\n let result = s + closers.join(\"\");\n\n // Handle parentheses ONLY if not inside code\n const finalFenceMatches = Array.from(\n result.matchAll(/^(\\s*)(`{3,}|~{3,})/gm)\n );\n const hasUnclosedBacktick = (result.match(/`/g) || []).length % 2 === 1;\n const hasUnclosedCodeFence = finalFenceMatches.length % 2 === 1;\n\n let shouldCloseParens = !hasUnclosedBacktick && !hasUnclosedCodeFence;\n\n if (shouldCloseParens) {\n const lastOpenParen = result.lastIndexOf(\"(\");\n if (lastOpenParen !== -1) {\n // Check if this paren is inside a backtick pair\n const beforeParen = result.substring(0, lastOpenParen);\n const backticksBeforeParen = (beforeParen.match(/`/g) || []).length;\n if (backticksBeforeParen % 2 === 1) {\n shouldCloseParens = false;\n }\n }\n }\n\n if (shouldCloseParens) {\n const openParens = (result.match(/\\(/g) || []).length;\n const closeParens = (result.match(/\\)/g) || []).length;\n if (openParens > closeParens) {\n result += \")\".repeat(openParens - closeParens);\n }\n }\n\n return result;\n}"],"mappings":";AAAA;AAAA,EAEE;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP;AAAA,EAIE,aAAAA;AAAA,OAGK;;;ACdP;AAAA,EAEE;AAAA,EAGA;AAAA,EACA;AAAA,OACK;AAQA,IAAM,6BAAN,cAAyC,UAAU;AAAA,EACxD;AAAA,EAEA,YAAY,QAA0C;AACpD,UAAM;AAAA,MACJ,GAAG;AAAA,MACH,KAAK,GAAG,OAAO,UAAU,UAAU,OAAO,OAAO;AAAA,IACnD,CAAC;AACD,SAAK,aAAa,OAAO;AAAA,EAC3B;AAAA,EAEA,QAAQ,OAA6C;AACnD,UAAM,aAAa;AAAA,MACjB,GAAG,KAAK,UAAU,UAAU,KAAK,OAAO;AAAA,MACxC,KAAK,YAAY,KAAK;AAAA,IACxB;AACA,WAAO,yBAAyB,UAAU;AAAA,EAC5C;AACF;;;ADhBA,SAAS,uBAAuB;AAqCzB,IAAK,0BAAL,kBAAKC,6BAAL;AACL,EAAAA,yBAAA,+BAA4B;AAC5B,EAAAA,yBAAA,0BAAuB;AACvB,EAAAA,yBAAA,sBAAmB;AACnB,EAAAA,yBAAA,4BAAyB;AACzB,EAAAA,yBAAA,2BAAwB;AACxB,EAAAA,yBAAA,gCAA6B;AAC7B,EAAAA,yBAAA,yBAAsB;AAPZ,SAAAA;AAAA,GAAA;AAsDL,IAAK,wCAAL,kBAAKC,2CAAL;AACL,EAAAA,uCAAA,kBAAe;AACf,EAAAA,uCAAA,eAAY;AACZ,EAAAA,uCAAA,gBAAa;AACb,EAAAA,uCAAA,WAAQ;AAJE,SAAAA;AAAA,GAAA;AAOL,IAAM,iBAAN,MAAqB;AAAA,EAC1B;AAAA,EACA;AAAA,EAE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AEA,MAAI,mBAAmB;AACrB,UAAM,cAAc,OAAO,MAAM,KAAK,KAAK,CAAC,GAAG;AAC/C,UAAM,eAAe,OAAO,MAAM,KAAK,KAAK,CAAC,GAAG;AAChD,QAAI,aAAa,aAAa;AAC5B,gBAAU,IAAI,OAAO,aAAa,WAAW;AAAA,IAC/C;AAAA,EACF;AAEA,SAAO;AACT;","names":["HttpAgent","CopilotKitCoreErrorCode","CopilotKitCoreRuntimeConnectionStatus","HttpAgent","ToolCallStatus"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copilotkitnext/core",
3
- "version": "0.0.9-alpha.3",
3
+ "version": "0.0.11",
4
4
  "description": "Core web utilities for CopilotKit2",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -21,15 +21,15 @@
21
21
  "tsup": "^8.5.0",
22
22
  "typescript": "5.8.2",
23
23
  "vitest": "^3.2.4",
24
- "@copilotkitnext/eslint-config": "0.0.0",
25
- "@copilotkitnext/typescript-config": "0.0.0"
24
+ "@copilotkitnext/typescript-config": "0.0.0",
25
+ "@copilotkitnext/eslint-config": "0.0.0"
26
26
  },
27
27
  "dependencies": {
28
28
  "@ag-ui/client": "0.0.38-alpha.2",
29
29
  "rxjs": "7.8.1",
30
30
  "zod": "^3.25.75",
31
31
  "zod-to-json-schema": "^3.24.6",
32
- "@copilotkitnext/shared": "0.0.9-alpha.3"
32
+ "@copilotkitnext/shared": "0.0.11"
33
33
  },
34
34
  "engines": {
35
35
  "node": ">=18"