@copilotkit/runtime 1.9.1 → 1.9.2-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 (47) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/{chunk-RVLXQ2V5.mjs → chunk-44FYLJJJ.mjs} +2 -2
  3. package/dist/{chunk-2CND6WGV.mjs → chunk-ESXPDYNT.mjs} +2 -2
  4. package/dist/{chunk-BHNTR222.mjs → chunk-O6KXX5R5.mjs} +2 -2
  5. package/dist/{chunk-GOPTDPPB.mjs → chunk-YMIOUUPV.mjs} +260 -61
  6. package/dist/chunk-YMIOUUPV.mjs.map +1 -0
  7. package/dist/{chunk-EVF3MXEK.mjs → chunk-YXL4PSJM.mjs} +2 -2
  8. package/dist/index.d.ts +1 -1
  9. package/dist/index.js +305 -106
  10. package/dist/index.js.map +1 -1
  11. package/dist/index.mjs +5 -5
  12. package/dist/lib/index.d.ts +1 -1
  13. package/dist/lib/index.js +298 -99
  14. package/dist/lib/index.js.map +1 -1
  15. package/dist/lib/index.mjs +5 -5
  16. package/dist/lib/integrations/index.d.ts +2 -2
  17. package/dist/lib/integrations/index.js +16 -7
  18. package/dist/lib/integrations/index.js.map +1 -1
  19. package/dist/lib/integrations/index.mjs +4 -4
  20. package/dist/lib/integrations/nest/index.d.ts +1 -1
  21. package/dist/lib/integrations/nest/index.js +16 -7
  22. package/dist/lib/integrations/nest/index.js.map +1 -1
  23. package/dist/lib/integrations/nest/index.mjs +2 -2
  24. package/dist/lib/integrations/node-express/index.d.ts +1 -1
  25. package/dist/lib/integrations/node-express/index.js +16 -7
  26. package/dist/lib/integrations/node-express/index.js.map +1 -1
  27. package/dist/lib/integrations/node-express/index.mjs +2 -2
  28. package/dist/lib/integrations/node-http/index.d.ts +1 -1
  29. package/dist/lib/integrations/node-http/index.js +16 -7
  30. package/dist/lib/integrations/node-http/index.js.map +1 -1
  31. package/dist/lib/integrations/node-http/index.mjs +1 -1
  32. package/dist/{shared-0c31d7c5.d.ts → shared-e272b15a.d.ts} +1 -0
  33. package/package.json +2 -2
  34. package/src/agents/langgraph/event-source.ts +10 -1
  35. package/src/graphql/resolvers/copilot.resolver.ts +13 -0
  36. package/src/graphql/resolvers/state.resolver.ts +5 -7
  37. package/src/lib/runtime/copilot-runtime.ts +62 -6
  38. package/src/lib/runtime/remote-action-constructors.ts +37 -28
  39. package/src/lib/runtime/remote-lg-action.ts +45 -24
  40. package/src/lib/runtime/retry-utils.ts +96 -0
  41. package/src/lib/streaming.ts +54 -1
  42. package/src/service-adapters/events.ts +101 -6
  43. package/dist/chunk-GOPTDPPB.mjs.map +0 -1
  44. /package/dist/{chunk-RVLXQ2V5.mjs.map → chunk-44FYLJJJ.mjs.map} +0 -0
  45. /package/dist/{chunk-2CND6WGV.mjs.map → chunk-ESXPDYNT.mjs.map} +0 -0
  46. /package/dist/{chunk-BHNTR222.mjs.map → chunk-O6KXX5R5.mjs.map} +0 -0
  47. /package/dist/{chunk-EVF3MXEK.mjs.map → chunk-YXL4PSJM.mjs.map} +0 -0
