@copilotkitnext/core 0.0.11 → 0.0.12

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
@@ -27,8 +27,8 @@ type FrontendTool<T extends Record<string, unknown> = Record<string, unknown>> =
27
27
  interface CopilotKitCoreConfig {
28
28
  /** The endpoint of the CopilotRuntime. */
29
29
  runtimeUrl?: string;
30
- /** Mapping from agent name to its `AbstractAgent` instance. */
31
- agents?: Record<string, AbstractAgent>;
30
+ /** Mapping from agent name to its `AbstractAgent` instance. For development only - production requires CopilotRuntime. */
31
+ agents__unsafe_dev_only?: Record<string, AbstractAgent>;
32
32
  /** Headers appended to every HTTP request made by `CopilotKitCore`. */
33
33
  headers?: Record<string, string>;
34
34
  /** Properties sent as `forwardedProps` to the AG-UI agent. */
@@ -112,8 +112,8 @@ declare enum CopilotKitCoreRuntimeConnectionStatus {
112
112
  Error = "error"
113
113
  }
114
114
  declare class CopilotKitCore {
115
- headers: Record<string, string>;
116
- properties: Record<string, unknown>;
115
+ private _headers;
116
+ private _properties;
117
117
  private _context;
118
118
  private _agents;
119
119
  private _tools;
@@ -123,7 +123,7 @@ declare class CopilotKitCore {
123
123
  private _runtimeUrl?;
124
124
  private _runtimeVersion?;
125
125
  private _runtimeConnectionStatus;
126
- constructor({ runtimeUrl, headers, properties, agents, tools, }: CopilotKitCoreConfig);
126
+ constructor({ runtimeUrl, headers, properties, agents__unsafe_dev_only, tools, }: CopilotKitCoreConfig);
127
127
  private applyHeadersToAgent;
128
128
  private applyHeadersToAgents;
129
129
  private assignAgentIds;
@@ -139,6 +139,8 @@ declare class CopilotKitCore {
139
139
  get runtimeUrl(): string | undefined;
140
140
  setRuntimeUrl(runtimeUrl: string | undefined): void;
141
141
  get runtimeVersion(): string | undefined;
142
+ get headers(): Readonly<Record<string, string>>;
143
+ get properties(): Readonly<Record<string, unknown>>;
142
144
  get runtimeConnectionStatus(): CopilotKitCoreRuntimeConnectionStatus;
143
145
  /**
144
146
  * Runtime connection
@@ -149,9 +151,9 @@ declare class CopilotKitCore {
149
151
  */
150
152
  setHeaders(headers: Record<string, string>): void;
151
153
  setProperties(properties: Record<string, unknown>): void;
152
- setAgents(agents: Record<string, AbstractAgent>): void;
153
- addAgent({ id, agent }: CopilotKitCoreAddAgentParams): void;
154
- removeAgent(id: string): void;
154
+ setAgents__unsafe_dev_only(agents: Record<string, AbstractAgent>): void;
155
+ addAgent__unsafe_dev_only({ id, agent }: CopilotKitCoreAddAgentParams): void;
156
+ removeAgent__unsafe_dev_only(id: string): void;
155
157
  getAgent(id: string): AbstractAgent | undefined;
156
158
  /**
157
159
  * Context management
@@ -181,8 +183,8 @@ declare class CopilotKitCore {
181
183
  /**
182
184
  * Agent connectivity
183
185
  */
184
- connectAgent({ agent, agentId, }: CopilotKitCoreConnectAgentParams): Promise<RunAgentResult>;
185
- runAgent({ agent, withMessages, agentId, }: CopilotKitCoreRunAgentParams): Promise<RunAgentResult>;
186
+ connectAgent({ agent, agentId }: CopilotKitCoreConnectAgentParams): Promise<RunAgentResult>;
187
+ runAgent({ agent, withMessages, agentId }: CopilotKitCoreRunAgentParams): Promise<RunAgentResult>;
186
188
  private processAgentResult;
187
189
  private buildFrontendTools;
188
190
  private createAgentErrorSubscriber;
package/dist/index.d.ts CHANGED
@@ -27,8 +27,8 @@ type FrontendTool<T extends Record<string, unknown> = Record<string, unknown>> =
27
27
  interface CopilotKitCoreConfig {
28
28
  /** The endpoint of the CopilotRuntime. */
29
29
  runtimeUrl?: string;
30
- /** Mapping from agent name to its `AbstractAgent` instance. */
31
- agents?: Record<string, AbstractAgent>;
30
+ /** Mapping from agent name to its `AbstractAgent` instance. For development only - production requires CopilotRuntime. */
31
+ agents__unsafe_dev_only?: Record<string, AbstractAgent>;
32
32
  /** Headers appended to every HTTP request made by `CopilotKitCore`. */
33
33
  headers?: Record<string, string>;
34
34
  /** Properties sent as `forwardedProps` to the AG-UI agent. */
@@ -112,8 +112,8 @@ declare enum CopilotKitCoreRuntimeConnectionStatus {
112
112
  Error = "error"
113
113
  }
114
114
  declare class CopilotKitCore {
115
- headers: Record<string, string>;
116
- properties: Record<string, unknown>;
115
+ private _headers;
116
+ private _properties;
117
117
  private _context;
118
118
  private _agents;
119
119
  private _tools;
@@ -123,7 +123,7 @@ declare class CopilotKitCore {
123
123
  private _runtimeUrl?;
124
124
  private _runtimeVersion?;
125
125
  private _runtimeConnectionStatus;
126
- constructor({ runtimeUrl, headers, properties, agents, tools, }: CopilotKitCoreConfig);
126
+ constructor({ runtimeUrl, headers, properties, agents__unsafe_dev_only, tools, }: CopilotKitCoreConfig);
127
127
  private applyHeadersToAgent;
128
128
  private applyHeadersToAgents;
129
129
  private assignAgentIds;
@@ -139,6 +139,8 @@ declare class CopilotKitCore {
139
139
  get runtimeUrl(): string | undefined;
140
140
  setRuntimeUrl(runtimeUrl: string | undefined): void;
141
141
  get runtimeVersion(): string | undefined;
142
+ get headers(): Readonly<Record<string, string>>;
143
+ get properties(): Readonly<Record<string, unknown>>;
142
144
  get runtimeConnectionStatus(): CopilotKitCoreRuntimeConnectionStatus;
143
145
  /**
144
146
  * Runtime connection
@@ -149,9 +151,9 @@ declare class CopilotKitCore {
149
151
  */
150
152
  setHeaders(headers: Record<string, string>): void;
151
153
  setProperties(properties: Record<string, unknown>): void;
152
- setAgents(agents: Record<string, AbstractAgent>): void;
153
- addAgent({ id, agent }: CopilotKitCoreAddAgentParams): void;
154
- removeAgent(id: string): void;
154
+ setAgents__unsafe_dev_only(agents: Record<string, AbstractAgent>): void;
155
+ addAgent__unsafe_dev_only({ id, agent }: CopilotKitCoreAddAgentParams): void;
156
+ removeAgent__unsafe_dev_only(id: string): void;
155
157
  getAgent(id: string): AbstractAgent | undefined;
156
158
  /**
157
159
  * Context management
@@ -181,8 +183,8 @@ declare class CopilotKitCore {
181
183
  /**
182
184
  * Agent connectivity
183
185
  */
184
- connectAgent({ agent, agentId, }: CopilotKitCoreConnectAgentParams): Promise<RunAgentResult>;
185
- runAgent({ agent, withMessages, agentId, }: CopilotKitCoreRunAgentParams): Promise<RunAgentResult>;
186
+ connectAgent({ agent, agentId }: CopilotKitCoreConnectAgentParams): Promise<RunAgentResult>;
187
+ runAgent({ agent, withMessages, agentId }: CopilotKitCoreRunAgentParams): Promise<RunAgentResult>;
186
188
  private processAgentResult;
187
189
  private buildFrontendTools;
188
190
  private createAgentErrorSubscriber;
package/dist/index.js CHANGED
@@ -73,8 +73,8 @@ var CopilotKitCoreRuntimeConnectionStatus = /* @__PURE__ */ ((CopilotKitCoreRunt
73
73
  return CopilotKitCoreRuntimeConnectionStatus2;
74
74
  })(CopilotKitCoreRuntimeConnectionStatus || {});
75
75
  var CopilotKitCore = class {
76
- headers;
77
- properties;
76
+ _headers;
77
+ _properties;
78
78
  _context = {};
79
79
  _agents = {};
80
80
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -89,12 +89,12 @@ var CopilotKitCore = class {
89
89
  runtimeUrl,
90
90
  headers = {},
91
91
  properties = {},
92
- agents = {},
92
+ agents__unsafe_dev_only = {},
93
93
  tools = []
94
94
  }) {
95
- this.headers = headers;
96
- this.properties = properties;
97
- this.localAgents = this.assignAgentIds(agents);
95
+ this._headers = headers;
96
+ this._properties = properties;
97
+ this.localAgents = this.assignAgentIds(agents__unsafe_dev_only);
98
98
  this.applyHeadersToAgents(this.localAgents);
99
99
  this._agents = this.localAgents;
100
100
  this._tools = tools;
@@ -187,6 +187,12 @@ var CopilotKitCore = class {
187
187
  get runtimeVersion() {
188
188
  return this._runtimeVersion;
189
189
  }
190
+ get headers() {
191
+ return this._headers;
192
+ }
193
+ get properties() {
194
+ return this._properties;
195
+ }
190
196
  get runtimeConnectionStatus() {
191
197
  return this._runtimeConnectionStatus;
192
198
  }
@@ -280,9 +286,7 @@ var CopilotKitCore = class {
280
286
  "Subscriber onAgentsChanged error:"
281
287
  );
282
288
  const message = error instanceof Error ? error.message : JSON.stringify(error);
283
- import_shared.logger.warn(
284
- `Failed to load runtime info (${this.runtimeUrl}/info): ${message}`
285
- );
289
+ import_shared.logger.warn(`Failed to load runtime info (${this.runtimeUrl}/info): ${message}`);
286
290
  const runtimeError = error instanceof Error ? error : new Error(String(error));
287
291
  await this.emitError({
288
292
  error: runtimeError,
@@ -297,7 +301,7 @@ var CopilotKitCore = class {
297
301
  * Configuration updates
298
302
  */
299
303
  setHeaders(headers) {
300
- this.headers = headers;
304
+ this._headers = headers;
301
305
  this.applyHeadersToAgents(this._agents);
302
306
  void this.notifySubscribers(
303
307
  (subscriber) => subscriber.onHeadersChanged?.({
@@ -308,7 +312,7 @@ var CopilotKitCore = class {
308
312
  );
309
313
  }
310
314
  setProperties(properties) {
311
- this.properties = properties;
315
+ this._properties = properties;
312
316
  void this.notifySubscribers(
313
317
  (subscriber) => subscriber.onPropertiesChanged?.({
314
318
  copilotkit: this,
@@ -317,7 +321,7 @@ var CopilotKitCore = class {
317
321
  "Subscriber onPropertiesChanged error:"
318
322
  );
319
323
  }
320
- setAgents(agents) {
324
+ setAgents__unsafe_dev_only(agents) {
321
325
  this.localAgents = this.assignAgentIds(agents);
322
326
  this._agents = { ...this.localAgents, ...this.remoteAgents };
323
327
  this.applyHeadersToAgents(this._agents);
@@ -329,7 +333,7 @@ var CopilotKitCore = class {
329
333
  "Subscriber onAgentsChanged error:"
330
334
  );
331
335
  }
332
- addAgent({ id, agent }) {
336
+ addAgent__unsafe_dev_only({ id, agent }) {
333
337
  this.localAgents[id] = agent;
334
338
  if (!agent.agentId) {
335
339
  agent.agentId = id;
@@ -344,7 +348,7 @@ var CopilotKitCore = class {
344
348
  "Subscriber onAgentsChanged error:"
345
349
  );
346
350
  }
347
- removeAgent(id) {
351
+ removeAgent__unsafe_dev_only(id) {
348
352
  delete this.localAgents[id];
349
353
  this._agents = { ...this.localAgents, ...this.remoteAgents };
350
354
  void this.notifySubscribers(
@@ -395,13 +399,9 @@ var CopilotKitCore = class {
395
399
  * Tool management
396
400
  */
397
401
  addTool(tool) {
398
- const existingToolIndex = this._tools.findIndex(
399
- (t) => t.name === tool.name && t.agentId === tool.agentId
400
- );
402
+ const existingToolIndex = this._tools.findIndex((t) => t.name === tool.name && t.agentId === tool.agentId);
401
403
  if (existingToolIndex !== -1) {
402
- import_shared.logger.warn(
403
- `Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}', skipping.`
404
- );
404
+ import_shared.logger.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}', skipping.`);
405
405
  return;
406
406
  }
407
407
  this._tools.push(tool);
@@ -422,9 +422,7 @@ var CopilotKitCore = class {
422
422
  getTool(params) {
423
423
  const { toolName, agentId } = params;
424
424
  if (agentId) {
425
- const agentTool = this._tools.find(
426
- (tool) => tool.name === toolName && tool.agentId === agentId
427
- );
425
+ const agentTool = this._tools.find((tool) => tool.name === toolName && tool.agentId === agentId);
428
426
  if (agentTool) {
429
427
  return agentTool;
430
428
  }
@@ -452,10 +450,7 @@ var CopilotKitCore = class {
452
450
  /**
453
451
  * Agent connectivity
454
452
  */
455
- async connectAgent({
456
- agent,
457
- agentId
458
- }) {
453
+ async connectAgent({ agent, agentId }) {
459
454
  try {
460
455
  if (agent instanceof import_client2.HttpAgent) {
461
456
  agent.headers = { ...this.headers };
@@ -482,11 +477,7 @@ var CopilotKitCore = class {
482
477
  throw error;
483
478
  }
484
479
  }
485
- async runAgent({
486
- agent,
487
- withMessages,
488
- agentId
489
- }) {
480
+ async runAgent({ agent, withMessages, agentId }) {
490
481
  if (agent instanceof import_client2.HttpAgent) {
491
482
  agent.headers = { ...this.headers };
492
483
  }
@@ -530,9 +521,7 @@ var CopilotKitCore = class {
530
521
  for (const message of newMessages) {
531
522
  if (message.role === "assistant") {
532
523
  for (const toolCall of message.toolCalls || []) {
533
- if (newMessages.findIndex(
534
- (m) => m.role === "tool" && m.toolCallId === toolCall.id
535
- ) === -1) {
524
+ if (newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id) === -1) {
536
525
  const tool = this.getTool({
537
526
  toolName: toolCall.function.name,
538
527
  agentId
@@ -577,10 +566,7 @@ var CopilotKitCore = class {
577
566
  );
578
567
  if (!errorMessage) {
579
568
  try {
580
- const result = await tool.handler(
581
- parsedArgs,
582
- toolCall
583
- );
569
+ const result = await tool.handler(parsedArgs, toolCall);
584
570
  if (result === void 0 || result === null) {
585
571
  toolCallResult = "";
586
572
  } else if (typeof result === "string") {
@@ -624,9 +610,7 @@ var CopilotKitCore = class {
624
610
  }
625
611
  }
626
612
  if (!errorMessage || !isArgumentError) {
627
- const messageIndex = agent.messages.findIndex(
628
- (m) => m.id === message.id
629
- );
613
+ const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
630
614
  const toolMessage = {
631
615
  id: (0, import_shared.randomUUID)(),
632
616
  role: "tool",
@@ -684,10 +668,7 @@ var CopilotKitCore = class {
684
668
  );
685
669
  if (!errorMessage) {
686
670
  try {
687
- const result = await wildcardTool.handler(
688
- wildcardArgs,
689
- toolCall
690
- );
671
+ const result = await wildcardTool.handler(wildcardArgs, toolCall);
691
672
  if (result === void 0 || result === null) {
692
673
  toolCallResult = "";
693
674
  } else if (typeof result === "string") {
@@ -731,9 +712,7 @@ var CopilotKitCore = class {
731
712
  }
732
713
  }
733
714
  if (!errorMessage || !isArgumentError) {
734
- const messageIndex = agent.messages.findIndex(
735
- (m) => m.id === message.id
736
- );
715
+ const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
737
716
  const toolMessage = {
738
717
  id: (0, import_shared.randomUUID)(),
739
718
  role: "tool",
@@ -777,13 +756,9 @@ var CopilotKitCore = class {
777
756
  };
778
757
  return {
779
758
  onRunFailed: async ({ error }) => {
780
- await emitAgentError(
781
- error,
782
- "agent_run_failed_event" /* AGENT_RUN_FAILED_EVENT */,
783
- {
784
- source: "onRunFailed"
785
- }
786
- );
759
+ await emitAgentError(error, "agent_run_failed_event" /* AGENT_RUN_FAILED_EVENT */, {
760
+ source: "onRunFailed"
761
+ });
787
762
  },
788
763
  onRunErrorEvent: async ({ event }) => {
789
764
  const eventError = event?.rawEvent instanceof Error ? event.rawEvent : event?.rawEvent?.error instanceof Error ? event.rawEvent.error : void 0;
@@ -792,15 +767,11 @@ var CopilotKitCore = class {
792
767
  if (event?.code && !rawError.code) {
793
768
  rawError.code = event.code;
794
769
  }
795
- await emitAgentError(
796
- rawError,
797
- "agent_run_error_event" /* AGENT_RUN_ERROR_EVENT */,
798
- {
799
- source: "onRunErrorEvent",
800
- event,
801
- runtimeErrorCode: event?.code
802
- }
803
- );
770
+ await emitAgentError(rawError, "agent_run_error_event" /* AGENT_RUN_ERROR_EVENT */, {
771
+ source: "onRunErrorEvent",
772
+ event,
773
+ runtimeErrorCode: event?.code
774
+ });
804
775
  }
805
776
  };
806
777
  }
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.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;A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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":["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 { AgentDescription, DEFAULT_AGENT_ID, randomUUID, RuntimeInfo, logger } from \"@copilotkitnext/shared\";\nimport { AbstractAgent, AgentSubscriber, Context, HttpAgent, Message, RunAgentResult } 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. For development only - production requires CopilotRuntime. */\n agents__unsafe_dev_only?: 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 private _headers: Record<string, string>;\n private _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__unsafe_dev_only = {},\n tools = [],\n }: CopilotKitCoreConfig) {\n this._headers = headers;\n this._properties = properties;\n this.localAgents = this.assignAgentIds(agents__unsafe_dev_only);\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(agent: AbstractAgent, providedAgentId?: string): 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 ? runtimeUrl.replace(/\\/$/, \"\") : 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 headers(): Readonly<Record<string, string>> {\n return this._headers;\n }\n\n get properties(): Readonly<Record<string, unknown>> {\n return this._properties;\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 = 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 = 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 = 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 = 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 = error instanceof Error ? error.message : JSON.stringify(error);\n logger.warn(`Failed to load runtime info (${this.runtimeUrl}/info): ${message}`);\n const runtimeError = 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__unsafe_dev_only(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__unsafe_dev_only({ 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__unsafe_dev_only(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 === CopilotKitCoreRuntimeConnectionStatus.Disconnected ||\n this.runtimeConnectionStatus === 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>>(tool: FrontendTool<T>) {\n // Check if a tool with the same name and agentId already exists\n const existingToolIndex = this._tools.findIndex((t) => t.name === tool.name && t.agentId === tool.agentId);\n\n if (existingToolIndex !== -1) {\n logger.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || \"global\"}', skipping.`);\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((tool) => tool.name === toolName && tool.agentId === agentId);\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({ agent, agentId }: 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 = 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({ agent, withMessages, agentId }: 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 = 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 (newMessages.findIndex((m) => m.role === \"tool\" && m.toolCallId === toolCall.id) === -1) {\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 = 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, toolCall);\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 = 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((m) => m.id === message.id);\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 = 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(wildcardArgs as any, toolCall);\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 = 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: 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((m) => m.id === message.id);\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(agent: AbstractAgent, agentId?: string): 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(error, CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT, {\n source: \"onRunFailed\",\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\" ? event.rawEvent.error : (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(rawError, CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT, {\n source: \"onRunErrorEvent\",\n event,\n runtimeErrorCode: event?.code,\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,oBAAoF;AACpF,IAAAA,iBAA4F;;;ACD5F,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,KAAK,UAAU,UAAU,KAAK,OAAO;AAAA,MACxC,KAAK,YAAY,KAAK;AAAA,IACxB;AACA,eAAO,wCAAyB,UAAU;AAAA,EAC5C;AACF;;;AD7BA,gCAAgC;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,EAClB;AAAA,EACA;AA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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
@@ -1,12 +1,6 @@
1
1
  // src/core.ts
2
- import {
3
- DEFAULT_AGENT_ID,
4
- randomUUID,
5
- logger
6
- } from "@copilotkitnext/shared";
7
- import {
8
- HttpAgent as HttpAgent2
9
- } from "@ag-ui/client";
2
+ import { DEFAULT_AGENT_ID, randomUUID, logger } from "@copilotkitnext/shared";
3
+ import { HttpAgent as HttpAgent2 } from "@ag-ui/client";
10
4
 
11
5
  // src/agent.ts
12
6
  import {
@@ -52,8 +46,8 @@ var CopilotKitCoreRuntimeConnectionStatus = /* @__PURE__ */ ((CopilotKitCoreRunt
52
46
  return CopilotKitCoreRuntimeConnectionStatus2;
53
47
  })(CopilotKitCoreRuntimeConnectionStatus || {});
54
48
  var CopilotKitCore = class {
55
- headers;
56
- properties;
49
+ _headers;
50
+ _properties;
57
51
  _context = {};
58
52
  _agents = {};
59
53
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -68,12 +62,12 @@ var CopilotKitCore = class {
68
62
  runtimeUrl,
69
63
  headers = {},
70
64
  properties = {},
71
- agents = {},
65
+ agents__unsafe_dev_only = {},
72
66
  tools = []
73
67
  }) {
74
- this.headers = headers;
75
- this.properties = properties;
76
- this.localAgents = this.assignAgentIds(agents);
68
+ this._headers = headers;
69
+ this._properties = properties;
70
+ this.localAgents = this.assignAgentIds(agents__unsafe_dev_only);
77
71
  this.applyHeadersToAgents(this.localAgents);
78
72
  this._agents = this.localAgents;
79
73
  this._tools = tools;
@@ -166,6 +160,12 @@ var CopilotKitCore = class {
166
160
  get runtimeVersion() {
167
161
  return this._runtimeVersion;
168
162
  }
163
+ get headers() {
164
+ return this._headers;
165
+ }
166
+ get properties() {
167
+ return this._properties;
168
+ }
169
169
  get runtimeConnectionStatus() {
170
170
  return this._runtimeConnectionStatus;
171
171
  }
@@ -259,9 +259,7 @@ var CopilotKitCore = class {
259
259
  "Subscriber onAgentsChanged error:"
260
260
  );
261
261
  const message = error instanceof Error ? error.message : JSON.stringify(error);
262
- logger.warn(
263
- `Failed to load runtime info (${this.runtimeUrl}/info): ${message}`
264
- );
262
+ logger.warn(`Failed to load runtime info (${this.runtimeUrl}/info): ${message}`);
265
263
  const runtimeError = error instanceof Error ? error : new Error(String(error));
266
264
  await this.emitError({
267
265
  error: runtimeError,
@@ -276,7 +274,7 @@ var CopilotKitCore = class {
276
274
  * Configuration updates
277
275
  */
278
276
  setHeaders(headers) {
279
- this.headers = headers;
277
+ this._headers = headers;
280
278
  this.applyHeadersToAgents(this._agents);
281
279
  void this.notifySubscribers(
282
280
  (subscriber) => subscriber.onHeadersChanged?.({
@@ -287,7 +285,7 @@ var CopilotKitCore = class {
287
285
  );
288
286
  }
289
287
  setProperties(properties) {
290
- this.properties = properties;
288
+ this._properties = properties;
291
289
  void this.notifySubscribers(
292
290
  (subscriber) => subscriber.onPropertiesChanged?.({
293
291
  copilotkit: this,
@@ -296,7 +294,7 @@ var CopilotKitCore = class {
296
294
  "Subscriber onPropertiesChanged error:"
297
295
  );
298
296
  }
299
- setAgents(agents) {
297
+ setAgents__unsafe_dev_only(agents) {
300
298
  this.localAgents = this.assignAgentIds(agents);
301
299
  this._agents = { ...this.localAgents, ...this.remoteAgents };
302
300
  this.applyHeadersToAgents(this._agents);
@@ -308,7 +306,7 @@ var CopilotKitCore = class {
308
306
  "Subscriber onAgentsChanged error:"
309
307
  );
310
308
  }
311
- addAgent({ id, agent }) {
309
+ addAgent__unsafe_dev_only({ id, agent }) {
312
310
  this.localAgents[id] = agent;
313
311
  if (!agent.agentId) {
314
312
  agent.agentId = id;
@@ -323,7 +321,7 @@ var CopilotKitCore = class {
323
321
  "Subscriber onAgentsChanged error:"
324
322
  );
325
323
  }
326
- removeAgent(id) {
324
+ removeAgent__unsafe_dev_only(id) {
327
325
  delete this.localAgents[id];
328
326
  this._agents = { ...this.localAgents, ...this.remoteAgents };
329
327
  void this.notifySubscribers(
@@ -374,13 +372,9 @@ var CopilotKitCore = class {
374
372
  * Tool management
375
373
  */
376
374
  addTool(tool) {
377
- const existingToolIndex = this._tools.findIndex(
378
- (t) => t.name === tool.name && t.agentId === tool.agentId
379
- );
375
+ const existingToolIndex = this._tools.findIndex((t) => t.name === tool.name && t.agentId === tool.agentId);
380
376
  if (existingToolIndex !== -1) {
381
- logger.warn(
382
- `Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}', skipping.`
383
- );
377
+ logger.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}', skipping.`);
384
378
  return;
385
379
  }
386
380
  this._tools.push(tool);
@@ -401,9 +395,7 @@ var CopilotKitCore = class {
401
395
  getTool(params) {
402
396
  const { toolName, agentId } = params;
403
397
  if (agentId) {
404
- const agentTool = this._tools.find(
405
- (tool) => tool.name === toolName && tool.agentId === agentId
406
- );
398
+ const agentTool = this._tools.find((tool) => tool.name === toolName && tool.agentId === agentId);
407
399
  if (agentTool) {
408
400
  return agentTool;
409
401
  }
@@ -431,10 +423,7 @@ var CopilotKitCore = class {
431
423
  /**
432
424
  * Agent connectivity
433
425
  */
434
- async connectAgent({
435
- agent,
436
- agentId
437
- }) {
426
+ async connectAgent({ agent, agentId }) {
438
427
  try {
439
428
  if (agent instanceof HttpAgent2) {
440
429
  agent.headers = { ...this.headers };
@@ -461,11 +450,7 @@ var CopilotKitCore = class {
461
450
  throw error;
462
451
  }
463
452
  }
464
- async runAgent({
465
- agent,
466
- withMessages,
467
- agentId
468
- }) {
453
+ async runAgent({ agent, withMessages, agentId }) {
469
454
  if (agent instanceof HttpAgent2) {
470
455
  agent.headers = { ...this.headers };
471
456
  }
@@ -509,9 +494,7 @@ var CopilotKitCore = class {
509
494
  for (const message of newMessages) {
510
495
  if (message.role === "assistant") {
511
496
  for (const toolCall of message.toolCalls || []) {
512
- if (newMessages.findIndex(
513
- (m) => m.role === "tool" && m.toolCallId === toolCall.id
514
- ) === -1) {
497
+ if (newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id) === -1) {
515
498
  const tool = this.getTool({
516
499
  toolName: toolCall.function.name,
517
500
  agentId
@@ -556,10 +539,7 @@ var CopilotKitCore = class {
556
539
  );
557
540
  if (!errorMessage) {
558
541
  try {
559
- const result = await tool.handler(
560
- parsedArgs,
561
- toolCall
562
- );
542
+ const result = await tool.handler(parsedArgs, toolCall);
563
543
  if (result === void 0 || result === null) {
564
544
  toolCallResult = "";
565
545
  } else if (typeof result === "string") {
@@ -603,9 +583,7 @@ var CopilotKitCore = class {
603
583
  }
604
584
  }
605
585
  if (!errorMessage || !isArgumentError) {
606
- const messageIndex = agent.messages.findIndex(
607
- (m) => m.id === message.id
608
- );
586
+ const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
609
587
  const toolMessage = {
610
588
  id: randomUUID(),
611
589
  role: "tool",
@@ -663,10 +641,7 @@ var CopilotKitCore = class {
663
641
  );
664
642
  if (!errorMessage) {
665
643
  try {
666
- const result = await wildcardTool.handler(
667
- wildcardArgs,
668
- toolCall
669
- );
644
+ const result = await wildcardTool.handler(wildcardArgs, toolCall);
670
645
  if (result === void 0 || result === null) {
671
646
  toolCallResult = "";
672
647
  } else if (typeof result === "string") {
@@ -710,9 +685,7 @@ var CopilotKitCore = class {
710
685
  }
711
686
  }
712
687
  if (!errorMessage || !isArgumentError) {
713
- const messageIndex = agent.messages.findIndex(
714
- (m) => m.id === message.id
715
- );
688
+ const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
716
689
  const toolMessage = {
717
690
  id: randomUUID(),
718
691
  role: "tool",
@@ -756,13 +729,9 @@ var CopilotKitCore = class {
756
729
  };
757
730
  return {
758
731
  onRunFailed: async ({ error }) => {
759
- await emitAgentError(
760
- error,
761
- "agent_run_failed_event" /* AGENT_RUN_FAILED_EVENT */,
762
- {
763
- source: "onRunFailed"
764
- }
765
- );
732
+ await emitAgentError(error, "agent_run_failed_event" /* AGENT_RUN_FAILED_EVENT */, {
733
+ source: "onRunFailed"
734
+ });
766
735
  },
767
736
  onRunErrorEvent: async ({ event }) => {
768
737
  const eventError = event?.rawEvent instanceof Error ? event.rawEvent : event?.rawEvent?.error instanceof Error ? event.rawEvent.error : void 0;
@@ -771,15 +740,11 @@ var CopilotKitCore = class {
771
740
  if (event?.code && !rawError.code) {
772
741
  rawError.code = event.code;
773
742
  }
774
- await emitAgentError(
775
- rawError,
776
- "agent_run_error_event" /* AGENT_RUN_ERROR_EVENT */,
777
- {
778
- source: "onRunErrorEvent",
779
- event,
780
- runtimeErrorCode: event?.code
781
- }
782
- );
743
+ await emitAgentError(rawError, "agent_run_error_event" /* AGENT_RUN_ERROR_EVENT */, {
744
+ source: "onRunErrorEvent",
745
+ event,
746
+ runtimeErrorCode: event?.code
747
+ });
783
748
  }
784
749
  };
785
750
  }
@@ -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.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;AAA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}
1
+ {"version":3,"sources":["../src/core.ts","../src/agent.ts","../src/types.ts","../src/utils/markdown.ts"],"sourcesContent":["import { AgentDescription, DEFAULT_AGENT_ID, randomUUID, RuntimeInfo, logger } from \"@copilotkitnext/shared\";\nimport { AbstractAgent, AgentSubscriber, Context, HttpAgent, Message, RunAgentResult } 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. For development only - production requires CopilotRuntime. */\n agents__unsafe_dev_only?: 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 private _headers: Record<string, string>;\n private _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__unsafe_dev_only = {},\n tools = [],\n }: CopilotKitCoreConfig) {\n this._headers = headers;\n this._properties = properties;\n this.localAgents = this.assignAgentIds(agents__unsafe_dev_only);\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(agent: AbstractAgent, providedAgentId?: string): 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 ? runtimeUrl.replace(/\\/$/, \"\") : 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 headers(): Readonly<Record<string, string>> {\n return this._headers;\n }\n\n get properties(): Readonly<Record<string, unknown>> {\n return this._properties;\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 = 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 = 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 = 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 = 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 = error instanceof Error ? error.message : JSON.stringify(error);\n logger.warn(`Failed to load runtime info (${this.runtimeUrl}/info): ${message}`);\n const runtimeError = 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__unsafe_dev_only(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__unsafe_dev_only({ 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__unsafe_dev_only(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 === CopilotKitCoreRuntimeConnectionStatus.Disconnected ||\n this.runtimeConnectionStatus === 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>>(tool: FrontendTool<T>) {\n // Check if a tool with the same name and agentId already exists\n const existingToolIndex = this._tools.findIndex((t) => t.name === tool.name && t.agentId === tool.agentId);\n\n if (existingToolIndex !== -1) {\n logger.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || \"global\"}', skipping.`);\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((tool) => tool.name === toolName && tool.agentId === agentId);\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({ agent, agentId }: 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 = 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({ agent, withMessages, agentId }: 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 = 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 (newMessages.findIndex((m) => m.role === \"tool\" && m.toolCallId === toolCall.id) === -1) {\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 = 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, toolCall);\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 = 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((m) => m.id === message.id);\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 = 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(wildcardArgs as any, toolCall);\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 = 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: 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((m) => m.id === message.id);\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(agent: AbstractAgent, agentId?: string): 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(error, CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT, {\n source: \"onRunFailed\",\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\" ? event.rawEvent.error : (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(rawError, CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT, {\n source: \"onRunErrorEvent\",\n event,\n runtimeErrorCode: event?.code,\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,SAA2B,kBAAkB,YAAyB,cAAc;AACpF,SAAkD,aAAAA,kBAA0C;;;ACD5F;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;;;AD7BA,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,g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,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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copilotkitnext/core",
3
- "version": "0.0.11",
3
+ "version": "0.0.12",
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/typescript-config": "0.0.0",
25
- "@copilotkitnext/eslint-config": "0.0.0"
24
+ "@copilotkitnext/eslint-config": "0.0.0",
25
+ "@copilotkitnext/typescript-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.11"
32
+ "@copilotkitnext/shared": "0.0.12"
33
33
  },
34
34
  "engines": {
35
35
  "node": ">=18"