@copilotkit/runtime 1.9.1 → 1.9.2-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/{chunk-RVLXQ2V5.mjs → chunk-44FYLJJJ.mjs} +2 -2
  3. package/dist/{chunk-2CND6WGV.mjs → chunk-ESXPDYNT.mjs} +2 -2
  4. package/dist/{chunk-BHNTR222.mjs → chunk-O6KXX5R5.mjs} +2 -2
  5. package/dist/{chunk-GOPTDPPB.mjs → chunk-YMIOUUPV.mjs} +260 -61
  6. package/dist/chunk-YMIOUUPV.mjs.map +1 -0
  7. package/dist/{chunk-EVF3MXEK.mjs → chunk-YXL4PSJM.mjs} +2 -2
  8. package/dist/index.d.ts +1 -1
  9. package/dist/index.js +305 -106
  10. package/dist/index.js.map +1 -1
  11. package/dist/index.mjs +5 -5
  12. package/dist/lib/index.d.ts +1 -1
  13. package/dist/lib/index.js +298 -99
  14. package/dist/lib/index.js.map +1 -1
  15. package/dist/lib/index.mjs +5 -5
  16. package/dist/lib/integrations/index.d.ts +2 -2
  17. package/dist/lib/integrations/index.js +16 -7
  18. package/dist/lib/integrations/index.js.map +1 -1
  19. package/dist/lib/integrations/index.mjs +4 -4
  20. package/dist/lib/integrations/nest/index.d.ts +1 -1
  21. package/dist/lib/integrations/nest/index.js +16 -7
  22. package/dist/lib/integrations/nest/index.js.map +1 -1
  23. package/dist/lib/integrations/nest/index.mjs +2 -2
  24. package/dist/lib/integrations/node-express/index.d.ts +1 -1
  25. package/dist/lib/integrations/node-express/index.js +16 -7
  26. package/dist/lib/integrations/node-express/index.js.map +1 -1
  27. package/dist/lib/integrations/node-express/index.mjs +2 -2
  28. package/dist/lib/integrations/node-http/index.d.ts +1 -1
  29. package/dist/lib/integrations/node-http/index.js +16 -7
  30. package/dist/lib/integrations/node-http/index.js.map +1 -1
  31. package/dist/lib/integrations/node-http/index.mjs +1 -1
  32. package/dist/{shared-0c31d7c5.d.ts → shared-e272b15a.d.ts} +1 -0
  33. package/package.json +2 -2
  34. package/src/agents/langgraph/event-source.ts +10 -1
  35. package/src/graphql/resolvers/copilot.resolver.ts +13 -0
  36. package/src/graphql/resolvers/state.resolver.ts +5 -7
  37. package/src/lib/runtime/copilot-runtime.ts +62 -6
  38. package/src/lib/runtime/remote-action-constructors.ts +37 -28
  39. package/src/lib/runtime/remote-lg-action.ts +45 -24
  40. package/src/lib/runtime/retry-utils.ts +96 -0
  41. package/src/lib/streaming.ts +54 -1
  42. package/src/service-adapters/events.ts +101 -6
  43. package/dist/chunk-GOPTDPPB.mjs.map +0 -1
  44. /package/dist/{chunk-RVLXQ2V5.mjs.map → chunk-44FYLJJJ.mjs.map} +0 -0
  45. /package/dist/{chunk-2CND6WGV.mjs.map → chunk-ESXPDYNT.mjs.map} +0 -0
  46. /package/dist/{chunk-BHNTR222.mjs.map → chunk-O6KXX5R5.mjs.map} +0 -0
  47. /package/dist/{chunk-EVF3MXEK.mjs.map → chunk-YXL4PSJM.mjs.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @copilotkit/runtime
2
2
 
3
+ ## 1.9.2-next.0
4
+
5
+ ### Patch Changes
6
+
7
+ - 10345a5: - feat: structured error visibility system for streaming errors
8
+ - Updated dependencies [10345a5]
9
+ - @copilotkit/shared@1.9.2-next.0
10
+
3
11
  ## 1.9.1
4
12
 
5
13
  ### Patch Changes
@@ -2,7 +2,7 @@ import {
2
2
  getCommonConfig,
3
3
  getRuntimeInstanceTelemetryInfo,
4
4
  telemetry_client_default
5
- } from "./chunk-GOPTDPPB.mjs";
5
+ } from "./chunk-YMIOUUPV.mjs";
6
6
  import {
7
7
  __name
8
8
  } from "./chunk-FHD4JECV.mjs";
