@copilotkit/runtime 1.9.2-next.10 → 1.9.2-next.3

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 (84) hide show
  1. package/CHANGELOG.md +0 -53
  2. package/dist/{chunk-XWBDEXDA.mjs → chunk-5BIEM2UU.mjs} +3 -4
  3. package/dist/{chunk-XWBDEXDA.mjs.map → chunk-5BIEM2UU.mjs.map} +1 -1
  4. package/dist/{chunk-PMIAGZGS.mjs → chunk-GSYE3DGY.mjs} +2414 -2928
  5. package/dist/chunk-GSYE3DGY.mjs.map +1 -0
  6. package/dist/{chunk-GS7DO47Q.mjs → chunk-IIXJVVTV.mjs} +78 -155
  7. package/dist/chunk-IIXJVVTV.mjs.map +1 -0
  8. package/dist/{chunk-TOBFVWZU.mjs → chunk-MIPAKFI5.mjs} +2 -2
  9. package/dist/{chunk-VBXBFZEL.mjs → chunk-N24X5I3C.mjs} +2 -2
  10. package/dist/{chunk-6RUTA76W.mjs → chunk-WFYPJXWX.mjs} +2 -2
  11. package/dist/{chunk-5OK4GLKL.mjs → chunk-XDBXF3Q6.mjs} +2 -19
  12. package/dist/chunk-XDBXF3Q6.mjs.map +1 -0
  13. package/dist/{groq-adapter-172a2ca4.d.ts → groq-adapter-25a2bd35.d.ts} +1 -1
  14. package/dist/index.d.ts +3 -4
  15. package/dist/index.js +2598 -3250
  16. package/dist/index.js.map +1 -1
  17. package/dist/index.mjs +8 -12
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/lib/index.d.ts +4 -5
  20. package/dist/lib/index.js +2730 -3339
  21. package/dist/lib/index.js.map +1 -1
  22. package/dist/lib/index.mjs +8 -9
  23. package/dist/lib/integrations/index.d.ts +3 -3
  24. package/dist/lib/integrations/index.js +96 -160
  25. package/dist/lib/integrations/index.js.map +1 -1
  26. package/dist/lib/integrations/index.mjs +6 -7
  27. package/dist/lib/integrations/nest/index.d.ts +2 -2
  28. package/dist/lib/integrations/nest/index.js +96 -160
  29. package/dist/lib/integrations/nest/index.js.map +1 -1
  30. package/dist/lib/integrations/nest/index.mjs +4 -5
  31. package/dist/lib/integrations/node-express/index.d.ts +2 -2
  32. package/dist/lib/integrations/node-express/index.js +96 -160
  33. package/dist/lib/integrations/node-express/index.js.map +1 -1
  34. package/dist/lib/integrations/node-express/index.mjs +4 -5
  35. package/dist/lib/integrations/node-http/index.d.ts +2 -2
  36. package/dist/lib/integrations/node-http/index.js +96 -160
  37. package/dist/lib/integrations/node-http/index.js.map +1 -1
  38. package/dist/lib/integrations/node-http/index.mjs +3 -4
  39. package/dist/service-adapters/index.d.ts +4 -6
  40. package/dist/service-adapters/index.js +107 -225
  41. package/dist/service-adapters/index.js.map +1 -1
  42. package/dist/service-adapters/index.mjs +2 -6
  43. package/dist/{shared-bd953ebf.d.ts → shared-e272b15a.d.ts} +5 -45
  44. package/dist/utils/index.d.ts +1 -17
  45. package/dist/utils/index.js +2 -3
  46. package/dist/utils/index.js.map +1 -1
  47. package/dist/utils/index.mjs +1 -1
  48. package/package.json +2 -2
  49. package/src/agents/langgraph/event-source.ts +38 -36
  50. package/src/agents/langgraph/events.ts +1 -19
  51. package/src/graphql/resolvers/copilot.resolver.ts +45 -108
  52. package/src/graphql/resolvers/state.resolver.ts +3 -3
  53. package/src/lib/integrations/shared.ts +0 -43
  54. package/src/lib/runtime/copilot-runtime.ts +83 -412
  55. package/src/lib/runtime/langgraph/langgraph-agent.ts +0 -12
  56. package/src/lib/runtime/remote-action-constructors.ts +3 -28
  57. package/src/lib/runtime/remote-lg-action.ts +40 -130
  58. package/src/lib/streaming.ts +36 -125
  59. package/src/service-adapters/anthropic/anthropic-adapter.ts +8 -67
  60. package/src/service-adapters/anthropic/utils.ts +8 -3
  61. package/src/service-adapters/events.ts +81 -37
  62. package/src/service-adapters/groq/groq-adapter.ts +56 -66
  63. package/src/service-adapters/index.ts +0 -1
  64. package/src/service-adapters/openai/openai-adapter.ts +3 -18
  65. package/src/utils/failed-response-status-reasons.ts +1 -23
  66. package/tests/service-adapters/anthropic/anthropic-adapter.test.ts +387 -172
  67. package/dist/chunk-5OK4GLKL.mjs.map +0 -1
  68. package/dist/chunk-AMUJQ6IR.mjs +0 -50
  69. package/dist/chunk-AMUJQ6IR.mjs.map +0 -1
  70. package/dist/chunk-GS7DO47Q.mjs.map +0 -1
  71. package/dist/chunk-PMIAGZGS.mjs.map +0 -1
  72. package/dist/service-adapters/shared/index.d.ts +0 -9
  73. package/dist/service-adapters/shared/index.js +0 -72
  74. package/dist/service-adapters/shared/index.js.map +0 -1
  75. package/dist/service-adapters/shared/index.mjs +0 -8
  76. package/dist/service-adapters/shared/index.mjs.map +0 -1
  77. package/src/lib/error-messages.ts +0 -200
  78. package/src/lib/runtime/__tests__/copilot-runtime-trace.test.ts +0 -169
  79. package/src/service-adapters/shared/error-utils.ts +0 -61
  80. package/src/service-adapters/shared/index.ts +0 -1
  81. package/dist/{chunk-TOBFVWZU.mjs.map → chunk-MIPAKFI5.mjs.map} +0 -0
  82. package/dist/{chunk-VBXBFZEL.mjs.map → chunk-N24X5I3C.mjs.map} +0 -0
  83. package/dist/{chunk-6RUTA76W.mjs.map → chunk-WFYPJXWX.mjs.map} +0 -0
  84. package/dist/{langserve-fc5cac89.d.ts → langserve-4a5c9217.d.ts} +7 -7
