@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/lib/index.js CHANGED
@@ -44,7 +44,7 @@ var require_package = __commonJS({
44
44
  publishConfig: {
45
45
  access: "public"
46
46
  },
47
- version: "1.9.1",
47
+ version: "1.9.2-next.1",
48
48
  sideEffects: false,
49
49
  main: "./dist/index.js",
50
50
  module: "./dist/index.mjs",
@@ -2734,14 +2734,14 @@ GenerateCopilotResponseInput = _ts_decorate17([
2734
2734
  var import_graphql_yoga = require("graphql-yoga");
2735
2735
 
2736
2736
  // src/service-adapters/events.ts
2737
- var import_shared20 = require("@copilotkit/shared");
2737
+ var import_shared21 = require("@copilotkit/shared");
2738
2738
  var import_rxjs3 = require("rxjs");
2739
2739
 
2740
2740
  // src/lib/telemetry-client.ts
2741
- var import_shared19 = require("@copilotkit/shared");
2741
+ var import_shared20 = require("@copilotkit/shared");
2742
2742
 
2743
2743
  // src/lib/runtime/remote-actions.ts
2744
- var import_shared14 = require("@copilotkit/shared");
2744
+ var import_shared15 = require("@copilotkit/shared");
2745
2745
 
2746
2746
  // src/lib/runtime/remote-action-constructors.ts
2747
2747
  var import_node_crypto2 = require("crypto");
@@ -2982,6 +2982,9 @@ var RemoteLangGraphEventSource = class {
2982
2982
  return events;
2983
2983
  }), (0, import_rxjs.catchError)((error) => {
2984
2984
  console.error(error);
2985
+ if (error instanceof import_shared7.CopilotKitError || (error == null ? void 0 : error.name) && error.name.includes("CopilotKit")) {
2986
+ throw error;
2987
+ }
2985
2988
  const events = [];
2986
2989
  if ((lastEventWithState == null ? void 0 : lastEventWithState.lastMessageId) && !lastEventWithState.isToolCall) {
2987
2990
  events.push({
@@ -3022,32 +3025,119 @@ var import_shared8 = require("@copilotkit/shared");
3022
3025
  var import_partial_json = require("partial-json");
3023
3026
  var import_shared9 = require("@copilotkit/shared");
3024
3027
  var import_messages3 = require("@langchain/core/messages");
3028
+
3029
+ // src/lib/runtime/retry-utils.ts
3030
+ var RETRY_CONFIG = {
3031
+ maxRetries: 3,
3032
+ baseDelayMs: 1e3,
3033
+ maxDelayMs: 5e3,
3034
+ // HTTP status codes that should be retried
3035
+ retryableStatusCodes: [
3036
+ 502,
3037
+ 503,
3038
+ 504,
3039
+ 408,
3040
+ 429
3041
+ ],
3042
+ // Network error patterns that should be retried
3043
+ retryableErrorMessages: [
3044
+ "fetch failed",
3045
+ "network error",
3046
+ "connection timeout",
3047
+ "ECONNREFUSED",
3048
+ "ETIMEDOUT",
3049
+ "ENOTFOUND",
3050
+ "ECONNRESET"
3051
+ ]
3052
+ };
3053
+ function isRetryableError(error, response) {
3054
+ var _a, _b;
3055
+ if (response && RETRY_CONFIG.retryableStatusCodes.includes(response.status)) {
3056
+ return true;
3057
+ }
3058
+ const errorCode = ((_a = error == null ? void 0 : error.cause) == null ? void 0 : _a.code) || (error == null ? void 0 : error.code);
3059
+ if (errorCode && RETRY_CONFIG.retryableErrorMessages.includes(errorCode)) {
3060
+ return true;
3061
+ }
3062
+ const errorMessage = ((_b = error == null ? void 0 : error.message) == null ? void 0 : _b.toLowerCase()) || "";
3063
+ return RETRY_CONFIG.retryableErrorMessages.some((msg) => errorMessage.includes(msg));
3064
+ }
3065
+ __name(isRetryableError, "isRetryableError");
3066
+ function sleep(ms) {
3067
+ return new Promise((resolve) => setTimeout(resolve, ms));
3068
+ }
3069
+ __name(sleep, "sleep");
3070
+ function calculateDelay(attempt) {
3071
+ const delay = RETRY_CONFIG.baseDelayMs * Math.pow(2, attempt);
3072
+ return Math.min(delay, RETRY_CONFIG.maxDelayMs);
3073
+ }
3074
+ __name(calculateDelay, "calculateDelay");
3075
+ async function fetchWithRetry(url, options, logger2) {
3076
+ let lastError;
3077
+ for (let attempt = 0; attempt <= RETRY_CONFIG.maxRetries; attempt++) {
3078
+ try {
3079
+ const response = await fetch(url, options);
3080
+ if (isRetryableError(null, response) && attempt < RETRY_CONFIG.maxRetries) {
3081
+ const delay = calculateDelay(attempt);
3082
+ 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.`);
3083
+ await sleep(delay);
3084
+ continue;
3085
+ }
3086
+ return response;
3087
+ } catch (error) {
3088
+ lastError = error;
3089
+ if (isRetryableError(error) && attempt < RETRY_CONFIG.maxRetries) {
3090
+ const delay = calculateDelay(attempt);
3091
+ 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)}`);
3092
+ await sleep(delay);
3093
+ continue;
3094
+ }
3095
+ break;
3096
+ }
3097
+ }
3098
+ throw lastError;
3099
+ }
3100
+ __name(fetchWithRetry, "fetchWithRetry");
3101
+
3102
+ // src/lib/runtime/remote-lg-action.ts
3025
3103
  var activeInterruptEvent = false;
3026
3104
  async function execute(args) {
3027
3105
  return new ReadableStream({
3028
3106
  async start(controller) {
3029
- try {
3030
- await streamEvents(controller, args);
3031
- controller.close();
3032
- } catch (err) {
3033
- const cause = err == null ? void 0 : err.cause;
3034
- const errorCode = (cause == null ? void 0 : cause.code) || (err == null ? void 0 : err.code);
3035
- if (errorCode === "ECONNREFUSED") {
3036
- throw new import_shared9.CopilotKitMisuseError({
3037
- message: `
3038
- The LangGraph client could not connect to the graph. Please further check previous logs, which includes further details.
3039
-
3040
- See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3041
- });
3042
- } else {
3043
- throw new import_shared9.CopilotKitMisuseError({
3044
- message: `
3045
- The LangGraph client threw unhandled error ${err}.
3046
-
3047
- See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3048
- });
3107
+ let lastError;
3108
+ for (let attempt = 0; attempt <= RETRY_CONFIG.maxRetries; attempt++) {
3109
+ try {
3110
+ await streamEvents(controller, args);
3111
+ controller.close();
3112
+ return;
3113
+ } catch (err) {
3114
+ lastError = err;
3115
+ if (isRetryableError(err) && attempt < RETRY_CONFIG.maxRetries) {
3116
+ const delay = calculateDelay(attempt);
3117
+ 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)}`);
3118
+ await sleep(delay);
3119
+ continue;
3120
+ }
3121
+ break;
3049
3122
  }
3050
3123
  }
3124
+ const cause = lastError == null ? void 0 : lastError.cause;
3125
+ const errorCode = (cause == null ? void 0 : cause.code) || (lastError == null ? void 0 : lastError.code);
3126
+ if (errorCode === "ECONNREFUSED") {
3127
+ throw new import_shared9.CopilotKitMisuseError({
3128
+ message: `
3129
+ The LangGraph client could not connect to the graph after ${RETRY_CONFIG.maxRetries + 1} attempts. Please further check previous logs, which includes further details.
3130
+
3131
+ See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3132
+ });
3133
+ } else {
3134
+ throw new import_shared9.CopilotKitMisuseError({
3135
+ message: `
3136
+ The LangGraph client threw unhandled error ${lastError}.
3137
+
3138
+ See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3139
+ });
3140
+ }
3051
3141
  }
3052
3142
  });
3053
3143
  }
@@ -3647,9 +3737,10 @@ function filterObjectBySchemaKeys(obj, schemaKeys) {
3647
3737
  __name(filterObjectBySchemaKeys, "filterObjectBySchemaKeys");
3648
3738
 
3649
3739
  // src/lib/runtime/remote-action-constructors.ts
3650
- var import_shared10 = require("@copilotkit/shared");
3740
+ var import_shared11 = require("@copilotkit/shared");
3651
3741
 
3652
3742
  // src/lib/streaming.ts
3743
+ var import_shared10 = require("@copilotkit/shared");
3653
3744
  async function writeJsonLineResponseToEventStream(response, eventStream$) {
3654
3745
  const reader = response.getReader();
3655
3746
  const decoder = new TextDecoder();
@@ -3688,16 +3779,44 @@ async function writeJsonLineResponseToEventStream(response, eventStream$) {
3688
3779
  }
3689
3780
  } catch (error) {
3690
3781
  console.error("Error in stream", error);
3691
- eventStream$.error(error);
3782
+ const structuredError = convertStreamingErrorToStructured(error);
3783
+ eventStream$.error(structuredError);
3692
3784
  return;
3693
3785
  }
3694
3786
  eventStream$.complete();
3695
3787
  }
3696
3788
  __name(writeJsonLineResponseToEventStream, "writeJsonLineResponseToEventStream");
3789
+ function convertStreamingErrorToStructured(error) {
3790
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
3791
+ 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") {
3792
+ return new import_shared10.CopilotKitError({
3793
+ 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.",
3794
+ code: import_shared10.CopilotKitErrorCode.NETWORK_ERROR
3795
+ });
3796
+ }
3797
+ 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"))) {
3798
+ return new import_shared10.CopilotKitLowLevelError({
3799
+ error: error instanceof Error ? error : new Error(String(error)),
3800
+ url: "streaming connection",
3801
+ message: "Network error occurred during streaming. Please check your connection and try again."
3802
+ });
3803
+ }
3804
+ 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"))) {
3805
+ return new import_shared10.CopilotKitError({
3806
+ message: "Request was cancelled",
3807
+ code: import_shared10.CopilotKitErrorCode.UNKNOWN
3808
+ });
3809
+ }
3810
+ return new import_shared10.CopilotKitError({
3811
+ message: `Streaming error: ${(error == null ? void 0 : error.message) || String(error)}`,
3812
+ code: import_shared10.CopilotKitErrorCode.UNKNOWN
3813
+ });
3814
+ }
3815
+ __name(convertStreamingErrorToStructured, "convertStreamingErrorToStructured");
3697
3816
 
3698
3817
  // src/lib/runtime/remote-action-constructors.ts
3699
- var import_shared11 = require("@copilotkit/shared");
3700
3818
  var import_shared12 = require("@copilotkit/shared");
3819
+ var import_shared13 = require("@copilotkit/shared");
3701
3820
  function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, messages, agentStates }) {
3702
3821
  const agents = endpoint.agents.map((agent) => ({
3703
3822
  name: agent.name,
@@ -3720,8 +3839,8 @@ function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, m
3720
3839
  if (agentStates) {
3721
3840
  const jsonState = agentStates.find((state2) => state2.agentName === name);
3722
3841
  if (jsonState) {
3723
- state = (0, import_shared12.parseJson)(jsonState.state, {});
3724
- config2 = (0, import_shared12.parseJson)(jsonState.config, {});
3842
+ state = (0, import_shared13.parseJson)(jsonState.state, {});
3843
+ config2 = (0, import_shared13.parseJson)(jsonState.config, {});
3725
3844
  }
3726
3845
  }
3727
3846
  try {
@@ -3741,7 +3860,7 @@ function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, m
3741
3860
  state,
3742
3861
  config: config2,
3743
3862
  properties: graphqlContext.properties,
3744
- actions: (0, import_shared12.tryMap)(actionInputsWithoutAgents, (action) => ({
3863
+ actions: (0, import_shared13.tryMap)(actionInputsWithoutAgents, (action) => ({
3745
3864
  name: action.name,
3746
3865
  description: action.description,
3747
3866
  parameters: JSON.parse(action.jsonSchema)
@@ -3790,7 +3909,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3790
3909
  });
3791
3910
  const fetchUrl = `${url}/actions/execute`;
3792
3911
  try {
3793
- const response = await fetch(fetchUrl, {
3912
+ const response = await fetchWithRetry(fetchUrl, {
3794
3913
  method: "POST",
3795
3914
  headers,
3796
3915
  body: JSON.stringify({
@@ -3798,7 +3917,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3798
3917
  arguments: args,
3799
3918
  properties: graphqlContext.properties
3800
3919
  })
3801
- });
3920
+ }, logger2);
3802
3921
  if (!response.ok) {
3803
3922
  logger2.error({
3804
3923
  url,
@@ -3806,11 +3925,11 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3806
3925
  body: await response.text()
3807
3926
  }, "Failed to execute remote action");
3808
3927
  if (response.status === 404) {
3809
- throw new import_shared11.CopilotKitApiDiscoveryError({
3928
+ throw new import_shared12.CopilotKitApiDiscoveryError({
3810
3929
  url: fetchUrl
3811
3930
  });
3812
3931
  }
3813
- throw new import_shared11.ResolvedCopilotKitError({
3932
+ throw new import_shared12.ResolvedCopilotKitError({
3814
3933
  status: response.status,
3815
3934
  url: fetchUrl,
3816
3935
  isRemoteEndpoint: true
@@ -3824,10 +3943,10 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3824
3943
  }, "Executed remote action");
3825
3944
  return result;
3826
3945
  } catch (error) {
3827
- if (error instanceof import_shared10.CopilotKitError) {
3946
+ if (error instanceof import_shared11.CopilotKitError) {
3828
3947
  throw error;
3829
3948
  }
3830
- throw new import_shared10.CopilotKitLowLevelError({
3949
+ throw new import_shared11.CopilotKitLowLevelError({
3831
3950
  error,
3832
3951
  url: fetchUrl
3833
3952
  });
@@ -3855,13 +3974,13 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3855
3974
  if (agentStates) {
3856
3975
  const jsonState = agentStates.find((state2) => state2.agentName === name);
3857
3976
  if (jsonState) {
3858
- state = (0, import_shared12.parseJson)(jsonState.state, {});
3859
- config2 = (0, import_shared12.parseJson)(jsonState.config, {});
3977
+ state = (0, import_shared13.parseJson)(jsonState.state, {});
3978
+ config2 = (0, import_shared13.parseJson)(jsonState.config, {});
3860
3979
  }
3861
3980
  }
3862
3981
  const fetchUrl = `${url}/agents/execute`;
3863
3982
  try {
3864
- const response = await fetch(fetchUrl, {
3983
+ const response = await fetchWithRetry(fetchUrl, {
3865
3984
  method: "POST",
3866
3985
  headers,
3867
3986
  body: JSON.stringify({
@@ -3875,14 +3994,14 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3875
3994
  state,
3876
3995
  config: config2,
3877
3996
  properties: graphqlContext.properties,
3878
- actions: (0, import_shared12.tryMap)(actionInputsWithoutAgents, (action) => ({
3997
+ actions: (0, import_shared13.tryMap)(actionInputsWithoutAgents, (action) => ({
3879
3998
  name: action.name,
3880
3999
  description: action.description,
3881
4000
  parameters: JSON.parse(action.jsonSchema)
3882
4001
  })),
3883
4002
  metaEvents
3884
4003
  })
3885
- });
4004
+ }, logger2);
3886
4005
  if (!response.ok) {
3887
4006
  logger2.error({
3888
4007
  url,
@@ -3890,11 +4009,11 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3890
4009
  body: await response.text()
3891
4010
  }, "Failed to execute remote agent");
3892
4011
  if (response.status === 404) {
3893
- throw new import_shared11.CopilotKitApiDiscoveryError({
4012
+ throw new import_shared12.CopilotKitApiDiscoveryError({
3894
4013
  url: fetchUrl
3895
4014
  });
3896
4015
  }
3897
- throw new import_shared11.ResolvedCopilotKitError({
4016
+ throw new import_shared12.ResolvedCopilotKitError({
3898
4017
  status: response.status,
3899
4018
  url: fetchUrl,
3900
4019
  isRemoteEndpoint: true
@@ -3912,10 +4031,10 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
3912
4031
  throw new Error("Unsupported agent type");
3913
4032
  }
3914
4033
  } catch (error) {
3915
- if (error instanceof import_shared10.CopilotKitError) {
4034
+ if (error instanceof import_shared11.CopilotKitError) {
3916
4035
  throw error;
3917
4036
  }
3918
- throw new import_shared10.CopilotKitLowLevelError({
4037
+ throw new import_shared11.CopilotKitLowLevelError({
3919
4038
  error,
3920
4039
  url: fetchUrl
3921
4040
  });
@@ -3945,10 +4064,10 @@ function createHeaders(onBeforeRequest, graphqlContext) {
3945
4064
  __name(createHeaders, "createHeaders");
3946
4065
 
3947
4066
  // src/lib/runtime/remote-actions.ts
3948
- var import_shared15 = require("@copilotkit/shared");
4067
+ var import_shared16 = require("@copilotkit/shared");
3949
4068
 
3950
4069
  // src/lib/runtime/agui-action.ts
3951
- var import_shared13 = require("@copilotkit/shared");
4070
+ var import_shared14 = require("@copilotkit/shared");
3952
4071
  function constructAGUIRemoteAction({ logger: logger2, messages, agentStates, agent, metaEvents }) {
3953
4072
  const action = {
3954
4073
  name: agent.agentId,
@@ -3973,7 +4092,7 @@ function constructAGUIRemoteAction({ logger: logger2, messages, agentStates, age
3973
4092
  if (agentStates) {
3974
4093
  const jsonState = agentStates.find((state2) => state2.agentName === agent.agentId);
3975
4094
  if (jsonState) {
3976
- state = (0, import_shared13.parseJson)(jsonState.state, {});
4095
+ state = (0, import_shared14.parseJson)(jsonState.state, {});
3977
4096
  }
3978
4097
  }
3979
4098
  agent.state = state;
@@ -4080,7 +4199,7 @@ async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: l
4080
4199
  status: response.status,
4081
4200
  body: await response.text()
4082
4201
  }, "Failed to fetch actions from url");
4083
- throw new import_shared15.ResolvedCopilotKitError({
4202
+ throw new import_shared16.ResolvedCopilotKitError({
4084
4203
  status: response.status,
4085
4204
  url: fetchUrl,
4086
4205
  isRemoteEndpoint: true
@@ -4092,10 +4211,10 @@ async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: l
4092
4211
  }, "Fetched actions from url");
4093
4212
  return json;
4094
4213
  } catch (error) {
4095
- if (error instanceof import_shared15.CopilotKitError) {
4214
+ if (error instanceof import_shared16.CopilotKitError) {
4096
4215
  throw error;
4097
4216
  }
4098
- throw new import_shared15.CopilotKitLowLevelError({
4217
+ throw new import_shared16.CopilotKitLowLevelError({
4099
4218
  error,
4100
4219
  url: fetchUrl
4101
4220
  });
@@ -4153,9 +4272,9 @@ async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, m
4153
4272
  }));
4154
4273
  for (const [key, agent] of Object.entries(agents)) {
4155
4274
  if (agent.agentId !== void 0 && agent.agentId !== key) {
4156
- throw new import_shared15.CopilotKitError({
4275
+ throw new import_shared16.CopilotKitError({
4157
4276
  message: `Agent ${key} has agentId ${agent.agentId} which does not match the key ${key}`,
4158
- code: import_shared14.CopilotKitErrorCode.UNKNOWN
4277
+ code: import_shared15.CopilotKitErrorCode.UNKNOWN
4159
4278
  });
4160
4279
  } else if (agent.agentId === void 0) {
4161
4280
  agent.agentId = key;
@@ -4176,7 +4295,7 @@ __name(setupRemoteActions, "setupRemoteActions");
4176
4295
  var import_node_crypto3 = require("crypto");
4177
4296
 
4178
4297
  // src/lib/runtime/copilot-runtime.ts
4179
- var import_shared18 = require("@copilotkit/shared");
4298
+ var import_shared19 = require("@copilotkit/shared");
4180
4299
 
4181
4300
  // src/service-adapters/langchain/langserve.ts
4182
4301
  var import_remote = require("langchain/runnables/remote");
@@ -4257,11 +4376,11 @@ var RemoteChain = class {
4257
4376
  __name(RemoteChain, "RemoteChain");
4258
4377
 
4259
4378
  // src/service-adapters/empty/empty-adapter.ts
4260
- var import_shared16 = require("@copilotkit/shared");
4379
+ var import_shared17 = require("@copilotkit/shared");
4261
4380
  var EmptyAdapter = class {
4262
4381
  async process(request) {
4263
4382
  return {
4264
- threadId: request.threadId || (0, import_shared16.randomUUID)()
4383
+ threadId: request.threadId || (0, import_shared17.randomUUID)()
4265
4384
  };
4266
4385
  }
4267
4386
  };
@@ -4394,9 +4513,9 @@ __name(ImageMessage, "ImageMessage");
4394
4513
 
4395
4514
  // src/service-adapters/conversion.ts
4396
4515
  var import_class_transformer = require("class-transformer");
4397
- var import_shared17 = require("@copilotkit/shared");
4516
+ var import_shared18 = require("@copilotkit/shared");
4398
4517
  function convertGqlInputToMessages(inputMessages) {
4399
- const messages = (0, import_shared17.tryMap)(inputMessages, (message) => {
4518
+ const messages = (0, import_shared18.tryMap)(inputMessages, (message) => {
4400
4519
  if (message.textMessage) {
4401
4520
  return (0, import_class_transformer.plainToInstance)(TextMessage, {
4402
4521
  id: message.id,
@@ -4590,7 +4709,7 @@ var CopilotRuntime = class {
4590
4709
  this.mcpServersConfig = params == null ? void 0 : params.mcpServers;
4591
4710
  this.createMCPClientImpl = params == null ? void 0 : params.createMCPClient;
4592
4711
  if (this.mcpServersConfig && this.mcpServersConfig.length > 0 && !this.createMCPClientImpl) {
4593
- throw new import_shared18.CopilotKitMisuseError({
4712
+ throw new import_shared19.CopilotKitMisuseError({
4594
4713
  message: "MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`."
4595
4714
  });
4596
4715
  }
@@ -4646,7 +4765,7 @@ var CopilotRuntime = class {
4646
4765
  }
4647
4766
  } else {
4648
4767
  newMessages.unshift({
4649
- id: (0, import_shared18.randomId)(),
4768
+ id: (0, import_shared19.randomId)(),
4650
4769
  createdAt: /* @__PURE__ */ new Date(),
4651
4770
  textMessage: {
4652
4771
  role: MessageRole.system,
@@ -4666,11 +4785,16 @@ var CopilotRuntime = class {
4666
4785
  const requestStartTime = Date.now();
4667
4786
  const streamedChunks = [];
4668
4787
  try {
4788
+ if (Object.keys(this.agents).length && (agentSession == null ? void 0 : agentSession.agentName) && !this.delegateAgentProcessingToServiceAdapter) {
4789
+ this.agents = {
4790
+ [agentSession.agentName]: this.agents[agentSession.agentName]
4791
+ };
4792
+ }
4669
4793
  if (agentSession && !this.delegateAgentProcessingToServiceAdapter) {
4670
4794
  return await this.processAgentRequest(request);
4671
4795
  }
4672
4796
  if (serviceAdapter instanceof EmptyAdapter) {
4673
- throw new import_shared18.CopilotKitMisuseError({
4797
+ throw new import_shared19.CopilotKitMisuseError({
4674
4798
  message: `Invalid adapter configuration: EmptyAdapter is only meant to be used with agent lock mode.
4675
4799
  For non-agent components like useCopilotChatSuggestions, CopilotTextarea, or CopilotTask,
4676
4800
  please use an LLM adapter instead.`
@@ -4700,7 +4824,7 @@ please use an LLM adapter instead.`
4700
4824
  const serverSideActionsInput = serverSideActions.map((action) => ({
4701
4825
  name: action.name,
4702
4826
  description: action.description,
4703
- jsonSchema: JSON.stringify((0, import_shared18.actionParametersToJsonSchema)(action.parameters))
4827
+ jsonSchema: JSON.stringify((0, import_shared19.actionParametersToJsonSchema)(action.parameters))
4704
4828
  }));
4705
4829
  const actionInputs = flattenToolCallsNoDuplicates([
4706
4830
  ...serverSideActionsInput,
@@ -4829,12 +4953,12 @@ please use an LLM adapter instead.`
4829
4953
  console.error("Error logging LLM error:", logError);
4830
4954
  }
4831
4955
  }
4832
- if (error instanceof import_shared18.CopilotKitError) {
4956
+ if (error instanceof import_shared19.CopilotKitError) {
4833
4957
  throw error;
4834
4958
  }
4835
4959
  console.error("Error getting response:", error);
4836
- eventSource.sendErrorMessageToChat();
4837
- throw error;
4960
+ const structuredError = this.convertStreamingErrorToStructured(error);
4961
+ throw structuredError;
4838
4962
  }
4839
4963
  }
4840
4964
  async discoverAgentsFromEndpoints(graphqlContext) {
@@ -4855,12 +4979,12 @@ please use an LLM adapter instead.`
4855
4979
  try {
4856
4980
  data = await client.assistants.search();
4857
4981
  if (data && "detail" in data && data.detail.toLowerCase() === "not found") {
4858
- throw new import_shared18.CopilotKitAgentDiscoveryError({
4982
+ throw new import_shared19.CopilotKitAgentDiscoveryError({
4859
4983
  availableAgents: this.availableAgents
4860
4984
  });
4861
4985
  }
4862
4986
  } catch (e) {
4863
- throw new import_shared18.CopilotKitMisuseError({
4987
+ throw new import_shared19.CopilotKitMisuseError({
4864
4988
  message: `
4865
4989
  Failed to find or contact remote endpoint at url ${endpoint.deploymentUrl}.
4866
4990
  Make sure the API is running and that it's indeed a LangGraph platform url.
@@ -4882,7 +5006,7 @@ please use an LLM adapter instead.`
4882
5006
  const cpkEndpoint = endpoint;
4883
5007
  const fetchUrl = `${endpoint.url}/info`;
4884
5008
  try {
4885
- const response = await fetch(fetchUrl, {
5009
+ const response = await fetchWithRetry(fetchUrl, {
4886
5010
  method: "POST",
4887
5011
  headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
4888
5012
  body: JSON.stringify({
@@ -4891,11 +5015,11 @@ please use an LLM adapter instead.`
4891
5015
  });
4892
5016
  if (!response.ok) {
4893
5017
  if (response.status === 404) {
4894
- throw new import_shared18.CopilotKitApiDiscoveryError({
5018
+ throw new import_shared19.CopilotKitApiDiscoveryError({
4895
5019
  url: fetchUrl
4896
5020
  });
4897
5021
  }
4898
- throw new import_shared18.ResolvedCopilotKitError({
5022
+ throw new import_shared19.ResolvedCopilotKitError({
4899
5023
  status: response.status,
4900
5024
  url: fetchUrl,
4901
5025
  isRemoteEndpoint: true
@@ -4905,7 +5029,7 @@ please use an LLM adapter instead.`
4905
5029
  const endpointAgents = ((data == null ? void 0 : data.agents) ?? []).map((agent) => ({
4906
5030
  name: agent.name,
4907
5031
  description: agent.description ?? "" ?? "",
4908
- id: (0, import_shared18.randomId)(),
5032
+ id: (0, import_shared19.randomId)(),
4909
5033
  endpoint
4910
5034
  }));
4911
5035
  return [
@@ -4913,10 +5037,10 @@ please use an LLM adapter instead.`
4913
5037
  ...endpointAgents
4914
5038
  ];
4915
5039
  } catch (error) {
4916
- if (error instanceof import_shared18.CopilotKitError) {
5040
+ if (error instanceof import_shared19.CopilotKitError) {
4917
5041
  throw error;
4918
5042
  }
4919
- throw new import_shared18.CopilotKitLowLevelError({
5043
+ throw new import_shared19.CopilotKitLowLevelError({
4920
5044
  error,
4921
5045
  url: fetchUrl
4922
5046
  });
@@ -4971,7 +5095,7 @@ please use an LLM adapter instead.`
4971
5095
  const cpkEndpoint = agentWithEndpoint.endpoint;
4972
5096
  const fetchUrl = `${cpkEndpoint.url}/agents/state`;
4973
5097
  try {
4974
- const response = await fetch(fetchUrl, {
5098
+ const response = await fetchWithRetry(fetchUrl, {
4975
5099
  method: "POST",
4976
5100
  headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
4977
5101
  body: JSON.stringify({
@@ -4982,11 +5106,11 @@ please use an LLM adapter instead.`
4982
5106
  });
4983
5107
  if (!response.ok) {
4984
5108
  if (response.status === 404) {
4985
- throw new import_shared18.CopilotKitApiDiscoveryError({
5109
+ throw new import_shared19.CopilotKitApiDiscoveryError({
4986
5110
  url: fetchUrl
4987
5111
  });
4988
5112
  }
4989
- throw new import_shared18.ResolvedCopilotKitError({
5113
+ throw new import_shared19.ResolvedCopilotKitError({
4990
5114
  status: response.status,
4991
5115
  url: fetchUrl,
4992
5116
  isRemoteEndpoint: true
@@ -4999,10 +5123,10 @@ please use an LLM adapter instead.`
4999
5123
  messages: JSON.stringify(data.messages)
5000
5124
  };
5001
5125
  } catch (error) {
5002
- if (error instanceof import_shared18.CopilotKitError) {
5126
+ if (error instanceof import_shared19.CopilotKitError) {
5003
5127
  throw error;
5004
5128
  }
5005
- throw new import_shared18.CopilotKitLowLevelError({
5129
+ throw new import_shared19.CopilotKitLowLevelError({
5006
5130
  error,
5007
5131
  url: fetchUrl
5008
5132
  });
@@ -5022,7 +5146,7 @@ please use an LLM adapter instead.`
5022
5146
  const messages = convertGqlInputToMessages(rawMessages);
5023
5147
  const currentAgent = serverSideActions.find((action) => action.name === agentName && isRemoteAgentAction(action));
5024
5148
  if (!currentAgent) {
5025
- throw new import_shared18.CopilotKitAgentDiscoveryError({
5149
+ throw new import_shared19.CopilotKitAgentDiscoveryError({
5026
5150
  agentName,
5027
5151
  availableAgents: this.availableAgents
5028
5152
  });
@@ -5034,7 +5158,7 @@ please use an LLM adapter instead.`
5034
5158
  )).map((action) => ({
5035
5159
  name: action.name,
5036
5160
  description: action.description,
5037
- jsonSchema: JSON.stringify((0, import_shared18.actionParametersToJsonSchema)(action.parameters))
5161
+ jsonSchema: JSON.stringify((0, import_shared19.actionParametersToJsonSchema)(action.parameters))
5038
5162
  }));
5039
5163
  const allAvailableActions = flattenToolCallsNoDuplicates([
5040
5164
  ...availableActionsForCurrentAgent,
@@ -5134,7 +5258,8 @@ please use an LLM adapter instead.`
5134
5258
  console.error("Error logging agent error:", logError);
5135
5259
  }
5136
5260
  }
5137
- eventStream$.error(err);
5261
+ const structuredError = this.convertStreamingErrorToStructured(err);
5262
+ eventStream$.error(structuredError);
5138
5263
  eventStream$.complete();
5139
5264
  },
5140
5265
  complete: () => eventStream$.complete()
@@ -5296,6 +5421,32 @@ please use an LLM adapter instead.`
5296
5421
  return "langchain";
5297
5422
  return void 0;
5298
5423
  }
5424
+ convertStreamingErrorToStructured(error) {
5425
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
5426
+ 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") {
5427
+ return new import_shared19.CopilotKitError({
5428
+ message: "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
5429
+ code: import_shared19.CopilotKitErrorCode.NETWORK_ERROR
5430
+ });
5431
+ }
5432
+ 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"))) {
5433
+ return new import_shared19.CopilotKitLowLevelError({
5434
+ error: error instanceof Error ? error : new Error(String(error)),
5435
+ url: "agent streaming connection",
5436
+ message: "Network error occurred during agent streaming. Please check your connection and try again."
5437
+ });
5438
+ }
5439
+ 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"))) {
5440
+ return new import_shared19.CopilotKitError({
5441
+ message: "Agent request was cancelled",
5442
+ code: import_shared19.CopilotKitErrorCode.UNKNOWN
5443
+ });
5444
+ }
5445
+ return new import_shared19.CopilotKitError({
5446
+ message: `Agent streaming error: ${(error == null ? void 0 : error.message) || String(error)}`,
5447
+ code: import_shared19.CopilotKitErrorCode.UNKNOWN
5448
+ });
5449
+ }
5299
5450
  };
5300
5451
  __name(CopilotRuntime, "CopilotRuntime");
5301
5452
  function flattenToolCallsNoDuplicates(toolsByPriority) {
@@ -5338,7 +5489,7 @@ __name(resolveEndpointType, "resolveEndpointType");
5338
5489
 
5339
5490
  // src/lib/telemetry-client.ts
5340
5491
  var packageJson = require_package();
5341
- var telemetryClient = new import_shared19.TelemetryClient({
5492
+ var telemetryClient = new import_shared20.TelemetryClient({
5342
5493
  packageName: packageJson.name,
5343
5494
  packageVersion: packageJson.version
5344
5495
  });
@@ -5517,16 +5668,17 @@ var RuntimeEventSource = class {
5517
5668
  const errorMessage = `\u274C ${message}`;
5518
5669
  if (!this.callback) {
5519
5670
  this.stream(async (eventStream$) => {
5520
- eventStream$.sendTextMessage((0, import_shared20.randomId)(), errorMessage);
5671
+ eventStream$.sendTextMessage((0, import_shared21.randomId)(), errorMessage);
5521
5672
  });
5522
5673
  } else {
5523
- this.eventStream$.sendTextMessage((0, import_shared20.randomId)(), errorMessage);
5674
+ this.eventStream$.sendTextMessage((0, import_shared21.randomId)(), errorMessage);
5524
5675
  }
5525
5676
  }
5526
5677
  processRuntimeEvents({ serverSideActions, guardrailsResult$, actionInputsWithoutAgents, threadId }) {
5527
5678
  this.callback(this.eventStream$).catch((error) => {
5528
5679
  console.error("Error in event source callback", error);
5529
- this.sendErrorMessageToChat();
5680
+ const structuredError = convertStreamingErrorToStructured2(error);
5681
+ this.eventStream$.error(structuredError);
5530
5682
  this.eventStream$.complete();
5531
5683
  });
5532
5684
  return this.eventStream$.pipe(
@@ -5565,7 +5717,15 @@ var RuntimeEventSource = class {
5565
5717
  telemetry_client_default.capture("oss.runtime.server_action_executed", {});
5566
5718
  return (0, import_rxjs3.concat)((0, import_rxjs3.of)(eventWithState.event), toolCallEventStream$).pipe((0, import_rxjs3.catchError)((error) => {
5567
5719
  console.error("Error in tool call stream", error);
5568
- this.sendErrorMessageToChat();
5720
+ const structuredError = convertStreamingErrorToStructured2(error);
5721
+ toolCallEventStream$.sendActionExecutionResult({
5722
+ actionExecutionId: eventWithState.actionExecutionId,
5723
+ actionName: eventWithState.action.name,
5724
+ error: {
5725
+ code: structuredError.code,
5726
+ message: structuredError.message
5727
+ }
5728
+ });
5569
5729
  return import_rxjs3.EMPTY;
5570
5730
  }));
5571
5731
  } else {
@@ -5638,12 +5798,13 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
5638
5798
  next: (event) => eventStream$.next(event),
5639
5799
  error: (err) => {
5640
5800
  console.error("Error in stream", err);
5801
+ const structuredError = convertStreamingErrorToStructured2(err);
5641
5802
  eventStream$.sendActionExecutionResult({
5642
5803
  actionExecutionId,
5643
5804
  actionName: action.name,
5644
5805
  error: {
5645
- code: "STREAM_ERROR",
5646
- message: err.message
5806
+ code: structuredError.code,
5807
+ message: structuredError.message
5647
5808
  }
5648
5809
  });
5649
5810
  eventStream$.complete();
@@ -5676,6 +5837,40 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
5676
5837
  }
5677
5838
  }
5678
5839
  __name(executeAction, "executeAction");
5840
+ function convertStreamingErrorToStructured2(error) {
5841
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
5842
+ 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") {
5843
+ return new import_shared21.CopilotKitError({
5844
+ message: "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
5845
+ code: import_shared21.CopilotKitErrorCode.NETWORK_ERROR
5846
+ });
5847
+ }
5848
+ 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"))) {
5849
+ return new import_shared21.CopilotKitLowLevelError({
5850
+ error: error instanceof Error ? error : new Error(String(error)),
5851
+ url: "event streaming connection",
5852
+ message: "Network error occurred during event streaming. Please check your connection and try again."
5853
+ });
5854
+ }
5855
+ 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"))) {
5856
+ return new import_shared21.CopilotKitError({
5857
+ message: "Request was cancelled",
5858
+ code: import_shared21.CopilotKitErrorCode.UNKNOWN
5859
+ });
5860
+ }
5861
+ const errorMessage = (error == null ? void 0 : error.message) || String(error);
5862
+ if (errorMessage.includes("401") || errorMessage.toLowerCase().includes("api key") || errorMessage.toLowerCase().includes("unauthorized") || errorMessage.toLowerCase().includes("authentication") || errorMessage.toLowerCase().includes("incorrect api key")) {
5863
+ return new import_shared21.CopilotKitError({
5864
+ message: `Event streaming error: ${errorMessage}`,
5865
+ code: import_shared21.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR
5866
+ });
5867
+ }
5868
+ return new import_shared21.CopilotKitError({
5869
+ message: `Event streaming error: ${errorMessage}`,
5870
+ code: import_shared21.CopilotKitErrorCode.UNKNOWN
5871
+ });
5872
+ }
5873
+ __name(convertStreamingErrorToStructured2, "convertStreamingErrorToStructured");
5679
5874
 
5680
5875
  // src/graphql/resolvers/copilot.resolver.ts
5681
5876
  var import_graphql_scalars2 = require("graphql-scalars");
@@ -5716,7 +5911,7 @@ var UnknownErrorResponse = class extends FailedResponseStatus {
5716
5911
  __name(UnknownErrorResponse, "UnknownErrorResponse");
5717
5912
 
5718
5913
  // src/graphql/resolvers/copilot.resolver.ts
5719
- var import_shared21 = require("@copilotkit/shared");
5914
+ var import_shared22 = require("@copilotkit/shared");
5720
5915
 
5721
5916
  // src/graphql/types/agents-response.type.ts
5722
5917
  var import_type_graphql19 = require("type-graphql");
@@ -5772,6 +5967,7 @@ AgentsResponse = _ts_decorate18([
5772
5967
  ], AgentsResponse);
5773
5968
 
5774
5969
  // src/graphql/resolvers/copilot.resolver.ts
5970
+ var import_shared23 = require("@copilotkit/shared");
5775
5971
  function _ts_decorate19(decorators, target, key, desc) {
5776
5972
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
5777
5973
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -5911,7 +6107,7 @@ var CopilotResolver = class {
5911
6107
  ctx.properties["copilotCloudPublicApiKey"] = copilotCloudPublicApiKey;
5912
6108
  }
5913
6109
  logger2.debug("Processing");
5914
- const { eventSource, threadId = (0, import_shared21.randomId)(), runId, serverSideActions, actionInputsWithoutAgents, extensions } = await copilotRuntime.processRuntimeRequest({
6110
+ const { eventSource, threadId = (0, import_shared22.randomId)(), runId, serverSideActions, actionInputsWithoutAgents, extensions } = await copilotRuntime.processRuntimeRequest({
5915
6111
  serviceAdapter,
5916
6112
  messages: data.messages,
5917
6113
  actions: data.frontend.actions.filter((action) => action.available !== ActionInputAvailability.disabled),
@@ -6054,7 +6250,7 @@ var CopilotResolver = class {
6054
6250
  });
6055
6251
  outputMessages = [
6056
6252
  (0, import_class_transformer3.plainToInstance)(TextMessage, {
6057
- id: (0, import_shared21.randomId)(),
6253
+ id: (0, import_shared22.randomId)(),
6058
6254
  createdAt: /* @__PURE__ */ new Date(),
6059
6255
  content: result.reason,
6060
6256
  role: MessageRole.assistant
@@ -6232,7 +6428,7 @@ var CopilotResolver = class {
6232
6428
  event
6233
6429
  }, "Agent message event received");
6234
6430
  pushMessage({
6235
- id: (0, import_shared21.randomId)(),
6431
+ id: (0, import_shared22.randomId)(),
6236
6432
  status: new SuccessMessageStatus(),
6237
6433
  threadId: event.threadId,
6238
6434
  agentName: event.agentName,
@@ -6245,7 +6441,7 @@ var CopilotResolver = class {
6245
6441
  createdAt: /* @__PURE__ */ new Date()
6246
6442
  });
6247
6443
  outputMessages.push((0, import_class_transformer3.plainToInstance)(AgentStateMessage, {
6248
- id: (0, import_shared21.randomId)(),
6444
+ id: (0, import_shared22.randomId)(),
6249
6445
  threadId: event.threadId,
6250
6446
  agentName: event.agentName,
6251
6447
  nodeName: event.nodeName,
@@ -6263,6 +6459,12 @@ var CopilotResolver = class {
6263
6459
  logger2.error({
6264
6460
  err
6265
6461
  }, "Error in event stream");
6462
+ if (err instanceof import_shared23.CopilotKitError || err instanceof Error && err.name && err.name.includes("CopilotKit")) {
6463
+ eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
6464
+ rejectOutputMessagesPromise(err);
6465
+ stopStreamingMessages(err);
6466
+ return;
6467
+ }
6266
6468
  responseStatus$.next(new UnknownErrorResponse({
6267
6469
  description: `An unknown error has occurred in the event stream`
6268
6470
  }));
@@ -6440,6 +6642,7 @@ LoadAgentStateInput = _ts_decorate21([
6440
6642
  ], LoadAgentStateInput);
6441
6643
 
6442
6644
  // src/graphql/resolvers/state.resolver.ts
6645
+ var import_shared24 = require("@copilotkit/shared");
6443
6646
  function _ts_decorate22(decorators, target, key, desc) {
6444
6647
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
6445
6648
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -6467,12 +6670,13 @@ var StateResolver = class {
6467
6670
  const agents = await ctx._copilotkit.runtime.discoverAgentsFromEndpoints(ctx);
6468
6671
  const agent = agents.find((agent2) => agent2.name === data.agentName);
6469
6672
  if (!agent) {
6470
- return {
6471
- threadId: data.threadId || "",
6472
- threadExists: false,
6473
- state: JSON.stringify({}),
6474
- messages: JSON.stringify([])
6475
- };
6673
+ throw new import_shared24.CopilotKitAgentDiscoveryError({
6674
+ agentName: data.agentName,
6675
+ availableAgents: agents.map((a) => ({
6676
+ name: a.name,
6677
+ id: a.name
6678
+ }))
6679
+ });
6476
6680
  }
6477
6681
  const state = await ctx._copilotkit.runtime.loadAgentState(ctx, data.threadId, data.agentName);
6478
6682
  return state;