@copilotkit/runtime 1.9.1 → 1.9.2-next.1

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 +16 -0
  2. package/dist/{chunk-2CND6WGV.mjs → chunk-C3SWOFLO.mjs} +2 -2
  3. package/dist/{chunk-EVF3MXEK.mjs → chunk-KPFOAXRX.mjs} +2 -2
  4. package/dist/{chunk-RVLXQ2V5.mjs → chunk-RIPQZJB5.mjs} +2 -2
  5. package/dist/{chunk-GOPTDPPB.mjs → chunk-XGBY45FP.mjs} +265 -61
  6. package/dist/chunk-XGBY45FP.mjs.map +1 -0
  7. package/dist/{chunk-BHNTR222.mjs → chunk-YV3YXRMR.mjs} +2 -2
  8. package/dist/index.d.ts +1 -1
  9. package/dist/index.js +310 -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 +303 -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 +70 -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-2CND6WGV.mjs.map → chunk-C3SWOFLO.mjs.map} +0 -0
  45. /package/dist/{chunk-EVF3MXEK.mjs.map → chunk-KPFOAXRX.mjs.map} +0 -0
  46. /package/dist/{chunk-RVLXQ2V5.mjs.map → chunk-RIPQZJB5.mjs.map} +0 -0
  47. /package/dist/{chunk-BHNTR222.mjs.map → chunk-YV3YXRMR.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.1",
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,
@@ -5078,11 +5197,16 @@ var CopilotRuntime = class {
5078
5197
  const requestStartTime = Date.now();
5079
5198
  const streamedChunks = [];
5080
5199
  try {
5200
+ if (Object.keys(this.agents).length && (agentSession == null ? void 0 : agentSession.agentName) && !this.delegateAgentProcessingToServiceAdapter) {
5201
+ this.agents = {
5202
+ [agentSession.agentName]: this.agents[agentSession.agentName]
5203
+ };
5204
+ }
5081
5205
  if (agentSession && !this.delegateAgentProcessingToServiceAdapter) {
5082
5206
  return await this.processAgentRequest(request);
5083
5207
  }
5084
5208
  if (serviceAdapter instanceof EmptyAdapter) {
5085
- throw new import_shared20.CopilotKitMisuseError({
5209
+ throw new import_shared21.CopilotKitMisuseError({
5086
5210
  message: `Invalid adapter configuration: EmptyAdapter is only meant to be used with agent lock mode.
5087
5211
  For non-agent components like useCopilotChatSuggestions, CopilotTextarea, or CopilotTask,
5088
5212
  please use an LLM adapter instead.`
@@ -5112,7 +5236,7 @@ please use an LLM adapter instead.`
5112
5236
  const serverSideActionsInput = serverSideActions.map((action) => ({
5113
5237
  name: action.name,
5114
5238
  description: action.description,
5115
- jsonSchema: JSON.stringify((0, import_shared20.actionParametersToJsonSchema)(action.parameters))
5239
+ jsonSchema: JSON.stringify((0, import_shared21.actionParametersToJsonSchema)(action.parameters))
5116
5240
  }));
5117
5241
  const actionInputs = flattenToolCallsNoDuplicates([
5118
5242
  ...serverSideActionsInput,
@@ -5241,12 +5365,12 @@ please use an LLM adapter instead.`
5241
5365
  console.error("Error logging LLM error:", logError);
5242
5366
  }
5243
5367
  }
5244
- if (error instanceof import_shared20.CopilotKitError) {
5368
+ if (error instanceof import_shared21.CopilotKitError) {
5245
5369
  throw error;
5246
5370
  }
5247
5371
  console.error("Error getting response:", error);
5248
- eventSource.sendErrorMessageToChat();
5249
- throw error;
5372
+ const structuredError = this.convertStreamingErrorToStructured(error);
5373
+ throw structuredError;
5250
5374
  }
5251
5375
  }
5252
5376
  async discoverAgentsFromEndpoints(graphqlContext) {
@@ -5267,12 +5391,12 @@ please use an LLM adapter instead.`
5267
5391
  try {
5268
5392
  data = await client.assistants.search();
5269
5393
  if (data && "detail" in data && data.detail.toLowerCase() === "not found") {
5270
- throw new import_shared20.CopilotKitAgentDiscoveryError({
5394
+ throw new import_shared21.CopilotKitAgentDiscoveryError({
5271
5395
  availableAgents: this.availableAgents
5272
5396
  });
5273
5397
  }
5274
5398
  } catch (e) {
5275
- throw new import_shared20.CopilotKitMisuseError({
5399
+ throw new import_shared21.CopilotKitMisuseError({
5276
5400
  message: `
5277
5401
  Failed to find or contact remote endpoint at url ${endpoint.deploymentUrl}.
5278
5402
  Make sure the API is running and that it's indeed a LangGraph platform url.
@@ -5294,7 +5418,7 @@ please use an LLM adapter instead.`
5294
5418
  const cpkEndpoint = endpoint;
5295
5419
  const fetchUrl = `${endpoint.url}/info`;
5296
5420
  try {
5297
- const response = await fetch(fetchUrl, {
5421
+ const response = await fetchWithRetry(fetchUrl, {
5298
5422
  method: "POST",
5299
5423
  headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
5300
5424
  body: JSON.stringify({
@@ -5303,11 +5427,11 @@ please use an LLM adapter instead.`
5303
5427
  });
5304
5428
  if (!response.ok) {
5305
5429
  if (response.status === 404) {
5306
- throw new import_shared20.CopilotKitApiDiscoveryError({
5430
+ throw new import_shared21.CopilotKitApiDiscoveryError({
5307
5431
  url: fetchUrl
5308
5432
  });
5309
5433
  }
5310
- throw new import_shared20.ResolvedCopilotKitError({
5434
+ throw new import_shared21.ResolvedCopilotKitError({
5311
5435
  status: response.status,
5312
5436
  url: fetchUrl,
5313
5437
  isRemoteEndpoint: true
@@ -5317,7 +5441,7 @@ please use an LLM adapter instead.`
5317
5441
  const endpointAgents = ((data == null ? void 0 : data.agents) ?? []).map((agent) => ({
5318
5442
  name: agent.name,
5319
5443
  description: agent.description ?? "" ?? "",
5320
- id: (0, import_shared20.randomId)(),
5444
+ id: (0, import_shared21.randomId)(),
5321
5445
  endpoint
5322
5446
  }));
5323
5447
  return [
@@ -5325,10 +5449,10 @@ please use an LLM adapter instead.`
5325
5449
  ...endpointAgents
5326
5450
  ];
5327
5451
  } catch (error) {
5328
- if (error instanceof import_shared20.CopilotKitError) {
5452
+ if (error instanceof import_shared21.CopilotKitError) {
5329
5453
  throw error;
5330
5454
  }
5331
- throw new import_shared20.CopilotKitLowLevelError({
5455
+ throw new import_shared21.CopilotKitLowLevelError({
5332
5456
  error,
5333
5457
  url: fetchUrl
5334
5458
  });
@@ -5383,7 +5507,7 @@ please use an LLM adapter instead.`
5383
5507
  const cpkEndpoint = agentWithEndpoint.endpoint;
5384
5508
  const fetchUrl = `${cpkEndpoint.url}/agents/state`;
5385
5509
  try {
5386
- const response = await fetch(fetchUrl, {
5510
+ const response = await fetchWithRetry(fetchUrl, {
5387
5511
  method: "POST",
5388
5512
  headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
5389
5513
  body: JSON.stringify({
@@ -5394,11 +5518,11 @@ please use an LLM adapter instead.`
5394
5518
  });
5395
5519
  if (!response.ok) {
5396
5520
  if (response.status === 404) {
5397
- throw new import_shared20.CopilotKitApiDiscoveryError({
5521
+ throw new import_shared21.CopilotKitApiDiscoveryError({
5398
5522
  url: fetchUrl
5399
5523
  });
5400
5524
  }
5401
- throw new import_shared20.ResolvedCopilotKitError({
5525
+ throw new import_shared21.ResolvedCopilotKitError({
5402
5526
  status: response.status,
5403
5527
  url: fetchUrl,
5404
5528
  isRemoteEndpoint: true
@@ -5411,10 +5535,10 @@ please use an LLM adapter instead.`
5411
5535
  messages: JSON.stringify(data.messages)
5412
5536
  };
5413
5537
  } catch (error) {
5414
- if (error instanceof import_shared20.CopilotKitError) {
5538
+ if (error instanceof import_shared21.CopilotKitError) {
5415
5539
  throw error;
5416
5540
  }
5417
- throw new import_shared20.CopilotKitLowLevelError({
5541
+ throw new import_shared21.CopilotKitLowLevelError({
5418
5542
  error,
5419
5543
  url: fetchUrl
5420
5544
  });
@@ -5434,7 +5558,7 @@ please use an LLM adapter instead.`
5434
5558
  const messages = convertGqlInputToMessages(rawMessages);
5435
5559
  const currentAgent = serverSideActions.find((action) => action.name === agentName && isRemoteAgentAction(action));
5436
5560
  if (!currentAgent) {
5437
- throw new import_shared20.CopilotKitAgentDiscoveryError({
5561
+ throw new import_shared21.CopilotKitAgentDiscoveryError({
5438
5562
  agentName,
5439
5563
  availableAgents: this.availableAgents
5440
5564
  });
@@ -5446,7 +5570,7 @@ please use an LLM adapter instead.`
5446
5570
  )).map((action) => ({
5447
5571
  name: action.name,
5448
5572
  description: action.description,
5449
- jsonSchema: JSON.stringify((0, import_shared20.actionParametersToJsonSchema)(action.parameters))
5573
+ jsonSchema: JSON.stringify((0, import_shared21.actionParametersToJsonSchema)(action.parameters))
5450
5574
  }));
5451
5575
  const allAvailableActions = flattenToolCallsNoDuplicates([
5452
5576
  ...availableActionsForCurrentAgent,
@@ -5546,7 +5670,8 @@ please use an LLM adapter instead.`
5546
5670
  console.error("Error logging agent error:", logError);
5547
5671
  }
5548
5672
  }
5549
- eventStream$.error(err);
5673
+ const structuredError = this.convertStreamingErrorToStructured(err);
5674
+ eventStream$.error(structuredError);
5550
5675
  eventStream$.complete();
5551
5676
  },
5552
5677
  complete: () => eventStream$.complete()
@@ -5708,6 +5833,32 @@ please use an LLM adapter instead.`
5708
5833
  return "langchain";
5709
5834
  return void 0;
5710
5835
  }
5836
+ convertStreamingErrorToStructured(error) {
5837
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
5838
+ 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") {
5839
+ return new import_shared21.CopilotKitError({
5840
+ message: "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
5841
+ code: import_shared21.CopilotKitErrorCode.NETWORK_ERROR
5842
+ });
5843
+ }
5844
+ 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"))) {
5845
+ return new import_shared21.CopilotKitLowLevelError({
5846
+ error: error instanceof Error ? error : new Error(String(error)),
5847
+ url: "agent streaming connection",
5848
+ message: "Network error occurred during agent streaming. Please check your connection and try again."
5849
+ });
5850
+ }
5851
+ 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"))) {
5852
+ return new import_shared21.CopilotKitError({
5853
+ message: "Agent request was cancelled",
5854
+ code: import_shared21.CopilotKitErrorCode.UNKNOWN
5855
+ });
5856
+ }
5857
+ return new import_shared21.CopilotKitError({
5858
+ message: `Agent streaming error: ${(error == null ? void 0 : error.message) || String(error)}`,
5859
+ code: import_shared21.CopilotKitErrorCode.UNKNOWN
5860
+ });
5861
+ }
5711
5862
  };
5712
5863
  __name(CopilotRuntime, "CopilotRuntime");
5713
5864
  function flattenToolCallsNoDuplicates(toolsByPriority) {
@@ -5750,7 +5901,7 @@ __name(resolveEndpointType, "resolveEndpointType");
5750
5901
 
5751
5902
  // src/lib/telemetry-client.ts
5752
5903
  var packageJson = require_package();
5753
- var telemetryClient = new import_shared21.TelemetryClient({
5904
+ var telemetryClient = new import_shared22.TelemetryClient({
5754
5905
  packageName: packageJson.name,
5755
5906
  packageVersion: packageJson.version
5756
5907
  });
@@ -5929,16 +6080,17 @@ var RuntimeEventSource = class {
5929
6080
  const errorMessage = `\u274C ${message}`;
5930
6081
  if (!this.callback) {
5931
6082
  this.stream(async (eventStream$) => {
5932
- eventStream$.sendTextMessage((0, import_shared22.randomId)(), errorMessage);
6083
+ eventStream$.sendTextMessage((0, import_shared23.randomId)(), errorMessage);
5933
6084
  });
5934
6085
  } else {
5935
- this.eventStream$.sendTextMessage((0, import_shared22.randomId)(), errorMessage);
6086
+ this.eventStream$.sendTextMessage((0, import_shared23.randomId)(), errorMessage);
5936
6087
  }
5937
6088
  }
5938
6089
  processRuntimeEvents({ serverSideActions, guardrailsResult$, actionInputsWithoutAgents, threadId }) {
5939
6090
  this.callback(this.eventStream$).catch((error) => {
5940
6091
  console.error("Error in event source callback", error);
5941
- this.sendErrorMessageToChat();
6092
+ const structuredError = convertStreamingErrorToStructured2(error);
6093
+ this.eventStream$.error(structuredError);
5942
6094
  this.eventStream$.complete();
5943
6095
  });
5944
6096
  return this.eventStream$.pipe(
@@ -5977,7 +6129,15 @@ var RuntimeEventSource = class {
5977
6129
  telemetry_client_default.capture("oss.runtime.server_action_executed", {});
5978
6130
  return (0, import_rxjs3.concat)((0, import_rxjs3.of)(eventWithState.event), toolCallEventStream$).pipe((0, import_rxjs3.catchError)((error) => {
5979
6131
  console.error("Error in tool call stream", error);
5980
- this.sendErrorMessageToChat();
6132
+ const structuredError = convertStreamingErrorToStructured2(error);
6133
+ toolCallEventStream$.sendActionExecutionResult({
6134
+ actionExecutionId: eventWithState.actionExecutionId,
6135
+ actionName: eventWithState.action.name,
6136
+ error: {
6137
+ code: structuredError.code,
6138
+ message: structuredError.message
6139
+ }
6140
+ });
5981
6141
  return import_rxjs3.EMPTY;
5982
6142
  }));
5983
6143
  } else {
@@ -6050,12 +6210,13 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
6050
6210
  next: (event) => eventStream$.next(event),
6051
6211
  error: (err) => {
6052
6212
  console.error("Error in stream", err);
6213
+ const structuredError = convertStreamingErrorToStructured2(err);
6053
6214
  eventStream$.sendActionExecutionResult({
6054
6215
  actionExecutionId,
6055
6216
  actionName: action.name,
6056
6217
  error: {
6057
- code: "STREAM_ERROR",
6058
- message: err.message
6218
+ code: structuredError.code,
6219
+ message: structuredError.message
6059
6220
  }
6060
6221
  });
6061
6222
  eventStream$.complete();
@@ -6088,6 +6249,40 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
6088
6249
  }
6089
6250
  }
6090
6251
  __name(executeAction, "executeAction");
6252
+ function convertStreamingErrorToStructured2(error) {
6253
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
6254
+ 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") {
6255
+ return new import_shared23.CopilotKitError({
6256
+ message: "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
6257
+ code: import_shared23.CopilotKitErrorCode.NETWORK_ERROR
6258
+ });
6259
+ }
6260
+ 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"))) {
6261
+ return new import_shared23.CopilotKitLowLevelError({
6262
+ error: error instanceof Error ? error : new Error(String(error)),
6263
+ url: "event streaming connection",
6264
+ message: "Network error occurred during event streaming. Please check your connection and try again."
6265
+ });
6266
+ }
6267
+ 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"))) {
6268
+ return new import_shared23.CopilotKitError({
6269
+ message: "Request was cancelled",
6270
+ code: import_shared23.CopilotKitErrorCode.UNKNOWN
6271
+ });
6272
+ }
6273
+ const errorMessage = (error == null ? void 0 : error.message) || String(error);
6274
+ if (errorMessage.includes("401") || errorMessage.toLowerCase().includes("api key") || errorMessage.toLowerCase().includes("unauthorized") || errorMessage.toLowerCase().includes("authentication") || errorMessage.toLowerCase().includes("incorrect api key")) {
6275
+ return new import_shared23.CopilotKitError({
6276
+ message: `Event streaming error: ${errorMessage}`,
6277
+ code: import_shared23.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR
6278
+ });
6279
+ }
6280
+ return new import_shared23.CopilotKitError({
6281
+ message: `Event streaming error: ${errorMessage}`,
6282
+ code: import_shared23.CopilotKitErrorCode.UNKNOWN
6283
+ });
6284
+ }
6285
+ __name(convertStreamingErrorToStructured2, "convertStreamingErrorToStructured");
6091
6286
 
6092
6287
  // src/graphql/resolvers/copilot.resolver.ts
6093
6288
  var import_graphql_scalars2 = require("graphql-scalars");
@@ -6128,7 +6323,7 @@ var UnknownErrorResponse = class extends FailedResponseStatus {
6128
6323
  __name(UnknownErrorResponse, "UnknownErrorResponse");
6129
6324
 
6130
6325
  // src/graphql/resolvers/copilot.resolver.ts
6131
- var import_shared23 = require("@copilotkit/shared");
6326
+ var import_shared24 = require("@copilotkit/shared");
6132
6327
 
6133
6328
  // src/graphql/types/agents-response.type.ts
6134
6329
  var import_type_graphql19 = require("type-graphql");
@@ -6184,6 +6379,7 @@ AgentsResponse = _ts_decorate18([
6184
6379
  ], AgentsResponse);
6185
6380
 
6186
6381
  // src/graphql/resolvers/copilot.resolver.ts
6382
+ var import_shared25 = require("@copilotkit/shared");
6187
6383
  function _ts_decorate19(decorators, target, key, desc) {
6188
6384
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
6189
6385
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -6323,7 +6519,7 @@ var CopilotResolver = class {
6323
6519
  ctx.properties["copilotCloudPublicApiKey"] = copilotCloudPublicApiKey;
6324
6520
  }
6325
6521
  logger2.debug("Processing");
6326
- const { eventSource, threadId = (0, import_shared23.randomId)(), runId, serverSideActions, actionInputsWithoutAgents, extensions } = await copilotRuntime.processRuntimeRequest({
6522
+ const { eventSource, threadId = (0, import_shared24.randomId)(), runId, serverSideActions, actionInputsWithoutAgents, extensions } = await copilotRuntime.processRuntimeRequest({
6327
6523
  serviceAdapter,
6328
6524
  messages: data.messages,
6329
6525
  actions: data.frontend.actions.filter((action) => action.available !== ActionInputAvailability.disabled),
@@ -6466,7 +6662,7 @@ var CopilotResolver = class {
6466
6662
  });
6467
6663
  outputMessages = [
6468
6664
  (0, import_class_transformer3.plainToInstance)(TextMessage, {
6469
- id: (0, import_shared23.randomId)(),
6665
+ id: (0, import_shared24.randomId)(),
6470
6666
  createdAt: /* @__PURE__ */ new Date(),
6471
6667
  content: result.reason,
6472
6668
  role: MessageRole.assistant
@@ -6644,7 +6840,7 @@ var CopilotResolver = class {
6644
6840
  event
6645
6841
  }, "Agent message event received");
6646
6842
  pushMessage({
6647
- id: (0, import_shared23.randomId)(),
6843
+ id: (0, import_shared24.randomId)(),
6648
6844
  status: new SuccessMessageStatus(),
6649
6845
  threadId: event.threadId,
6650
6846
  agentName: event.agentName,
@@ -6657,7 +6853,7 @@ var CopilotResolver = class {
6657
6853
  createdAt: /* @__PURE__ */ new Date()
6658
6854
  });
6659
6855
  outputMessages.push((0, import_class_transformer3.plainToInstance)(AgentStateMessage, {
6660
- id: (0, import_shared23.randomId)(),
6856
+ id: (0, import_shared24.randomId)(),
6661
6857
  threadId: event.threadId,
6662
6858
  agentName: event.agentName,
6663
6859
  nodeName: event.nodeName,
@@ -6675,6 +6871,12 @@ var CopilotResolver = class {
6675
6871
  logger2.error({
6676
6872
  err
6677
6873
  }, "Error in event stream");
6874
+ if (err instanceof import_shared25.CopilotKitError || err instanceof Error && err.name && err.name.includes("CopilotKit")) {
6875
+ eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
6876
+ rejectOutputMessagesPromise(err);
6877
+ stopStreamingMessages(err);
6878
+ return;
6879
+ }
6678
6880
  responseStatus$.next(new UnknownErrorResponse({
6679
6881
  description: `An unknown error has occurred in the event stream`
6680
6882
  }));
@@ -6852,6 +7054,7 @@ LoadAgentStateInput = _ts_decorate21([
6852
7054
  ], LoadAgentStateInput);
6853
7055
 
6854
7056
  // src/graphql/resolvers/state.resolver.ts
7057
+ var import_shared26 = require("@copilotkit/shared");
6855
7058
  function _ts_decorate22(decorators, target, key, desc) {
6856
7059
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
6857
7060
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -6879,12 +7082,13 @@ var StateResolver = class {
6879
7082
  const agents = await ctx._copilotkit.runtime.discoverAgentsFromEndpoints(ctx);
6880
7083
  const agent = agents.find((agent2) => agent2.name === data.agentName);
6881
7084
  if (!agent) {
6882
- return {
6883
- threadId: data.threadId || "",
6884
- threadExists: false,
6885
- state: JSON.stringify({}),
6886
- messages: JSON.stringify([])
6887
- };
7085
+ throw new import_shared26.CopilotKitAgentDiscoveryError({
7086
+ agentName: data.agentName,
7087
+ availableAgents: agents.map((a) => ({
7088
+ name: a.name,
7089
+ id: a.name
7090
+ }))
7091
+ });
6888
7092
  }
6889
7093
  const state = await ctx._copilotkit.runtime.loadAgentState(ctx, data.threadId, data.agentName);
6890
7094
  return state;