@@ -25,10 +25,6 @@ import {
25
25
  CopilotKitMisuseError,
26
26
  CopilotKitErrorCode,
27
27
  CopilotKitLowLevelError,
28
- CopilotTraceHandler,
29
- CopilotTraceEvent,
30
- CopilotRequestContext,
31
- ensureStructuredError,
32
28
  } from "@copilotkit/shared";
33
29
  import {
34
30
  CopilotServiceAdapter,
@@ -66,7 +62,7 @@ import { ExtensionsInput } from "../../graphql/inputs/extensions.input";
66
62
  import { ExtensionsResponse } from "../../graphql/types/extensions-response.type";
67
63
  import { LoadAgentStateResponse } from "../../graphql/types/load-agent-state-response.type";
68
64
  import { Client as LangGraphClient } from "@langchain/langgraph-sdk";
69
- import { langchainMessagesToCopilotKit, isUserConfigurationError } from "./remote-lg-action";
65
+ import { langchainMessagesToCopilotKit } from "./remote-lg-action";
70
66
  import { MetaEventInput } from "../../graphql/inputs/meta-event.input";
71
67
  import {
72
68
  CopilotObservabilityConfig,
@@ -85,13 +81,10 @@ import {
85
81
  convertMCPToolsToActions,
86
82
  generateMcpToolInstructions,
87
83
  } from "./mcp-tools-utils";
88
- import { LangGraphAgent } from "./langgraph/langgraph-agent";
89
84
  // Define the function type alias here or import if defined elsewhere
90
85
  type CreateMCPClientFunction = (config: MCPEndpointConfig) => Promise<MCPClient>;
91
86
  // --- MCP Imports ---
92
87
 
93
- import { generateHelpfulErrorMessage } from "../streaming";
94
-
95
88
  export interface CopilotRuntimeRequest {
96
89
  serviceAdapter: CopilotServiceAdapter;
97
90
  messages: MessageInput[];
@@ -281,25 +274,6 @@ export interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []
281
274
  * ```
282
275
  */
283
276
  createMCPClient?: CreateMCPClientFunction;
284
-
285
- /**
286
- * Optional trace handler for comprehensive debugging and observability.
287
- *
288
- * **Requires publicApiKey**: Tracing only works when requests include a valid publicApiKey.
289
- * This is a premium CopilotKit Cloud feature.
290
- *
291
- * @param traceEvent - Structured trace event with rich debugging context
292
- *
293
- * @example
294
- * ```typescript
295
- * const runtime = new CopilotRuntime({
296
- * onTrace: (traceEvent) => {
297
- * debugDashboard.capture(traceEvent);
298
- * }
299
- * });
300
- * ```
301
- */
302
- onTrace?: CopilotTraceHandler;
303
277
  }
304
278
 
305
279
  export class CopilotRuntime<const T extends Parameter[] | [] = []> {
@@ -312,8 +286,6 @@ export class CopilotRuntime<const T extends Parameter[] | [] = []> {
312
286
  private delegateAgentProcessingToServiceAdapter: boolean;
313
287
  private observability?: CopilotObservabilityConfig;
314
288
  private availableAgents: Pick<AgentWithEndpoint, "name" | "id">[];
315
- private onTrace?: CopilotTraceHandler;
316
- private hasWarnedAboutTracing = false;
317
289
 
318
290
  // +++ MCP Properties +++
319
291
  private readonly mcpServersConfig?: MCPEndpointConfig[];
@@ -331,21 +303,7 @@ export class CopilotRuntime<const T extends Parameter[] | [] = []> {
331
303
  params?.remoteEndpoints.some((e) => e.type === EndpointType.LangGraphPlatform)
332
304
  ) {
333
305
  console.warn("Actions set in runtime instance will not be available for the agent");
334
- console.warn(
335
- `LangGraph Platform remote endpoints are deprecated in favor of the "agents" property`,
336
- );
337
306
  }
338
-
339
- // TODO: finalize
340
- // if (
341
- // params?.agents &&
342
- // Object.values(params.agents).some((agent) => {
343
- // return agent instanceof AguiLangGraphAgent && !(agent instanceof LangGraphAgent);
344
- // })
345
- // ) {
346
- // console.warn('LangGraph Agent class should be imported from @copilotkit/runtime. ')
347
- // }
348
-
349
307
  this.actions = params?.actions || [];
350
308
  this.availableAgents = [];
351
309
 
@@ -362,7 +320,6 @@ export class CopilotRuntime<const T extends Parameter[] | [] = []> {
362
320
  params?.delegateAgentProcessingToServiceAdapter || false;
363
321
  this.observability = params?.observability_c;
364
322
  this.agents = params?.agents ?? {};
365
- this.onTrace = params?.onTrace;
366
323
  // +++ MCP Initialization +++
367
324
  this.mcpServersConfig = params?.mcpServers;
368
325
  this.createMCPClientImpl = params?.createMCPClient;
@@ -495,32 +452,6 @@ export class CopilotRuntime<const T extends Parameter[] | [] = []> {
495
452
  // For storing streamed chunks if progressive logging is enabled
496
453
  const streamedChunks: any[] = [];
497
454
 
498
- // Trace request start
499
- await this.trace(
500
- "request",
501
- {
502
- threadId,
503
- runId,
504
- source: "runtime",
505
- request: {
506
- operation: "processRuntimeRequest",
507
- method: "POST",
508
- url: url,
509
- startTime: requestStartTime,
510
- },
511
- agent: agentSession ? { name: agentSession.agentName } : undefined,
512
- messages: {
513
- input: rawMessages,
514
- messageCount: rawMessages.length,
515
- },
516
- technical: {
517
- environment: process.env.NODE_ENV,
518
- },
519
- },
520
- undefined,
521
- publicApiKey,
522
- );
523
-
524
455
  try {
525
456
  if (
526
457
  Object.keys(this.agents).length &&
@@ -744,62 +675,17 @@ please use an LLM adapter instead.`,
744
675
  }
745
676
  }
746
677
 
747
- let structuredError: CopilotKitError;
748
-
749
678
  if (error instanceof CopilotKitError) {
750
- structuredError = error;
751
- } else {
752
- // Convert non-CopilotKitErrors to structured errors, but preserve already structured ones
753
- structuredError = ensureStructuredError(error, (err) =>
754
- this.convertStreamingErrorToStructured(err),
755
- );
679
+ throw error;
756
680
  }
757
681
 
758
- // Trace the error
759
- await this.trace(
760
- "error",
761
- {
762
- threadId,
763
- runId,
764
- source: "runtime",
765
- request: {
766
- operation: "processRuntimeRequest",
767
- method: "POST",
768
- url: url,
769
- startTime: requestStartTime,
770
- },
771
- response: {
772
- endTime: Date.now(),
773
- latency: Date.now() - requestStartTime,
774
- },
775
- agent: agentSession ? { name: agentSession.agentName } : undefined,
776
- technical: {
777
- environment: process.env.NODE_ENV,
778
- stackTrace: error instanceof Error ? error.stack : undefined,
779
- },
780
- },
781
- structuredError,
782
- publicApiKey,
783
- );
784
-
682
+ // Convert non-CopilotKitErrors to structured errors
683
+ console.error("Error getting response:", error);
684
+ const structuredError = this.convertStreamingErrorToStructured(error);
785
685
  throw structuredError;
786
686
  }
