@copilotkit/runtime 1.9.2-next.9 → 1.9.3-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/dist/{chunk-Z5GYTKMD.mjs → chunk-EK5RTZVJ.mjs} +225 -149
  3. package/dist/chunk-EK5RTZVJ.mjs.map +1 -0
  4. package/dist/{chunk-SMDVD4VG.mjs → chunk-KCYFFRJY.mjs} +2 -2
  5. package/dist/{chunk-4JBKY7XT.mjs → chunk-QLLV2QVK.mjs} +48 -28
  6. package/dist/chunk-QLLV2QVK.mjs.map +1 -0
  7. package/dist/{chunk-5YGKE5SN.mjs → chunk-R5D7D7YN.mjs} +2 -2
  8. package/dist/{chunk-UUXRYAB4.mjs → chunk-RCCT2GOF.mjs} +2 -2
  9. package/dist/{chunk-ALZ5H3VD.mjs → chunk-YGS5B7PN.mjs} +2 -2
  10. package/dist/{groq-adapter-172a2ca4.d.ts → groq-adapter-742818f2.d.ts} +5 -1
  11. package/dist/index.d.ts +3 -3
  12. package/dist/index.js +267 -171
  13. package/dist/index.js.map +1 -1
  14. package/dist/index.mjs +9 -9
  15. package/dist/{langserve-fc5cac89.d.ts → langserve-3e8d0e06.d.ts} +6 -0
  16. package/dist/lib/index.d.ts +155 -5
  17. package/dist/lib/index.js +221 -168
  18. package/dist/lib/index.js.map +1 -1
  19. package/dist/lib/index.mjs +9 -9
  20. package/dist/lib/integrations/index.d.ts +3 -3
  21. package/dist/lib/integrations/index.js +11 -11
  22. package/dist/lib/integrations/index.js.map +1 -1
  23. package/dist/lib/integrations/index.mjs +8 -8
  24. package/dist/lib/integrations/nest/index.d.ts +2 -2
  25. package/dist/lib/integrations/nest/index.js +11 -11
  26. package/dist/lib/integrations/nest/index.js.map +1 -1
  27. package/dist/lib/integrations/nest/index.mjs +4 -4
  28. package/dist/lib/integrations/node-express/index.d.ts +2 -2
  29. package/dist/lib/integrations/node-express/index.js +11 -11
  30. package/dist/lib/integrations/node-express/index.js.map +1 -1
  31. package/dist/lib/integrations/node-express/index.mjs +4 -4
  32. package/dist/lib/integrations/node-http/index.d.ts +2 -2
  33. package/dist/lib/integrations/node-http/index.js +11 -11
  34. package/dist/lib/integrations/node-http/index.js.map +1 -1
  35. package/dist/lib/integrations/node-http/index.mjs +3 -3
  36. package/dist/service-adapters/index.d.ts +5 -4
  37. package/dist/service-adapters/index.js +47 -27
  38. package/dist/service-adapters/index.js.map +1 -1
  39. package/dist/service-adapters/index.mjs +1 -1
  40. package/dist/{shared-bd953ebf.d.ts → shared-96b46379.d.ts} +16 -18
  41. package/package.json +11 -11
  42. package/src/graphql/resolvers/copilot.resolver.ts +1 -2
  43. package/src/lib/runtime/__tests__/{copilot-runtime-trace.test.ts → copilot-runtime-error.test.ts} +27 -27
  44. package/src/lib/runtime/__tests__/mcp-tools-utils.test.ts +464 -0
  45. package/src/lib/runtime/agui-action.ts +9 -3
  46. package/src/lib/runtime/copilot-runtime.ts +112 -124
  47. package/src/lib/runtime/mcp-tools-utils.ts +84 -18
  48. package/src/lib/runtime/remote-actions.ts +6 -0
  49. package/src/service-adapters/anthropic/anthropic-adapter.ts +64 -4
  50. package/src/service-adapters/anthropic/utils.ts +3 -8
  51. package/src/service-adapters/events.ts +40 -1
  52. package/src/service-adapters/google/google-genai-adapter.ts +5 -0
  53. package/src/service-adapters/openai/openai-adapter.ts +0 -14
  54. package/tests/service-adapters/anthropic/anthropic-adapter.test.ts +172 -387
  55. package/dist/chunk-4JBKY7XT.mjs.map +0 -1
  56. package/dist/chunk-Z5GYTKMD.mjs.map +0 -1
  57. /package/dist/{chunk-SMDVD4VG.mjs.map → chunk-KCYFFRJY.mjs.map} +0 -0
  58. /package/dist/{chunk-5YGKE5SN.mjs.map → chunk-R5D7D7YN.mjs.map} +0 -0
  59. /package/dist/{chunk-UUXRYAB4.mjs.map → chunk-RCCT2GOF.mjs.map} +0 -0
  60. /package/dist/{chunk-ALZ5H3VD.mjs.map → chunk-YGS5B7PN.mjs.map} +0 -0