package/dist/index.js CHANGED
@@ -44,7 +44,7 @@ var require_package = __commonJS({
44
44
  publishConfig: {
45
45
  access: "public"
46
46
  },
47
- version: "1.9.1",
47
+ version: "1.9.2-next.0",
48
48
  sideEffects: false,
49
49
  main: "./dist/index.js",
50
50
  module: "./dist/index.mjs",
@@ -2744,14 +2744,14 @@ GenerateCopilotResponseInput = _ts_decorate17([
2744
2744
  var import_graphql_yoga = require("graphql-yoga");
2745
2745
 
2746
2746
  // src/service-adapters/events.ts
2747
- var import_shared22 = require("@copilotkit/shared");
2747
+ var import_shared23 = require("@copilotkit/shared");
2748
2748
  var import_rxjs3 = require("rxjs");
2749
2749
 
2750
2750
  // src/lib/telemetry-client.ts
2751
- var import_shared21 = require("@copilotkit/shared");
2751
+ var import_shared22 = require("@copilotkit/shared");
2752
2752
 
2753
2753
  // src/lib/runtime/remote-actions.ts
2754
- var import_shared14 = require("@copilotkit/shared");
2754
+ var import_shared15 = require("@copilotkit/shared");
2755
2755
 
2756
2756
  // src/lib/runtime/remote-action-constructors.ts
2757
2757
  var import_node_crypto2 = require("crypto");
@@ -2992,6 +2992,9 @@ var RemoteLangGraphEventSource = class {
2992
2992
  return events;
2993
2993
  }), (0, import_rxjs.catchError)((error) => {
2994
2994
  console.error(error);
2995
+ if (error instanceof import_shared7.CopilotKitError || (error == null ? void 0 : error.name) && error.name.includes("CopilotKit")) {
2996
+ throw error;
2997
+ }
2995
2998
  const events = [];
2996
2999
  if ((lastEventWithState == null ? void 0 : lastEventWithState.lastMessageId) && !lastEventWithState.isToolCall) {
2997
3000
  events.push({
@@ -3032,32 +3035,119 @@ var import_shared8 = require("@copilotkit/shared");
3032
3035
  var import_partial_json = require("partial-json");
3033
3036
  var import_shared9 = require("@copilotkit/shared");
3034
3037
  var import_messages3 = require("@langchain/core/messages");
3038
+
3039
+ // src/lib/runtime/retry-utils.ts
3040
+ var RETRY_CONFIG = {
3041
+ maxRetries: 3,
3042
+ baseDelayMs: 1e3,
3043
+ maxDelayMs: 5e3,
3044
+ // HTTP status codes that should be retried
3045
+ retryableStatusCodes: [
3046
+ 502,
3047
+ 503,
3048
+ 504,
3049
+ 408,
3050
+ 429
3051
+ ],
3052
+ // Network error patterns that should be retried
3053
+ retryableErrorMessages: [
3054
+ "fetch failed",
3055
+ "network error",
3056
+ "connection timeout",
3057
+ "ECONNREFUSED",
3058
+ "ETIMEDOUT",
3059
+ "ENOTFOUND",
3060
+ "ECONNRESET"
3061
+ ]
3062
+ };
3063
+ function isRetryableError(error, response) {
3064
+ var _a, _b;
3065
+ if (response && RETRY_CONFIG.retryableStatusCodes.includes(response.status)) {
3066
+ return true;
3067
+ }
3068
+ const errorCode = ((_a = error == null ? void 0 : error.cause) == null ? void 0 : _a.code) || (error == null ? void 0 : error.code);
3069
+ if (errorCode && RETRY_CONFIG.retryableErrorMessages.includes(errorCode)) {
3070
+ return true;
3071
+ }
3072
+ const errorMessage = ((_b = error == null ? void 0 : error.message) == null ? void 0 : _b.toLowerCase()) || "";
3073
+ return RETRY_CONFIG.retryableErrorMessages.some((msg) => errorMessage.includes(msg));
3074
+ }
3075
+ __name(isRetryableError, "isRetryableError");
3076
+ function sleep(ms) {
3077
+ return new Promise((resolve) => setTimeout(resolve, ms));
3078
+ }
3079
+ __name(sleep, "sleep");
3080
+ function calculateDelay(attempt) {
3081
+ const delay = RETRY_CONFIG.baseDelayMs * Math.pow(2, attempt);
3082
+ return Math.min(delay, RETRY_CONFIG.maxDelayMs);
3083
+ }
3084
+ __name(calculateDelay, "calculateDelay");
3085
+ async function fetchWithRetry(url, options, logger2) {
3086
+ let lastError;
3087
+ for (let attempt = 0; attempt <= RETRY_CONFIG.maxRetries; attempt++) {
3088
+ try {
3089
+ const response = await fetch(url, options);
3090
+ if (isRetryableError(null, response) && attempt < RETRY_CONFIG.maxRetries) {
3091
+ const delay = calculateDelay(attempt);
3092
+ logger2 == null ? void 0 : logger2.warn(`Request to ${url} failed with status ${response.status}. Retrying attempt ${attempt + 1}/${RETRY_CONFIG.maxRetries + 1} in ${delay}ms.`);
3093
+ await sleep(delay);
3094
+ continue;
3095
+ }
3096
+ return response;
3097
+ } catch (error) {
3098
+ lastError = error;
3099
+ if (isRetryableError(error) && attempt < RETRY_CONFIG.maxRetries) {
3100
+ const delay = calculateDelay(attempt);
3101
+ logger2 == null ? void 0 : logger2.warn(`Request to ${url} failed with network error. Retrying attempt ${attempt + 1}/${RETRY_CONFIG.maxRetries + 1} in ${delay}ms. Error: ${(error == null ? void 0 : error.message) || String(error)}`);
3102
+ await sleep(delay);
3103
+ continue;
3104
+ }
3105
+ break;
3106
+ }
3107
+ }
3108
+ throw lastError;
3109
+ }
3110
+ __name(fetchWithRetry, "fetchWithRetry");
3111
+
3112
+ // src/lib/runtime/remote-lg-action.ts
3035
3113
  var activeInterruptEvent = false;
3036
3114
  async function execute(args) {
3037
3115
  return new ReadableStream({
3038
3116
  async start(controller) {
3039
- try {
3040
- await streamEvents(controller, args);
3041
- controller.close();
3042
- } catch (err) {
3043
- const cause = err == null ? void 0 : err.cause;
3044
- const errorCode = (cause == null ? void 0 : cause.code) || (err == null ? void 0 : err.code);
3045
- if (errorCode === "ECONNREFUSED") {
3046
- throw new import_shared9.CopilotKitMisuseError({
3047
- message: `
3048
- The LangGraph client could not connect to the graph. Please further check previous logs, which includes further details.
3049
-
3050
- See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3051
- });
3052
- } else {
3053
- throw new import_shared9.CopilotKitMisuseError({
3054
- message: `
3055
- The LangGraph client threw unhandled error ${err}.
3056
-
3057
- See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3058
- });
3117
+ let lastError;
3118
+ for (let attempt = 0; attempt <= RETRY_CONFIG.maxRetries; attempt++) {
3119
+ try {
3120
+ await streamEvents(controller, args);
3121
+ controller.close();
3122
+ return;
3123
+ } catch (err) {
3124
+ lastError = err;
3125
+ if (isRetryableError(err) && attempt < RETRY_CONFIG.maxRetries) {
3126
+ const delay = calculateDelay(attempt);
3127
+ console.warn(`LangGraph connection attempt ${attempt + 1}/${RETRY_CONFIG.maxRetries + 1} failed. Retrying in ${delay}ms. Error: ${(err == null ? void 0 : err.message) || String(err)}`);
3128
+ await sleep(delay);
3129
+ continue;
3130
+ }
3131
+ break;
3059
3132
  }
3060
3133
  }
3134
+ const cause = lastError == null ? void 0 : lastError.cause;
3135
+ const errorCode = (cause == null ? void 0 : cause.code) || (lastError == null ? void 0 : lastError.code);
3136
+ if (errorCode === "ECONNREFUSED") {
3137
+ throw new import_shared9.CopilotKitMisuseError({
3138
+ message: `
3139
+ The LangGraph client could not connect to the graph after ${RETRY_CONFIG.maxRetries + 1} attempts. Please further check previous logs, which includes further details.
3140
+
3141
+ See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3142
+ });
3143
+ } else {
3144
+ throw new import_shared9.CopilotKitMisuseError({
3145
+ message: `
3146
+ The LangGraph client threw unhandled error ${lastError}.
3147
+
3148
+ See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3149
+ });
3150
+ }
3061
3151
  }
3062
3152
  });
3063
3153
  }
@@ -3657,9 +3747,10 @@ function filterObjectBySchemaKeys(obj, schemaKeys) {
3657
3747
  __name(filterObjectBySchemaKeys, "filterObjectBySchemaKeys");
3658
3748
 
3659
3749
  // src/lib/runtime/remote-action-constructors.ts
3660
- var import_shared10 = require("@copilotkit/shared");
3750
+ var import_shared11 = require("@copilotkit/shared");
3661
3751
 
3662
3752
  // src/lib/streaming.ts
3753
+ var import_shared10 = require("@copilotkit/shared");
3663
3754
  async function writeJsonLineResponseToEventStream(response, eventStream$) {
3664
3755
  const reader = response.getReader();
3665
3756
  const decoder = new TextDecoder();
@@ -3698,16 +3789,44 @@ async function writeJsonLineResponseToEventStream(response, eventStream$) {
3698
3789
  }
3699
3790
  } catch (error) {
3700
3791
  console.error("Error in stream", error);
3701
- eventStream$.error(error);
3792
+ const structuredError = convertStreamingErrorToStructured(error);
3793
+ eventStream$.error(structuredError);
3702
3794
  return;
3703
3795
  }
3704
3796
  eventStream$.complete();
3705
3797
  }
3706
3798
  __name(writeJsonLineResponseToEventStream, "writeJsonLineResponseToEventStream");
3799
+ function convertStreamingErrorToStructured(error) {
3800
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
3801
+ if (((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.includes("terminated")) || ((_b = error == null ? void 0 : error.cause) == null ? void 0 : _b.code) === "UND_ERR_SOCKET" || ((_c = error == null ? void 0 : error.message) == null ? void 0 : _c.includes("other side closed")) || (error == null ? void 0 : error.code) === "UND_ERR_SOCKET") {
3802
+ return new import_shared10.CopilotKitError({
3803
+ message: "Connection to agent was unexpectedly terminated. This is likely due to the agent service being down or experiencing issues. Please check your agent logs and try again.",
3804
+ code: import_shared10.CopilotKitErrorCode.NETWORK_ERROR
3805
+ });
3806
+ }
3807
+ if (((_d = error == null ? void 0 : error.message) == null ? void 0 : _d.includes("fetch failed")) || ((_e = error == null ? void 0 : error.message) == null ? void 0 : _e.includes("ECONNREFUSED")) || ((_f = error == null ? void 0 : error.message) == null ? void 0 : _f.includes("ENOTFOUND")) || ((_g = error == null ? void 0 : error.message) == null ? void 0 : _g.includes("ETIMEDOUT"))) {
3808
+ return new import_shared10.CopilotKitLowLevelError({
3809
+ error: error instanceof Error ? error : new Error(String(error)),
3810
+ url: "streaming connection",
3811
+ message: "Network error occurred during streaming. Please check your connection and try again."
3812
+ });
3813
+ }
3814
+ if (((_h = error == null ? void 0 : error.message) == null ? void 0 : _h.includes("aborted")) || ((_i = error == null ? void 0 : error.message) == null ? void 0 : _i.includes("canceled")) || ((_j = error == null ? void 0 : error.message) == null ? void 0 : _j.includes("signal is aborted"))) {
3815
+ return new import_shared10.CopilotKitError({
3816
+ message: "Request was cancelled",
3817
+ code: import_shared10.CopilotKitErrorCode.UNKNOWN
3818
+ });
3819
+ }
3820
+ return new import_shared10.CopilotKitError({
3821
+ message: `Streaming error: ${(error == null ? void 0 : error.message) || String(error)}`,
3822
+ code: import_shared10.CopilotKitErrorCode.UNKNOWN
3823
+ });
3824
+ }
3825
+ __name(convertStreamingErrorToStructured, "convertStreamingErrorToStructured");
3707
3826
 
3708
3827
  // src/lib/runtime/remote-action-constructors.ts
3709
- var import_shared11 = require("@copilotkit/shared");
3710
3828
  var import_shared12 = require("@copilotkit/shared");
3829
+ var import_shared13 = require("@copilotkit/shared");
3711
3830
  function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, messages, agentStates }) {
3712
3831
  const agents = endpoint.agents.map((agent) => ({
3713
3832
  name: agent.name,
@@ -3730,8 +3849,8 @@ function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, m
3730
3849
  if (agentStates) {
3731
3850
  const jsonState = agentStates.find((state2) => state2.agentName === name);
3732
3851
  if (jsonState) {
3733
- state = (0, import_shared12.parseJson)(jsonState.state, {});
3734
- config2 = (0, import_shared12.parseJson)(jsonState.config, {});
3852
+ state = (0, import_shared13.parseJson)(jsonState.state, {});
3853
+ config2 = (0, import_shared13.parseJson)(jsonState.config, {});
3735
3854
  }
3736
3855
  }
3737
3856
  try {
@@ -3751,7 +3870,7 @@ function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, m
3751
3870
  state,
3752
3871
  config: config2,
3753
3872
  properties: graphqlContext.properties,
3754
- actions: (0, import_shared12.tryMap)(actionInputsWithoutAgents, (action) => ({
3873
+ actions: (0, import_shared13.tryMap)(actionInputsWithoutAgents, (action) => ({
3755
3874
  name: action.name,
3756
3875
  description: action.description,
3757
3876
  parameters: JSON.parse(action.jsonSchema)
@@ -3800,7 +3919,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3800
3919
  });
3801
3920
  const fetchUrl = `${url}/actions/execute`;
3802
3921
  try {
3803
- const response = await fetch(fetchUrl, {
3922
+ const response = await fetchWithRetry(fetchUrl, {
3804
3923
  method: "POST",
3805
3924
  headers,
3806
3925
  body: JSON.stringify({
@@ -3808,7 +3927,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3808
3927
  arguments: args,
3809
3928
  properties: graphqlContext.properties
3810
3929
  })
3811
- });
3930
+ }, logger2);
3812
3931
  if (!response.ok) {
3813
3932
  logger2.error({
3814
3933
  url,
@@ -3816,11 +3935,11 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3816
3935
  body: await response.text()
3817
3936
  }, "Failed to execute remote action");
3818
3937
  if (response.status === 404) {
3819
- throw new import_shared11.CopilotKitApiDiscoveryError({
3938
+ throw new import_shared12.CopilotKitApiDiscoveryError({
3820
3939
  url: fetchUrl
3821
3940
  });
3822
3941
  }
3823
- throw new import_shared11.ResolvedCopilotKitError({
3942
+ throw new import_shared12.ResolvedCopilotKitError({
3824
3943
  status: response.status,
3825
3944
  url: fetchUrl,
3826
3945
  isRemoteEndpoint: true
@@ -3834,10 +3953,10 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3834
3953
  }, "Executed remote action");
3835
3954
  return result;
3836
3955
  } catch (error) {
3837
- if (error instanceof import_shared10.CopilotKitError) {
3956
+ if (error instanceof import_shared11.CopilotKitError) {
3838
3957
  throw error;
3839
3958
  }
3840
- throw new import_shared10.CopilotKitLowLevelError({
3959
+ throw new import_shared11.CopilotKitLowLevelError({
3841
3960
  error,
3842
3961
  url: fetchUrl
3843
3962
  });
@@ -3865,13 +3984,13 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3865
3984
  if (agentStates) {
3866
3985
  const jsonState = agentStates.find((state2) => state2.agentName === name);
3867
3986
  if (jsonState) {
3868
- state = (0, import_shared12.parseJson)(jsonState.state, {});
3869
- config2 = (0, import_shared12.parseJson)(jsonState.config, {});
3987
+ state = (0, import_shared13.parseJson)(jsonState.state, {});
3988
+ config2 = (0, import_shared13.parseJson)(jsonState.config, {});
3870
3989
  }
3871
3990
  }
3872
3991
  const fetchUrl = `${url}/agents/execute`;
3873
3992
  try {
3874
- const response = await fetch(fetchUrl, {
3993
+ const response = await fetchWithRetry(fetchUrl, {
3875
3994
  method: "POST",
3876
3995
  headers,
3877
3996
  body: JSON.stringify({
@@ -3885,14 +4004,14 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3885
4004
  state,
3886
4005
  config: config2,
3887
4006
  properties: graphqlContext.properties,
3888
- actions: (0, import_shared12.tryMap)(actionInputsWithoutAgents, (action) => ({
4007
+ actions: (0, import_shared13.tryMap)(actionInputsWithoutAgents, (action) => ({
3889
4008
  name: action.name,
3890
4009
  description: action.description,
3891
4010
  parameters: JSON.parse(action.jsonSchema)
3892
4011
  })),
3893
4012
  metaEvents
3894
4013
  })
3895
- });
4014
+ }, logger2);
3896
4015
  if (!response.ok) {
3897
4016
  logger2.error({
3898
4017
  url,
@@ -3900,11 +4019,11 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3900
4019
  body: await response.text()
3901
4020
  }, "Failed to execute remote agent");
3902
4021
  if (response.status === 404) {
3903
- throw new import_shared11.CopilotKitApiDiscoveryError({
4022
+ throw new import_shared12.CopilotKitApiDiscoveryError({
3904
4023
  url: fetchUrl
3905
4024
  });
3906
4025
  }
3907
- throw new import_shared11.ResolvedCopilotKitError({
4026
+ throw new import_shared12.ResolvedCopilotKitError({
3908
4027
  status: response.status,
3909
4028
  url: fetchUrl,
3910
4029
  isRemoteEndpoint: true
@@ -3922,10 +4041,10 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3922
4041
  throw new Error("Unsupported agent type");
3923
4042
  }
3924
4043
  } catch (error) {
3925
- if (error instanceof import_shared10.CopilotKitError) {
4044
+ if (error instanceof import_shared11.CopilotKitError) {
3926
4045
  throw error;
3927
4046
  }
3928
- throw new import_shared10.CopilotKitLowLevelError({
4047
+ throw new import_shared11.CopilotKitLowLevelError({
3929
4048
  error,
3930
4049
  url: fetchUrl
3931
4050
  });
@@ -3955,10 +4074,10 @@ function createHeaders(onBeforeRequest, graphqlContext) {
3955
4074
  __name(createHeaders, "createHeaders");
3956
4075
 
3957
4076
  // src/lib/runtime/remote-actions.ts
3958
- var import_shared15 = require("@copilotkit/shared");
4077
+ var import_shared16 = require("@copilotkit/shared");
3959
4078
 
3960
4079
  // src/lib/runtime/agui-action.ts
3961
- var import_shared13 = require("@copilotkit/shared");
4080
+ var import_shared14 = require("@copilotkit/shared");
3962
4081
  function constructAGUIRemoteAction({ logger: logger2, messages, agentStates, agent, metaEvents }) {
3963
4082
  const action = {
3964
4083
  name: agent.agentId,
@@ -3983,7 +4102,7 @@ function constructAGUIRemoteAction({ logger: logger2, messages, agentStates, age
3983
4102
  if (agentStates) {
3984
4103
  const jsonState = agentStates.find((state2) => state2.agentName === agent.agentId);
3985
4104
  if (jsonState) {
3986
- state = (0, import_shared13.parseJson)(jsonState.state, {});
4105
+ state = (0, import_shared14.parseJson)(jsonState.state, {});
3987
4106
  }
3988
4107
  }
3989
4108
  agent.state = state;
@@ -4090,7 +4209,7 @@ async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: l
4090
4209
  status: response.status,
4091
4210
  body: await response.text()
4092
4211
  }, "Failed to fetch actions from url");
4093
- throw new import_shared15.ResolvedCopilotKitError({
4212
+ throw new import_shared16.ResolvedCopilotKitError({
4094
4213
  status: response.status,
4095
4214
  url: fetchUrl,
4096
4215
  isRemoteEndpoint: true
@@ -4102,10 +4221,10 @@ async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: l
4102
4221
  }, "Fetched actions from url");
4103
4222
  return json;
4104
4223
  } catch (error) {
4105
- if (error instanceof import_shared15.CopilotKitError) {
4224
+ if (error instanceof import_shared16.CopilotKitError) {
4106
4225
  throw error;
4107
4226
  }
4108
- throw new import_shared15.CopilotKitLowLevelError({
4227
+ throw new import_shared16.CopilotKitLowLevelError({
4109
4228
  error,
4110
4229
  url: fetchUrl
4111
4230
  });
@@ -4163,9 +4282,9 @@ async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, m
4163
4282
  }));
4164
4283
  for (const [key, agent] of Object.entries(agents)) {
4165
4284
  if (agent.agentId !== void 0 && agent.agentId !== key) {
4166
- throw new import_shared15.CopilotKitError({
4285
+ throw new import_shared16.CopilotKitError({
4167
4286
  message: `Agent ${key} has agentId ${agent.agentId} which does not match the key ${key}`,
4168
- code: import_shared14.CopilotKitErrorCode.UNKNOWN
4287
+ code: import_shared15.CopilotKitErrorCode.UNKNOWN
4169
4288
  });
4170
4289
  } else if (agent.agentId === void 0) {
4171
4290
  agent.agentId = key;
@@ -4186,7 +4305,7 @@ __name(setupRemoteActions, "setupRemoteActions");
4186
4305
  var import_node_crypto3 = require("crypto");
4187
4306
 
4188
4307
  // src/lib/runtime/copilot-runtime.ts
4189
- var import_shared20 = require("@copilotkit/shared");
4308
+ var import_shared21 = require("@copilotkit/shared");
4190
4309
 
4191
4310
  // src/service-adapters/langchain/langserve.ts
4192
4311
  var import_remote = require("langchain/runnables/remote");
@@ -4416,7 +4535,7 @@ function convertMessageToAnthropicMessage(message) {
4416
4535
  __name(convertMessageToAnthropicMessage, "convertMessageToAnthropicMessage");
4417
4536
 
4418
4537
  // src/service-adapters/anthropic/anthropic-adapter.ts
4419
- var import_shared16 = require("@copilotkit/shared");
4538
+ var import_shared17 = require("@copilotkit/shared");
4420
4539
  var DEFAULT_MODEL3 = "claude-3-5-sonnet-latest";
4421
4540
  var AnthropicAdapter = class {
4422
4541
  model = DEFAULT_MODEL3;
@@ -4498,8 +4617,8 @@ var AnthropicAdapter = class {
4498
4617
  eventSource.stream(async (eventStream$) => {
4499
4618
  let mode = null;
4500
4619
  let didOutputText = false;
4501
- let currentMessageId = (0, import_shared16.randomId)();
4502
- let currentToolCallId = (0, import_shared16.randomId)();
4620
+ let currentMessageId = (0, import_shared17.randomId)();
4621
+ let currentToolCallId = (0, import_shared17.randomId)();
4503
4622
  let filterThinkingTextBuffer = new FilterThinkingTextBuffer();
4504
4623
  try {
4505
4624
  for await (const chunk of stream) {
@@ -4565,7 +4684,7 @@ var AnthropicAdapter = class {
4565
4684
  throw error;
4566
4685
  }
4567
4686
  return {
4568
- threadId: threadId || (0, import_shared16.randomUUID)()
4687
+ threadId: threadId || (0, import_shared17.randomUUID)()
4569
4688
  };
4570
4689
  }
4571
4690
  };
@@ -4605,7 +4724,7 @@ var FilterThinkingTextBuffer = /* @__PURE__ */ __name(class FilterThinkingTextBu
4605
4724
 
4606
4725
  // src/service-adapters/experimental/ollama/ollama-adapter.ts
4607
4726
  var import_ollama = require("@langchain/community/llms/ollama");
4608
- var import_shared17 = require("@copilotkit/shared");
4727
+ var import_shared18 = require("@copilotkit/shared");
4609
4728
  var DEFAULT_MODEL4 = "llama3:latest";
4610
4729
  var ExperimentalOllamaAdapter = class {
4611
4730
  model;
@@ -4624,7 +4743,7 @@ var ExperimentalOllamaAdapter = class {
4624
4743
  const contents = messages.filter((m) => m.isTextMessage()).map((m) => m.content);
4625
4744
  const _stream = await ollama.stream(contents);
4626
4745
  eventSource.stream(async (eventStream$) => {
4627
- const currentMessageId = (0, import_shared17.randomId)();
4746
+ const currentMessageId = (0, import_shared18.randomId)();
4628
4747
  eventStream$.sendTextMessageStart({
4629
4748
  messageId: currentMessageId
4630
4749
  });
@@ -4640,7 +4759,7 @@ var ExperimentalOllamaAdapter = class {
4640
4759
  eventStream$.complete();
4641
4760
  });
4642
4761
  return {
4643
- threadId: request.threadId || (0, import_shared17.randomUUID)()
4762
+ threadId: request.threadId || (0, import_shared18.randomUUID)()
4644
4763
  };
4645
4764
  }
4646
4765
  };
@@ -4668,11 +4787,11 @@ var BedrockAdapter = class extends LangChainAdapter {
4668
4787
  __name(BedrockAdapter, "BedrockAdapter");
4669
4788
 
4670
4789
  // src/service-adapters/empty/empty-adapter.ts
4671
- var import_shared18 = require("@copilotkit/shared");
4790
+ var import_shared19 = require("@copilotkit/shared");
4672
4791
  var EmptyAdapter = class {
4673
4792
  async process(request) {
4674
4793
  return {
4675
- threadId: request.threadId || (0, import_shared18.randomUUID)()
4794
+ threadId: request.threadId || (0, import_shared19.randomUUID)()
4676
4795
  };
4677
4796
  }
4678
4797
  };
@@ -4806,9 +4925,9 @@ __name(ImageMessage, "ImageMessage");
4806
4925
 
4807
4926
  // src/service-adapters/conversion.ts
4808
4927
  var import_class_transformer = require("class-transformer");
4809
- var import_shared19 = require("@copilotkit/shared");
4928
+ var import_shared20 = require("@copilotkit/shared");
4810
4929
  function convertGqlInputToMessages(inputMessages) {
4811
- const messages = (0, import_shared19.tryMap)(inputMessages, (message) => {
4930
+ const messages = (0, import_shared20.tryMap)(inputMessages, (message) => {
4812
4931
  if (message.textMessage) {
4813
4932
  return (0, import_class_transformer.plainToInstance)(TextMessage, {
4814
4933
  id: message.id,
@@ -5002,7 +5121,7 @@ var CopilotRuntime = class {
5002
5121
  this.mcpServersConfig = params == null ? void 0 : params.mcpServers;
5003
5122
  this.createMCPClientImpl = params == null ? void 0 : params.createMCPClient;
5004
5123
  if (this.mcpServersConfig && this.mcpServersConfig.length > 0 && !this.createMCPClientImpl) {
5005
- throw new import_shared20.CopilotKitMisuseError({
5124
+ throw new import_shared21.CopilotKitMisuseError({
5006
5125
  message: "MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`."
5007
5126
  });
5008
5127
  }
@@ -5058,7 +5177,7 @@ var CopilotRuntime = class {
5058
5177
  }
5059
5178
  } else {
5060
5179
  newMessages.unshift({
5061
- id: (0, import_shared20.randomId)(),
5180
+ id: (0, import_shared21.randomId)(),
5062
5181
  createdAt: /* @__PURE__ */ new Date(),
5063
5182
  textMessage: {
5064
5183
  role: MessageRole.system,
@@ -5082,7 +5201,7 @@ var CopilotRuntime = class {
5082
5201
  return await this.processAgentRequest(request);
5083
5202
  }
5084
5203
  if (serviceAdapter instanceof EmptyAdapter) {
5085
- throw new import_shared20.CopilotKitMisuseError({
5204
+ throw new import_shared21.CopilotKitMisuseError({
5086
5205
  message: `Invalid adapter configuration: EmptyAdapter is only meant to be used with agent lock mode.
5087
5206
  For non-agent components like useCopilotChatSuggestions, CopilotTextarea, or CopilotTask,
5088
5207
  please use an LLM adapter instead.`
@@ -5112,7 +5231,7 @@ please use an LLM adapter instead.`
5112
5231
  const serverSideActionsInput = serverSideActions.map((action) => ({
5113
5232
  name: action.name,
5114
5233
  description: action.description,
5115
- jsonSchema: JSON.stringify((0, import_shared20.actionParametersToJsonSchema)(action.parameters))
5234
+ jsonSchema: JSON.stringify((0, import_shared21.actionParametersToJsonSchema)(action.parameters))
5116
5235
  }));
5117
5236
  const actionInputs = flattenToolCallsNoDuplicates([
5118
5237
  ...serverSideActionsInput,
@@ -5241,12 +5360,12 @@ please use an LLM adapter instead.`
5241
5360
  console.error("Error logging LLM error:", logError);
5242
5361
  }
5243
5362
  }
5244
- if (error instanceof import_shared20.CopilotKitError) {
5363
+ if (error instanceof import_shared21.CopilotKitError) {
5245
5364
  throw error;
5246
5365
  }
5247
5366
  console.error("Error getting response:", error);
5248
- eventSource.sendErrorMessageToChat();
5249
- throw error;
5367
+ const structuredError = this.convertStreamingErrorToStructured(error);
5368
+ throw structuredError;
5250
5369
  }
5251
5370
  }
5252
5371
  async discoverAgentsFromEndpoints(graphqlContext) {
@@ -5267,12 +5386,12 @@ please use an LLM adapter instead.`
5267
5386
  try {
5268
5387
  data = await client.assistants.search();
5269
5388
  if (data && "detail" in data && data.detail.toLowerCase() === "not found") {
5270
- throw new import_shared20.CopilotKitAgentDiscoveryError({
5389
+ throw new import_shared21.CopilotKitAgentDiscoveryError({
5271
5390
  availableAgents: this.availableAgents
5272
5391
  });
5273
5392
  }
5274
5393
  } catch (e) {
5275
- throw new import_shared20.CopilotKitMisuseError({
5394
+ throw new import_shared21.CopilotKitMisuseError({
5276
5395
  message: `
5277
5396
  Failed to find or contact remote endpoint at url ${endpoint.deploymentUrl}.
5278
5397
  Make sure the API is running and that it's indeed a LangGraph platform url.
@@ -5294,7 +5413,7 @@ please use an LLM adapter instead.`
5294
5413
  const cpkEndpoint = endpoint;
5295
5414
  const fetchUrl = `${endpoint.url}/info`;
5296
5415
  try {
5297
- const response = await fetch(fetchUrl, {
5416
+ const response = await fetchWithRetry(fetchUrl, {
5298
5417
  method: "POST",
5299
5418
  headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
5300
5419
  body: JSON.stringify({
@@ -5303,11 +5422,11 @@ please use an LLM adapter instead.`
5303
5422
  });
5304
5423
  if (!response.ok) {
5305
5424
  if (response.status === 404) {
5306
- throw new import_shared20.CopilotKitApiDiscoveryError({
5425
+ throw new import_shared21.CopilotKitApiDiscoveryError({
5307
5426
  url: fetchUrl
5308
5427
  });
5309
5428
  }
5310
- throw new import_shared20.ResolvedCopilotKitError({
5429
+ throw new import_shared21.ResolvedCopilotKitError({
5311
5430
  status: response.status,
5312
5431
  url: fetchUrl,
5313
5432
  isRemoteEndpoint: true
@@ -5317,7 +5436,7 @@ please use an LLM adapter instead.`
5317
5436
  const endpointAgents = ((data == null ? void 0 : data.agents) ?? []).map((agent) => ({
5318
5437
  name: agent.name,
5319
5438
  description: agent.description ?? "" ?? "",
5320
- id: (0, import_shared20.randomId)(),
5439
+ id: (0, import_shared21.randomId)(),
5321
5440
  endpoint
5322
5441
  }));
5323
5442
  return [
@@ -5325,10 +5444,10 @@ please use an LLM adapter instead.`
5325
5444
  ...endpointAgents
5326
5445
  ];
5327
5446
  } catch (error) {
5328
- if (error instanceof import_shared20.CopilotKitError) {
5447
+ if (error instanceof import_shared21.CopilotKitError) {
5329
5448
  throw error;
5330
5449
  }
5331
- throw new import_shared20.CopilotKitLowLevelError({
5450
+ throw new import_shared21.CopilotKitLowLevelError({
5332
5451
  error,
5333
5452
  url: fetchUrl
5334
5453
  });
@@ -5383,7 +5502,7 @@ please use an LLM adapter instead.`
5383
5502
  const cpkEndpoint = agentWithEndpoint.endpoint;
5384
5503
  const fetchUrl = `${cpkEndpoint.url}/agents/state`;
5385
5504
  try {
5386
- const response = await fetch(fetchUrl, {
5505
+ const response = await fetchWithRetry(fetchUrl, {
5387
5506
  method: "POST",
5388
5507
  headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
5389
5508
  body: JSON.stringify({
@@ -5394,11 +5513,11 @@ please use an LLM adapter instead.`
5394
5513
  });
5395
5514
  if (!response.ok) {
5396
5515
  if (response.status === 404) {
5397
- throw new import_shared20.CopilotKitApiDiscoveryError({
5516
+ throw new import_shared21.CopilotKitApiDiscoveryError({
5398
5517
  url: fetchUrl
5399
5518
  });
5400
5519
  }
5401
- throw new import_shared20.ResolvedCopilotKitError({
5520
+ throw new import_shared21.ResolvedCopilotKitError({
5402
5521
  status: response.status,
5403
5522
  url: fetchUrl,
5404
5523
  isRemoteEndpoint: true
@@ -5411,10 +5530,10 @@ please use an LLM adapter instead.`
5411
5530
  messages: JSON.stringify(data.messages)
5412
5531
  };
5413
5532
  } catch (error) {
5414
- if (error instanceof import_shared20.CopilotKitError) {
5533
+ if (error instanceof import_shared21.CopilotKitError) {
5415
5534
  throw error;
5416
5535
  }
5417
- throw new import_shared20.CopilotKitLowLevelError({
5536
+ throw new import_shared21.CopilotKitLowLevelError({
5418
5537
  error,
5419
5538
  url: fetchUrl
5420
5539
  });
@@ -5434,7 +5553,7 @@ please use an LLM adapter instead.`
5434
5553
  const messages = convertGqlInputToMessages(rawMessages);
5435
5554
  const currentAgent = serverSideActions.find((action) => action.name === agentName && isRemoteAgentAction(action));
5436
5555
  if (!currentAgent) {
5437
- throw new import_shared20.CopilotKitAgentDiscoveryError({
5556
+ throw new import_shared21.CopilotKitAgentDiscoveryError({
5438
5557
  agentName,
5439
5558
  availableAgents: this.availableAgents
5440
5559
  });
@@ -5446,7 +5565,7 @@ please use an LLM adapter instead.`
5446
5565
  )).map((action) => ({
5447
5566
  name: action.name,
5448
5567
  description: action.description,
5449
- jsonSchema: JSON.stringify((0, import_shared20.actionParametersToJsonSchema)(action.parameters))
5568
+ jsonSchema: JSON.stringify((0, import_shared21.actionParametersToJsonSchema)(action.parameters))
5450
5569
  }));
5451
5570
  const allAvailableActions = flattenToolCallsNoDuplicates([
5452
5571
  ...availableActionsForCurrentAgent,
@@ -5546,7 +5665,8 @@ please use an LLM adapter instead.`
5546
5665
  console.error("Error logging agent error:", logError);
5547
5666
  }
5548
5667
  }
5549
- eventStream$.error(err);
5668
+ const structuredError = this.convertStreamingErrorToStructured(err);
5669
+ eventStream$.error(structuredError);
5550
5670
  eventStream$.complete();
5551
5671
  },
5552
5672
  complete: () => eventStream$.complete()
@@ -5708,6 +5828,32 @@ please use an LLM adapter instead.`
5708
5828
  return "langchain";
5709
5829
  return void 0;
5710
5830
  }
5831
+ convertStreamingErrorToStructured(error) {
5832
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
5833
+ if (((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.includes("terminated")) || ((_b = error == null ? void 0 : error.cause) == null ? void 0 : _b.code) === "UND_ERR_SOCKET" || ((_c = error == null ? void 0 : error.message) == null ? void 0 : _c.includes("other side closed")) || (error == null ? void 0 : error.code) === "UND_ERR_SOCKET") {
5834
+ return new import_shared21.CopilotKitError({
5835
+ message: "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
5836
+ code: import_shared21.CopilotKitErrorCode.NETWORK_ERROR
5837
+ });
5838
+ }
5839
+ if (((_d = error == null ? void 0 : error.message) == null ? void 0 : _d.includes("fetch failed")) || ((_e = error == null ? void 0 : error.message) == null ? void 0 : _e.includes("ECONNREFUSED")) || ((_f = error == null ? void 0 : error.message) == null ? void 0 : _f.includes("ENOTFOUND")) || ((_g = error == null ? void 0 : error.message) == null ? void 0 : _g.includes("ETIMEDOUT"))) {
5840
+ return new import_shared21.CopilotKitLowLevelError({
5841
+ error: error instanceof Error ? error : new Error(String(error)),
5842
+ url: "agent streaming connection",
5843
+ message: "Network error occurred during agent streaming. Please check your connection and try again."
5844
+ });
5845
+ }
5846
+ if (((_h = error == null ? void 0 : error.message) == null ? void 0 : _h.includes("aborted")) || ((_i = error == null ? void 0 : error.message) == null ? void 0 : _i.includes("canceled")) || ((_j = error == null ? void 0 : error.message) == null ? void 0 : _j.includes("signal is aborted"))) {
5847
+ return new import_shared21.CopilotKitError({
5848
+ message: "Agent request was cancelled",
5849
+ code: import_shared21.CopilotKitErrorCode.UNKNOWN
5850
+ });
5851
+ }
5852
+ return new import_shared21.CopilotKitError({
5853
+ message: `Agent streaming error: ${(error == null ? void 0 : error.message) || String(error)}`,
5854
+ code: import_shared21.CopilotKitErrorCode.UNKNOWN
5855
+ });
5856
+ }
5711
5857
  };
5712
5858
  __name(CopilotRuntime, "CopilotRuntime");
5713
5859
  function flattenToolCallsNoDuplicates(toolsByPriority) {
@@ -5750,7 +5896,7 @@ __name(resolveEndpointType, "resolveEndpointType");
5750
5896
 
5751
5897
  // src/lib/telemetry-client.ts
5752
5898
  var packageJson = require_package();
5753
- var telemetryClient = new import_shared21.TelemetryClient({
5899
+ var telemetryClient = new import_shared22.TelemetryClient({
5754
5900
  packageName: packageJson.name,
5755
5901
  packageVersion: packageJson.version
5756
5902
  });
@@ -5929,16 +6075,17 @@ var RuntimeEventSource = class {
5929
6075
  const errorMessage = `\u274C ${message}`;
5930
6076
  if (!this.callback) {
5931
6077
  this.stream(async (eventStream$) => {
5932
- eventStream$.sendTextMessage((0, import_shared22.randomId)(), errorMessage);
6078
+ eventStream$.sendTextMessage((0, import_shared23.randomId)(), errorMessage);
5933
6079
  });
5934
6080
  } else {
5935
- this.eventStream$.sendTextMessage((0, import_shared22.randomId)(), errorMessage);
6081
+ this.eventStream$.sendTextMessage((0, import_shared23.randomId)(), errorMessage);
5936
6082
  }
5937
6083
  }
5938
6084
  processRuntimeEvents({ serverSideActions, guardrailsResult$, actionInputsWithoutAgents, threadId }) {
5939
6085
  this.callback(this.eventStream$).catch((error) => {
5940
6086
  console.error("Error in event source callback", error);
5941
- this.sendErrorMessageToChat();
6087
+ const structuredError = convertStreamingErrorToStructured2(error);
6088
+ this.eventStream$.error(structuredError);
5942
6089
  this.eventStream$.complete();
5943
6090
  });
5944
6091
  return this.eventStream$.pipe(
@@ -5977,7 +6124,15 @@ var RuntimeEventSource = class {
5977
6124
  telemetry_client_default.capture("oss.runtime.server_action_executed", {});
5978
6125
  return (0, import_rxjs3.concat)((0, import_rxjs3.of)(eventWithState.event), toolCallEventStream$).pipe((0, import_rxjs3.catchError)((error) => {
5979
6126
  console.error("Error in tool call stream", error);
5980
- this.sendErrorMessageToChat();
6127
+ const structuredError = convertStreamingErrorToStructured2(error);
6128
+ toolCallEventStream$.sendActionExecutionResult({
6129
+ actionExecutionId: eventWithState.actionExecutionId,
6130
+ actionName: eventWithState.action.name,
6131
+ error: {
6132
+ code: structuredError.code,
6133
+ message: structuredError.message
6134
+ }
6135
+ });
5981
6136
  return import_rxjs3.EMPTY;
5982
6137
  }));
5983
6138
  } else {
@@ -6050,12 +6205,13 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
6050
6205
  next: (event) => eventStream$.next(event),
6051
6206
  error: (err) => {
6052
6207
  console.error("Error in stream", err);
6208
+ const structuredError = convertStreamingErrorToStructured2(err);
6053
6209
  eventStream$.sendActionExecutionResult({
6054
6210
  actionExecutionId,
6055
6211
  actionName: action.name,
6056
6212
  error: {
6057
- code: "STREAM_ERROR",
6058
- message: err.message
6213
+ code: structuredError.code,
6214
+ message: structuredError.message
6059
6215
  }
6060
6216
  });
6061
6217
  eventStream$.complete();
@@ -6088,6 +6244,40 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
6088
6244
  }
6089
6245
  }
6090
6246
  __name(executeAction, "executeAction");
6247
+ function convertStreamingErrorToStructured2(error) {
6248
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
6249
+ if (((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.includes("terminated")) || ((_b = error == null ? void 0 : error.cause) == null ? void 0 : _b.code) === "UND_ERR_SOCKET" || ((_c = error == null ? void 0 : error.message) == null ? void 0 : _c.includes("other side closed")) || (error == null ? void 0 : error.code) === "UND_ERR_SOCKET") {
6250
+ return new import_shared23.CopilotKitError({
6251
+ message: "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
6252
+ code: import_shared23.CopilotKitErrorCode.NETWORK_ERROR
6253
+ });
6254
+ }
6255
+ if (((_d = error == null ? void 0 : error.message) == null ? void 0 : _d.includes("fetch failed")) || ((_e = error == null ? void 0 : error.message) == null ? void 0 : _e.includes("ECONNREFUSED")) || ((_f = error == null ? void 0 : error.message) == null ? void 0 : _f.includes("ENOTFOUND")) || ((_g = error == null ? void 0 : error.message) == null ? void 0 : _g.includes("ETIMEDOUT"))) {
6256
+ return new import_shared23.CopilotKitLowLevelError({
6257
+ error: error instanceof Error ? error : new Error(String(error)),
6258
+ url: "event streaming connection",
6259
+ message: "Network error occurred during event streaming. Please check your connection and try again."
6260
+ });
6261
+ }
6262
+ if (((_h = error == null ? void 0 : error.message) == null ? void 0 : _h.includes("aborted")) || ((_i = error == null ? void 0 : error.message) == null ? void 0 : _i.includes("canceled")) || ((_j = error == null ? void 0 : error.message) == null ? void 0 : _j.includes("signal is aborted"))) {
6263
+ return new import_shared23.CopilotKitError({
6264
+ message: "Request was cancelled",
6265
+ code: import_shared23.CopilotKitErrorCode.UNKNOWN
6266
+ });
6267
+ }
6268
+ const errorMessage = (error == null ? void 0 : error.message) || String(error);
6269
+ if (errorMessage.includes("401") || errorMessage.toLowerCase().includes("api key") || errorMessage.toLowerCase().includes("unauthorized") || errorMessage.toLowerCase().includes("authentication") || errorMessage.toLowerCase().includes("incorrect api key")) {
6270
+ return new import_shared23.CopilotKitError({
6271
+ message: `Event streaming error: ${errorMessage}`,
6272
+ code: import_shared23.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR
6273
+ });
6274
+ }
6275
+ return new import_shared23.CopilotKitError({
6276
+ message: `Event streaming error: ${errorMessage}`,
6277
+ code: import_shared23.CopilotKitErrorCode.UNKNOWN
6278
+ });
6279
+ }
6280
+ __name(convertStreamingErrorToStructured2, "convertStreamingErrorToStructured");
6091
6281
 
6092
6282
  // src/graphql/resolvers/copilot.resolver.ts
6093
6283
  var import_graphql_scalars2 = require("graphql-scalars");
@@ -6128,7 +6318,7 @@ var UnknownErrorResponse = class extends FailedResponseStatus {
6128
6318
  __name(UnknownErrorResponse, "UnknownErrorResponse");
6129
6319
 
6130
6320
  // src/graphql/resolvers/copilot.resolver.ts
6131
- var import_shared23 = require("@copilotkit/shared");
6321
+ var import_shared24 = require("@copilotkit/shared");
6132
6322
 
6133
6323
  // src/graphql/types/agents-response.type.ts
6134
6324
  var import_type_graphql19 = require("type-graphql");
@@ -6184,6 +6374,7 @@ AgentsResponse = _ts_decorate18([
6184
6374
  ], AgentsResponse);
6185
6375
 
6186
6376
  // src/graphql/resolvers/copilot.resolver.ts
6377
+ var import_shared25 = require("@copilotkit/shared");
6187
6378
  function _ts_decorate19(decorators, target, key, desc) {
6188
6379
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
6189
6380
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -6323,7 +6514,7 @@ var CopilotResolver = class {
6323
6514
  ctx.properties["copilotCloudPublicApiKey"] = copilotCloudPublicApiKey;
6324
6515
  }
6325
6516
  logger2.debug("Processing");
6326
- const { eventSource, threadId = (0, import_shared23.randomId)(), runId, serverSideActions, actionInputsWithoutAgents, extensions } = await copilotRuntime.processRuntimeRequest({
6517
+ const { eventSource, threadId = (0, import_shared24.randomId)(), runId, serverSideActions, actionInputsWithoutAgents, extensions } = await copilotRuntime.processRuntimeRequest({
6327
6518
  serviceAdapter,
6328
6519
  messages: data.messages,
6329
6520
  actions: data.frontend.actions.filter((action) => action.available !== ActionInputAvailability.disabled),
@@ -6466,7 +6657,7 @@ var CopilotResolver = class {
6466
6657
  });
6467
6658
  outputMessages = [
6468
6659
  (0, import_class_transformer3.plainToInstance)(TextMessage, {
6469
- id: (0, import_shared23.randomId)(),
6660
+ id: (0, import_shared24.randomId)(),
6470
6661
  createdAt: /* @__PURE__ */ new Date(),
6471
6662
  content: result.reason,
6472
6663
  role: MessageRole.assistant
@@ -6644,7 +6835,7 @@ var CopilotResolver = class {
6644
6835
  event
6645
6836
  }, "Agent message event received");
6646
6837
  pushMessage({
6647
- id: (0, import_shared23.randomId)(),
6838
+ id: (0, import_shared24.randomId)(),
6648
6839
  status: new SuccessMessageStatus(),
6649
6840
  threadId: event.threadId,
6650
6841
  agentName: event.agentName,
@@ -6657,7 +6848,7 @@ var CopilotResolver = class {
6657
6848
  createdAt: /* @__PURE__ */ new Date()
6658
6849
  });
6659
6850
  outputMessages.push((0, import_class_transformer3.plainToInstance)(AgentStateMessage, {
6660
- id: (0, import_shared23.randomId)(),
6851
+ id: (0, import_shared24.randomId)(),
6661
6852
  threadId: event.threadId,
6662
6853
  agentName: event.agentName,
6663
6854
  nodeName: event.nodeName,
@@ -6675,6 +6866,12 @@ var CopilotResolver = class {
6675
6866
  logger2.error({
6676
6867
  err
6677
6868
  }, "Error in event stream");
6869
+ if (err instanceof import_shared25.CopilotKitError || err instanceof Error && err.name && err.name.includes("CopilotKit")) {
6870
+ eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
6871
+ rejectOutputMessagesPromise(err);
6872
+ stopStreamingMessages(err);
6873
+ return;
6874
+ }
6678
6875
  responseStatus$.next(new UnknownErrorResponse({
6679
6876
  description: `An unknown error has occurred in the event stream`
6680
6877
  }));
@@ -6852,6 +7049,7 @@ LoadAgentStateInput = _ts_decorate21([
6852
7049
  ], LoadAgentStateInput);
6853
7050
 
6854
7051
  // src/graphql/resolvers/state.resolver.ts
7052
+ var import_shared26 = require("@copilotkit/shared");
6855
7053
  function _ts_decorate22(decorators, target, key, desc) {
6856
7054
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
6857
7055
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -6879,12 +7077,13 @@ var StateResolver = class {
6879
7077
  const agents = await ctx._copilotkit.runtime.discoverAgentsFromEndpoints(ctx);
6880
7078
  const agent = agents.find((agent2) => agent2.name === data.agentName);
6881
7079
  if (!agent) {
6882
- return {
6883
- threadId: data.threadId || "",
6884
- threadExists: false,
6885
- state: JSON.stringify({}),
6886
- messages: JSON.stringify([])
6887
- };
7080
+ throw new import_shared26.CopilotKitAgentDiscoveryError({
7081
+ agentName: data.agentName,
7082
+ availableAgents: agents.map((a) => ({
7083
+ name: a.name,
7084
+ id: a.name
7085
+ }))
7086
+ });
6888
7087
  }
6889
7088
  const state = await ctx._copilotkit.runtime.loadAgentState(ctx, data.threadId, data.agentName);
6890
7089
  return state;