787
687
  }
788
688
 
789
- async getAllAgents(graphqlContext: GraphQLContext): Promise<(AgentWithEndpoint | Agent)[]> {
790
- const [agentsWithEndpoints, aguiAgents] = await Promise.all([
791
- this.discoverAgentsFromEndpoints(graphqlContext),
792
- this.discoverAgentsFromAgui(),
793
- ]);
794
-
795
- this.availableAgents = [...agentsWithEndpoints, ...aguiAgents].map((a) => ({
796
- name: a.name,
797
- id: a.id,
798
- }));
799
-
800
- return [...agentsWithEndpoints, ...aguiAgents];
801
- }
802
-
803
689
  async discoverAgentsFromEndpoints(graphqlContext: GraphQLContext): Promise<AgentWithEndpoint[]> {
804
690
  const agents: Promise<AgentWithEndpoint[]> = this.remoteEndpointDefinitions.reduce(
805
691
  async (acc: Promise<Agent[]>, endpoint) => {
@@ -881,41 +767,7 @@ please use an LLM adapter instead.`,
881
767
  },
882
768
  Promise.resolve([]),
883
769
  );
884
-
885
- return agents;
886
- }
887
-
888
- async discoverAgentsFromAgui(): Promise<AgentWithEndpoint[]> {
889
- const agents: Promise<AgentWithEndpoint[]> = Object.values(this.agents ?? []).reduce(
890
- async (acc: Promise<Agent[]>, agent: LangGraphAgent) => {
891
- const agents = await acc;
892
-
893
- const client = agent.client;
894
- let data: Array<{ assistant_id: string; graph_id: string }> | { detail: string } = [];
895
- try {
896
- data = await client.assistants.search();
897
-
898
- if (data && "detail" in data && (data.detail as string).toLowerCase() === "not found") {
899
- throw new CopilotKitAgentDiscoveryError({ availableAgents: this.availableAgents });
900
- }
901
- } catch (e) {
902
- throw new CopilotKitMisuseError({
903
- message: `
904
- Failed to find or contact agent ${agent.graphId}.
905
- Make sure the LangGraph API is running and the agent is defined in langgraph.json
906
-
907
- See more: https://docs.copilotkit.ai/troubleshooting/common-issues`,
908
- });
909
- }
910
- const endpointAgents = data.map((entry) => ({
911
- name: entry.graph_id,
912
- id: entry.assistant_id,
913
- description: "",
914
- }));
915
- return [...agents, ...endpointAgents];
916
- },
917
- Promise.resolve([]),
918
- );
770
+ this.availableAgents = ((await agents) ?? []).map((a) => ({ name: a.name, id: a.id }));
919
771
 
