@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
@@ -5,11 +5,14 @@ import {
5
5
  ResultMessage,
6
6
  TextMessage
7
7
  } from "./chunk-SHBDMA63.mjs";
8
+ import {
9
+ BaseMessageInput
10
+ } from "./chunk-2OZAGFV3.mjs";
8
11
  import {
9
12
  EmptyAdapter,
10
13
  RemoteChain,
11
14
  streamLangChainResponse
12
- } from "./chunk-4JBKY7XT.mjs";
15
+ } from "./chunk-QLLV2QVK.mjs";
13
16
  import {
14
17
  GuardrailsValidationFailureResponse,
15
18
  MessageStreamInterruptedResponse,
@@ -17,9 +20,6 @@ import {
17
20
  SuccessResponseStatus,
18
21
  UnknownErrorResponse
19
22
  } from "./chunk-XWBDEXDA.mjs";
20
- import {
21
- BaseMessageInput
22
- } from "./chunk-2OZAGFV3.mjs";
23
23
  import {
24
24
  __commonJS,
25
25
  __name,
@@ -40,7 +40,7 @@ var require_package = __commonJS({
40
40
  publishConfig: {
41
41
  access: "public"
42
42
  },
43
- version: "1.9.2-next.9",
43
+ version: "1.9.3-next.0",
44
44
  sideEffects: false,
45
45
  main: "./dist/index.js",
46
46
  module: "./dist/index.mjs",
@@ -78,11 +78,11 @@ var require_package = __commonJS({
78
78
  "zod-to-json-schema": "^3.23.5"
79
79
  },
80
80
  dependencies: {
81
- "@ag-ui/client": "0.0.28",
82
- "@ag-ui/core": "0.0.28",
83
- "@ag-ui/encoder": "0.0.28",
84
- "@ag-ui/langgraph": "0.0.4",
85
- "@ag-ui/proto": "0.0.28",
81
+ "@ag-ui/client": "0.0.35",
82
+ "@ag-ui/core": "0.0.35",
83
+ "@ag-ui/encoder": "0.0.35",
84
+ "@ag-ui/langgraph": "0.0.7",
85
+ "@ag-ui/proto": "0.0.35",
86
86
  "@anthropic-ai/sdk": "^0.27.3",
87
87
  "@copilotkit/shared": "workspace:*",
88
88
  "@graphql-yoga/plugin-defer-stream": "^3.3.1",
@@ -110,10 +110,10 @@ var require_package = __commonJS({
110
110
  zod: "^3.23.3"
111
111
  },
112
112
  peerDependencies: {
113
- "@ag-ui/client": ">=0.0.28",
114
- "@ag-ui/core": ">=0.0.28",
115
- "@ag-ui/encoder": ">=0.0.28",
116
- "@ag-ui/proto": ">=0.0.28"
113
+ "@ag-ui/client": ">=0.0.34",
114
+ "@ag-ui/core": ">=0.0.34",
115
+ "@ag-ui/encoder": ">=0.0.34",
116
+ "@ag-ui/proto": ">=0.0.34"
117
117
  },
118
118
  keywords: [
119
119
  "copilotkit",
@@ -2632,7 +2632,7 @@ function extractParametersFromSchema(toolOrSchema) {
2632
2632
  var _a;
2633
2633
  const parameters = [];
2634
2634
  const schema = "schema" in (toolOrSchema || {}) ? toolOrSchema.schema : toolOrSchema;
2635
- const toolParameters = (schema == null ? void 0 : schema.parameters) || ((_a = schema == null ? void 0 : schema.parameters) == null ? void 0 : _a.jsonSchema);
2635
+ const toolParameters = ((_a = schema == null ? void 0 : schema.parameters) == null ? void 0 : _a.jsonSchema) || (schema == null ? void 0 : schema.parameters);
2636
2636
  const properties = toolParameters == null ? void 0 : toolParameters.properties;
2637
2637
  const requiredParams = new Set((toolParameters == null ? void 0 : toolParameters.required) || []);
2638
2638
  if (!properties) {
@@ -2641,12 +2641,29 @@ function extractParametersFromSchema(toolOrSchema) {
2641
2641
  for (const paramName in properties) {
2642
2642
  if (Object.prototype.hasOwnProperty.call(properties, paramName)) {
2643
2643
  const paramDef = properties[paramName];
2644
+ let type = paramDef.type || "string";
2645
+ let description = paramDef.description || "";
2646
+ if (type === "array" && paramDef.items) {
2647
+ const itemType = paramDef.items.type || "object";
2648
+ if (itemType === "object" && paramDef.items.properties) {
2649
+ const itemProperties = Object.keys(paramDef.items.properties).join(", ");
2650
+ description = description + (description ? " " : "") + `Array of objects with properties: ${itemProperties}`;
2651
+ } else {
2652
+ type = `array<${itemType}>`;
2653
+ }
2654
+ }
2655
+ if (paramDef.enum && Array.isArray(paramDef.enum)) {
2656
+ const enumValues = paramDef.enum.join(" | ");
2657
+ description = description + (description ? " " : "") + `Allowed values: ${enumValues}`;
2658
+ }
2659
+ if (type === "object" && paramDef.properties) {
2660
+ const objectProperties = Object.keys(paramDef.properties).join(", ");
2661
+ description = description + (description ? " " : "") + `Object with properties: ${objectProperties}`;
2662
+ }
2644
2663
  parameters.push({
2645
2664
  name: paramName,
2646
- // Infer type, default to string. MCP schemas might have more complex types.
2647
- // This might need refinement based on common MCP schema practices.
2648
- type: paramDef.type || "string",
2649
- description: paramDef.description,
2665
+ type,
2666
+ description,
2650
2667
  required: requiredParams.has(paramName)
2651
2668
  });
2652
2669
  }
@@ -2660,9 +2677,7 @@ function convertMCPToolsToActions(mcpTools, mcpEndpoint) {
2660
2677
  const parameters = extractParametersFromSchema(tool);
2661
2678
  const handler = /* @__PURE__ */ __name(async (params) => {
2662
2679
  try {
2663
- const result = await tool.execute({
2664
- params
2665
- });
2680
+ const result = await tool.execute(params);
2666
2681
  return typeof result === "string" ? result : JSON.stringify(result);
2667
2682
  } catch (error) {
2668
2683
  console.error(`Error executing MCP tool '${toolName}' from endpoint ${mcpEndpoint}:`, error);
@@ -2688,17 +2703,38 @@ function generateMcpToolInstructions(toolsMap) {
2688
2703
  }
2689
2704
  const toolEntries = Object.entries(toolsMap);
2690
2705
  const toolsDoc = toolEntries.map(([name, tool]) => {
2706
+ var _a;
2691
2707
  let paramsDoc = " No parameters required";
2692
2708
  try {
2693
2709
  if (tool.schema && typeof tool.schema === "object") {
2694
2710
  const schema = tool.schema;
2695
- if (schema.properties) {
2696
- const requiredParams = schema.required || [];
2697
- const paramsList = Object.entries(schema.properties).map(([paramName, propSchema]) => {
2711
+ const toolParameters = ((_a = schema.parameters) == null ? void 0 : _a.jsonSchema) || schema.parameters;
2712
+ const properties = (toolParameters == null ? void 0 : toolParameters.properties) || schema.properties;
2713
+ const requiredParams = (toolParameters == null ? void 0 : toolParameters.required) || schema.required || [];
2714
+ if (properties) {
2715
+ const paramsList = Object.entries(properties).map(([paramName, propSchema]) => {
2698
2716
  const propDetails = propSchema;
2699
2717
  const requiredMark = requiredParams.includes(paramName) ? "*" : "";
2700
- const typeInfo = propDetails.type || "any";
2701
- const description = propDetails.description ? ` - ${propDetails.description}` : "";
2718
+ let typeInfo = propDetails.type || "any";
2719
+ let description = propDetails.description ? ` - ${propDetails.description}` : "";
2720
+ if (typeInfo === "array" && propDetails.items) {
2721
+ const itemType = propDetails.items.type || "object";
2722
+ if (itemType === "object" && propDetails.items.properties) {
2723
+ const itemProps = Object.keys(propDetails.items.properties).join(", ");
2724
+ typeInfo = `array<object>`;
2725
+ description = description + (description ? " " : " - ") + `Array of objects with properties: ${itemProps}`;
2726
+ } else {
2727
+ typeInfo = `array<${itemType}>`;
2728
+ }
2729
+ }
2730
+ if (propDetails.enum && Array.isArray(propDetails.enum)) {
2731
+ const enumValues = propDetails.enum.join(" | ");
2732
+ description = description + (description ? " " : " - ") + `Allowed values: ${enumValues}`;
2733
+ }
2734
+ if (typeInfo === "object" && propDetails.properties) {
2735
+ const objectProps = Object.keys(propDetails.properties).join(", ");
2736
+ description = description + (description ? " " : " - ") + `Object with properties: ${objectProps}`;
2737
+ }
2702
2738
  return ` - ${paramName}${requiredMark} (${typeInfo})${description}`;
2703
2739
  });
2704
2740
  if (paramsList.length > 0) {
@@ -2719,8 +2755,11 @@ ${toolsDoc}
2719
2755
  When using these tools:
2720
2756
  1. Only provide valid parameters according to their type requirements
2721
2757
  2. Required parameters are marked with *
2722
- 3. Format API calls correctly with the expected parameter structure
2723
- 4. Always check tool responses to determine your next action`;
2758
+ 3. For array parameters, provide data in the correct array format
2759
+ 4. For object parameters, include all required nested properties
2760
+ 5. For enum parameters, use only the allowed values listed
2761
+ 6. Format API calls correctly with the expected parameter structure
2762
+ 7. Always check tool responses to determine your next action`;
2724
2763
  }
2725
2764
  __name(generateMcpToolInstructions, "generateMcpToolInstructions");
2726
2765
 
@@ -2735,8 +2774,8 @@ var CopilotRuntime = class {
2735
2774
  delegateAgentProcessingToServiceAdapter;
2736
2775
  observability;
2737
2776
  availableAgents;
2738
- onTrace;
2739
- hasWarnedAboutTracing = false;
2777
+ onError;
2778
+ hasWarnedAboutError = false;
2740
2779
  // +++ MCP Properties +++
2741
2780
  mcpServersConfig;
2742
2781
  mcpActionCache = /* @__PURE__ */ new Map();
@@ -2762,7 +2801,7 @@ var CopilotRuntime = class {
2762
2801
  this.delegateAgentProcessingToServiceAdapter = (params == null ? void 0 : params.delegateAgentProcessingToServiceAdapter) || false;
2763
2802
  this.observability = params == null ? void 0 : params.observability_c;
2764
2803
  this.agents = (params == null ? void 0 : params.agents) ?? {};
2765
- this.onTrace = params == null ? void 0 : params.onTrace;
2804
+ this.onError = params == null ? void 0 : params.onError;
2766
2805
  this.mcpServersConfig = params == null ? void 0 : params.mcpServers;
2767
2806
  this.createMCPClientImpl = params == null ? void 0 : params.createMCPClient;
2768
2807
  if (this.mcpServersConfig && this.mcpServersConfig.length > 0 && !this.createMCPClientImpl) {
@@ -2807,7 +2846,7 @@ var CopilotRuntime = class {
2807
2846
  if (!mcpToolInstructions) {
2808
2847
  return messages;
2809
2848
  }
2810
- 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.";
2849
+ const instructions = mcpToolInstructions + "\nUse them when appropriate to fulfill the user's request.";
2811
2850
  const systemMessageIndex = messages.findIndex((msg) => {
2812
2851
  var _a;
2813
2852
  return ((_a = msg.textMessage) == null ? void 0 : _a.role) === "system";
@@ -2838,30 +2877,30 @@ var CopilotRuntime = class {
2838
2877
  async processRuntimeRequest(request) {
2839
2878
  var _a, _b, _c, _d, _e;
2840
2879
  const { serviceAdapter, messages: rawMessages, actions: clientSideActionsInput, threadId, runId, outputMessagesPromise, graphqlContext, forwardedParameters, url, extensions, agentSession, agentStates, publicApiKey } = request;
2841
- const eventSource = new RuntimeEventSource();
2842
- const requestStartTime = Date.now();
2843
- const streamedChunks = [];
2844
- await this.trace("request", {
2845
- threadId,
2846
- runId,
2847
- source: "runtime",
2848
- request: {
2849
- operation: "processRuntimeRequest",
2850
- method: "POST",
2851
- url,
2852
- startTime: requestStartTime
2853
- },
2854
- agent: agentSession ? {
2855
- name: agentSession.agentName
2856
- } : void 0,
2857
- messages: {
2858
- input: rawMessages,
2859
- messageCount: rawMessages.length
2880
+ const eventSource = new RuntimeEventSource({
2881
+ errorHandler: async (error, context) => {
2882
+ await this.error("error", context, error, publicApiKey);
2860
2883
  },
2861
- technical: {
2862
- environment: process.env.NODE_ENV
2884
+ errorContext: {
2885
+ threadId,
2886
+ runId,
2887
+ source: "runtime",
2888
+ request: {
2889
+ operation: "processRuntimeRequest",
2890
+ method: "POST",
2891
+ url,
2892
+ startTime: Date.now()
2893
+ },
2894
+ agent: agentSession ? {
2895
+ name: agentSession.agentName
2896
+ } : void 0,
2897
+ technical: {
2898
+ environment: process.env.NODE_ENV
2899
+ }
2863
2900
  }
2864
- }, void 0, publicApiKey);
2901
+ });
2902
+ const requestStartTime = Date.now();
2903
+ const streamedChunks = [];
2865
2904
  try {
2866
2905
  if (Object.keys(this.agents).length && (agentSession == null ? void 0 : agentSession.agentName) && !this.delegateAgentProcessingToServiceAdapter) {
2867
2906
  this.agents = {
@@ -3037,7 +3076,7 @@ please use an LLM adapter instead.`
3037
3076
  } else {
3038
3077
  structuredError = ensureStructuredError2(error, (err) => this.convertStreamingErrorToStructured(err));
3039
3078
  }
3040
- await this.trace("error", {
3079
+ await this.error("error", {
3041
3080
  threadId,
3042
3081
  runId,
3043
3082
  source: "runtime",
@@ -3063,10 +3102,8 @@ please use an LLM adapter instead.`
3063
3102
  }
3064
3103
  }
3065
3104
  async getAllAgents(graphqlContext) {
3066
- const [agentsWithEndpoints, aguiAgents] = await Promise.all([
3067
- this.discoverAgentsFromEndpoints(graphqlContext),
3068
- this.discoverAgentsFromAgui()
3069
- ]);
3105
+ const agentsWithEndpoints = await this.discoverAgentsFromEndpoints(graphqlContext);
3106
+ const aguiAgents = this.discoverAgentsFromAgui();
3070
3107
  this.availableAgents = [
3071
3108
  ...agentsWithEndpoints,
3072
3109
  ...aguiAgents
@@ -3166,40 +3203,15 @@ please use an LLM adapter instead.`
3166
3203
  }, Promise.resolve([]));
3167
3204
  return agents;
3168
3205
  }
3169
- async discoverAgentsFromAgui() {
3170
- const agents = Object.values(this.agents ?? []).reduce(async (acc, agent) => {
3171
- const agents2 = await acc;
3172
- const client = agent.client;
3173
- let data = [];
3174
- try {
3175
- data = await client.assistants.search();
3176
- if (data && "detail" in data && data.detail.toLowerCase() === "not found") {
3177
- throw new CopilotKitAgentDiscoveryError({
3178
- availableAgents: this.availableAgents
3179
- });
3180
- }
3181
- } catch (e) {
3182
- throw new CopilotKitMisuseError2({
3183
- message: `
3184
- Failed to find or contact agent ${agent.graphId}.
3185
- Make sure the LangGraph API is running and the agent is defined in langgraph.json
3186
-
3187
- See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3188
- });
3189
- }
3190
- const endpointAgents = data.map((entry) => ({
3191
- name: entry.graph_id,
3192
- id: entry.assistant_id,
3193
- description: ""
3194
- }));
3195
- return [
3196
- ...agents2,
3197
- ...endpointAgents
3198
- ];
3199
- }, Promise.resolve([]));
3200
- return agents;
3206
+ discoverAgentsFromAgui() {
3207
+ return Object.entries(this.agents ?? []).map(([key, agent]) => ({
3208
+ name: agent.agentName ?? key,
3209
+ id: agent.agentId ?? key,
3210
+ description: agent.description ?? ""
3211
+ }));
3201
3212
  }
3202
3213
  async loadAgentState(graphqlContext, threadId, agentName) {
3214
+ var _a;
3203
3215
  const agents = await this.getAllAgents(graphqlContext);
3204
3216
  const agent = agents.find((agent2) => agent2.name === agentName);
3205
3217
  if (!agent) {
@@ -3259,33 +3271,38 @@ please use an LLM adapter instead.`
3259
3271
  const propertyHeaders = graphqlContext.properties.authorization ? {
3260
3272
  authorization: `Bearer ${graphqlContext.properties.authorization}`
3261
3273
  } : null;
3262
- let client;
3263
- if ("endpoint" in agent && agent.endpoint.type === EndpointType.LangGraphPlatform) {
3264
- client = new LangGraphClient2({
3265
- apiUrl: agent.endpoint.deploymentUrl,
3266
- apiKey: agent.endpoint.langsmithApiKey,
3267
- defaultHeaders: {
3268
- ...propertyHeaders
3269
- }
3270
- });
3271
- } else {
3272
- const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name];
3273
- if (!aguiAgent) {
3274
- throw new Error(`Agent: ${agent.name} could not be resolved`);
3275
- }
3276
- client = aguiAgent.client;
3277
- }
3278
3274
  let state = {};
3279
3275
  try {
3280
- state = (await client.threads.getState(threadId)).values;
3276
+ let client;
3277
+ if ("endpoint" in agent && agent.endpoint.type === EndpointType.LangGraphPlatform) {
3278
+ client = new LangGraphClient2({
3279
+ apiUrl: agent.endpoint.deploymentUrl,
3280
+ apiKey: agent.endpoint.langsmithApiKey,
3281
+ defaultHeaders: {
3282
+ ...propertyHeaders
3283
+ }
3284
+ });
3285
+ } else {
3286
+ const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name];
3287
+ if (!aguiAgent) {
3288
+ throw new Error(`Agent: ${agent.name} could not be resolved`);
3289
+ }
3290
+ client = aguiAgent.client ?? null;
3291
+ }
3292
+ state = client ? (await client.threads.getState(threadId)).values : {};
3281
3293
  } catch (error) {
3282
3294
  const errorMessage = error instanceof Error ? error.message : String(error);
3283
- console.debug(`Agent '${agentName}' configuration issue: ${errorMessage}`);
3284
- throw new ResolvedCopilotKitError({
3285
- status: 400,
3286
- message: `Agent '${agentName}' failed to execute: ${errorMessage}`,
3287
- code: CopilotKitErrorCode2.CONFIGURATION_ERROR
3288
- });
3295
+ const errorStatus = ((_a = error == null ? void 0 : error.response) == null ? void 0 : _a.status) || (error == null ? void 0 : error.status);
3296
+ if (errorStatus === 404) {
3297
+ state = {};
3298
+ } else {
3299
+ console.debug(`Agent '${agentName}' configuration issue: ${errorMessage}`);
3300
+ throw new ResolvedCopilotKitError({
3301
+ status: 400,
3302
+ message: `Agent '${agentName}' failed to execute: ${errorMessage}`,
3303
+ code: CopilotKitErrorCode2.CONFIGURATION_ERROR
3304
+ });
3305
+ }
3289
3306
  }
3290
3307
  if (Object.keys(state).length === 0) {
3291
3308
  return {
@@ -3313,7 +3330,7 @@ please use an LLM adapter instead.`
3313
3330
  const requestStartTime = Date.now();
3314
3331
  const streamedChunks = [];
3315
3332
  const threadId = threadIdFromRequest ?? agentSession.threadId;
3316
- await this.trace("agent_state", {
3333
+ await this.error("agent_state", {
3317
3334
  threadId,
3318
3335
  source: "agent",
3319
3336
  request: {
@@ -3381,7 +3398,27 @@ please use an LLM adapter instead.`
3381
3398
  properties: graphqlContext.properties
3382
3399
  }));
3383
3400
  try {
3384
- const eventSource = new RuntimeEventSource();
3401
+ const eventSource = new RuntimeEventSource({
3402
+ errorHandler: async (error, context) => {
3403
+ await this.error("error", context, error, publicApiKey);
3404
+ },
3405
+ errorContext: {
3406
+ threadId,
3407
+ source: "agent",
3408
+ request: {
3409
+ operation: "processAgentRequest",
3410
+ method: "POST",
3411
+ startTime: requestStartTime
3412
+ },
3413
+ agent: {
3414
+ name: agentName,
3415
+ nodeName
3416
+ },
3417
+ technical: {
3418
+ environment: process.env.NODE_ENV
3419
+ }
3420
+ }
3421
+ });
3385
3422
  const stream = await currentAgent.remoteAgentHandler({
3386
3423
  name: agentName,
3387
3424
  threadId,
@@ -3449,7 +3486,7 @@ please use an LLM adapter instead.`
3449
3486
  }
3450
3487
  }
3451
3488
  const structuredError = ensureStructuredError2(err, (error) => this.convertStreamingErrorToStructured(error));
3452
- await this.trace("error", {
3489
+ await this.error("error", {
3453
3490
  threadId,
3454
3491
  source: "agent",
3455
3492
  request: {
@@ -3538,7 +3575,7 @@ please use an LLM adapter instead.`
3538
3575
  }
3539
3576
  }
3540
3577
  const structuredError = ensureStructuredError2(error, (err) => this.convertStreamingErrorToStructured(err));
3541
- await this.trace("error", {
3578
+ await this.error("error", {
3542
3579
  threadId,
3543
3580
  source: "agent",
3544
3581
  request: {
@@ -3564,7 +3601,7 @@ please use an LLM adapter instead.`
3564
3601
  }
3565
3602
  }
3566
3603
  async getServerSideActions(request) {
3567
- var _a, _b;
3604
+ var _a, _b, _c;
3568
3605
  const { graphqlContext, messages: rawMessages, agentStates, url } = request;
3569
3606
  const inputMessages = convertGqlInputToMessages(rawMessages);
3570
3607
  const langserveFunctions = [];
@@ -3587,7 +3624,8 @@ please use an LLM adapter instead.`
3587
3624
  agentStates,
3588
3625
  frontendUrl: url,
3589
3626
  agents: this.agents,
3590
- metaEvents: request.metaEvents
3627
+ metaEvents: request.metaEvents,
3628
+ nodeName: (_a = request.agentSession) == null ? void 0 : _a.nodeName
3591
3629
  });
3592
3630
  const configuredActions = typeof this.actions === "function" ? this.actions({
3593
3631
  properties: graphqlContext.properties,
@@ -3596,7 +3634,7 @@ please use an LLM adapter instead.`
3596
3634
  const requestSpecificMCPActions = [];
3597
3635
  if (this.createMCPClientImpl) {
3598
3636
  const baseEndpoints = this.mcpServersConfig || [];
3599
- const requestEndpoints = ((_a = graphqlContext.properties) == null ? void 0 : _a.mcpServers) || ((_b = graphqlContext.properties) == null ? void 0 : _b.mcpEndpoints) || [];
3637
+ const requestEndpoints = ((_b = graphqlContext.properties) == null ? void 0 : _b.mcpServers) || ((_c = graphqlContext.properties) == null ? void 0 : _c.mcpEndpoints) || [];
3600
3638
  const effectiveEndpointsMap = /* @__PURE__ */ new Map();
3601
3639
  [
3602
3640
  ...baseEndpoints
@@ -3669,18 +3707,18 @@ please use an LLM adapter instead.`
3669
3707
  code: CopilotKitErrorCode2.UNKNOWN
3670
3708
  });
3671
3709
  }
3672
- async trace(type, context, error, publicApiKey) {
3673
- if (!this.onTrace)
3710
+ async error(type, context, error, publicApiKey) {
3711
+ if (!this.onError)
3674
3712
  return;
3675
3713
  if (!publicApiKey) {
3676
- if (!this.hasWarnedAboutTracing) {
3677
- console.warn("CopilotKit: onTrace handler provided but requires publicApiKey to be defined for tracing to work.");
3678
- this.hasWarnedAboutTracing = true;
3714
+ if (!this.hasWarnedAboutError) {
3715
+ console.warn("CopilotKit: onError handler provided but requires publicApiKey to be defined for error handling to work.");
3716
+ this.hasWarnedAboutError = true;
3679
3717
  }
3680
3718
  return;
3681
3719
  }
3682
3720
  try {
3683
- const traceEvent = {
3721
+ const errorEvent = {
3684
3722
  type,
3685
3723
  timestamp: Date.now(),
3686
3724
  context,
@@ -3688,20 +3726,20 @@ please use an LLM adapter instead.`
3688
3726
  error
3689
3727
  }
3690
3728
  };
3691
- await this.onTrace(traceEvent);
3692
- } catch (traceError) {
3693
- console.error("Error in onTrace handler:", traceError);
3729
+ await this.onError(errorEvent);
3730
+ } catch (errorHandlerError) {
3731
+ console.error("Error in onError handler:", errorHandlerError);
3694
3732
  }
3695
3733
  }
3696
3734
  /**
3697
- * Public method to trace GraphQL validation errors
3698
- * This allows the GraphQL resolver to send validation errors through the trace system
3735
+ * Public method to handle GraphQL validation errors
3736
+ * This allows the GraphQL resolver to send validation errors through the error system
3699
3737
  */
3700
- async traceGraphQLError(error, context) {
3701
- if (!this.onTrace)
3738
+ async errorGraphQLError(error, context) {
3739
+ if (!this.onError)
3702
3740
  return;
3703
3741
  try {
3704
- await this.onTrace({
3742
+ await this.onError({
3705
3743
  type: "error",
3706
3744
  timestamp: Date.now(),
3707
3745
  context: {
@@ -3721,8 +3759,8 @@ please use an LLM adapter instead.`
3721
3759
  },
3722
3760
  error
3723
3761
  });
3724
- } catch (traceError) {
3725
- console.error("Error in onTrace handler:", traceError);
3762
+ } catch (errorHandlerError) {
3763
+ console.error("Error in onError handler:", errorHandlerError);
3726
3764
  }
3727
3765
  }
3728
3766
  };
@@ -4330,7 +4368,7 @@ import { CopilotKitLowLevelError as CopilotKitLowLevelError6, ResolvedCopilotKit
4330
4368
 
4331
4369
  // src/lib/runtime/agui-action.ts
4332
4370
  import { parseJson as parseJson3 } from "@copilotkit/shared";
4333
- function constructAGUIRemoteAction({ logger: logger2, messages, agentStates, agent, metaEvents }) {
4371
+ function constructAGUIRemoteAction({ logger: logger2, messages, agentStates, agent, metaEvents, threadMetadata, nodeName }) {
4334
4372
  const action = {
4335
4373
  name: agent.agentId,
4336
4374
  description: agent.description,
@@ -4365,11 +4403,19 @@ function constructAGUIRemoteAction({ logger: logger2, messages, agentStates, age
4365
4403
  parameters: JSON.parse(input.jsonSchema)
4366
4404
  };
4367
4405
  });
4368
- const forwardedProps = metaEvents.length ? {
4369
- command: {
4370
- resume: (_a = metaEvents[0]) == null ? void 0 : _a.response
4371
- }
4372
- } : void 0;
4406
+ const forwardedProps = {
4407
+ ...(metaEvents == null ? void 0 : metaEvents.length) ? {
4408
+ command: {
4409
+ resume: (_a = metaEvents[0]) == null ? void 0 : _a.response
4410
+ }
4411
+ } : {},
4412
+ ...threadMetadata ? {
4413
+ threadMetadata
4414
+ } : {},
4415
+ ...nodeName ? {
4416
+ nodeName
4417
+ } : {}
4418
+ };
4373
4419
  return agent.legacy_to_be_removed_runAgentBridged({
4374
4420
  tools,
4375
4421
  forwardedProps
@@ -4483,13 +4529,15 @@ async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: l
4483
4529
  }
4484
4530
  }
4485
4531
  __name(fetchRemoteInfo, "fetchRemoteInfo");
4486
- async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, messages, agentStates, frontendUrl, agents, metaEvents }) {
4532
+ async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, messages, agentStates, frontendUrl, agents, metaEvents, nodeName }) {
4533
+ var _a;
4487
4534
  const logger2 = graphqlContext.logger.child({
4488
4535
  component: "remote-actions.fetchRemoteActions"
4489
4536
  });
4490
4537
  logger2.debug({
4491
4538
  remoteEndpointDefinitions
4492
4539
  }, "Fetching from remote endpoints");
4540
+ const threadMetadata = ((_a = graphqlContext.properties) == null ? void 0 : _a.threadMetadata) || {};
4493
4541
  const filtered = remoteEndpointDefinitions.filter((value, index, self) => {
4494
4542
  if (value.type === "langgraph-platform") {
4495
4543
  return value;
@@ -4546,7 +4594,9 @@ async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, m
4546
4594
  messages,
4547
4595
  agentStates,
4548
4596
  agent,
4549
- metaEvents
4597
+ metaEvents,
4598
+ threadMetadata,
4599
+ nodeName
4550
4600
  }));
4551
4601
  }
4552
4602
  return result.flat();
@@ -4669,6 +4719,12 @@ __name(RuntimeEventSubject, "RuntimeEventSubject");
4669
4719
  var RuntimeEventSource = class {
4670
4720
  eventStream$ = new RuntimeEventSubject();
4671
4721
  callback;
4722
+ errorHandler;
4723
+ errorContext;
4724
+ constructor(params) {
4725
+ this.errorHandler = params == null ? void 0 : params.errorHandler;
4726
+ this.errorContext = params == null ? void 0 : params.errorContext;
4727
+ }
4672
4728
  async stream(callback) {
4673
4729
  this.callback = callback;
4674
4730
  }
@@ -4683,8 +4739,15 @@ var RuntimeEventSource = class {
4683
4739
  }
4684
4740
  }
4685
4741
  processRuntimeEvents({ serverSideActions, guardrailsResult$, actionInputsWithoutAgents, threadId }) {
4686
- this.callback(this.eventStream$).catch((error) => {
4742
+ this.callback(this.eventStream$).catch(async (error) => {
4687
4743
  const structuredError = ensureStructuredError3(error, convertStreamingErrorToStructured2);
4744
+ if (this.errorHandler && this.errorContext) {
4745
+ try {
4746
+ await this.errorHandler(structuredError, this.errorContext);
4747
+ } catch (errorHandlerError) {
4748
+ console.error("Error in streaming error handler:", errorHandlerError);
4749
+ }
4750
+ }
4688
4751
  this.eventStream$.error(structuredError);
4689
4752
  this.eventStream$.complete();
4690
4753
  });
@@ -4723,6 +4786,19 @@ var RuntimeEventSource = class {
4723
4786
  telemetry_client_default.capture("oss.runtime.server_action_executed", {});
4724
4787
  return concat(of(eventWithState.event), toolCallEventStream$).pipe(catchError2((error) => {
4725
4788
  const structuredError = ensureStructuredError3(error, convertStreamingErrorToStructured2);
4789
+ if (this.errorHandler && this.errorContext) {
4790
+ from2(this.errorHandler(structuredError, {
4791
+ ...this.errorContext,
4792
+ action: {
4793
+ name: eventWithState.action.name,
4794
+ executionId: eventWithState.actionExecutionId
4795
+ }
4796
+ })).subscribe({
4797
+ error: (errorHandlerError) => {
4798
+ console.error("Error in action execution error handler:", errorHandlerError);
4799
+ }
4800
+ });
4801
+ }
4726
4802
  toolCallEventStream$.sendActionExecutionResult({
4727
4803
  actionExecutionId: eventWithState.actionExecutionId,
4728
4804
  actionName: eventWithState.action.name,
@@ -5031,7 +5107,7 @@ var CopilotResolver = class {
5031
5107
  logger2.debug("Cloud configuration provided, checking for public API key in headers");
5032
5108
  if (!copilotCloudPublicApiKey) {
5033
5109
  logger2.error("Public API key not found in headers");
5034
- await copilotRuntime.traceGraphQLError({
5110
+ await copilotRuntime.errorGraphQLError({
5035
5111
  message: "X-CopilotCloud-Public-API-Key header is required",
5036
5112
  code: "MISSING_PUBLIC_API_KEY",
5037
5113
  type: "GraphQLError"
@@ -5839,4 +5915,4 @@ export {
5839
5915
  getCommonConfig,
5840
5916
  copilotRuntimeNodeHttpEndpoint
5841
5917
  };
5842
- //# sourceMappingURL=chunk-Z5GYTKMD.mjs.map
5918
+ //# sourceMappingURL=chunk-EK5RTZVJ.mjs.map