package/dist/lib/index.js CHANGED
@@ -44,7 +44,7 @@ var require_package = __commonJS({
44
44
  publishConfig: {
45
45
  access: "public"
46
46
  },
47
- version: "1.9.2-next.9",
47
+ version: "1.9.3-next.0",
48
48
  sideEffects: false,
49
49
  main: "./dist/index.js",
50
50
  module: "./dist/index.mjs",
@@ -82,11 +82,11 @@ var require_package = __commonJS({
82
82
  "zod-to-json-schema": "^3.23.5"
83
83
  },
84
84
  dependencies: {
85
- "@ag-ui/client": "0.0.28",
86
- "@ag-ui/core": "0.0.28",
87
- "@ag-ui/encoder": "0.0.28",
88
- "@ag-ui/langgraph": "0.0.4",
89
- "@ag-ui/proto": "0.0.28",
85
+ "@ag-ui/client": "0.0.35",
86
+ "@ag-ui/core": "0.0.35",
87
+ "@ag-ui/encoder": "0.0.35",
88
+ "@ag-ui/langgraph": "0.0.7",
89
+ "@ag-ui/proto": "0.0.35",
90
90
  "@anthropic-ai/sdk": "^0.27.3",
91
91
  "@copilotkit/shared": "workspace:*",
92
92
  "@graphql-yoga/plugin-defer-stream": "^3.3.1",
@@ -114,10 +114,10 @@ var require_package = __commonJS({
114
114
  zod: "^3.23.3"
115
115
  },
116
116
  peerDependencies: {
117
- "@ag-ui/client": ">=0.0.28",
118
- "@ag-ui/core": ">=0.0.28",
119
- "@ag-ui/encoder": ">=0.0.28",
120
- "@ag-ui/proto": ">=0.0.28"
117
+ "@ag-ui/client": ">=0.0.34",
118
+ "@ag-ui/core": ">=0.0.34",
119
+ "@ag-ui/encoder": ">=0.0.34",
120
+ "@ag-ui/proto": ">=0.0.34"
121
121
  },
122
122
  keywords: [
123
123
  "copilotkit",
@@ -420,7 +420,6 @@ var OpenAIAdapter = class {
420
420
  const { threadId: threadIdFromRequest, model = this.model, messages, actions, eventSource, forwardedParameters } = request;
421
421
  const tools = actions.map(convertActionInputToOpenAITool);
422
422
  const threadId = threadIdFromRequest ?? (0, import_shared3.randomUUID)();
423
- console.log("messages", messages);
424
423
  const validToolUseIds = /* @__PURE__ */ new Set();
425
424
  for (const message of messages) {
426
425
  if (message.isActionExecutionMessage()) {
@@ -450,29 +449,6 @@ var OpenAIAdapter = class {
450
449
  }
451
450
  };
452
451
  }
453
- console.log("INPUT", {
454
- model,
455
- stream: true,
456
- messages: openaiMessages,
457
- ...tools.length > 0 && {
458
- tools
459
- },
460
- ...(forwardedParameters == null ? void 0 : forwardedParameters.maxTokens) && {
461
- max_tokens: forwardedParameters.maxTokens
462
- },
463
- ...(forwardedParameters == null ? void 0 : forwardedParameters.stop) && {
464
- stop: forwardedParameters.stop
465
- },
466
- ...toolChoice && {
467
- tool_choice: toolChoice
468
- },
469
- ...this.disableParallelToolCalls && {
470
- parallel_tool_calls: false
471
- },
472
- ...(forwardedParameters == null ? void 0 : forwardedParameters.temperature) && {
473
- temperature: forwardedParameters.temperature
474
- }
475
- });
476
452
  try {
477
453
  const stream = this.openai.beta.chat.completions.stream({
478
454
  model,
@@ -854,6 +830,7 @@ var GoogleGenerativeAIAdapter = class extends LangChainAdapter {
854
830
  return message.content && String(message.content).trim().length > 0 || message.tool_calls && message.tool_calls.length > 0;
855
831
  });
856
832
  const model = new import_google_gauth.ChatGoogle({
833
+ apiKey: (options == null ? void 0 : options.apiKey) ?? process.env.GOOGLE_API_KEY,
857
834
  modelName: (options == null ? void 0 : options.model) ?? "gemini-1.5-pro",
858
835
  apiVersion: "v1beta"
859
836
  }).bindTools(tools);
@@ -4172,7 +4149,7 @@ function extractParametersFromSchema(toolOrSchema) {
4172
4149
  var _a;
4173
4150
  const parameters = [];
4174
4151
  const schema = "schema" in (toolOrSchema || {}) ? toolOrSchema.schema : toolOrSchema;
4175
- const toolParameters = (schema == null ? void 0 : schema.parameters) || ((_a = schema == null ? void 0 : schema.parameters) == null ? void 0 : _a.jsonSchema);
4152
+ const toolParameters = ((_a = schema == null ? void 0 : schema.parameters) == null ? void 0 : _a.jsonSchema) || (schema == null ? void 0 : schema.parameters);
4176
4153
  const properties = toolParameters == null ? void 0 : toolParameters.properties;
4177
4154
  const requiredParams = new Set((toolParameters == null ? void 0 : toolParameters.required) || []);
4178
4155
  if (!properties) {
@@ -4181,12 +4158,29 @@ function extractParametersFromSchema(toolOrSchema) {
4181
4158
  for (const paramName in properties) {
4182
4159
  if (Object.prototype.hasOwnProperty.call(properties, paramName)) {
4183
4160
  const paramDef = properties[paramName];
4161
+ let type = paramDef.type || "string";
4162
+ let description = paramDef.description || "";
4163
+ if (type === "array" && paramDef.items) {
4164
+ const itemType = paramDef.items.type || "object";
4165
+ if (itemType === "object" && paramDef.items.properties) {
4166
+ const itemProperties = Object.keys(paramDef.items.properties).join(", ");
4167
+ description = description + (description ? " " : "") + `Array of objects with properties: ${itemProperties}`;
4168
+ } else {
4169
+ type = `array<${itemType}>`;
4170
+ }
4171
+ }
4172
+ if (paramDef.enum && Array.isArray(paramDef.enum)) {
4173
+ const enumValues = paramDef.enum.join(" | ");
4174
+ description = description + (description ? " " : "") + `Allowed values: ${enumValues}`;
4175
+ }
4176
+ if (type === "object" && paramDef.properties) {
4177
+ const objectProperties = Object.keys(paramDef.properties).join(", ");
4178
+ description = description + (description ? " " : "") + `Object with properties: ${objectProperties}`;
4179
+ }
4184
4180
  parameters.push({
4185
4181
  name: paramName,
4186
- // Infer type, default to string. MCP schemas might have more complex types.
4187
- // This might need refinement based on common MCP schema practices.
4188
- type: paramDef.type || "string",
4189
- description: paramDef.description,
4182
+ type,
4183
+ description,
4190
4184
  required: requiredParams.has(paramName)
4191
4185
  });
4192
4186
  }
@@ -4200,9 +4194,7 @@ function convertMCPToolsToActions(mcpTools, mcpEndpoint) {
4200
4194
  const parameters = extractParametersFromSchema(tool);
4201
4195
  const handler = /* @__PURE__ */ __name(async (params) => {
4202
4196
  try {
4203
- const result = await tool.execute({
4204
- params
4205
- });
4197
+ const result = await tool.execute(params);
4206
4198
  return typeof result === "string" ? result : JSON.stringify(result);
4207
4199
  } catch (error) {
4208
4200
  console.error(`Error executing MCP tool '${toolName}' from endpoint ${mcpEndpoint}:`, error);
@@ -4228,17 +4220,38 @@ function generateMcpToolInstructions(toolsMap) {
4228
4220
  }
4229
4221
  const toolEntries = Object.entries(toolsMap);
4230
4222
  const toolsDoc = toolEntries.map(([name, tool]) => {
4223
+ var _a;
4231
4224
  let paramsDoc = " No parameters required";
4232
4225
  try {
4233
4226
  if (tool.schema && typeof tool.schema === "object") {
4234
4227
  const schema = tool.schema;
4235
- if (schema.properties) {
4236
- const requiredParams = schema.required || [];
4237
- const paramsList = Object.entries(schema.properties).map(([paramName, propSchema]) => {
4228
+ const toolParameters = ((_a = schema.parameters) == null ? void 0 : _a.jsonSchema) || schema.parameters;
4229
+ const properties = (toolParameters == null ? void 0 : toolParameters.properties) || schema.properties;
4230
+ const requiredParams = (toolParameters == null ? void 0 : toolParameters.required) || schema.required || [];
4231
+ if (properties) {
4232
+ const paramsList = Object.entries(properties).map(([paramName, propSchema]) => {
4238
4233
  const propDetails = propSchema;
4239
4234
  const requiredMark = requiredParams.includes(paramName) ? "*" : "";
4240
- const typeInfo = propDetails.type || "any";
4241
- const description = propDetails.description ? ` - ${propDetails.description}` : "";
4235
+ let typeInfo = propDetails.type || "any";
4236
+ let description = propDetails.description ? ` - ${propDetails.description}` : "";
4237
+ if (typeInfo === "array" && propDetails.items) {
4238
+ const itemType = propDetails.items.type || "object";
4239
+ if (itemType === "object" && propDetails.items.properties) {
4240
+ const itemProps = Object.keys(propDetails.items.properties).join(", ");
4241
+ typeInfo = `array<object>`;
4242
+ description = description + (description ? " " : " - ") + `Array of objects with properties: ${itemProps}`;
4243
+ } else {
4244
+ typeInfo = `array<${itemType}>`;
4245
+ }
4246
+ }
4247
+ if (propDetails.enum && Array.isArray(propDetails.enum)) {
4248
+ const enumValues = propDetails.enum.join(" | ");
4249
+ description = description + (description ? " " : " - ") + `Allowed values: ${enumValues}`;
4250
+ }
4251
+ if (typeInfo === "object" && propDetails.properties) {
4252
+ const objectProps = Object.keys(propDetails.properties).join(", ");
4253
+ description = description + (description ? " " : " - ") + `Object with properties: ${objectProps}`;
4254
+ }
4242
4255
  return ` - ${paramName}${requiredMark} (${typeInfo})${description}`;
4243
4256
  });
4244
4257
  if (paramsList.length > 0) {
@@ -4259,8 +4272,11 @@ ${toolsDoc}
4259
4272
  When using these tools:
4260
4273
  1. Only provide valid parameters according to their type requirements
4261
4274
  2. Required parameters are marked with *
4262
- 3. Format API calls correctly with the expected parameter structure
4263
- 4. Always check tool responses to determine your next action`;
4275
+ 3. For array parameters, provide data in the correct array format
4276
+ 4. For object parameters, include all required nested properties
4277
+ 5. For enum parameters, use only the allowed values listed
4278
+ 6. Format API calls correctly with the expected parameter structure
4279
+ 7. Always check tool responses to determine your next action`;
4264
4280
  }
4265
4281
  __name(generateMcpToolInstructions, "generateMcpToolInstructions");
4266
4282
 
@@ -4275,8 +4291,8 @@ var CopilotRuntime = class {
4275
4291
  delegateAgentProcessingToServiceAdapter;
4276
4292
  observability;
4277
4293
  availableAgents;
4278
- onTrace;
4279
- hasWarnedAboutTracing = false;
4294
+ onError;
4295
+ hasWarnedAboutError = false;
4280
4296
  // +++ MCP Properties +++
4281
4297
  mcpServersConfig;
4282
4298
  mcpActionCache = /* @__PURE__ */ new Map();
@@ -4302,7 +4318,7 @@ var CopilotRuntime = class {
4302
4318
  this.delegateAgentProcessingToServiceAdapter = (params == null ? void 0 : params.delegateAgentProcessingToServiceAdapter) || false;
4303
4319
  this.observability = params == null ? void 0 : params.observability_c;
4304
4320
  this.agents = (params == null ? void 0 : params.agents) ?? {};
4305
- this.onTrace = params == null ? void 0 : params.onTrace;
4321
+ this.onError = params == null ? void 0 : params.onError;
4306
4322
  this.mcpServersConfig = params == null ? void 0 : params.mcpServers;
4307
4323
  this.createMCPClientImpl = params == null ? void 0 : params.createMCPClient;
4308
4324
  if (this.mcpServersConfig && this.mcpServersConfig.length > 0 && !this.createMCPClientImpl) {
@@ -4347,7 +4363,7 @@ var CopilotRuntime = class {
4347
4363
  if (!mcpToolInstructions) {
4348
4364
  return messages;
4349
4365
  }
4350
- const instructions = "You have access to the following tools provided by external Model Context Protocol (MCP) servers:\n" + mcpToolInstructions + "\nUse them when appropriate to fulfill the user's request.";
4366
+ const instructions = mcpToolInstructions + "\nUse them when appropriate to fulfill the user's request.";
4351
4367
  const systemMessageIndex = messages.findIndex((msg) => {
4352
4368
  var _a;
4353
4369
  return ((_a = msg.textMessage) == null ? void 0 : _a.role) === "system";
@@ -4378,30 +4394,30 @@ var CopilotRuntime = class {
4378
4394
  async processRuntimeRequest(request) {
4379
4395
  var _a, _b, _c, _d, _e;
4380
4396
  const { serviceAdapter, messages: rawMessages, actions: clientSideActionsInput, threadId, runId, outputMessagesPromise, graphqlContext, forwardedParameters, url, extensions, agentSession, agentStates, publicApiKey } = request;
4381
- const eventSource = new RuntimeEventSource();
4382
- const requestStartTime = Date.now();
4383
- const streamedChunks = [];
4384
- await this.trace("request", {
4385
- threadId,
4386
- runId,
4387
- source: "runtime",
4388
- request: {
4389
- operation: "processRuntimeRequest",
4390
- method: "POST",
4391
- url,
4392
- startTime: requestStartTime
4393
- },
4394
- agent: agentSession ? {
4395
- name: agentSession.agentName
4396
- } : void 0,
4397
- messages: {
4398
- input: rawMessages,
4399
- messageCount: rawMessages.length
4397
+ const eventSource = new RuntimeEventSource({
4398
+ errorHandler: async (error, context) => {
4399
+ await this.error("error", context, error, publicApiKey);
4400
4400
  },
4401
- technical: {
4402
- environment: process.env.NODE_ENV
4401
+ errorContext: {
4402
+ threadId,
4403
+ runId,
4404
+ source: "runtime",
4405
+ request: {
4406
+ operation: "processRuntimeRequest",
4407
+ method: "POST",
4408
+ url,
4409
+ startTime: Date.now()
4410
+ },
4411
+ agent: agentSession ? {
4412
+ name: agentSession.agentName
4413
+ } : void 0,
4414
+ technical: {
4415
+ environment: process.env.NODE_ENV
4416
+ }
4403
4417
  }
4404
- }, void 0, publicApiKey);
4418
+ });
4419
+ const requestStartTime = Date.now();
4420
+ const streamedChunks = [];
4405
4421
  try {
4406
4422
  if (Object.keys(this.agents).length && (agentSession == null ? void 0 : agentSession.agentName) && !this.delegateAgentProcessingToServiceAdapter) {
4407
4423
  this.agents = {
@@ -4577,7 +4593,7 @@ please use an LLM adapter instead.`
4577
4593
  } else {
4578
4594
  structuredError = (0, import_shared15.ensureStructuredError)(error, (err) => this.convertStreamingErrorToStructured(err));
4579
4595
  }
4580
- await this.trace("error", {
4596
+ await this.error("error", {
4581
4597
  threadId,
4582
4598
  runId,
4583
4599
  source: "runtime",
@@ -4603,10 +4619,8 @@ please use an LLM adapter instead.`
4603
4619
  }
4604
4620
  }
4605
4621
  async getAllAgents(graphqlContext) {
4606
- const [agentsWithEndpoints, aguiAgents] = await Promise.all([
4607
- this.discoverAgentsFromEndpoints(graphqlContext),
4608
- this.discoverAgentsFromAgui()
4609
- ]);
4622
+ const agentsWithEndpoints = await this.discoverAgentsFromEndpoints(graphqlContext);
4623
+ const aguiAgents = this.discoverAgentsFromAgui();
4610
4624
  this.availableAgents = [
4611
4625
  ...agentsWithEndpoints,
4612
4626
  ...aguiAgents
@@ -4706,40 +4720,15 @@ please use an LLM adapter instead.`
4706
4720
  }, Promise.resolve([]));
4707
4721
  return agents;
4708
4722
  }
4709
- async discoverAgentsFromAgui() {
4710
- const agents = Object.values(this.agents ?? []).reduce(async (acc, agent) => {
4711
- const agents2 = await acc;
4712
- const client = agent.client;
4713
- let data = [];
4714
- try {
4715
- data = await client.assistants.search();
4716
- if (data && "detail" in data && data.detail.toLowerCase() === "not found") {
4717
- throw new import_shared15.CopilotKitAgentDiscoveryError({
4718
- availableAgents: this.availableAgents
4719
- });
4720
- }
4721
- } catch (e) {
4722
- throw new import_shared15.CopilotKitMisuseError({
4723
- message: `
4724
- Failed to find or contact agent ${agent.graphId}.
4725
- Make sure the LangGraph API is running and the agent is defined in langgraph.json
4726
-
4727
- See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
4728
- });
4729
- }
4730
- const endpointAgents = data.map((entry) => ({
4731
- name: entry.graph_id,
4732
- id: entry.assistant_id,
4733
- description: ""
4734
- }));
4735
- return [
4736
- ...agents2,
4737
- ...endpointAgents
4738
- ];
4739
- }, Promise.resolve([]));
4740
- return agents;
4723
+ discoverAgentsFromAgui() {
4724
+ return Object.entries(this.agents ?? []).map(([key, agent]) => ({
4725
+ name: agent.agentName ?? key,
4726
+ id: agent.agentId ?? key,
4727
+ description: agent.description ?? ""
4728
+ }));
4741
4729
  }
4742
4730
  async loadAgentState(graphqlContext, threadId, agentName) {
4731
+ var _a;
4743
4732
  const agents = await this.getAllAgents(graphqlContext);
4744
4733
  const agent = agents.find((agent2) => agent2.name === agentName);
4745
4734
  if (!agent) {
@@ -4799,33 +4788,38 @@ please use an LLM adapter instead.`
4799
4788
  const propertyHeaders = graphqlContext.properties.authorization ? {
4800
4789
  authorization: `Bearer ${graphqlContext.properties.authorization}`
4801
4790
  } : null;
4802
- let client;
4803
- if ("endpoint" in agent && agent.endpoint.type === EndpointType.LangGraphPlatform) {
4804
- client = new import_langgraph_sdk2.Client({
4805
- apiUrl: agent.endpoint.deploymentUrl,
4806
- apiKey: agent.endpoint.langsmithApiKey,
4807
- defaultHeaders: {
4808
- ...propertyHeaders
4809
- }
4810
- });
4811
- } else {
4812
- const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name];
4813
- if (!aguiAgent) {
4814
- throw new Error(`Agent: ${agent.name} could not be resolved`);
4815
- }
4816
- client = aguiAgent.client;
4817
- }
4818
4791
  let state = {};
4819
4792
  try {
4820
- state = (await client.threads.getState(threadId)).values;
4793
+ let client;
4794
+ if ("endpoint" in agent && agent.endpoint.type === EndpointType.LangGraphPlatform) {
4795
+ client = new import_langgraph_sdk2.Client({
4796
+ apiUrl: agent.endpoint.deploymentUrl,
4797
+ apiKey: agent.endpoint.langsmithApiKey,
4798
+ defaultHeaders: {
4799
+ ...propertyHeaders
4800
+ }
4801
+ });
4802
+ } else {
4803
+ const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name];
4804
+ if (!aguiAgent) {
4805
+ throw new Error(`Agent: ${agent.name} could not be resolved`);
4806
+ }
4807
+ client = aguiAgent.client ?? null;
4808
+ }
4809
+ state = client ? (await client.threads.getState(threadId)).values : {};
4821
4810
  } catch (error) {
4822
4811
  const errorMessage = error instanceof Error ? error.message : String(error);
4823
- console.debug(`Agent '${agentName}' configuration issue: ${errorMessage}`);
4824
- throw new import_shared15.ResolvedCopilotKitError({
4825
- status: 400,
4826
- message: `Agent '${agentName}' failed to execute: ${errorMessage}`,
4827
- code: import_shared15.CopilotKitErrorCode.CONFIGURATION_ERROR
4828
- });
4812
+ const errorStatus = ((_a = error == null ? void 0 : error.response) == null ? void 0 : _a.status) || (error == null ? void 0 : error.status);
4813
+ if (errorStatus === 404) {
4814
+ state = {};
4815
+ } else {
4816
+ console.debug(`Agent '${agentName}' configuration issue: ${errorMessage}`);
4817
+ throw new import_shared15.ResolvedCopilotKitError({
4818
+ status: 400,
4819
+ message: `Agent '${agentName}' failed to execute: ${errorMessage}`,
4820
+ code: import_shared15.CopilotKitErrorCode.CONFIGURATION_ERROR
4821
+ });
4822
+ }
4829
4823
  }
4830
4824
  if (Object.keys(state).length === 0) {
4831
4825
  return {
@@ -4853,7 +4847,7 @@ please use an LLM adapter instead.`
4853
4847
  const requestStartTime = Date.now();
4854
4848
  const streamedChunks = [];
4855
4849
  const threadId = threadIdFromRequest ?? agentSession.threadId;
4856
- await this.trace("agent_state", {
4850
+ await this.error("agent_state", {
4857
4851
  threadId,
4858
4852
  source: "agent",
4859
4853
  request: {
@@ -4921,7 +4915,27 @@ please use an LLM adapter instead.`
4921
4915
  properties: graphqlContext.properties
4922
4916
  }));
4923
4917
  try {
4924
- const eventSource = new RuntimeEventSource();
4918
+ const eventSource = new RuntimeEventSource({
4919
+ errorHandler: async (error, context) => {
4920
+ await this.error("error", context, error, publicApiKey);
4921
+ },
4922
+ errorContext: {
4923
+ threadId,
4924
+ source: "agent",
4925
+ request: {
4926
+ operation: "processAgentRequest",
4927
+ method: "POST",
4928
+ startTime: requestStartTime
4929
+ },
4930
+ agent: {
4931
+ name: agentName,
4932
+ nodeName
4933
+ },
4934
+ technical: {
4935
+ environment: process.env.NODE_ENV
4936
+ }
4937
+ }
4938
+ });
4925
4939
  const stream = await currentAgent.remoteAgentHandler({
4926
4940
  name: agentName,
4927
4941
  threadId,
@@ -4989,7 +5003,7 @@ please use an LLM adapter instead.`
4989
5003
  }
4990
5004
  }
4991
5005
  const structuredError = (0, import_shared15.ensureStructuredError)(err, (error) => this.convertStreamingErrorToStructured(error));
4992
- await this.trace("error", {
5006
+ await this.error("error", {
4993
5007
  threadId,
4994
5008
  source: "agent",
4995
5009
  request: {
@@ -5078,7 +5092,7 @@ please use an LLM adapter instead.`
5078
5092
  }
5079
5093
  }
5080
5094
  const structuredError = (0, import_shared15.ensureStructuredError)(error, (err) => this.convertStreamingErrorToStructured(err));
5081
- await this.trace("error", {
5095
+ await this.error("error", {
5082
5096
  threadId,
5083
5097
  source: "agent",
5084
5098
  request: {
@@ -5104,7 +5118,7 @@ please use an LLM adapter instead.`
5104
5118
  }
5105
5119
  }
5106
5120
  async getServerSideActions(request) {
5107
- var _a, _b;
5121
+ var _a, _b, _c;
5108
5122
  const { graphqlContext, messages: rawMessages, agentStates, url } = request;
5109
5123
  const inputMessages = convertGqlInputToMessages(rawMessages);
5110
5124
  const langserveFunctions = [];
@@ -5127,7 +5141,8 @@ please use an LLM adapter instead.`
5127
5141
  agentStates,
5128
5142
  frontendUrl: url,
5129
5143
  agents: this.agents,
5130
- metaEvents: request.metaEvents
5144
+ metaEvents: request.metaEvents,
5145
+ nodeName: (_a = request.agentSession) == null ? void 0 : _a.nodeName
5131
5146
  });
5132
5147
  const configuredActions = typeof this.actions === "function" ? this.actions({
5133
5148
  properties: graphqlContext.properties,
@@ -5136,7 +5151,7 @@ please use an LLM adapter instead.`
5136
5151
  const requestSpecificMCPActions = [];
5137
5152
  if (this.createMCPClientImpl) {
5138
5153
  const baseEndpoints = this.mcpServersConfig || [];
5139
- const requestEndpoints = ((_a = graphqlContext.properties) == null ? void 0 : _a.mcpServers) || ((_b = graphqlContext.properties) == null ? void 0 : _b.mcpEndpoints) || [];
5154
+ const requestEndpoints = ((_b = graphqlContext.properties) == null ? void 0 : _b.mcpServers) || ((_c = graphqlContext.properties) == null ? void 0 : _c.mcpEndpoints) || [];
5140
5155
  const effectiveEndpointsMap = /* @__PURE__ */ new Map();
5141
5156
  [
5142
5157
  ...baseEndpoints
@@ -5209,18 +5224,18 @@ please use an LLM adapter instead.`
5209
5224
  code: import_shared15.CopilotKitErrorCode.UNKNOWN
5210
5225
  });
5211
5226
  }
5212
- async trace(type, context, error, publicApiKey) {
5213
- if (!this.onTrace)
5227
+ async error(type, context, error, publicApiKey) {
5228
+ if (!this.onError)
5214
5229
  return;
5215
5230
  if (!publicApiKey) {
5216
- if (!this.hasWarnedAboutTracing) {
5217
- console.warn("CopilotKit: onTrace handler provided but requires publicApiKey to be defined for tracing to work.");
5218
- this.hasWarnedAboutTracing = true;
5231
+ if (!this.hasWarnedAboutError) {
5232
+ console.warn("CopilotKit: onError handler provided but requires publicApiKey to be defined for error handling to work.");
5233
+ this.hasWarnedAboutError = true;
5219
5234
  }
5220
5235
  return;
5221
5236
  }
5222
5237
  try {
5223
- const traceEvent = {
5238
+ const errorEvent = {
5224
5239
  type,
5225
5240
  timestamp: Date.now(),
5226
5241
  context,
@@ -5228,20 +5243,20 @@ please use an LLM adapter instead.`
5228
5243
  error
5229
5244
  }
5230
5245
  };
5231
- await this.onTrace(traceEvent);
5232
- } catch (traceError) {
5233
- console.error("Error in onTrace handler:", traceError);
5246
+ await this.onError(errorEvent);
5247
+ } catch (errorHandlerError) {
5248
+ console.error("Error in onError handler:", errorHandlerError);
5234
5249
  }
5235
5250
  }
5236
5251
  /**
5237
- * Public method to trace GraphQL validation errors
5238
- * This allows the GraphQL resolver to send validation errors through the trace system
5252
+ * Public method to handle GraphQL validation errors
5253
+ * This allows the GraphQL resolver to send validation errors through the error system
5239
5254
  */
5240
- async traceGraphQLError(error, context) {
5241
- if (!this.onTrace)
5255
+ async errorGraphQLError(error, context) {
5256
+ if (!this.onError)
5242
5257
  return;
5243
5258
  try {
5244
- await this.onTrace({
5259
+ await this.onError({
5245
5260
  type: "error",
5246
5261
  timestamp: Date.now(),
5247
5262
  context: {
@@ -5261,8 +5276,8 @@ please use an LLM adapter instead.`
5261
5276
  },
5262
5277
  error
5263
5278
  });
5264
- } catch (traceError) {
5265
- console.error("Error in onTrace handler:", traceError);
5279
+ } catch (errorHandlerError) {
5280
+ console.error("Error in onError handler:", errorHandlerError);
5266
5281
  }
5267
5282
  }
5268
5283
  };
@@ -5870,7 +5885,7 @@ var import_shared23 = require("@copilotkit/shared");
5870
5885
 
5871
5886
  // src/lib/runtime/agui-action.ts
5872
5887
  var import_shared21 = require("@copilotkit/shared");
5873
- function constructAGUIRemoteAction({ logger: logger2, messages, agentStates, agent, metaEvents }) {
5888
+ function constructAGUIRemoteAction({ logger: logger2, messages, agentStates, agent, metaEvents, threadMetadata, nodeName }) {
5874
5889
  const action = {
5875
5890
  name: agent.agentId,
5876
5891
  description: agent.description,
@@ -5905,11 +5920,19 @@ function constructAGUIRemoteAction({ logger: logger2, messages, agentStates, age
5905
5920
  parameters: JSON.parse(input.jsonSchema)
5906
5921
  };
5907
5922
  });
5908
- const forwardedProps = metaEvents.length ? {
5909
- command: {
5910
- resume: (_a = metaEvents[0]) == null ? void 0 : _a.response
5911
- }
5912
- } : void 0;
5923
+ const forwardedProps = {
5924
+ ...(metaEvents == null ? void 0 : metaEvents.length) ? {
5925
+ command: {
5926
+ resume: (_a = metaEvents[0]) == null ? void 0 : _a.response
5927
+ }
5928
+ } : {},
5929
+ ...threadMetadata ? {
5930
+ threadMetadata
5931
+ } : {},
5932
+ ...nodeName ? {
5933
+ nodeName
5934
+ } : {}
5935
+ };
5913
5936
  return agent.legacy_to_be_removed_runAgentBridged({
5914
5937
  tools,
5915
5938
  forwardedProps
@@ -6023,13 +6046,15 @@ async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: l
6023
6046
  }
6024
6047
  }
6025
6048
  __name(fetchRemoteInfo, "fetchRemoteInfo");
6026
- async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, messages, agentStates, frontendUrl, agents, metaEvents }) {
6049
+ async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, messages, agentStates, frontendUrl, agents, metaEvents, nodeName }) {
6050
+ var _a;
6027
6051
  const logger2 = graphqlContext.logger.child({
6028
6052
  component: "remote-actions.fetchRemoteActions"
6029
6053
  });
6030
6054
  logger2.debug({
6031
6055
  remoteEndpointDefinitions
6032
6056
  }, "Fetching from remote endpoints");
6057
+ const threadMetadata = ((_a = graphqlContext.properties) == null ? void 0 : _a.threadMetadata) || {};
6033
6058
  const filtered = remoteEndpointDefinitions.filter((value, index, self) => {
6034
6059
  if (value.type === "langgraph-platform") {
6035
6060
  return value;
@@ -6086,7 +6111,9 @@ async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, m
6086
6111
  messages,
6087
6112
  agentStates,
6088
6113
  agent,
6089
- metaEvents
6114
+ metaEvents,
6115
+ threadMetadata,
6116
+ nodeName
6090
6117
  }));
6091
6118
  }
6092
6119
  return result.flat();
@@ -6209,6 +6236,12 @@ __name(RuntimeEventSubject, "RuntimeEventSubject");
6209
6236
  var RuntimeEventSource = class {
6210
6237
  eventStream$ = new RuntimeEventSubject();
6211
6238
  callback;
6239
+ errorHandler;
6240
+ errorContext;
6241
+ constructor(params) {
6242
+ this.errorHandler = params == null ? void 0 : params.errorHandler;
6243
+ this.errorContext = params == null ? void 0 : params.errorContext;
6244
+ }
6212
6245
  async stream(callback) {
6213
6246
  this.callback = callback;
6214
6247
  }
@@ -6223,8 +6256,15 @@ var RuntimeEventSource = class {
6223
6256
  }
6224
6257
  }
6225
6258
  processRuntimeEvents({ serverSideActions, guardrailsResult$, actionInputsWithoutAgents, threadId }) {
6226
- this.callback(this.eventStream$).catch((error) => {
6259
+ this.callback(this.eventStream$).catch(async (error) => {
6227
6260
  const structuredError = (0, import_shared24.ensureStructuredError)(error, convertStreamingErrorToStructured2);
6261
+ if (this.errorHandler && this.errorContext) {
6262
+ try {
6263
+ await this.errorHandler(structuredError, this.errorContext);
6264
+ } catch (errorHandlerError) {
6265
+ console.error("Error in streaming error handler:", errorHandlerError);
6266
+ }
6267
+ }
6228
6268
  this.eventStream$.error(structuredError);
6229
6269
  this.eventStream$.complete();
6230
6270
  });
@@ -6263,6 +6303,19 @@ var RuntimeEventSource = class {
6263
6303
  telemetry_client_default.capture("oss.runtime.server_action_executed", {});
6264
6304
  return (0, import_rxjs3.concat)((0, import_rxjs3.of)(eventWithState.event), toolCallEventStream$).pipe((0, import_rxjs3.catchError)((error) => {
6265
6305
  const structuredError = (0, import_shared24.ensureStructuredError)(error, convertStreamingErrorToStructured2);
6306
+ if (this.errorHandler && this.errorContext) {
6307
+ (0, import_rxjs3.from)(this.errorHandler(structuredError, {
6308
+ ...this.errorContext,
6309
+ action: {
6310
+ name: eventWithState.action.name,
6311
+ executionId: eventWithState.actionExecutionId
6312
+ }
6313
+ })).subscribe({
6314
+ error: (errorHandlerError) => {
6315
+ console.error("Error in action execution error handler:", errorHandlerError);
6316
+ }
6317
+ });
6318
+ }
6266
6319
  toolCallEventStream$.sendActionExecutionResult({
6267
6320
  actionExecutionId: eventWithState.actionExecutionId,
6268
6321
  actionName: eventWithState.action.name,
@@ -6607,7 +6660,7 @@ var CopilotResolver = class {
6607
6660
  logger2.debug("Cloud configuration provided, checking for public API key in headers");
6608
6661
  if (!copilotCloudPublicApiKey) {
6609
6662
  logger2.error("Public API key not found in headers");
6610
- await copilotRuntime.traceGraphQLError({
6663
+ await copilotRuntime.errorGraphQLError({
6611
6664
  message: "X-CopilotCloud-Public-API-Key header is required",
6612
6665
  code: "MISSING_PUBLIC_API_KEY",
6613
6666
  type: "GraphQLError"