920
772
  return agents;
921
773
  }
@@ -925,18 +777,50 @@ please use an LLM adapter instead.`,
925
777
  threadId: string,
926
778
  agentName: string,
927
779
  ): Promise<LoadAgentStateResponse> {
928
- const agents = await this.getAllAgents(graphqlContext);
780
+ const agentsWithEndpoints = await this.discoverAgentsFromEndpoints(graphqlContext);
929
781
 
930
- const agent = agents.find((agent) => agent.name === agentName);
931
- if (!agent) {
782
+ const agentWithEndpoint = agentsWithEndpoints.find((agent) => agent.name === agentName);
783
+ if (!agentWithEndpoint) {
932
784
  throw new Error("Agent not found");
933
785
  }
934
786
 
935
- if (
936
- "endpoint" in agent &&
937
- (agent.endpoint.type === EndpointType.CopilotKit || !("type" in agent.endpoint))
787
+ if (agentWithEndpoint.endpoint.type === EndpointType.LangGraphPlatform) {
788
+ const propertyHeaders = graphqlContext.properties.authorization
789
+ ? { authorization: `Bearer ${graphqlContext.properties.authorization}` }
790
+ : null;
791
+
792
+ const client = new LangGraphClient({
793
+ apiUrl: agentWithEndpoint.endpoint.deploymentUrl,
794
+ apiKey: agentWithEndpoint.endpoint.langsmithApiKey,
795
+ defaultHeaders: { ...propertyHeaders },
796
+ });
797
+ let state: any = {};
798
+ try {
799
+ state = (await client.threads.getState(threadId)).values as any;
800
+ } catch (error) {}
801
+
802
+ if (Object.keys(state).length === 0) {
803
+ return {
804
+ threadId: threadId || "",
805
+ threadExists: false,
806
+ state: JSON.stringify({}),
807
+ messages: JSON.stringify([]),
808
+ };
809
+ } else {
810
+ const { messages, ...stateWithoutMessages } = state;
811
+ const copilotkitMessages = langchainMessagesToCopilotKit(messages);
812
+ return {
813
+ threadId: threadId || "",
814
+ threadExists: true,
815
+ state: JSON.stringify(stateWithoutMessages),
816
+ messages: JSON.stringify(copilotkitMessages),
817
+ };
818
+ }
819
+ } else if (
820
+ agentWithEndpoint.endpoint.type === EndpointType.CopilotKit ||
821
+ !("type" in agentWithEndpoint.endpoint)
938
822
  ) {
939
- const cpkEndpoint = agent.endpoint as CopilotKitEndpoint;
823
+ const cpkEndpoint = agentWithEndpoint.endpoint as CopilotKitEndpoint;
940
824
  const fetchUrl = `${cpkEndpoint.url}/agents/state`;
941
825
  try {
942
826
  const response = await fetchWithRetry(fetchUrl, {
@@ -952,24 +836,10 @@ please use an LLM adapter instead.`,
952
836
  if (response.status === 404) {
953
837
  throw new CopilotKitApiDiscoveryError({ url: fetchUrl });
954
838
  }
