@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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @copilotkit/runtime
2
2
 
3
+ ## 1.9.2-next.1
4
+
5
+ ### Patch Changes
6
+
7
+ - f295375: - fix: remove all agents as tools when there is an active agent session
8
+ - fix formatting
9
+ - @copilotkit/shared@1.9.2-next.1
10
+
11
+ ## 1.9.2-next.0
12
+
13
+ ### Patch Changes
14
+
15
+ - 10345a5: - feat: structured error visibility system for streaming errors
16
+ - Updated dependencies [10345a5]
17
+ - @copilotkit/shared@1.9.2-next.0
18
+
3
19
  ## 1.9.1
4
20
 
5
21
  ### Patch Changes
@@ -2,7 +2,7 @@ import {
2
2
  copilotRuntimeNodeHttpEndpoint,
3
3
  getRuntimeInstanceTelemetryInfo,
4
4
  telemetry_client_default
5
- } from "./chunk-GOPTDPPB.mjs";
5
+ } from "./chunk-XGBY45FP.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-C3SWOFLO.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-XGBY45FP.mjs";
6
6
  import {
7
7
  __name
8
8
  } from "./chunk-FHD4JECV.mjs";
@@ -22,4 +22,4 @@ __name(copilotRuntimeNodeExpressEndpoint, "copilotRuntimeNodeExpressEndpoint");
22
22
  export {
23
23
  copilotRuntimeNodeExpressEndpoint
24
24
  };