@@ -77,4 +77,4 @@ export {
77
77
  config,
78
78
  copilotRuntimeNextJSPagesRouterEndpoint
79
79
  };
80
- //# sourceMappingURL=chunk-RVLXQ2V5.mjs.map
80
+ //# sourceMappingURL=chunk-44FYLJJJ.mjs.map
@@ -2,7 +2,7 @@ import {
2
2
  copilotRuntimeNodeHttpEndpoint,
3
3
  getRuntimeInstanceTelemetryInfo,
4
4
  telemetry_client_default
5
- } from "./chunk-GOPTDPPB.mjs";
5
+ } from "./chunk-YMIOUUPV.mjs";
6
6
  import {
7
7
  __name
8
8
  } from "./chunk-FHD4JECV.mjs";
@@ -22,4 +22,4 @@ __name(copilotRuntimeNestEndpoint, "copilotRuntimeNestEndpoint");
22
22
  export {
23
23
  copilotRuntimeNestEndpoint
24
24
  };
25
- //# sourceMappingURL=chunk-2CND6WGV.mjs.map
25
+ //# sourceMappingURL=chunk-ESXPDYNT.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  LangGraphEventTypes
3
- } from "./chunk-GOPTDPPB.mjs";
3
+ } from "./chunk-YMIOUUPV.mjs";
4
4
  import {
5
5
  __name
6
6
  } from "./chunk-FHD4JECV.mjs";
@@ -138,4 +138,4 @@ export {
138
138
  CustomEventNames,
139
139
  LangGraphAgent
140
140
  };