955
-
956
- // Extract semantic error information from response body
957
- let errorMessage = `HTTP ${response.status} error`;
958
- try {
959
- const errorBody = await response.text();
960
- const parsedError = JSON.parse(errorBody);
961
- if (parsedError.error && typeof parsedError.error === "string") {
962
- errorMessage = parsedError.error;
963
- }
964
- } catch {
965
- // If parsing fails, fall back to generic message
966
- }
967
-
968
839
  throw new ResolvedCopilotKitError({
969
840
  status: response.status,
970
841
  url: fetchUrl,
971
842
  isRemoteEndpoint: true,
972
- message: errorMessage,
973
843
  });
974
844
  }
975
845
 
@@ -986,64 +856,9 @@ please use an LLM adapter instead.`,
986
856
  }
987
857
  throw new CopilotKitLowLevelError({ error, url: fetchUrl });
988
858
  }
989
- }
990
-
991
- const propertyHeaders = graphqlContext.properties.authorization
992
- ? { authorization: `Bearer ${graphqlContext.properties.authorization}` }
993
- : null;
994
-
995
- let client: LangGraphClient;
996
- if ("endpoint" in agent && agent.endpoint.type === EndpointType.LangGraphPlatform) {
997
- client = new LangGraphClient({
998
- apiUrl: agent.endpoint.deploymentUrl,
999
- apiKey: agent.endpoint.langsmithApiKey,
1000
- defaultHeaders: { ...propertyHeaders },
1001
- });
1002
859
  } else {
1003
- const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name] as LangGraphAgent;
1004
- if (!aguiAgent) {
1005
- throw new Error(`Agent: ${agent.name} could not be resolved`);
1006
- }
1007
- // @ts-expect-error -- both clients are the same
1008
- client = aguiAgent.client;
860
+ throw new Error(`Unknown endpoint type: ${(agentWithEndpoint.endpoint as any).type}`);
1009
861
  }
1010
- let state: any = {};
1011
- try {
1012
- state = (await client.threads.getState(threadId)).values as any;
1013
- } catch (error) {
1014
- // All errors from agent state loading are user configuration issues
1015
- const errorMessage = error instanceof Error ? error.message : String(error);
1016
-
1017
- // Log user configuration errors at debug level to reduce noise
1018
- console.debug(`Agent '${agentName}' configuration issue: ${errorMessage}`);
1019
-
1020
- // Throw a configuration error - all agent state loading failures are user setup issues
1021
- throw new ResolvedCopilotKitError({
1022
- status: 400,
1023
- message: `Agent '${agentName}' failed to execute: ${errorMessage}`,
1024
- code: CopilotKitErrorCode.CONFIGURATION_ERROR,
1025
- });
1026
- }
1027
-
1028
- if (Object.keys(state).length === 0) {
1029
- return {
1030
- threadId: threadId || "",
1031
- threadExists: false,
1032
- state: JSON.stringify({}),
1033
- messages: JSON.stringify([]),
1034
- };
1035
- } else {
1036
- const { messages, ...stateWithoutMessages } = state;
1037
- const copilotkitMessages = langchainMessagesToCopilotKit(messages);
1038
- return {
1039
- threadId: threadId || "",
1040
- threadExists: true,
1041
- state: JSON.stringify(stateWithoutMessages),
1042
- messages: JSON.stringify(copilotkitMessages),
1043
- };
1044
- }
1045
-
1046
- throw new Error(`Agent: ${agent.name} could not be resolved`);
1047
862
  }
1048
863
 
1049
864
  private async processAgentRequest(
@@ -1069,33 +884,6 @@ please use an LLM adapter instead.`,
1069
884
  // for backwards compatibility, deal with the case when no threadId is provided