25
- //# sourceMappingURL=chunk-EVF3MXEK.mjs.map
25
+ //# sourceMappingURL=chunk-KPFOAXRX.mjs.map
@@ -2,7 +2,7 @@ import {
2
2
  getCommonConfig,
3
3
  getRuntimeInstanceTelemetryInfo,
4
4
  telemetry_client_default
5
- } from "./chunk-GOPTDPPB.mjs";
5
+ } from "./chunk-XGBY45FP.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-RIPQZJB5.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.1",
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";
@@ -3203,6 +3322,11 @@ var CopilotRuntime = class {
3203
3322
  const requestStartTime = Date.now();
3204
3323
  const streamedChunks = [];
3205
3324
  try {
3325
+ if (Object.keys(this.agents).length && (agentSession == null ? void 0 : agentSession.agentName) && !this.delegateAgentProcessingToServiceAdapter) {
3326
+ this.agents = {
3327
+ [agentSession.agentName]: this.agents[agentSession.agentName]
3328
+ };
3329
+ }
3206
3330
  if (agentSession && !this.delegateAgentProcessingToServiceAdapter) {
3207
3331
  return await this.processAgentRequest(request);
3208
3332
  }
@@ -3366,12 +3490,12 @@ please use an LLM adapter instead.`
3366
3490
  console.error("Error logging LLM error:", logError);
3367
3491
  }
3368
3492
  }
3369
- if (error instanceof CopilotKitError3) {
3493
+ if (error instanceof CopilotKitError5) {
3370
3494
  throw error;
3371
3495
  }
3372
3496
  console.error("Error getting response:", error);
3373
- eventSource.sendErrorMessageToChat();
3374
- throw error;
3497
+ const structuredError = this.convertStreamingErrorToStructured(error);
3498
+ throw structuredError;
3375
3499
  }
3376
3500
  }
3377
3501
  async discoverAgentsFromEndpoints(graphqlContext) {
@@ -3419,7 +3543,7 @@ please use an LLM adapter instead.`
3419
3543
  const cpkEndpoint = endpoint;
3420
3544
  const fetchUrl = `${endpoint.url}/info`;
3421
3545
  try {
3422
- const response = await fetch(fetchUrl, {
3546
+ const response = await fetchWithRetry(fetchUrl, {
3423
3547
  method: "POST",
3424
3548
  headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
3425
3549
  body: JSON.stringify({
@@ -3450,10 +3574,10 @@ please use an LLM adapter instead.`
3450
3574
  ...endpointAgents
3451
3575
  ];
3452
3576
  } catch (error) {
3453
- if (error instanceof CopilotKitError3) {
3577
+ if (error instanceof CopilotKitError5) {
3454
3578
  throw error;
3455
3579
  }
3456
- throw new CopilotKitLowLevelError3({
3580
+ throw new CopilotKitLowLevelError4({
3457
3581
  error,
3458
3582
  url: fetchUrl
3459
3583
  });
@@ -3508,7 +3632,7 @@ please use an LLM adapter instead.`
3508
3632
  const cpkEndpoint = agentWithEndpoint.endpoint;
3509
3633
  const fetchUrl = `${cpkEndpoint.url}/agents/state`;
3510
3634
  try {
3511
- const response = await fetch(fetchUrl, {
3635
+ const response = await fetchWithRetry(fetchUrl, {
3512
3636
  method: "POST",
3513
3637
  headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
3514
3638
  body: JSON.stringify({
@@ -3536,10 +3660,10 @@ please use an LLM adapter instead.`
3536
3660
  messages: JSON.stringify(data.messages)
3537
3661
  };
3538
3662
  } catch (error) {
3539
- if (error instanceof CopilotKitError3) {
3663
+ if (error instanceof CopilotKitError5) {
3540
3664
  throw error;
3541
3665
  }
3542
- throw new CopilotKitLowLevelError3({
3666
+ throw new CopilotKitLowLevelError4({
3543
3667
  error,
3544
3668
  url: fetchUrl
3545
3669
  });
@@ -3671,7 +3795,8 @@ please use an LLM adapter instead.`
3671
3795
  console.error("Error logging agent error:", logError);
3672
3796
  }
3673
3797
  }
3674
- eventStream$.error(err);
3798
+ const structuredError = this.convertStreamingErrorToStructured(err);
3799
+ eventStream$.error(structuredError);
3675
3800
  eventStream$.complete();
3676
3801
  },
3677
3802
  complete: () => eventStream$.complete()
@@ -3833,6 +3958,32 @@ please use an LLM adapter instead.`
3833
3958
  return "langchain";
3834
3959
  return void 0;
3835
3960
  }
3961
+ convertStreamingErrorToStructured(error) {
3962
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
3963
+ 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") {
3964
+ return new CopilotKitError5({
3965
+ message: "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
3966
+ code: CopilotKitErrorCode3.NETWORK_ERROR
3967
+ });
3968
+ }
3969
+ 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"))) {
3970
+ return new CopilotKitLowLevelError4({
3971
+ error: error instanceof Error ? error : new Error(String(error)),
3972
+ url: "agent streaming connection",
3973
+ message: "Network error occurred during agent streaming. Please check your connection and try again."
3974
+ });
3975
+ }
3976
+ 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"))) {
3977
+ return new CopilotKitError5({
3978
+ message: "Agent request was cancelled",
3979
+ code: CopilotKitErrorCode3.UNKNOWN
3980
+ });
3981
+ }
3982
+ return new CopilotKitError5({
3983
+ message: `Agent streaming error: ${(error == null ? void 0 : error.message) || String(error)}`,
3984
+ code: CopilotKitErrorCode3.UNKNOWN
3985
+ });
3986
+ }
3836
3987
  };
3837
3988
  __name(CopilotRuntime, "CopilotRuntime");
3838
3989
  function flattenToolCallsNoDuplicates(toolsByPriority) {
@@ -4063,7 +4214,8 @@ var RuntimeEventSource = class {
4063
4214
  processRuntimeEvents({ serverSideActions, guardrailsResult$, actionInputsWithoutAgents, threadId }) {
4064
4215
  this.callback(this.eventStream$).catch((error) => {
4065
4216
  console.error("Error in event source callback", error);
4066
- this.sendErrorMessageToChat();
4217
+ const structuredError = convertStreamingErrorToStructured2(error);
4218
+ this.eventStream$.error(structuredError);
4067
4219
  this.eventStream$.complete();
4068
4220
  });
4069
4221
  return this.eventStream$.pipe(
@@ -4102,7 +4254,15 @@ var RuntimeEventSource = class {
4102
4254
  telemetry_client_default.capture("oss.runtime.server_action_executed", {});
4103
4255
  return concat(of(eventWithState.event), toolCallEventStream$).pipe(catchError2((error) => {
4104
4256
  console.error("Error in tool call stream", error);
4105
- this.sendErrorMessageToChat();
4257
+ const structuredError = convertStreamingErrorToStructured2(error);
4258
+ toolCallEventStream$.sendActionExecutionResult({
4259
+ actionExecutionId: eventWithState.actionExecutionId,
4260
+ actionName: eventWithState.action.name,
4261
+ error: {
4262
+ code: structuredError.code,
4263
+ message: structuredError.message
4264
+ }
4265
+ });
4106
4266
  return EMPTY;
4107
4267
  }));
4108
4268
  } else {
@@ -4175,12 +4335,13 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
4175
4335
  next: (event) => eventStream$.next(event),
4176
4336
  error: (err) => {
4177
4337
  console.error("Error in stream", err);
4338
+ const structuredError = convertStreamingErrorToStructured2(err);
4178
4339
  eventStream$.sendActionExecutionResult({
4179
4340
  actionExecutionId,
4180
4341
  actionName: action.name,
4181
4342
  error: {
4182
- code: "STREAM_ERROR",
4183
- message: err.message
4343
+ code: structuredError.code,
4344
+ message: structuredError.message
4184
4345
  }
4185
4346
  });
4186
4347
  eventStream$.complete();
@@ -4213,6 +4374,40 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
4213
4374
  }
4214
4375
  }
4215
4376
  __name(executeAction, "executeAction");
4377
+ function convertStreamingErrorToStructured2(error) {
4378
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
4379
+ 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") {
4380
+ return new CopilotKitError6({
4381
+ message: "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
4382
+ code: CopilotKitErrorCode4.NETWORK_ERROR
4383
+ });
4384
+ }
4385
+ 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"))) {
4386
+ return new CopilotKitLowLevelError5({
4387
+ error: error instanceof Error ? error : new Error(String(error)),
4388
+ url: "event streaming connection",
4389
+ message: "Network error occurred during event streaming. Please check your connection and try again."
4390
+ });
4391
+ }
4392
+ 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"))) {
4393
+ return new CopilotKitError6({
4394
+ message: "Request was cancelled",
4395
+ code: CopilotKitErrorCode4.UNKNOWN
4396
+ });
4397
+ }
4398
+ const errorMessage = (error == null ? void 0 : error.message) || String(error);
4399
+ if (errorMessage.includes("401") || errorMessage.toLowerCase().includes("api key") || errorMessage.toLowerCase().includes("unauthorized") || errorMessage.toLowerCase().includes("authentication") || errorMessage.toLowerCase().includes("incorrect api key")) {
4400
+ return new CopilotKitError6({
4401
+ message: `Event streaming error: ${errorMessage}`,
4402
+ code: CopilotKitErrorCode4.MISSING_PUBLIC_API_KEY_ERROR
4403
+ });
4404
+ }
4405
+ return new CopilotKitError6({
4406
+ message: `Event streaming error: ${errorMessage}`,
4407
+ code: CopilotKitErrorCode4.UNKNOWN
4408
+ });
4409
+ }
4410
+ __name(convertStreamingErrorToStructured2, "convertStreamingErrorToStructured");
4216
4411
 
4217
4412
  // src/graphql/resolvers/copilot.resolver.ts
4218
4413
  import { GraphQLJSONObject } from "graphql-scalars";
@@ -4274,6 +4469,7 @@ AgentsResponse = _ts_decorate16([
4274
4469
  ], AgentsResponse);
4275
4470
 
4276
4471
  // src/graphql/resolvers/copilot.resolver.ts
4472
+ import { CopilotKitError as CopilotKitError7 } from "@copilotkit/shared";
4277
4473
  function _ts_decorate17(decorators, target, key, desc) {
4278
4474
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4279
4475
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -4765,6 +4961,12 @@ var CopilotResolver = class {
4765
4961
  logger2.error({
4766
4962
  err
4767
4963
  }, "Error in event stream");
4964
+ if (err instanceof CopilotKitError7 || err instanceof Error && err.name && err.name.includes("CopilotKit")) {
4965
+ eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
4966
+ rejectOutputMessagesPromise(err);
4967
+ stopStreamingMessages(err);
4968
+ return;
4969
+ }
4768
4970
  responseStatus$.next(new UnknownErrorResponse({
4769
4971
  description: `An unknown error has occurred in the event stream`
4770
4972
  }));
@@ -4942,6 +5144,7 @@ LoadAgentStateInput = _ts_decorate19([
4942
5144
  ], LoadAgentStateInput);
4943
5145
 
4944
5146
  // src/graphql/resolvers/state.resolver.ts
5147
+ import { CopilotKitAgentDiscoveryError as CopilotKitAgentDiscoveryError2 } from "@copilotkit/shared";
4945
5148
  function _ts_decorate20(decorators, target, key, desc) {
4946
5149
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4947
5150
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -4969,12 +5172,13 @@ var StateResolver = class {
4969
5172
  const agents = await ctx._copilotkit.runtime.discoverAgentsFromEndpoints(ctx);
4970
5173
  const agent = agents.find((agent2) => agent2.name === data.agentName);
4971
5174
  if (!agent) {
4972
- return {
4973
- threadId: data.threadId || "",
4974
- threadExists: false,
4975
- state: JSON.stringify({}),
4976
- messages: JSON.stringify([])
4977
- };
5175
+ throw new CopilotKitAgentDiscoveryError2({
5176
+ agentName: data.agentName,
5177
+ availableAgents: agents.map((a) => ({
5178
+ name: a.name,
5179
+ id: a.name
5180
+ }))
5181
+ });
4978
5182
  }
4979
5183
  const state = await ctx._copilotkit.runtime.loadAgentState(ctx, data.threadId, data.agentName);
4980
5184
  return state;
@@ -5121,4 +5325,4 @@ export {
5121
5325
  getCommonConfig,
5122
5326
  copilotRuntimeNodeHttpEndpoint
5123
5327
  };
5124
- //# sourceMappingURL=chunk-GOPTDPPB.mjs.map
5328
+ //# sourceMappingURL=chunk-XGBY45FP.mjs.map