141
- //# sourceMappingURL=chunk-BHNTR222.mjs.map
141
+ //# sourceMappingURL=chunk-O6KXX5R5.mjs.map
@@ -40,7 +40,7 @@ var require_package = __commonJS({
40
40
  publishConfig: {
41
41
  access: "public"
42
42
  },
43
- version: "1.9.1",
43
+ version: "1.9.2-next.0",
44
44
  sideEffects: false,
45
45
  main: "./dist/index.js",
46
46
  module: "./dist/index.mjs",
@@ -1485,14 +1485,14 @@ GenerateCopilotResponseInput = _ts_decorate15([
1485
1485
  import { Repeater } from "graphql-yoga";
1486
1486
 
1487
1487
  // src/service-adapters/events.ts
1488
- import { randomId as randomId3 } from "@copilotkit/shared";
1488
+ import { randomId as randomId3, CopilotKitError as CopilotKitError6, CopilotKitErrorCode as CopilotKitErrorCode4, CopilotKitLowLevelError as CopilotKitLowLevelError5 } from "@copilotkit/shared";
1489
1489
  import { of, concat, scan as scan2, concatMap, ReplaySubject as ReplaySubject2, firstValueFrom, from as from2, catchError as catchError2, EMPTY } from "rxjs";
1490
1490
 
1491
1491
  // src/lib/telemetry-client.ts
1492
1492
  import { TelemetryClient } from "@copilotkit/shared";
1493
1493
 
1494
1494
  // src/lib/runtime/remote-actions.ts
1495
- import { CopilotKitErrorCode } from "@copilotkit/shared";
1495
+ import { CopilotKitErrorCode as CopilotKitErrorCode2 } from "@copilotkit/shared";
1496
1496
 
1497
1497
  // src/lib/runtime/remote-action-constructors.ts
1498
1498
  import { createHash as createHash2 } from "crypto";
@@ -1532,7 +1532,7 @@ var CustomEventNames;
1532
1532
  })(CustomEventNames || (CustomEventNames = {}));
1533
1533
 
1534
1534
  // src/agents/langgraph/event-source.ts
1535
- import { randomId } from "@copilotkit/shared";
1535
+ import { randomId, CopilotKitError } from "@copilotkit/shared";
1536
1536
  var RemoteLangGraphEventSource = class {
1537
1537
  eventStream$ = new ReplaySubject();
1538
1538
  shouldEmitToolCall(shouldEmitToolCalls, toolCallName) {
@@ -1733,6 +1733,9 @@ var RemoteLangGraphEventSource = class {
1733
1733
  return events;
1734
1734
  }), catchError((error) => {
1735
1735
  console.error(error);
1736
+ if (error instanceof CopilotKitError || (error == null ? void 0 : error.name) && error.name.includes("CopilotKit")) {
1737
+ throw error;
1738
+ }
1736
1739
  const events = [];
1737
1740
  if ((lastEventWithState == null ? void 0 : lastEventWithState.lastMessageId) && !lastEventWithState.isToolCall) {
1738
1741
  events.push({
@@ -1773,32 +1776,119 @@ import { isValidUUID, randomUUID } from "@copilotkit/shared";
1773
1776
  import { parse as parsePartialJson } from "partial-json";
1774
1777
  import { parseJson, CopilotKitMisuseError } from "@copilotkit/shared";
1775
1778
  import { RemoveMessage } from "@langchain/core/messages";
1779
+
1780
+ // src/lib/runtime/retry-utils.ts
1781
+ var RETRY_CONFIG = {
1782
+ maxRetries: 3,
1783
+ baseDelayMs: 1e3,
1784
+ maxDelayMs: 5e3,
1785
+ // HTTP status codes that should be retried
1786
+ retryableStatusCodes: [
1787
+ 502,
1788
+ 503,
1789
+ 504,
1790
+ 408,
1791
+ 429
1792
+ ],
1793
+ // Network error patterns that should be retried
1794
+ retryableErrorMessages: [
1795
+ "fetch failed",
1796
+ "network error",
1797
+ "connection timeout",
1798
+ "ECONNREFUSED",
1799
+ "ETIMEDOUT",
1800
+ "ENOTFOUND",
1801
+ "ECONNRESET"
1802
+ ]
1803
+ };
1804
+ function isRetryableError(error, response) {
1805
+ var _a, _b;
1806
+ if (response && RETRY_CONFIG.retryableStatusCodes.includes(response.status)) {
1807
+ return true;
1808
+ }
1809
+ const errorCode = ((_a = error == null ? void 0 : error.cause) == null ? void 0 : _a.code) || (error == null ? void 0 : error.code);
1810
+ if (errorCode && RETRY_CONFIG.retryableErrorMessages.includes(errorCode)) {
1811
+ return true;
1812
+ }
1813
+ const errorMessage = ((_b = error == null ? void 0 : error.message) == null ? void 0 : _b.toLowerCase()) || "";
1814
+ return RETRY_CONFIG.retryableErrorMessages.some((msg) => errorMessage.includes(msg));
1815
+ }
1816
+ __name(isRetryableError, "isRetryableError");
1817
+ function sleep(ms) {
1818
+ return new Promise((resolve) => setTimeout(resolve, ms));
1819
+ }
1820
+ __name(sleep, "sleep");
1821
+ function calculateDelay(attempt) {
1822
+ const delay = RETRY_CONFIG.baseDelayMs * Math.pow(2, attempt);
1823
+ return Math.min(delay, RETRY_CONFIG.maxDelayMs);
1824
+ }
1825
+ __name(calculateDelay, "calculateDelay");
1826
+ async function fetchWithRetry(url, options, logger2) {
1827
+ let lastError;
1828
+ for (let attempt = 0; attempt <= RETRY_CONFIG.maxRetries; attempt++) {
1829
+ try {
1830
+ const response = await fetch(url, options);
1831
+ if (isRetryableError(null, response) && attempt < RETRY_CONFIG.maxRetries) {
1832
+ const delay = calculateDelay(attempt);
1833
+ 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.`);
1834
+ await sleep(delay);
1835
+ continue;
1836
+ }
1837
+ return response;
1838
+ } catch (error) {
1839
+ lastError = error;
1840
+ if (isRetryableError(error) && attempt < RETRY_CONFIG.maxRetries) {
1841
+ const delay = calculateDelay(attempt);
1842
+ 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)}`);
1843
+ await sleep(delay);
1844
+ continue;
1845
+ }
1846
+ break;
1847
+ }
1848
+ }
1849
+ throw lastError;
1850
+ }
1851
+ __name(fetchWithRetry, "fetchWithRetry");
1852
+
1853
+ // src/lib/runtime/remote-lg-action.ts
1776
1854
  var activeInterruptEvent = false;
1777
1855
  async function execute(args) {
1778
1856
  return new ReadableStream({
1779
1857
  async start(controller) {
1780
- try {
1781
- await streamEvents(controller, args);
1782
- controller.close();
1783
- } catch (err) {
1784
- const cause = err == null ? void 0 : err.cause;
1785
- const errorCode = (cause == null ? void 0 : cause.code) || (err == null ? void 0 : err.code);
1786
- if (errorCode === "ECONNREFUSED") {
1787
- throw new CopilotKitMisuseError({
1788
- message: `
1789
- The LangGraph client could not connect to the graph. Please further check previous logs, which includes further details.
1790
-
1791
- See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
1792
- });
1793
- } else {
1794
- throw new CopilotKitMisuseError({
1795
- message: `
1796
- The LangGraph client threw unhandled error ${err}.
1797
-
1798
- See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
1799
- });
1858
+ let lastError;
1859
+ for (let attempt = 0; attempt <= RETRY_CONFIG.maxRetries; attempt++) {
1860
+ try {
1861
+ await streamEvents(controller, args);
1862
+ controller.close();
1863
+ return;
1864
+ } catch (err) {
1865
+ lastError = err;
1866
+ if (isRetryableError(err) && attempt < RETRY_CONFIG.maxRetries) {
1867
+ const delay = calculateDelay(attempt);
1868
+ 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)}`);
1869
+ await sleep(delay);
1870
+ continue;
1871
+ }
1872
+ break;
1800
1873
  }
1801
1874
  }
1875
+ const cause = lastError == null ? void 0 : lastError.cause;
1876
+ const errorCode = (cause == null ? void 0 : cause.code) || (lastError == null ? void 0 : lastError.code);
1877
+ if (errorCode === "ECONNREFUSED") {
1878
+ throw new CopilotKitMisuseError({
1879
+ message: `
1880
+ The LangGraph client could not connect to the graph after ${RETRY_CONFIG.maxRetries + 1} attempts. Please further check previous logs, which includes further details.
1881
+
1882
+ See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
1883
+ });
1884
+ } else {
1885
+ throw new CopilotKitMisuseError({
1886
+ message: `
1887
+ The LangGraph client threw unhandled error ${lastError}.
1888
+
1889
+ See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
1890
+ });
1891
+ }
1802
1892
  }
1803
1893
  });
1804
1894
  }
@@ -2398,9 +2488,10 @@ function filterObjectBySchemaKeys(obj, schemaKeys) {
2398
2488
  __name(filterObjectBySchemaKeys, "filterObjectBySchemaKeys");
2399
2489
 
2400
2490
  // src/lib/runtime/remote-action-constructors.ts
2401
- import { CopilotKitError, CopilotKitLowLevelError } from "@copilotkit/shared";
2491
+ import { CopilotKitError as CopilotKitError3, CopilotKitLowLevelError as CopilotKitLowLevelError2 } from "@copilotkit/shared";
2402
2492
 
2403
2493
  // src/lib/streaming.ts
2494
+ import { CopilotKitLowLevelError, CopilotKitError as CopilotKitError2, CopilotKitErrorCode } from "@copilotkit/shared";
2404
2495
  async function writeJsonLineResponseToEventStream(response, eventStream$) {
2405
2496
  const reader = response.getReader();
2406
2497
  const decoder = new TextDecoder();
@@ -2439,12 +2530,40 @@ async function writeJsonLineResponseToEventStream(response, eventStream$) {
2439
2530
  }
2440
2531
  } catch (error) {
2441
2532
  console.error("Error in stream", error);
2442
- eventStream$.error(error);
2533
+ const structuredError = convertStreamingErrorToStructured(error);
2534
+ eventStream$.error(structuredError);
2443
2535
  return;
2444
2536
  }
2445
2537
  eventStream$.complete();
2446
2538
  }
2447
2539
  __name(writeJsonLineResponseToEventStream, "writeJsonLineResponseToEventStream");
2540
+ function convertStreamingErrorToStructured(error) {
2541
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2542
+ 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") {
2543
+ return new CopilotKitError2({
2544
+ 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.",
2545
+ code: CopilotKitErrorCode.NETWORK_ERROR
2546
+ });
2547
+ }
2548
+ 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"))) {
2549
+ return new CopilotKitLowLevelError({
2550
+ error: error instanceof Error ? error : new Error(String(error)),
2551
+ url: "streaming connection",
2552
+ message: "Network error occurred during streaming. Please check your connection and try again."
2553
+ });
2554
+ }
2555
+ 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"))) {
2556
+ return new CopilotKitError2({
2557
+ message: "Request was cancelled",
2558
+ code: CopilotKitErrorCode.UNKNOWN
2559
+ });
2560
+ }
2561
+ return new CopilotKitError2({
2562
+ message: `Streaming error: ${(error == null ? void 0 : error.message) || String(error)}`,
2563
+ code: CopilotKitErrorCode.UNKNOWN
2564
+ });
2565
+ }
2566
+ __name(convertStreamingErrorToStructured, "convertStreamingErrorToStructured");
2448
2567
 
2449
2568
  // src/lib/runtime/remote-action-constructors.ts
2450
2569
  import { CopilotKitApiDiscoveryError, ResolvedCopilotKitError } from "@copilotkit/shared";
@@ -2541,7 +2660,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
2541
2660
  });
2542
2661
  const fetchUrl = `${url}/actions/execute`;
2543
2662
  try {
2544
- const response = await fetch(fetchUrl, {
2663
+ const response = await fetchWithRetry(fetchUrl, {
2545
2664
  method: "POST",
2546
2665
  headers,
2547
2666
  body: JSON.stringify({
@@ -2549,7 +2668,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
2549
2668
  arguments: args,
2550
2669
  properties: graphqlContext.properties
2551
2670
  })
2552
- });
2671
+ }, logger2);
2553
2672
  if (!response.ok) {
2554
2673
  logger2.error({
2555
2674
  url,
@@ -2575,10 +2694,10 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
2575
2694
  }, "Executed remote action");
2576
2695
  return result;
2577
2696
  } catch (error) {
2578
- if (error instanceof CopilotKitError) {
2697
+ if (error instanceof CopilotKitError3) {
2579
2698
  throw error;
2580
2699
  }
2581
- throw new CopilotKitLowLevelError({
2700
+ throw new CopilotKitLowLevelError2({
2582
2701
  error,
2583
2702
  url: fetchUrl
2584
2703
  });
@@ -2612,7 +2731,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
2612
2731
  }
2613
2732
  const fetchUrl = `${url}/agents/execute`;
2614
2733
  try {
2615
- const response = await fetch(fetchUrl, {
2734
+ const response = await fetchWithRetry(fetchUrl, {
2616
2735
  method: "POST",
2617
2736
  headers,
2618
2737
  body: JSON.stringify({
@@ -2633,7 +2752,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
2633
2752
  })),
2634
2753
  metaEvents
2635
2754
  })
2636
- });
2755
+ }, logger2);
2637
2756
  if (!response.ok) {
2638
2757
  logger2.error({
2639
2758
  url,
@@ -2663,10 +2782,10 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
2663
2782
  throw new Error("Unsupported agent type");
2664
2783
  }
2665
2784
  } catch (error) {
2666
- if (error instanceof CopilotKitError) {
2785
+ if (error instanceof CopilotKitError3) {
2667
2786
  throw error;
2668
2787
  }
2669
- throw new CopilotKitLowLevelError({
2788
+ throw new CopilotKitLowLevelError2({
2670
2789
  error,
2671
2790
  url: fetchUrl
2672
2791
  });
@@ -2696,7 +2815,7 @@ function createHeaders(onBeforeRequest, graphqlContext) {
2696
2815
  __name(createHeaders, "createHeaders");
2697
2816
 
2698
2817
  // src/lib/runtime/remote-actions.ts
2699
- import { CopilotKitLowLevelError as CopilotKitLowLevelError2, ResolvedCopilotKitError as ResolvedCopilotKitError2, CopilotKitError as CopilotKitError2 } from "@copilotkit/shared";
2818
+ import { CopilotKitLowLevelError as CopilotKitLowLevelError3, ResolvedCopilotKitError as ResolvedCopilotKitError2, CopilotKitError as CopilotKitError4 } from "@copilotkit/shared";
2700
2819
 
2701
2820
  // src/lib/runtime/agui-action.ts
2702
2821
  import { parseJson as parseJson3 } from "@copilotkit/shared";
@@ -2843,10 +2962,10 @@ async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: l
2843
2962
  }, "Fetched actions from url");
2844
2963
  return json;
2845
2964
  } catch (error) {
2846
- if (error instanceof CopilotKitError2) {
2965
+ if (error instanceof CopilotKitError4) {
2847
2966
  throw error;
2848
2967
  }
2849
- throw new CopilotKitLowLevelError2({
2968
+ throw new CopilotKitLowLevelError3({
2850
2969
  error,
2851
2970
  url: fetchUrl
2852
2971
  });
@@ -2904,9 +3023,9 @@ async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, m
2904
3023
  }));
2905
3024
  for (const [key, agent] of Object.entries(agents)) {
2906
3025
  if (agent.agentId !== void 0 && agent.agentId !== key) {
2907
- throw new CopilotKitError2({
3026
+ throw new CopilotKitError4({
2908
3027
  message: `Agent ${key} has agentId ${agent.agentId} which does not match the key ${key}`,
2909
- code: CopilotKitErrorCode.UNKNOWN
3028
+ code: CopilotKitErrorCode2.UNKNOWN
2910
3029
  });
2911
3030
  } else if (agent.agentId === void 0) {
2912
3031
  agent.agentId = key;
@@ -2927,7 +3046,7 @@ __name(setupRemoteActions, "setupRemoteActions");
2927
3046
  import { createHash as createHash3 } from "crypto";
2928
3047
 
2929
3048
  // src/lib/runtime/copilot-runtime.ts
2930
- import { actionParametersToJsonSchema, ResolvedCopilotKitError as ResolvedCopilotKitError3, CopilotKitApiDiscoveryError as CopilotKitApiDiscoveryError2, randomId as randomId2, CopilotKitError as CopilotKitError3, CopilotKitLowLevelError as CopilotKitLowLevelError3, CopilotKitAgentDiscoveryError, CopilotKitMisuseError as CopilotKitMisuseError2 } from "@copilotkit/shared";
3049
+ import { actionParametersToJsonSchema, ResolvedCopilotKitError as ResolvedCopilotKitError3, CopilotKitApiDiscoveryError as CopilotKitApiDiscoveryError2, randomId as randomId2, CopilotKitError as CopilotKitError5, CopilotKitAgentDiscoveryError, CopilotKitMisuseError as CopilotKitMisuseError2, CopilotKitErrorCode as CopilotKitErrorCode3, CopilotKitLowLevelError as CopilotKitLowLevelError4 } from "@copilotkit/shared";
2931
3050
 
2932
3051
  // src/service-adapters/conversion.ts
2933
3052
  import { plainToInstance } from "class-transformer";
@@ -3366,12 +3485,12 @@ please use an LLM adapter instead.`
3366
3485
  console.error("Error logging LLM error:", logError);
3367
3486
  }
3368
3487
  }
3369
- if (error instanceof CopilotKitError3) {
3488
+ if (error instanceof CopilotKitError5) {
3370
3489
  throw error;
3371
3490
  }
3372
3491
  console.error("Error getting response:", error);
3373
- eventSource.sendErrorMessageToChat();
3374
- throw error;
3492
+ const structuredError = this.convertStreamingErrorToStructured(error);
3493
+ throw structuredError;
3375
3494
  }
3376
3495
  }
3377
3496
  async discoverAgentsFromEndpoints(graphqlContext) {
@@ -3419,7 +3538,7 @@ please use an LLM adapter instead.`
3419
3538
  const cpkEndpoint = endpoint;
3420
3539
  const fetchUrl = `${endpoint.url}/info`;
3421
3540
  try {
3422
- const response = await fetch(fetchUrl, {
3541
+ const response = await fetchWithRetry(fetchUrl, {
3423
3542
  method: "POST",
3424
3543
  headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
3425
3544
  body: JSON.stringify({
@@ -3450,10 +3569,10 @@ please use an LLM adapter instead.`
3450
3569
  ...endpointAgents
3451
3570
  ];
3452
3571
  } catch (error) {
3453
- if (error instanceof CopilotKitError3) {
3572
+ if (error instanceof CopilotKitError5) {
3454
3573
  throw error;
3455
3574
  }
3456
- throw new CopilotKitLowLevelError3({
3575
+ throw new CopilotKitLowLevelError4({
3457
3576
  error,
3458
3577
  url: fetchUrl
3459
3578
  });
@@ -3508,7 +3627,7 @@ please use an LLM adapter instead.`
3508
3627
  const cpkEndpoint = agentWithEndpoint.endpoint;
3509
3628
  const fetchUrl = `${cpkEndpoint.url}/agents/state`;
3510
3629
  try {
3511
- const response = await fetch(fetchUrl, {
3630
+ const response = await fetchWithRetry(fetchUrl, {
3512
3631
  method: "POST",
3513
3632
  headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
3514
3633
  body: JSON.stringify({
@@ -3536,10 +3655,10 @@ please use an LLM adapter instead.`
3536
3655
  messages: JSON.stringify(data.messages)
3537
3656
  };
3538
3657
  } catch (error) {
3539
- if (error instanceof CopilotKitError3) {
3658
+ if (error instanceof CopilotKitError5) {
3540
3659
  throw error;
3541
3660
  }
3542
- throw new CopilotKitLowLevelError3({
3661
+ throw new CopilotKitLowLevelError4({
3543
3662
  error,
3544
3663
  url: fetchUrl
3545
3664
  });
@@ -3671,7 +3790,8 @@ please use an LLM adapter instead.`
3671
3790
  console.error("Error logging agent error:", logError);
3672
3791
  }
3673
3792
  }
3674
- eventStream$.error(err);
3793
+ const structuredError = this.convertStreamingErrorToStructured(err);
3794
+ eventStream$.error(structuredError);
3675
3795
  eventStream$.complete();
3676
3796
  },
3677
3797
  complete: () => eventStream$.complete()
@@ -3833,6 +3953,32 @@ please use an LLM adapter instead.`
3833
3953
  return "langchain";
3834
3954
  return void 0;
3835
3955
  }
3956
+ convertStreamingErrorToStructured(error) {
3957
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
3958
+ 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") {
3959
+ return new CopilotKitError5({
3960
+ message: "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
3961
+ code: CopilotKitErrorCode3.NETWORK_ERROR
3962
+ });
3963
+ }
3964
+ 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"))) {
3965
+ return new CopilotKitLowLevelError4({
3966
+ error: error instanceof Error ? error : new Error(String(error)),
3967
+ url: "agent streaming connection",
3968
+ message: "Network error occurred during agent streaming. Please check your connection and try again."
3969
+ });
3970
+ }
3971
+ 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"))) {
3972
+ return new CopilotKitError5({
3973
+ message: "Agent request was cancelled",
3974
+ code: CopilotKitErrorCode3.UNKNOWN
3975
+ });
3976
+ }
3977
+ return new CopilotKitError5({
3978
+ message: `Agent streaming error: ${(error == null ? void 0 : error.message) || String(error)}`,
3979
+ code: CopilotKitErrorCode3.UNKNOWN
3980
+ });
3981
+ }
3836
3982
  };
3837
3983
  __name(CopilotRuntime, "CopilotRuntime");
3838
3984
  function flattenToolCallsNoDuplicates(toolsByPriority) {
@@ -4063,7 +4209,8 @@ var RuntimeEventSource = class {
4063
4209
  processRuntimeEvents({ serverSideActions, guardrailsResult$, actionInputsWithoutAgents, threadId }) {
4064
4210
  this.callback(this.eventStream$).catch((error) => {
4065
4211
  console.error("Error in event source callback", error);
4066
- this.sendErrorMessageToChat();
4212
+ const structuredError = convertStreamingErrorToStructured2(error);
4213
+ this.eventStream$.error(structuredError);
4067
4214
  this.eventStream$.complete();
4068
4215
  });
4069
4216
  return this.eventStream$.pipe(
@@ -4102,7 +4249,15 @@ var RuntimeEventSource = class {
4102
4249
  telemetry_client_default.capture("oss.runtime.server_action_executed", {});
4103
4250
  return concat(of(eventWithState.event), toolCallEventStream$).pipe(catchError2((error) => {
4104
4251
  console.error("Error in tool call stream", error);
4105
- this.sendErrorMessageToChat();
4252
+ const structuredError = convertStreamingErrorToStructured2(error);
4253
+ toolCallEventStream$.sendActionExecutionResult({
4254
+ actionExecutionId: eventWithState.actionExecutionId,
4255
+ actionName: eventWithState.action.name,
4256
+ error: {
4257
+ code: structuredError.code,
4258
+ message: structuredError.message
4259
+ }
4260
+ });
4106
4261
  return EMPTY;
4107
4262
  }));
4108
4263
  } else {
@@ -4175,12 +4330,13 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
4175
4330
  next: (event) => eventStream$.next(event),
4176
4331
  error: (err) => {
4177
4332
  console.error("Error in stream", err);
4333
+ const structuredError = convertStreamingErrorToStructured2(err);
4178
4334
  eventStream$.sendActionExecutionResult({
4179
4335
  actionExecutionId,
4180
4336
  actionName: action.name,
4181
4337
  error: {
4182
- code: "STREAM_ERROR",
4183
- message: err.message
4338
+ code: structuredError.code,
4339
+ message: structuredError.message
4184
4340
  }
4185
4341
  });
4186
4342
  eventStream$.complete();
@@ -4213,6 +4369,40 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
4213
4369
  }
4214
4370
  }
4215
4371
  __name(executeAction, "executeAction");
4372
+ function convertStreamingErrorToStructured2(error) {
4373
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
4374
+ 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") {
4375
+ return new CopilotKitError6({
4376
+ message: "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
4377
+ code: CopilotKitErrorCode4.NETWORK_ERROR
4378
+ });
4379
+ }
4380
+ 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"))) {
4381
+ return new CopilotKitLowLevelError5({
4382
+ error: error instanceof Error ? error : new Error(String(error)),
4383
+ url: "event streaming connection",
4384
+ message: "Network error occurred during event streaming. Please check your connection and try again."
4385
+ });
4386
+ }
4387
+ 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"))) {
4388
+ return new CopilotKitError6({
4389
+ message: "Request was cancelled",
4390
+ code: CopilotKitErrorCode4.UNKNOWN
4391
+ });
4392
+ }
4393
+ const errorMessage = (error == null ? void 0 : error.message) || String(error);
4394
+ if (errorMessage.includes("401") || errorMessage.toLowerCase().includes("api key") || errorMessage.toLowerCase().includes("unauthorized") || errorMessage.toLowerCase().includes("authentication") || errorMessage.toLowerCase().includes("incorrect api key")) {
4395
+ return new CopilotKitError6({
4396
+ message: `Event streaming error: ${errorMessage}`,
4397
+ code: CopilotKitErrorCode4.MISSING_PUBLIC_API_KEY_ERROR
4398
+ });
4399
+ }
4400
+ return new CopilotKitError6({
4401
+ message: `Event streaming error: ${errorMessage}`,
4402
+ code: CopilotKitErrorCode4.UNKNOWN
4403
+ });
4404
+ }
4405
+ __name(convertStreamingErrorToStructured2, "convertStreamingErrorToStructured");
4216
4406
 
4217
4407
  // src/graphql/resolvers/copilot.resolver.ts
4218
4408
  import { GraphQLJSONObject } from "graphql-scalars";
@@ -4274,6 +4464,7 @@ AgentsResponse = _ts_decorate16([
4274
4464
  ], AgentsResponse);
4275
4465
 
4276
4466
  // src/graphql/resolvers/copilot.resolver.ts
4467
+ import { CopilotKitError as CopilotKitError7 } from "@copilotkit/shared";
4277
4468
  function _ts_decorate17(decorators, target, key, desc) {
4278
4469
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4279
4470
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -4765,6 +4956,12 @@ var CopilotResolver = class {
4765
4956
  logger2.error({
4766
4957
  err
4767
4958
  }, "Error in event stream");
4959
+ if (err instanceof CopilotKitError7 || err instanceof Error && err.name && err.name.includes("CopilotKit")) {
4960
+ eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
4961
+ rejectOutputMessagesPromise(err);
4962
+ stopStreamingMessages(err);
4963
+ return;
4964
+ }
4768
4965
  responseStatus$.next(new UnknownErrorResponse({
4769
4966
  description: `An unknown error has occurred in the event stream`
4770
4967
  }));
@@ -4942,6 +5139,7 @@ LoadAgentStateInput = _ts_decorate19([
4942
5139
  ], LoadAgentStateInput);
4943
5140
 
4944
5141
  // src/graphql/resolvers/state.resolver.ts
5142
+ import { CopilotKitAgentDiscoveryError as CopilotKitAgentDiscoveryError2 } from "@copilotkit/shared";
4945
5143
  function _ts_decorate20(decorators, target, key, desc) {
4946
5144
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4947
5145
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -4969,12 +5167,13 @@ var StateResolver = class {
4969
5167
  const agents = await ctx._copilotkit.runtime.discoverAgentsFromEndpoints(ctx);
4970
5168
  const agent = agents.find((agent2) => agent2.name === data.agentName);
4971
5169
  if (!agent) {
4972
- return {
4973
- threadId: data.threadId || "",
4974
- threadExists: false,
4975
- state: JSON.stringify({}),
4976
- messages: JSON.stringify([])
4977
- };
5170
+ throw new CopilotKitAgentDiscoveryError2({
5171
+ agentName: data.agentName,
5172
+ availableAgents: agents.map((a) => ({
5173
+ name: a.name,
5174
+ id: a.name
5175
+ }))
5176
+ });
4978
5177
  }
4979
5178
  const state = await ctx._copilotkit.runtime.loadAgentState(ctx, data.threadId, data.agentName);
4980
5179
  return state;
@@ -5121,4 +5320,4 @@ export {
5121
5320
  getCommonConfig,
5122
5321
  copilotRuntimeNodeHttpEndpoint
5123
5322
  };
5124
- //# sourceMappingURL=chunk-GOPTDPPB.mjs.map
5323
+ //# sourceMappingURL=chunk-YMIOUUPV.mjs.map