1070
885
  const threadId = threadIdFromRequest ?? agentSession.threadId;
1071
886
 
1072
- // Trace agent request start
1073
- await this.trace(
1074
- "agent_state",
1075
- {
1076
- threadId,
1077
- source: "agent",
1078
- request: {
1079
- operation: "processAgentRequest",
1080
- method: "POST",
1081
- startTime: requestStartTime,
1082
- },
1083
- agent: {
1084
- name: agentName,
1085
- nodeName: nodeName,
1086
- },
1087
- messages: {
1088
- input: rawMessages,
1089
- messageCount: rawMessages.length,
1090
- },
1091
- technical: {
1092
- environment: process.env.NODE_ENV,
1093
- },
1094
- },
1095
- undefined,
1096
- publicApiKey,
1097
- );
1098
-
1099
887
  const serverSideActions = await this.getServerSideActions(request);
1100
888
 
1101
889
  const messages = convertGqlInputToMessages(rawMessages);
@@ -1223,7 +1011,9 @@ please use an LLM adapter instead.`,
1223
1011
  eventSource.stream(async (eventStream$) => {
1224
1012
  from(stream).subscribe({
1225
1013
  next: (event) => eventStream$.next(event),
1226
- error: async (err) => {
1014
+ error: (err) => {
1015
+ console.error("Error in stream", err);
1016
+
1227
1017
  // Log error with observability if enabled
1228
1018
  if (this.observability?.enabled && publicApiKey) {
1229
1019
  try {
@@ -1245,39 +1035,8 @@ please use an LLM adapter instead.`,
1245
1035
  }
1246
1036
  }
1247
1037
 
1248
- // Preserve structured CopilotKit errors, only convert unstructured errors
1249
- const structuredError = ensureStructuredError(err, (error) =>
1250
- this.convertStreamingErrorToStructured(error),
1251
- );
1252
-
1253
- // Trace streaming errors
1254
- await this.trace(
1255
- "error",
1256
- {
1257
- threadId,
1258
- source: "agent",
1259
- request: {
1260
- operation: "processAgentRequest",
1261
- method: "POST",
1262
- startTime: requestStartTime,
1263
- },
1264
- response: {
1265
- endTime: Date.now(),
1266
- latency: Date.now() - requestStartTime,
1267
- },
1268
- agent: {
1269
- name: agentName,
1270
- nodeName: nodeName,
1271
- },
1272
- technical: {
1273
- environment: process.env.NODE_ENV,
1274
- stackTrace: err instanceof Error ? err.stack : undefined,
1275
- },
1276
- },
1277
- structuredError,
1278
- publicApiKey,
1279
- );
1280
-
1038
+ // Convert network termination errors to structured errors
1039
+ const structuredError = this.convertStreamingErrorToStructured(err);
1281
1040
  eventStream$.error(structuredError);
1282
1041
  eventStream$.complete();
1283
1042
  },
@@ -1355,41 +1114,8 @@ please use an LLM adapter instead.`,
1355
1114
  }
1356
1115
  }
1357
1116
 
1358
- // Ensure error is structured
1359
- const structuredError = ensureStructuredError(error, (err) =>
1360
- this.convertStreamingErrorToStructured(err),
1361
- );
1362
-
1363
- // Trace the agent error
1364
- await this.trace(
1365
- "error",
1366
- {
1367
- threadId,
1368
- source: "agent",
1369
- request: {
1370
- operation: "processAgentRequest",
1371
- method: "POST",
1372
- startTime: requestStartTime,
1373
- },
1374
- response: {
1375
- endTime: Date.now(),
1376
- latency: Date.now() - requestStartTime,
1377
- },
1378
- agent: {
1379
- name: agentName,
1380
- nodeName: nodeName,
1381
- },
1382
- technical: {
1383
- environment: process.env.NODE_ENV,
1384
- stackTrace: error instanceof Error ? error.stack : undefined,
1385
- },
1386
- },
1387
- structuredError,
1388
- publicApiKey,
1389
- );
1390
-
1391
1117
  console.error("Error getting response:", error);
1392
- throw structuredError;
1118
+ throw error;
1393
1119
  }
1394
1120
  }
1395
1121
 
@@ -1505,108 +1231,53 @@ please use an LLM adapter instead.`,
1505
1231
  }
1506
1232
 
1507
1233
  private convertStreamingErrorToStructured(error: any): CopilotKitError {
1508
- // Determine a more helpful error message based on context
1509
- let helpfulMessage = generateHelpfulErrorMessage(error, "agent streaming connection");
1510
-
1511
- // For network-related errors, use CopilotKitLowLevelError to preserve the original error
1234
+ // Handle network termination errors
1512
1235
  if (
1513
- error?.message?.includes("fetch failed") ||
1514
- error?.message?.includes("ECONNREFUSED") ||
1515
- error?.message?.includes("ENOTFOUND") ||
1516
- error?.message?.includes("ETIMEDOUT") ||
1517
1236
  error?.message?.includes("terminated") ||
1518
1237
  error?.cause?.code === "UND_ERR_SOCKET" ||
1519
1238
  error?.message?.includes("other side closed") ||
1520
1239
  error?.code === "UND_ERR_SOCKET"
1240
+ ) {
1241
+ return new CopilotKitError({
1242
+ message:
1243
+ "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
1244
+ code: CopilotKitErrorCode.NETWORK_ERROR,
1245
+ });
1246
+ }
1247
+
1248
+ // Handle other network-related errors
1249
+ if (
1250
+ error?.message?.includes("fetch failed") ||
1251
+ error?.message?.includes("ECONNREFUSED") ||
1252
+ error?.message?.includes("ENOTFOUND") ||
1253
+ error?.message?.includes("ETIMEDOUT")
1521
1254
  ) {
1522
1255
  return new CopilotKitLowLevelError({
1523
1256
  error: error instanceof Error ? error : new Error(String(error)),
1524
1257
  url: "agent streaming connection",
1525
- message: helpfulMessage,
1258
+ message:
1259
+ "Network error occurred during agent streaming. Please check your connection and try again.",
1260
+ });
1261
+ }
1262
+
1263
+ // Handle abort/cancellation errors (these are usually normal)
1264
+ if (
1265
+ error?.message?.includes("aborted") ||
1266
+ error?.message?.includes("canceled") ||
1267
+ error?.message?.includes("signal is aborted")
1268
+ ) {
1269
+ return new CopilotKitError({
1270
+ message: "Agent request was cancelled",
1271
+ code: CopilotKitErrorCode.UNKNOWN,
1526
1272
  });
1527
1273
  }
1528
1274
 
1529
- // For all other errors, preserve the raw error in a basic CopilotKitError
1275
+ // Default: convert unknown streaming errors
1530
1276
  return new CopilotKitError({
1531
- message: helpfulMessage,
1277
+ message: `Agent streaming error: ${error?.message || String(error)}`,
1532
1278
  code: CopilotKitErrorCode.UNKNOWN,
1533
1279
  });
1534
1280
  }
1535
-
1536
- private async trace(
1537
- type: CopilotTraceEvent["type"],
1538
- context: CopilotRequestContext,
1539
- error?: any,
1540
- publicApiKey?: string,
1541
- ): Promise<void> {
1542
- if (!this.onTrace) return;
1543
-
1544
- // Just check if publicApiKey is defined (regardless of validity)
1545
- if (!publicApiKey) {
1546
- if (!this.hasWarnedAboutTracing) {
1547
- console.warn(
1548
- "CopilotKit: onTrace handler provided but requires publicApiKey to be defined for tracing to work.",
1549
- );
1550
- this.hasWarnedAboutTracing = true;
1551
- }
1552
- return;
1553
- }
1554
-
1555
- try {
1556
- const traceEvent: CopilotTraceEvent = {
1557
- type,
1558
- timestamp: Date.now(),
1559
- context,
1560
- ...(error && { error }),
1561
- };
1562
-
1563
- await this.onTrace(traceEvent);
1564
- } catch (traceError) {
1565
- // Don't let trace errors break the main flow
1566
- console.error("Error in onTrace handler:", traceError);
1567
- }
1568
- }
1569
-
1570
- /**
1571
- * Public method to trace GraphQL validation errors
1572
- * This allows the GraphQL resolver to send validation errors through the trace system
1573
- */
1574
- public async traceGraphQLError(
1575
- error: { message: string; code: string; type: string },
1576
- context: {
1577
- operation: string;
1578
- cloudConfigPresent: boolean;
1579
- guardrailsEnabled: boolean;
1580
- },
1581
- ): Promise<void> {
1582
- if (!this.onTrace) return;
1583
-
1584
- try {
1585
- await this.onTrace({
1586
- type: "error",
1587
- timestamp: Date.now(),
1588
- context: {
1589
- source: "runtime",
1590
- request: {
1591
- operation: context.operation,
1592
- startTime: Date.now(),
1593
- },
1594
- technical: {
1595
- environment: process.env.NODE_ENV,
1596
- },
1597
- metadata: {
1598
- errorType: "GraphQLValidationError",
1599
- cloudConfigPresent: context.cloudConfigPresent,
1600
- guardrailsEnabled: context.guardrailsEnabled,
1601
- },
1602
- },
1603
- error,
1604
- });
1605
- } catch (traceError) {
1606
- // Don't let trace errors break the main flow
1607
- console.error("Error in onTrace handler:", traceError);
1608
- }
1609
- }
1610
1281
  }
1611
1282
 
1612
1283
  export function flattenToolCallsNoDuplicates(toolsByPriority: ActionInput[]): ActionInput[] {
@@ -16,7 +16,6 @@ import {
16
16
  LangGraphAgent as AGUILangGraphAgent,
17
17
  type LangGraphAgentConfig,
18
18
  ProcessedEvents,
19
- SchemaKeys,
20
19
  } from "@ag-ui/langgraph";
21
20
  import { Message as LangGraphMessage } from "@langchain/langgraph-sdk/dist/types.messages";
22
21
 
@@ -181,7 +180,6 @@ export class LangGraphAgent extends AGUILangGraphAgent {
181
180
  messages,
182
181
  tools,
183
182
  );
184
-
185
183
  return {
186
184
  ...rest,
187
185
  copilotkit: {
@@ -189,14 +187,4 @@ export class LangGraphAgent extends AGUILangGraphAgent {
189
187
  },
190
188
  };
191
189
  }
192
-
193
- async getSchemaKeys(): Promise<SchemaKeys> {
194
- const CONSTANT_KEYS = ["copilotkit"];
195
- const schemaKeys = await super.getSchemaKeys();
196
- return {
197
- config: schemaKeys.config,
198
- input: schemaKeys.input ? [...schemaKeys.input, ...CONSTANT_KEYS] : null,
199
- output: schemaKeys.output ? [...schemaKeys.output, ...CONSTANT_KEYS] : null,
200
- };
201
- }
202
190
  }