@copilotkit/runtime 1.9.2-next.8 → 1.9.2

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 (86) hide show
  1. package/CHANGELOG.md +177 -0
  2. package/dist/{chunk-4TLMVLU4.mjs → chunk-56ZNYBXV.mjs} +2 -2
  3. package/dist/chunk-AMUJQ6IR.mjs +50 -0
  4. package/dist/chunk-AMUJQ6IR.mjs.map +1 -0
  5. package/dist/{chunk-5SG4WWXH.mjs → chunk-GB4M7WUE.mjs} +2 -2
  6. package/dist/{chunk-JWPSIGSA.mjs → chunk-HJYWUUFY.mjs} +2 -2
  7. package/dist/{chunk-KYCDL2KX.mjs → chunk-M35WOOEP.mjs} +2 -2
  8. package/dist/{chunk-IIXJVVTV.mjs → chunk-QLLV2QVK.mjs} +132 -78
  9. package/dist/chunk-QLLV2QVK.mjs.map +1 -0
  10. package/dist/{chunk-WIXS6EG7.mjs → chunk-TE5QWP4H.mjs} +2401 -2055
  11. package/dist/chunk-TE5QWP4H.mjs.map +1 -0
  12. package/dist/{chunk-5BIEM2UU.mjs → chunk-XWBDEXDA.mjs} +4 -3
  13. package/dist/{chunk-5BIEM2UU.mjs.map → chunk-XWBDEXDA.mjs.map} +1 -1
  14. package/dist/{groq-adapter-25a2bd35.d.ts → groq-adapter-742818f2.d.ts} +5 -1
  15. package/dist/index.d.ts +4 -3
  16. package/dist/index.js +3747 -3303
  17. package/dist/index.js.map +1 -1
  18. package/dist/index.mjs +12 -8
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/{langserve-4a5c9217.d.ts → langserve-3e8d0e06.d.ts} +13 -7
  21. package/dist/lib/index.d.ts +155 -5
  22. package/dist/lib/index.js +2808 -2407
  23. package/dist/lib/index.js.map +1 -1
  24. package/dist/lib/index.mjs +9 -8
  25. package/dist/lib/integrations/index.d.ts +3 -3
  26. package/dist/lib/integrations/index.js +151 -96
  27. package/dist/lib/integrations/index.js.map +1 -1
  28. package/dist/lib/integrations/index.mjs +7 -6
  29. package/dist/lib/integrations/nest/index.d.ts +2 -2
  30. package/dist/lib/integrations/nest/index.js +151 -96
  31. package/dist/lib/integrations/nest/index.js.map +1 -1
  32. package/dist/lib/integrations/nest/index.mjs +5 -4
  33. package/dist/lib/integrations/node-express/index.d.ts +2 -2
  34. package/dist/lib/integrations/node-express/index.js +151 -96
  35. package/dist/lib/integrations/node-express/index.js.map +1 -1
  36. package/dist/lib/integrations/node-express/index.mjs +5 -4
  37. package/dist/lib/integrations/node-http/index.d.ts +2 -2
  38. package/dist/lib/integrations/node-http/index.js +151 -96
  39. package/dist/lib/integrations/node-http/index.js.map +1 -1
  40. package/dist/lib/integrations/node-http/index.mjs +4 -3
  41. package/dist/service-adapters/index.d.ts +6 -4
  42. package/dist/service-adapters/index.js +202 -107
  43. package/dist/service-adapters/index.js.map +1 -1
  44. package/dist/service-adapters/index.mjs +6 -2
  45. package/dist/service-adapters/shared/index.d.ts +9 -0
  46. package/dist/service-adapters/shared/index.js +72 -0
  47. package/dist/service-adapters/shared/index.js.map +1 -0
  48. package/dist/service-adapters/shared/index.mjs +8 -0
  49. package/dist/service-adapters/shared/index.mjs.map +1 -0
  50. package/dist/{shared-941d59dc.d.ts → shared-96b46379.d.ts} +23 -21
  51. package/dist/utils/index.d.ts +17 -1
  52. package/dist/utils/index.js +3 -2
  53. package/dist/utils/index.js.map +1 -1
  54. package/dist/utils/index.mjs +1 -1
  55. package/package.json +11 -11
  56. package/src/agents/langgraph/event-source.ts +36 -38
  57. package/src/agents/langgraph/events.ts +19 -1
  58. package/src/graphql/resolvers/copilot.resolver.ts +85 -42
  59. package/src/lib/error-messages.ts +200 -0
  60. package/src/lib/integrations/shared.ts +43 -0
  61. package/src/lib/runtime/__tests__/{copilot-runtime-trace.test.ts → copilot-runtime-error.test.ts} +27 -27
  62. package/src/lib/runtime/__tests__/mcp-tools-utils.test.ts +464 -0
  63. package/src/lib/runtime/agui-action.ts +9 -3
  64. package/src/lib/runtime/copilot-runtime.ts +156 -160
  65. package/src/lib/runtime/mcp-tools-utils.ts +84 -18
  66. package/src/lib/runtime/remote-action-constructors.ts +28 -3
  67. package/src/lib/runtime/remote-actions.ts +6 -0
  68. package/src/lib/runtime/remote-lg-action.ts +85 -3
  69. package/src/lib/streaming.ts +125 -36
  70. package/src/service-adapters/anthropic/anthropic-adapter.ts +67 -8
  71. package/src/service-adapters/anthropic/utils.ts +3 -8
  72. package/src/service-adapters/events.ts +75 -80
  73. package/src/service-adapters/google/google-genai-adapter.ts +5 -0
  74. package/src/service-adapters/groq/groq-adapter.ts +66 -56
  75. package/src/service-adapters/index.ts +1 -0
  76. package/src/service-adapters/openai/openai-adapter.ts +4 -3
  77. package/src/service-adapters/shared/error-utils.ts +61 -0
  78. package/src/service-adapters/shared/index.ts +1 -0
  79. package/src/utils/failed-response-status-reasons.ts +23 -1
  80. package/tests/service-adapters/anthropic/anthropic-adapter.test.ts +172 -387
  81. package/dist/chunk-IIXJVVTV.mjs.map +0 -1
  82. package/dist/chunk-WIXS6EG7.mjs.map +0 -1
  83. /package/dist/{chunk-4TLMVLU4.mjs.map → chunk-56ZNYBXV.mjs.map} +0 -0
  84. /package/dist/{chunk-5SG4WWXH.mjs.map → chunk-GB4M7WUE.mjs.map} +0 -0
  85. /package/dist/{chunk-JWPSIGSA.mjs.map → chunk-HJYWUUFY.mjs.map} +0 -0
  86. /package/dist/{chunk-KYCDL2KX.mjs.map → chunk-M35WOOEP.mjs.map} +0 -0
@@ -1,22 +1,22 @@
1
+ import {
2
+ ActionExecutionMessage,
3
+ AgentStateMessage,
4
+ ImageMessage,
5
+ ResultMessage,
6
+ TextMessage
7
+ } from "./chunk-SHBDMA63.mjs";
1
8
  import {
2
9
  EmptyAdapter,
3
10
  RemoteChain,
4
11
  streamLangChainResponse
5
- } from "./chunk-IIXJVVTV.mjs";
12
+ } from "./chunk-QLLV2QVK.mjs";
6
13
  import {
7
14
  GuardrailsValidationFailureResponse,
8
15
  MessageStreamInterruptedResponse,
9
16
  ResponseStatusUnion,
10
17
  SuccessResponseStatus,
11
18
  UnknownErrorResponse
12
- } from "./chunk-5BIEM2UU.mjs";
13
- import {
14
- ActionExecutionMessage,
15
- AgentStateMessage,
16
- ImageMessage,
17
- ResultMessage,
18
- TextMessage
19
- } from "./chunk-SHBDMA63.mjs";
19
+ } from "./chunk-XWBDEXDA.mjs";
20
20
  import {
21
21
  BaseMessageInput
22
22
  } from "./chunk-2OZAGFV3.mjs";
@@ -40,7 +40,7 @@ var require_package = __commonJS({
40
40
  publishConfig: {
41
41
  access: "public"
42
42
  },
43
- version: "1.9.2-next.8",
43
+ version: "1.9.2",
44
44
  sideEffects: false,
45
45
  main: "./dist/index.js",
46
46
  module: "./dist/index.mjs",
@@ -78,11 +78,11 @@ var require_package = __commonJS({
78
78
  "zod-to-json-schema": "^3.23.5"
79
79
  },
80
80
  dependencies: {
81
- "@ag-ui/client": "0.0.28",
82
- "@ag-ui/core": "0.0.28",
83
- "@ag-ui/encoder": "0.0.28",
84
- "@ag-ui/langgraph": "0.0.4",
85
- "@ag-ui/proto": "0.0.28",
81
+ "@ag-ui/client": "0.0.34",
82
+ "@ag-ui/core": "0.0.34",
83
+ "@ag-ui/encoder": "0.0.34",
84
+ "@ag-ui/langgraph": "0.0.6",
85
+ "@ag-ui/proto": "0.0.34",
86
86
  "@anthropic-ai/sdk": "^0.27.3",
87
87
  "@copilotkit/shared": "workspace:*",
88
88
  "@graphql-yoga/plugin-defer-stream": "^3.3.1",
@@ -110,10 +110,10 @@ var require_package = __commonJS({
110
110
  zod: "^3.23.3"
111
111
  },
112
112
  peerDependencies: {
113
- "@ag-ui/client": ">=0.0.28",
114
- "@ag-ui/core": ">=0.0.28",
115
- "@ag-ui/encoder": ">=0.0.28",
116
- "@ag-ui/proto": ">=0.0.28"
113
+ "@ag-ui/client": ">=0.0.34",
114
+ "@ag-ui/core": ">=0.0.34",
115
+ "@ag-ui/encoder": ">=0.0.34",
116
+ "@ag-ui/proto": ">=0.0.34"
117
117
  },
118
118
  keywords: [
119
119
  "copilotkit",
@@ -1485,20 +1485,166 @@ GenerateCopilotResponseInput = _ts_decorate15([
1485
1485
  import { Repeater } from "graphql-yoga";
1486
1486
 
1487
1487
  // src/service-adapters/events.ts
1488
- import { randomId as randomId3, CopilotKitError as CopilotKitError6, CopilotKitErrorCode as CopilotKitErrorCode4, CopilotKitLowLevelError as CopilotKitLowLevelError5 } from "@copilotkit/shared";
1489
- import { of, concat, scan as scan2, concatMap, ReplaySubject as ReplaySubject2, firstValueFrom, from as from2, catchError as catchError2, EMPTY } from "rxjs";
1490
-
1491
- // src/lib/telemetry-client.ts
1492
- import { TelemetryClient } from "@copilotkit/shared";
1488
+ import { CopilotKitError as CopilotKitError6, CopilotKitErrorCode as CopilotKitErrorCode4, CopilotKitLowLevelError as CopilotKitLowLevelError7, ensureStructuredError as ensureStructuredError3, randomId as randomId2, Severity } from "@copilotkit/shared";
1489
+ import { plainToInstance as plainToInstance2 } from "class-transformer";
1490
+ import { catchError as catchError2, concat, concatMap, EMPTY, firstValueFrom, from as from2, of, ReplaySubject as ReplaySubject2, scan as scan2 } from "rxjs";
1493
1491
 
1494
1492
  // src/lib/runtime/remote-actions.ts
1495
- import { CopilotKitErrorCode as CopilotKitErrorCode2 } from "@copilotkit/shared";
1493
+ import { CopilotKitErrorCode as CopilotKitErrorCode3 } from "@copilotkit/shared";
1496
1494
 
1497
1495
  // src/lib/runtime/remote-action-constructors.ts
1496
+ import { createHash as createHash3 } from "crypto";
1497
+
1498
+ // src/lib/telemetry-client.ts
1499
+ import { TelemetryClient } from "@copilotkit/shared";
1498
1500
  import { createHash as createHash2 } from "crypto";
1499
1501
 
1500
- // src/agents/langgraph/event-source.ts
1501
- import { catchError, mergeMap, ReplaySubject, scan } from "rxjs";
1502
+ // src/lib/runtime/copilot-runtime.ts
1503
+ import { actionParametersToJsonSchema, ResolvedCopilotKitError, CopilotKitApiDiscoveryError, randomId, CopilotKitError as CopilotKitError3, CopilotKitAgentDiscoveryError, CopilotKitMisuseError as CopilotKitMisuseError2, CopilotKitErrorCode as CopilotKitErrorCode2, CopilotKitLowLevelError as CopilotKitLowLevelError3, ensureStructuredError as ensureStructuredError2 } from "@copilotkit/shared";
1504
+
1505
+ // src/service-adapters/conversion.ts
1506
+ import { plainToInstance } from "class-transformer";
1507
+ import { tryMap } from "@copilotkit/shared";
1508
+ function convertGqlInputToMessages(inputMessages) {
1509
+ const messages = tryMap(inputMessages, (message) => {
1510
+ if (message.textMessage) {
1511
+ return plainToInstance(TextMessage, {
1512
+ id: message.id,
1513
+ createdAt: message.createdAt,
1514
+ role: message.textMessage.role,
1515
+ content: message.textMessage.content,
1516
+ parentMessageId: message.textMessage.parentMessageId
1517
+ });
1518
+ } else if (message.imageMessage) {
1519
+ return plainToInstance(ImageMessage, {
1520
+ id: message.id,
1521
+ createdAt: message.createdAt,
1522
+ role: message.imageMessage.role,
1523
+ bytes: message.imageMessage.bytes,
1524
+ format: message.imageMessage.format,
1525
+ parentMessageId: message.imageMessage.parentMessageId
1526
+ });
1527
+ } else if (message.actionExecutionMessage) {
1528
+ return plainToInstance(ActionExecutionMessage, {
1529
+ id: message.id,
1530
+ createdAt: message.createdAt,
1531
+ name: message.actionExecutionMessage.name,
1532
+ arguments: JSON.parse(message.actionExecutionMessage.arguments),
1533
+ parentMessageId: message.actionExecutionMessage.parentMessageId
1534
+ });
1535
+ } else if (message.resultMessage) {
1536
+ return plainToInstance(ResultMessage, {
1537
+ id: message.id,
1538
+ createdAt: message.createdAt,
1539
+ actionExecutionId: message.resultMessage.actionExecutionId,
1540
+ actionName: message.resultMessage.actionName,
1541
+ result: message.resultMessage.result
1542
+ });
1543
+ } else if (message.agentStateMessage) {
1544
+ return plainToInstance(AgentStateMessage, {
1545
+ id: message.id,
1546
+ threadId: message.agentStateMessage.threadId,
1547
+ createdAt: message.createdAt,
1548
+ agentName: message.agentStateMessage.agentName,
1549
+ nodeName: message.agentStateMessage.nodeName,
1550
+ runId: message.agentStateMessage.runId,
1551
+ active: message.agentStateMessage.active,
1552
+ role: message.agentStateMessage.role,
1553
+ state: JSON.parse(message.agentStateMessage.state),
1554
+ running: message.agentStateMessage.running
1555
+ });
1556
+ } else {
1557
+ return null;
1558
+ }
1559
+ });
1560
+ return messages.filter((m) => m);
1561
+ }
1562
+ __name(convertGqlInputToMessages, "convertGqlInputToMessages");
1563
+
1564
+ // src/lib/runtime/copilot-runtime.ts
1565
+ import { from } from "rxjs";
1566
+
1567
+ // src/lib/runtime/retry-utils.ts
1568
+ var RETRY_CONFIG = {
1569
+ maxRetries: 3,
1570
+ baseDelayMs: 1e3,
1571
+ maxDelayMs: 5e3,
1572
+ // HTTP status codes that should be retried
1573
+ retryableStatusCodes: [
1574
+ 502,
1575
+ 503,
1576
+ 504,
1577
+ 408,
1578
+ 429
1579
+ ],
1580
+ // Network error patterns that should be retried
1581
+ retryableErrorMessages: [
1582
+ "fetch failed",
1583
+ "network error",
1584
+ "connection timeout",
1585
+ "ECONNREFUSED",
1586
+ "ETIMEDOUT",
1587
+ "ENOTFOUND",
1588
+ "ECONNRESET"
1589
+ ]
1590
+ };
1591
+ function isRetryableError(error, response) {
1592
+ var _a, _b;
1593
+ if (response && RETRY_CONFIG.retryableStatusCodes.includes(response.status)) {
1594
+ return true;
1595
+ }
1596
+ const errorCode = ((_a = error == null ? void 0 : error.cause) == null ? void 0 : _a.code) || (error == null ? void 0 : error.code);
1597
+ if (errorCode && RETRY_CONFIG.retryableErrorMessages.includes(errorCode)) {
1598
+ return true;
1599
+ }
1600
+ const errorMessage = ((_b = error == null ? void 0 : error.message) == null ? void 0 : _b.toLowerCase()) || "";
1601
+ return RETRY_CONFIG.retryableErrorMessages.some((msg) => errorMessage.includes(msg));
1602
+ }
1603
+ __name(isRetryableError, "isRetryableError");
1604
+ function sleep(ms) {
1605
+ return new Promise((resolve) => setTimeout(resolve, ms));
1606
+ }
1607
+ __name(sleep, "sleep");
1608
+ function calculateDelay(attempt) {
1609
+ const delay = RETRY_CONFIG.baseDelayMs * Math.pow(2, attempt);
1610
+ return Math.min(delay, RETRY_CONFIG.maxDelayMs);
1611
+ }
1612
+ __name(calculateDelay, "calculateDelay");
1613
+ async function fetchWithRetry(url, options, logger2) {
1614
+ let lastError;
1615
+ for (let attempt = 0; attempt <= RETRY_CONFIG.maxRetries; attempt++) {
1616
+ try {
1617
+ const response = await fetch(url, options);
1618
+ if (isRetryableError(null, response) && attempt < RETRY_CONFIG.maxRetries) {
1619
+ const delay = calculateDelay(attempt);
1620
+ 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.`);
1621
+ await sleep(delay);
1622
+ continue;
1623
+ }
1624
+ return response;
1625
+ } catch (error) {
1626
+ lastError = error;
1627
+ if (isRetryableError(error) && attempt < RETRY_CONFIG.maxRetries) {
1628
+ const delay = calculateDelay(attempt);
1629
+ 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)}`);
1630
+ await sleep(delay);
1631
+ continue;
1632
+ }
1633
+ break;
1634
+ }
1635
+ }
1636
+ throw lastError;
1637
+ }
1638
+ __name(fetchWithRetry, "fetchWithRetry");
1639
+
1640
+ // src/lib/runtime/copilot-runtime.ts
1641
+ import { Client as LangGraphClient2 } from "@langchain/langgraph-sdk";
1642
+
1643
+ // src/lib/runtime/remote-lg-action.ts
1644
+ import { Client as LangGraphClient } from "@langchain/langgraph-sdk";
1645
+ import { createHash } from "crypto";
1646
+ import { isValidUUID, randomUUID } from "@copilotkit/shared";
1647
+ import { parse as parsePartialJson } from "partial-json";
1502
1648
 
1503
1649
  // src/agents/langgraph/events.ts
1504
1650
  var LangGraphEventTypes;
@@ -1517,6 +1663,7 @@ var LangGraphEventTypes;
1517
1663
  LangGraphEventTypes2["OnCustomEvent"] = "on_custom_event";
1518
1664
  LangGraphEventTypes2["OnInterrupt"] = "on_interrupt";
1519
1665
  LangGraphEventTypes2["OnCopilotKitInterrupt"] = "on_copilotkit_interrupt";
1666
+ LangGraphEventTypes2["OnCopilotKitError"] = "on_copilotkit_error";
1520
1667
  })(LangGraphEventTypes || (LangGraphEventTypes = {}));
1521
1668
  var MetaEventNames;
1522
1669
  (function(MetaEventNames2) {
@@ -1531,326 +1678,274 @@ var CustomEventNames;
1531
1678
  CustomEventNames2["CopilotKitExit"] = "copilotkit_exit";
1532
1679
  })(CustomEventNames || (CustomEventNames = {}));
1533
1680
 
1534
- // src/agents/langgraph/event-source.ts
1535
- import { randomId, CopilotKitError } from "@copilotkit/shared";
1536
- var RemoteLangGraphEventSource = class {
1537
- eventStream$ = new ReplaySubject();
1538
- shouldEmitToolCall(shouldEmitToolCalls, toolCallName) {
1539
- if (typeof shouldEmitToolCalls === "boolean") {
1540
- return shouldEmitToolCalls;
1541
- }
1542
- if (Array.isArray(shouldEmitToolCalls)) {
1543
- return shouldEmitToolCalls.includes(toolCallName);
1681
+ // src/lib/runtime/remote-lg-action.ts
1682
+ import { parseJson, CopilotKitMisuseError, CopilotKitLowLevelError as CopilotKitLowLevelError2, CopilotKitError as CopilotKitError2 } from "@copilotkit/shared";
1683
+ import { RemoveMessage } from "@langchain/core/messages";
1684
+
1685
+ // src/lib/streaming.ts
1686
+ import { CopilotKitLowLevelError, CopilotKitError, CopilotKitErrorCode, ensureStructuredError } from "@copilotkit/shared";
1687
+
1688
+ // src/lib/error-messages.ts
1689
+ var errorConfig = {
1690
+ errorPatterns: {
1691
+ ECONNREFUSED: {
1692
+ message: "Connection refused - the agent service is not running or not accessible at the specified address. Please check that your agent is started and listening on the correct port.",
1693
+ category: "network",
1694
+ severity: "error",
1695
+ actionable: true
1696
+ },
1697
+ ENOTFOUND: {
1698
+ message: "Host not found - the agent service URL appears to be incorrect or the service is not accessible. Please verify the agent endpoint URL.",
1699
+ category: "network",
1700
+ severity: "error",
1701
+ actionable: true
1702
+ },
1703
+ ETIMEDOUT: {
1704
+ message: "Connection timeout - the agent service is taking too long to respond. This could indicate network issues or an overloaded agent service.",
1705
+ category: "network",
1706
+ severity: "warning",
1707
+ actionable: true
1708
+ },
1709
+ terminated: {
1710
+ message: "Agent {context} was unexpectedly terminated. This often indicates an error in the agent service (e.g., authentication failures, missing environment variables, or agent crashes). Check the agent logs for the root cause.",
1711
+ category: "connection",
1712
+ severity: "error",
1713
+ actionable: true
1714
+ },
1715
+ UND_ERR_SOCKET: {
1716
+ message: "Socket connection was closed unexpectedly. This typically indicates the agent service encountered an error and shut down the connection. Check the agent logs for the underlying cause.",
1717
+ category: "connection",
1718
+ severity: "error",
1719
+ actionable: true
1720
+ },
1721
+ other_side_closed: {
1722
+ message: "The agent service closed the connection unexpectedly. This usually indicates an error in the agent service. Check the agent logs for more details.",
1723
+ category: "connection",
1724
+ severity: "error",
1725
+ actionable: true
1726
+ },
1727
+ fetch_failed: {
1728
+ message: "Failed to connect to the agent service. Please verify the agent is running and the endpoint URL is correct.",
1729
+ category: "network",
1730
+ severity: "error",
1731
+ actionable: true
1732
+ },
1733
+ // Authentication patterns
1734
+ "401": {
1735
+ message: "Authentication failed. Please check your API keys and ensure they are correctly configured.",
1736
+ category: "authentication",
1737
+ severity: "error",
1738
+ actionable: true
1739
+ },
1740
+ "api key": {
1741
+ message: "API key error detected. Please verify your API key is correct and has the necessary permissions.",
1742
+ category: "authentication",
1743
+ severity: "error",
1744
+ actionable: true
1745
+ },
1746
+ unauthorized: {
1747
+ message: "Unauthorized access. Please check your authentication credentials.",
1748
+ category: "authentication",
1749
+ severity: "error",
1750
+ actionable: true
1751
+ },
1752
+ // Python-specific error patterns
1753
+ AuthenticationError: {
1754
+ message: "OpenAI authentication failed. Please check your OPENAI_API_KEY environment variable or API key configuration.",
1755
+ category: "authentication",
1756
+ severity: "error",
1757
+ actionable: true
1758
+ },
1759
+ "Incorrect API key provided": {
1760
+ message: "OpenAI API key is invalid. Please verify your OPENAI_API_KEY is correct and active.",
1761
+ category: "authentication",
1762
+ severity: "error",
1763
+ actionable: true
1764
+ },
1765
+ RateLimitError: {
1766
+ message: "OpenAI rate limit exceeded. Please wait a moment and try again, or check your OpenAI usage limits.",
1767
+ category: "network",
1768
+ severity: "warning",
1769
+ actionable: true
1770
+ },
1771
+ InvalidRequestError: {
1772
+ message: "Invalid request to OpenAI API. Please check your request parameters and model configuration.",
1773
+ category: "validation",
1774
+ severity: "error",
1775
+ actionable: true
1776
+ },
1777
+ PermissionDeniedError: {
1778
+ message: "Permission denied for OpenAI API. Please check your API key permissions and billing status.",
1779
+ category: "authentication",
1780
+ severity: "error",
1781
+ actionable: true
1782
+ },
1783
+ NotFoundError: {
1784
+ message: "OpenAI resource not found. Please check your model name and availability.",
1785
+ category: "validation",
1786
+ severity: "error",
1787
+ actionable: true
1544
1788
  }
1545
- return shouldEmitToolCalls === toolCallName;
1789
+ },
1790
+ fallbacks: {
1791
+ network: "A network error occurred while connecting to the agent service. Please check your connection and ensure the agent service is running.",
1792
+ connection: "The connection to the agent service was lost unexpectedly. This may indicate an issue with the agent service.",
1793
+ authentication: "Authentication failed. Please check your API keys and credentials.",
1794
+ validation: "Invalid input or configuration. Please check your parameters and try again.",
1795
+ unknown: "An unexpected error occurred. Please check the logs for more details.",
1796
+ default: "An unexpected error occurred. Please check the logs for more details."
1797
+ },
1798
+ contextTemplates: {
1799
+ connection: "connection",
1800
+ event_streaming_connection: "event streaming connection",
1801
+ agent_streaming_connection: "agent streaming connection",
1802
+ langgraph_agent_connection: "LangGraph agent connection"
1546
1803
  }
1547
- getCurrentContent(event) {
1548
- var _a, _b, _c, _d, _e;
1549
- const content = ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.content) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.content);
1550
- if (!content) {
1551
- const toolCallChunks = this.getCurrentToolCallChunks(event) ?? [];
1552
- for (const chunk of toolCallChunks) {
1553
- if (chunk.args) {
1554
- return chunk.args;
1555
- }
1556
- }
1804
+ };
1805
+ function getFallbackMessage(category) {
1806
+ return errorConfig.fallbacks[category] || errorConfig.fallbacks.default;
1807
+ }
1808
+ __name(getFallbackMessage, "getFallbackMessage");
1809
+
1810
+ // src/lib/streaming.ts
1811
+ async function writeJsonLineResponseToEventStream(response, eventStream$) {
1812
+ const reader = response.getReader();
1813
+ const decoder = new TextDecoder();
1814
+ let buffer = [];
1815
+ function flushBuffer() {
1816
+ const currentBuffer = buffer.join("");
1817
+ if (currentBuffer.trim().length === 0) {
1818
+ return;
1557
1819
  }
1558
- if (typeof content === "string") {
1559
- return content;
1560
- } else if (Array.isArray(content) && content.length > 0) {
1561
- return content[0].text;
1820
+ const parts = currentBuffer.split("\n");
1821
+ if (parts.length === 0) {
1822
+ return;
1562
1823
  }
1563
- return null;
1824
+ const lastPartIsComplete = currentBuffer.endsWith("\n");
1825
+ buffer = [];
1826
+ if (!lastPartIsComplete) {
1827
+ buffer.push(parts.pop());
1828
+ }
1829
+ parts.map((part) => part.trim()).filter((part) => part != "").forEach((part) => {
1830
+ eventStream$.next(JSON.parse(part));
1831
+ });
1564
1832
  }
1565
- getCurrentMessageId(event) {
1566
- var _a, _b, _c, _d, _e;
1567
- return ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.id) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.id);
1833
+ __name(flushBuffer, "flushBuffer");
1834
+ try {
1835
+ while (true) {
1836
+ const { done, value } = await reader.read();
1837
+ if (!done) {
1838
+ buffer.push(decoder.decode(value, {
1839
+ stream: true
1840
+ }));
1841
+ }
1842
+ flushBuffer();
1843
+ if (done) {
1844
+ break;
1845
+ }
1846
+ }
1847
+ } catch (error) {
1848
+ const structuredError = ensureStructuredError(error, convertStreamingErrorToStructured);
1849
+ eventStream$.error(structuredError);
1850
+ return;
1568
1851
  }
1569
- getCurrentToolCallChunks(event) {
1570
- var _a, _b, _c, _d, _e;
1571
- return ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.tool_call_chunks) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.tool_call_chunks);
1852
+ eventStream$.complete();
1853
+ }
1854
+ __name(writeJsonLineResponseToEventStream, "writeJsonLineResponseToEventStream");
1855
+ function convertStreamingErrorToStructured(error) {
1856
+ var _a, _b, _c, _d, _e, _f, _g;
1857
+ let helpfulMessage = generateHelpfulErrorMessage(error);
1858
+ if (((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.includes("fetch failed")) || ((_b = error == null ? void 0 : error.message) == null ? void 0 : _b.includes("ECONNREFUSED")) || ((_c = error == null ? void 0 : error.message) == null ? void 0 : _c.includes("ENOTFOUND")) || ((_d = error == null ? void 0 : error.message) == null ? void 0 : _d.includes("ETIMEDOUT")) || ((_e = error == null ? void 0 : error.message) == null ? void 0 : _e.includes("terminated")) || ((_f = error == null ? void 0 : error.cause) == null ? void 0 : _f.code) === "UND_ERR_SOCKET" || ((_g = error == null ? void 0 : error.message) == null ? void 0 : _g.includes("other side closed")) || (error == null ? void 0 : error.code) === "UND_ERR_SOCKET") {
1859
+ return new CopilotKitLowLevelError({
1860
+ error: error instanceof Error ? error : new Error(String(error)),
1861
+ url: "streaming connection",
1862
+ message: helpfulMessage
1863
+ });
1572
1864
  }
1573
- getResponseMetadata(event) {
1574
- var _a, _b, _c, _d, _e;
1575
- return ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.response_metadata) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.response_metadata);
1865
+ return new CopilotKitError({
1866
+ message: helpfulMessage,
1867
+ code: CopilotKitErrorCode.UNKNOWN
1868
+ });
1869
+ }
1870
+ __name(convertStreamingErrorToStructured, "convertStreamingErrorToStructured");
1871
+ function generateHelpfulErrorMessage(error, context = "connection") {
1872
+ var _a, _b, _c, _d;
1873
+ const baseMessage = (error == null ? void 0 : error.message) || String(error);
1874
+ const originalErrorType = (error == null ? void 0 : error.originalErrorType) || ((_a = error == null ? void 0 : error.extensions) == null ? void 0 : _a.originalErrorType);
1875
+ const statusCode = (error == null ? void 0 : error.statusCode) || ((_b = error == null ? void 0 : error.extensions) == null ? void 0 : _b.statusCode);
1876
+ const responseData = (error == null ? void 0 : error.responseData) || ((_c = error == null ? void 0 : error.extensions) == null ? void 0 : _c.responseData);
1877
+ if (originalErrorType) {
1878
+ const typeConfig = errorConfig.errorPatterns[originalErrorType];
1879
+ if (typeConfig) {
1880
+ return typeConfig.message.replace("{context}", context);
1881
+ }
1576
1882
  }
1577
- processLangGraphEvents() {
1578
- let lastEventWithState = null;
1579
- return this.eventStream$.pipe(scan((acc, event) => {
1580
- if (event.event === LangGraphEventTypes.OnChatModelStream) {
1581
- const prevMessageId = acc.lastMessageId;
1582
- acc.currentContent = this.getCurrentContent(event);
1583
- acc.lastMessageId = this.getCurrentMessageId(event) ?? acc.lastMessageId;
1584
- const toolCallChunks = this.getCurrentToolCallChunks(event) ?? [];
1585
- const responseMetadata = this.getResponseMetadata(event);
1586
- const toolCallCheck = toolCallChunks && toolCallChunks.length > 0;
1587
- let isToolCallEnd = (responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "tool_calls";
1588
- acc.isToolCallStart = toolCallChunks.some((chunk) => chunk.name && chunk.id);
1589
- acc.isMessageStart = prevMessageId !== acc.lastMessageId && !acc.isToolCallStart;
1590
- let previousRoundHadToolCall = acc.isToolCall;
1591
- acc.isToolCall = toolCallCheck;
1592
- if (previousRoundHadToolCall && !toolCallCheck) {
1593
- isToolCallEnd = true;
1594
- }
1595
- acc.isToolCallEnd = isToolCallEnd;
1596
- acc.isMessageEnd = (responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "stop";
1597
- ({ name: acc.lastToolCallName, id: acc.lastToolCallId } = toolCallChunks.find((chunk) => chunk.name && chunk.id) ?? {
1598
- name: acc.lastToolCallName,
1599
- id: acc.lastToolCallId
1600
- });
1601
- }
1602
- acc.event = event;
1603
- lastEventWithState = acc;
1604
- return acc;
1605
- }, {
1606
- event: null,
1607
- isMessageStart: false,
1608
- isMessageEnd: false,
1609
- isToolCallStart: false,
1610
- isToolCallEnd: false,
1611
- isToolCall: false,
1612
- lastMessageId: null,
1613
- lastToolCallId: null,
1614
- lastToolCallName: null,
1615
- currentContent: null,
1616
- processedToolCallIds: /* @__PURE__ */ new Set()
1617
- }), mergeMap((acc) => {
1618
- const events = [];
1619
- let shouldEmitMessages = true;
1620
- let shouldEmitToolCalls = true;
1621
- if (acc.event.event == LangGraphEventTypes.OnChatModelStream) {
1622
- if ("copilotkit:emit-tool-calls" in (acc.event.metadata || {})) {
1623
- shouldEmitToolCalls = acc.event.metadata["copilotkit:emit-tool-calls"];
1624
- }
1625
- if ("copilotkit:emit-messages" in (acc.event.metadata || {})) {
1626
- shouldEmitMessages = acc.event.metadata["copilotkit:emit-messages"];
1627
- }
1628
- }
1629
- if (acc.event.event === LangGraphEventTypes.OnInterrupt) {
1630
- events.push({
1631
- type: RuntimeEventTypes.MetaEvent,
1632
- name: RuntimeMetaEventName.LangGraphInterruptEvent,
1633
- value: acc.event.value
1634
- });
1635
- }
1636
- if (acc.event.event === LangGraphEventTypes.OnCopilotKitInterrupt) {
1637
- events.push({
1638
- type: RuntimeEventTypes.MetaEvent,
1639
- name: RuntimeMetaEventName.CopilotKitLangGraphInterruptEvent,
1640
- data: acc.event.data
1641
- });
1642
- }
1643
- const responseMetadata = this.getResponseMetadata(acc.event);
1644
- if (acc.isToolCallEnd && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName) && acc.lastToolCallId && !acc.processedToolCallIds.has(acc.lastToolCallId)) {
1645
- acc.processedToolCallIds.add(acc.lastToolCallId);
1646
- events.push({
1647
- type: RuntimeEventTypes.ActionExecutionEnd,
1648
- actionExecutionId: acc.lastToolCallId
1649
- });
1650
- } else if ((responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "stop" && shouldEmitMessages) {
1651
- events.push({
1652
- type: RuntimeEventTypes.TextMessageEnd,
1653
- messageId: acc.lastMessageId
1654
- });
1655
- }
1656
- switch (acc.event.event) {
1657
- case LangGraphEventTypes.OnCustomEvent:
1658
- if (acc.event.name === CustomEventNames.CopilotKitManuallyEmitMessage) {
1659
- events.push({
1660
- type: RuntimeEventTypes.TextMessageStart,
1661
- messageId: acc.event.data.message_id
1662
- });
1663
- events.push({
1664
- type: RuntimeEventTypes.TextMessageContent,
1665
- messageId: acc.event.data.message_id,
1666
- content: acc.event.data.message
1667
- });
1668
- events.push({
1669
- type: RuntimeEventTypes.TextMessageEnd,
1670
- messageId: acc.event.data.message_id
1671
- });
1672
- } else if (acc.event.name === CustomEventNames.CopilotKitManuallyEmitToolCall) {
1673
- events.push({
1674
- type: RuntimeEventTypes.ActionExecutionStart,
1675
- actionExecutionId: acc.event.data.id,
1676
- actionName: acc.event.data.name,
1677
- parentMessageId: acc.event.data.id
1678
- });
1679
- events.push({
1680
- type: RuntimeEventTypes.ActionExecutionArgs,
1681
- actionExecutionId: acc.event.data.id,
1682
- args: JSON.stringify(acc.event.data.args)
1683
- });
1684
- events.push({
1685
- type: RuntimeEventTypes.ActionExecutionEnd,
1686
- actionExecutionId: acc.event.data.id
1687
- });
1688
- }
1689
- break;
1690
- case LangGraphEventTypes.OnCopilotKitStateSync:
1691
- events.push({
1692
- type: RuntimeEventTypes.AgentStateMessage,
1693
- threadId: acc.event.thread_id,
1694
- role: acc.event.role,
1695
- agentName: acc.event.agent_name,
1696
- nodeName: acc.event.node_name,
1697
- runId: acc.event.run_id,
1698
- active: acc.event.active,
1699
- state: JSON.stringify(acc.event.state),
1700
- running: acc.event.running
1701
- });
1702
- break;
1703
- case LangGraphEventTypes.OnChatModelStream:
1704
- if (acc.isToolCallStart && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName)) {
1705
- events.push({
1706
- type: RuntimeEventTypes.ActionExecutionStart,
1707
- actionExecutionId: acc.lastToolCallId,
1708
- actionName: acc.lastToolCallName,
1709
- parentMessageId: acc.lastMessageId
1710
- });
1711
- } else if (acc.isMessageStart && shouldEmitMessages) {
1712
- acc.processedToolCallIds.clear();
1713
- events.push({
1714
- type: RuntimeEventTypes.TextMessageStart,
1715
- messageId: acc.lastMessageId
1716
- });
1717
- }
1718
- if (acc.isToolCall && acc.currentContent && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName)) {
1719
- events.push({
1720
- type: RuntimeEventTypes.ActionExecutionArgs,
1721
- actionExecutionId: acc.lastToolCallId,
1722
- args: acc.currentContent
1723
- });
1724
- } else if (!acc.isToolCall && acc.currentContent && shouldEmitMessages) {
1725
- events.push({
1726
- type: RuntimeEventTypes.TextMessageContent,
1727
- messageId: acc.lastMessageId,
1728
- content: acc.currentContent
1729
- });
1730
- }
1731
- break;
1732
- }
1733
- return events;
1734
- }), catchError((error) => {
1735
- console.error(error);
1736
- if (error instanceof CopilotKitError || (error == null ? void 0 : error.name) && error.name.includes("CopilotKit")) {
1737
- throw error;
1738
- }
1739
- const events = [];
1740
- if ((lastEventWithState == null ? void 0 : lastEventWithState.lastMessageId) && !lastEventWithState.isToolCall) {
1741
- events.push({
1742
- type: RuntimeEventTypes.TextMessageEnd,
1743
- messageId: lastEventWithState.lastMessageId
1744
- });
1745
- }
1746
- if (lastEventWithState == null ? void 0 : lastEventWithState.lastToolCallId) {
1747
- events.push({
1748
- type: RuntimeEventTypes.ActionExecutionEnd,
1749
- actionExecutionId: lastEventWithState.lastToolCallId
1750
- });
1751
- }
1752
- const messageId = randomId();
1753
- events.push({
1754
- type: RuntimeEventTypes.TextMessageStart,
1755
- messageId
1756
- });
1757
- events.push({
1758
- type: RuntimeEventTypes.TextMessageContent,
1759
- messageId,
1760
- content: "\u274C An error occurred. Please try again."
1761
- });
1762
- events.push({
1763
- type: RuntimeEventTypes.TextMessageEnd,
1764
- messageId
1765
- });
1766
- return events;
1767
- }));
1883
+ for (const [pattern, config] of Object.entries(errorConfig.errorPatterns)) {
1884
+ const shouldMatch = (baseMessage == null ? void 0 : baseMessage.includes(pattern)) || ((_d = error == null ? void 0 : error.cause) == null ? void 0 : _d.code) === pattern || (error == null ? void 0 : error.code) === pattern || statusCode === parseInt(pattern) || pattern === "other_side_closed" && (baseMessage == null ? void 0 : baseMessage.includes("other side closed")) || pattern === "fetch_failed" && (baseMessage == null ? void 0 : baseMessage.includes("fetch failed")) || responseData && JSON.stringify(responseData).includes(pattern);
1885
+ if (shouldMatch) {
1886
+ return config.message.replace("{context}", context);
1887
+ }
1768
1888
  }
1769
- };
1770
- __name(RemoteLangGraphEventSource, "RemoteLangGraphEventSource");
1771
-
1772
- // src/lib/runtime/remote-lg-action.ts
1773
- import { Client as LangGraphClient } from "@langchain/langgraph-sdk";
1774
- import { createHash } from "crypto";
1775
- import { isValidUUID, randomUUID } from "@copilotkit/shared";
1776
- import { parse as parsePartialJson } from "partial-json";
1777
- import { parseJson, CopilotKitMisuseError } from "@copilotkit/shared";
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;
1889
+ if (isNetworkError(error)) {
1890
+ return getFallbackMessage("network");
1808
1891
  }
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;
1892
+ if (isConnectionError(error)) {
1893
+ return getFallbackMessage("connection");
1812
1894
  }
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));
1895
+ if (isAuthenticationError(error)) {
1896
+ return getFallbackMessage("authentication");
1897
+ }
1898
+ return getFallbackMessage("default");
1815
1899
  }
1816
- __name(isRetryableError, "isRetryableError");
1817
- function sleep(ms) {
1818
- return new Promise((resolve) => setTimeout(resolve, ms));
1900
+ __name(generateHelpfulErrorMessage, "generateHelpfulErrorMessage");
1901
+ function isNetworkError(error) {
1902
+ const networkPatterns = [
1903
+ "ECONNREFUSED",
1904
+ "ENOTFOUND",
1905
+ "ETIMEDOUT",
1906
+ "fetch_failed"
1907
+ ];
1908
+ return networkPatterns.some((pattern) => {
1909
+ var _a, _b;
1910
+ return ((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.includes(pattern)) || ((_b = error == null ? void 0 : error.cause) == null ? void 0 : _b.code) === pattern || (error == null ? void 0 : error.code) === pattern;
1911
+ });
1819
1912
  }
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);
1913
+ __name(isNetworkError, "isNetworkError");
1914
+ function isConnectionError(error) {
1915
+ const connectionPatterns = [
1916
+ "terminated",
1917
+ "UND_ERR_SOCKET",
1918
+ "other side closed"
1919
+ ];
1920
+ return connectionPatterns.some((pattern) => {
1921
+ var _a, _b;
1922
+ return ((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.includes(pattern)) || ((_b = error == null ? void 0 : error.cause) == null ? void 0 : _b.code) === pattern || (error == null ? void 0 : error.code) === pattern;
1923
+ });
1824
1924
  }
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;
1925
+ __name(isConnectionError, "isConnectionError");
1926
+ function isAuthenticationError(error) {
1927
+ var _a, _b;
1928
+ const authPatterns = [
1929
+ "401",
1930
+ "api key",
1931
+ "unauthorized",
1932
+ "authentication",
1933
+ "AuthenticationError",
1934
+ "PermissionDeniedError"
1935
+ ];
1936
+ const baseMessage = (error == null ? void 0 : error.message) || String(error);
1937
+ const originalErrorType = (error == null ? void 0 : error.originalErrorType) || ((_a = error == null ? void 0 : error.extensions) == null ? void 0 : _a.originalErrorType);
1938
+ const statusCode = (error == null ? void 0 : error.statusCode) || ((_b = error == null ? void 0 : error.extensions) == null ? void 0 : _b.statusCode);
1939
+ return authPatterns.some((pattern) => (baseMessage == null ? void 0 : baseMessage.toLowerCase().includes(pattern.toLowerCase())) || originalErrorType === pattern || statusCode === 401 || (error == null ? void 0 : error.status) === 401 || (error == null ? void 0 : error.statusCode) === 401);
1850
1940
  }
1851
- __name(fetchWithRetry, "fetchWithRetry");
1941
+ __name(isAuthenticationError, "isAuthenticationError");
1852
1942
 
1853
1943
  // src/lib/runtime/remote-lg-action.ts
1944
+ function isUserConfigurationError(error) {
1945
+ var _a, _b;
1946
+ return (error instanceof CopilotKitError2 || error instanceof CopilotKitLowLevelError2) && (error.code === "NETWORK_ERROR" || error.code === "AUTHENTICATION_ERROR" || error.statusCode === 401 || error.statusCode === 403 || ((_a = error.message) == null ? void 0 : _a.toLowerCase().includes("authentication")) || ((_b = error.message) == null ? void 0 : _b.toLowerCase().includes("api key")));
1947
+ }
1948
+ __name(isUserConfigurationError, "isUserConfigurationError");
1854
1949
  async function execute(args) {
1855
1950
  return new ReadableStream({
1856
1951
  async start(controller) {
@@ -1881,6 +1976,9 @@ async function execute(args) {
1881
1976
  See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
1882
1977
  });
1883
1978
  } else {
1979
+ if (lastError instanceof CopilotKitError2 || lastError instanceof CopilotKitLowLevelError2 || lastError instanceof Error && lastError.name && lastError.name.includes("CopilotKit")) {
1980
+ throw lastError;
1981
+ }
1884
1982
  throw new CopilotKitMisuseError({
1885
1983
  message: `
1886
1984
  The LangGraph client threw unhandled error ${lastError}.
@@ -2050,7 +2148,30 @@ async function streamEvents(controller, args) {
2050
2148
  ].includes(streamResponseChunk.event))
2051
2149
  continue;
2052
2150
  if (streamResponseChunk.event === "error") {
2053
- throw new Error(`Error event thrown: ${streamResponseChunk.data.message}`);
2151
+ const errorData = streamResponseChunk.data;
2152
+ if (errorData && typeof errorData === "object" && "error_details" in errorData) {
2153
+ const errorDetails = errorData.error_details;
2154
+ const preservedError = new CopilotKitLowLevelError2({
2155
+ error: new Error(errorDetails.message),
2156
+ url: "langgraph platform agent",
2157
+ message: `${errorDetails.type}: ${errorDetails.message}`
2158
+ });
2159
+ if (errorDetails.status_code) {
2160
+ preservedError.statusCode = errorDetails.status_code;
2161
+ }
2162
+ if (errorDetails.response_data) {
2163
+ preservedError.responseData = errorDetails.response_data;
2164
+ }
2165
+ preservedError.agentName = errorDetails.agent_name;
2166
+ preservedError.originalErrorType = errorDetails.type;
2167
+ throw preservedError;
2168
+ }
2169
+ const helpfulMessage = generateHelpfulErrorMessage(new Error(errorData.message), "LangGraph Platform agent");
2170
+ throw new CopilotKitLowLevelError2({
2171
+ error: new Error(errorData.message),
2172
+ url: "langgraph platform agent",
2173
+ message: helpfulMessage
2174
+ });
2054
2175
  }
2055
2176
  const chunk = streamResponseChunk;
2056
2177
  const interruptEvents = chunk.data.__interrupt__;
@@ -2160,11 +2281,21 @@ async function streamEvents(controller, args) {
2160
2281
  }));
2161
2282
  return Promise.resolve();
2162
2283
  } catch (e) {
2163
- logger2.error(e);
2284
+ if (isUserConfigurationError(e)) {
2285
+ logger2.debug({
2286
+ error: e.message,
2287
+ code: e.code
2288
+ }, "User configuration error");
2289
+ } else {
2290
+ logger2.error(e);
2291
+ }
2164
2292
  telemetry_client_default.capture("oss.runtime.agent_execution_stream_errored", {
2165
2293
  ...streamInfo,
2166
2294
  error: e.message
2167
2295
  });
2296
+ if (e instanceof CopilotKitError2 || e instanceof CopilotKitLowLevelError2 || e instanceof Error && e.name && e.name.includes("CopilotKit")) {
2297
+ throw e;
2298
+ }
2168
2299
  return Promise.resolve();
2169
2300
  }
2170
2301
  }
@@ -2496,857 +2627,721 @@ function emitInterrupt(interruptValue, emit) {
2496
2627
  }
2497
2628
  __name(emitInterrupt, "emitInterrupt");
2498
2629
 
2499
- // src/lib/runtime/remote-action-constructors.ts
2500
- import { CopilotKitError as CopilotKitError3, CopilotKitLowLevelError as CopilotKitLowLevelError2 } from "@copilotkit/shared";
2501
-
2502
- // src/lib/streaming.ts
2503
- import { CopilotKitLowLevelError, CopilotKitError as CopilotKitError2, CopilotKitErrorCode } from "@copilotkit/shared";
2504
- async function writeJsonLineResponseToEventStream(response, eventStream$) {
2505
- const reader = response.getReader();
2506
- const decoder = new TextDecoder();
2507
- let buffer = [];
2508
- function flushBuffer() {
2509
- const currentBuffer = buffer.join("");
2510
- if (currentBuffer.trim().length === 0) {
2511
- return;
2512
- }
2513
- const parts = currentBuffer.split("\n");
2514
- if (parts.length === 0) {
2515
- return;
2516
- }
2517
- const lastPartIsComplete = currentBuffer.endsWith("\n");
2518
- buffer = [];
2519
- if (!lastPartIsComplete) {
2520
- buffer.push(parts.pop());
2521
- }
2522
- parts.map((part) => part.trim()).filter((part) => part != "").forEach((part) => {
2523
- eventStream$.next(JSON.parse(part));
2524
- });
2630
+ // src/lib/runtime/mcp-tools-utils.ts
2631
+ function extractParametersFromSchema(toolOrSchema) {
2632
+ var _a;
2633
+ const parameters = [];
2634
+ const schema = "schema" in (toolOrSchema || {}) ? toolOrSchema.schema : toolOrSchema;
2635
+ const toolParameters = ((_a = schema == null ? void 0 : schema.parameters) == null ? void 0 : _a.jsonSchema) || (schema == null ? void 0 : schema.parameters);
2636
+ const properties = toolParameters == null ? void 0 : toolParameters.properties;
2637
+ const requiredParams = new Set((toolParameters == null ? void 0 : toolParameters.required) || []);
2638
+ if (!properties) {
2639
+ return parameters;
2525
2640
  }
2526
- __name(flushBuffer, "flushBuffer");
2527
- try {
2528
- while (true) {
2529
- const { done, value } = await reader.read();
2530
- if (!done) {
2531
- buffer.push(decoder.decode(value, {
2532
- stream: true
2533
- }));
2641
+ for (const paramName in properties) {
2642
+ if (Object.prototype.hasOwnProperty.call(properties, paramName)) {
2643
+ const paramDef = properties[paramName];
2644
+ let type = paramDef.type || "string";
2645
+ let description = paramDef.description || "";
2646
+ if (type === "array" && paramDef.items) {
2647
+ const itemType = paramDef.items.type || "object";
2648
+ if (itemType === "object" && paramDef.items.properties) {
2649
+ const itemProperties = Object.keys(paramDef.items.properties).join(", ");
2650
+ description = description + (description ? " " : "") + `Array of objects with properties: ${itemProperties}`;
2651
+ } else {
2652
+ type = `array<${itemType}>`;
2653
+ }
2534
2654
  }
2535
- flushBuffer();
2536
- if (done) {
2537
- break;
2655
+ if (paramDef.enum && Array.isArray(paramDef.enum)) {
2656
+ const enumValues = paramDef.enum.join(" | ");
2657
+ description = description + (description ? " " : "") + `Allowed values: ${enumValues}`;
2658
+ }
2659
+ if (type === "object" && paramDef.properties) {
2660
+ const objectProperties = Object.keys(paramDef.properties).join(", ");
2661
+ description = description + (description ? " " : "") + `Object with properties: ${objectProperties}`;
2538
2662
  }
2663
+ parameters.push({
2664
+ name: paramName,
2665
+ type,
2666
+ description,
2667
+ required: requiredParams.has(paramName)
2668
+ });
2539
2669
  }
2540
- } catch (error) {
2541
- console.error("Error in stream", error);
2542
- const structuredError = convertStreamingErrorToStructured(error);
2543
- eventStream$.error(structuredError);
2544
- return;
2545
2670
  }
2546
- eventStream$.complete();
2671
+ return parameters;
2547
2672
  }
2548
- __name(writeJsonLineResponseToEventStream, "writeJsonLineResponseToEventStream");
2549
- function convertStreamingErrorToStructured(error) {
2550
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2551
- 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") {
2552
- return new CopilotKitError2({
2553
- 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.",
2554
- code: CopilotKitErrorCode.NETWORK_ERROR
2555
- });
2556
- }
2557
- 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"))) {
2558
- return new CopilotKitLowLevelError({
2559
- error: error instanceof Error ? error : new Error(String(error)),
2560
- url: "streaming connection",
2561
- message: "Network error occurred during streaming. Please check your connection and try again."
2562
- });
2563
- }
2564
- 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"))) {
2565
- return new CopilotKitError2({
2566
- message: "Request was cancelled",
2567
- code: CopilotKitErrorCode.UNKNOWN
2673
+ __name(extractParametersFromSchema, "extractParametersFromSchema");
2674
+ function convertMCPToolsToActions(mcpTools, mcpEndpoint) {
2675
+ const actions = [];
2676
+ for (const [toolName, tool] of Object.entries(mcpTools)) {
2677
+ const parameters = extractParametersFromSchema(tool);
2678
+ const handler = /* @__PURE__ */ __name(async (params) => {
2679
+ try {
2680
+ const result = await tool.execute(params);
2681
+ return typeof result === "string" ? result : JSON.stringify(result);
2682
+ } catch (error) {
2683
+ console.error(`Error executing MCP tool '${toolName}' from endpoint ${mcpEndpoint}:`, error);
2684
+ throw new Error(`Execution failed for MCP tool '${toolName}': ${error instanceof Error ? error.message : String(error)}`);
2685
+ }
2686
+ }, "handler");
2687
+ actions.push({
2688
+ name: toolName,
2689
+ description: tool.description || `MCP tool: ${toolName} (from ${mcpEndpoint})`,
2690
+ parameters,
2691
+ handler,
2692
+ // Add metadata for easier identification/debugging
2693
+ _isMCPTool: true,
2694
+ _mcpEndpoint: mcpEndpoint
2568
2695
  });
2569
2696
  }
2570
- return new CopilotKitError2({
2571
- message: `Streaming error: ${(error == null ? void 0 : error.message) || String(error)}`,
2572
- code: CopilotKitErrorCode.UNKNOWN
2573
- });
2697
+ return actions;
2574
2698
  }
2575
- __name(convertStreamingErrorToStructured, "convertStreamingErrorToStructured");
2576
-
2577
- // src/lib/runtime/remote-action-constructors.ts
2578
- import { CopilotKitApiDiscoveryError, ResolvedCopilotKitError } from "@copilotkit/shared";
2579
- import { parseJson as parseJson2, tryMap } from "@copilotkit/shared";
2580
- function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, messages, agentStates }) {
2581
- const agents = endpoint.agents.map((agent) => ({
2582
- name: agent.name,
2583
- description: agent.description,
2584
- parameters: [],
2585
- handler: async (_args) => {
2586
- },
2587
- remoteAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName, additionalMessages = [], metaEvents }) => {
2588
- logger2.debug({
2589
- actionName: agent.name
2590
- }, "Executing LangGraph Platform agent");
2591
- telemetry_client_default.capture("oss.runtime.remote_action_executed", {
2592
- agentExecution: true,
2593
- type: "langgraph-platform",
2594
- agentsAmount: endpoint.agents.length,
2595
- hashedLgcKey: endpoint.langsmithApiKey ? createHash2("sha256").update(endpoint.langsmithApiKey).digest("hex") : null
2596
- });
2597
- let state = {};
2598
- let config = {};
2599
- if (agentStates) {
2600
- const jsonState = agentStates.find((state2) => state2.agentName === name);
2601
- if (jsonState) {
2602
- state = parseJson2(jsonState.state, {});
2603
- config = parseJson2(jsonState.config, {});
2699
+ __name(convertMCPToolsToActions, "convertMCPToolsToActions");
2700
+ function generateMcpToolInstructions(toolsMap) {
2701
+ if (!toolsMap || Object.keys(toolsMap).length === 0) {
2702
+ return "";
2703
+ }
2704
+ const toolEntries = Object.entries(toolsMap);
2705
+ const toolsDoc = toolEntries.map(([name, tool]) => {
2706
+ var _a;
2707
+ let paramsDoc = " No parameters required";
2708
+ try {
2709
+ if (tool.schema && typeof tool.schema === "object") {
2710
+ const schema = tool.schema;
2711
+ const toolParameters = ((_a = schema.parameters) == null ? void 0 : _a.jsonSchema) || schema.parameters;
2712
+ const properties = (toolParameters == null ? void 0 : toolParameters.properties) || schema.properties;
2713
+ const requiredParams = (toolParameters == null ? void 0 : toolParameters.required) || schema.required || [];
2714
+ if (properties) {
2715
+ const paramsList = Object.entries(properties).map(([paramName, propSchema]) => {
2716
+ const propDetails = propSchema;
2717
+ const requiredMark = requiredParams.includes(paramName) ? "*" : "";
2718
+ let typeInfo = propDetails.type || "any";
2719
+ let description = propDetails.description ? ` - ${propDetails.description}` : "";
2720
+ if (typeInfo === "array" && propDetails.items) {
2721
+ const itemType = propDetails.items.type || "object";
2722
+ if (itemType === "object" && propDetails.items.properties) {
2723
+ const itemProps = Object.keys(propDetails.items.properties).join(", ");
2724
+ typeInfo = `array<object>`;
2725
+ description = description + (description ? " " : " - ") + `Array of objects with properties: ${itemProps}`;
2726
+ } else {
2727
+ typeInfo = `array<${itemType}>`;
2728
+ }
2729
+ }
2730
+ if (propDetails.enum && Array.isArray(propDetails.enum)) {
2731
+ const enumValues = propDetails.enum.join(" | ");
2732
+ description = description + (description ? " " : " - ") + `Allowed values: ${enumValues}`;
2733
+ }
2734
+ if (typeInfo === "object" && propDetails.properties) {
2735
+ const objectProps = Object.keys(propDetails.properties).join(", ");
2736
+ description = description + (description ? " " : " - ") + `Object with properties: ${objectProps}`;
2737
+ }
2738
+ return ` - ${paramName}${requiredMark} (${typeInfo})${description}`;
2739
+ });
2740
+ if (paramsList.length > 0) {
2741
+ paramsDoc = paramsList.join("\n");
2742
+ }
2604
2743
  }
2605
2744
  }
2606
- try {
2607
- const response = await execute({
2608
- logger: logger2.child({
2609
- component: "remote-actions.remote-lg-action.streamEvents"
2610
- }),
2611
- deploymentUrl: endpoint.deploymentUrl,
2612
- langsmithApiKey: endpoint.langsmithApiKey,
2613
- agent,
2614
- threadId,
2615
- nodeName,
2616
- messages: [
2617
- ...messages,
2618
- ...additionalMessages
2619
- ],
2620
- state,
2621
- config,
2622
- properties: graphqlContext.properties,
2623
- actions: tryMap(actionInputsWithoutAgents, (action) => ({
2624
- name: action.name,
2625
- description: action.description,
2626
- parameters: JSON.parse(action.jsonSchema)
2627
- })),
2628
- metaEvents
2629
- });
2630
- const eventSource = new RemoteLangGraphEventSource();
2631
- writeJsonLineResponseToEventStream(response, eventSource.eventStream$);
2632
- return eventSource.processLangGraphEvents();
2633
- } catch (error) {
2634
- logger2.error({
2635
- url: endpoint.deploymentUrl,
2636
- status: 500,
2637
- body: error.message
2638
- }, "Failed to execute LangGraph Platform agent");
2639
- throw new Error("Failed to execute LangGraph Platform agent");
2640
- }
2745
+ } catch (e) {
2746
+ console.error(`Error parsing schema for tool ${name}:`, e);
2641
2747
  }
2642
- }));
2643
- return [
2644
- ...agents
2645
- ];
2748
+ return `- ${name}: ${tool.description || ""}
2749
+ ${paramsDoc}`;
2750
+ }).join("\n\n");
2751
+ return `You have access to the following external tools provided by Model Context Protocol (MCP) servers:
2752
+
2753
+ ${toolsDoc}
2754
+
2755
+ When using these tools:
2756
+ 1. Only provide valid parameters according to their type requirements
2757
+ 2. Required parameters are marked with *
2758
+ 3. For array parameters, provide data in the correct array format
2759
+ 4. For object parameters, include all required nested properties
2760
+ 5. For enum parameters, use only the allowed values listed
2761
+ 6. Format API calls correctly with the expected parameter structure
2762
+ 7. Always check tool responses to determine your next action`;
2646
2763
  }
2647
- __name(constructLGCRemoteAction, "constructLGCRemoteAction");
2648
- var RemoteAgentType;
2649
- (function(RemoteAgentType2) {
2650
- RemoteAgentType2["LangGraph"] = "langgraph";
2651
- RemoteAgentType2["CrewAI"] = "crewai";
2652
- })(RemoteAgentType || (RemoteAgentType = {}));
2653
- function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, logger: logger2, messages, agentStates }) {
2654
- const totalAgents = Array.isArray(json["agents"]) ? json["agents"].length : 0;
2655
- const actions = json["actions"].map((action) => ({
2656
- name: action.name,
2657
- description: action.description,
2658
- parameters: action.parameters,
2659
- handler: async (args) => {
2660
- logger2.debug({
2661
- actionName: action.name,
2662
- args
2663
- }, "Executing remote action");
2664
- const headers = createHeaders(onBeforeRequest, graphqlContext);
2665
- telemetry_client_default.capture("oss.runtime.remote_action_executed", {
2666
- agentExecution: false,
2667
- type: "self-hosted",
2668
- agentsAmount: totalAgents
2669
- });
2670
- const fetchUrl = `${url}/actions/execute`;
2671
- try {
2672
- const response = await fetchWithRetry(fetchUrl, {
2673
- method: "POST",
2674
- headers,
2675
- body: JSON.stringify({
2676
- name: action.name,
2677
- arguments: args,
2678
- properties: graphqlContext.properties
2679
- })
2680
- }, logger2);
2681
- if (!response.ok) {
2682
- logger2.error({
2683
- url,
2684
- status: response.status,
2685
- body: await response.text()
2686
- }, "Failed to execute remote action");
2687
- if (response.status === 404) {
2688
- throw new CopilotKitApiDiscoveryError({
2689
- url: fetchUrl
2690
- });
2691
- }
2692
- throw new ResolvedCopilotKitError({
2693
- status: response.status,
2694
- url: fetchUrl,
2695
- isRemoteEndpoint: true
2696
- });
2697
- }
2698
- const requestResult = await response.json();
2699
- const result = requestResult["result"];
2700
- logger2.debug({
2701
- actionName: action.name,
2702
- result
2703
- }, "Executed remote action");
2704
- return result;
2705
- } catch (error) {
2706
- if (error instanceof CopilotKitError3) {
2707
- throw error;
2708
- }
2709
- throw new CopilotKitLowLevelError2({
2710
- error,
2711
- url: fetchUrl
2712
- });
2713
- }
2764
+ __name(generateMcpToolInstructions, "generateMcpToolInstructions");
2765
+
2766
+ // src/lib/runtime/copilot-runtime.ts
2767
+ var CopilotRuntime = class {
2768
+ actions;
2769
+ agents;
2770
+ remoteEndpointDefinitions;
2771
+ langserve = [];
2772
+ onBeforeRequest;
2773
+ onAfterRequest;
2774
+ delegateAgentProcessingToServiceAdapter;
2775
+ observability;
2776
+ availableAgents;
2777
+ onError;
2778
+ hasWarnedAboutError = false;
2779
+ // +++ MCP Properties +++
2780
+ mcpServersConfig;
2781
+ mcpActionCache = /* @__PURE__ */ new Map();
2782
+ // --- MCP Properties ---
2783
+ // +++ MCP Client Factory +++
2784
+ createMCPClientImpl;
2785
+ // --- MCP Client Factory ---
2786
+ constructor(params) {
2787
+ var _a, _b, _c, _d;
2788
+ if ((params == null ? void 0 : params.actions) && (params == null ? void 0 : params.remoteEndpoints) && (params == null ? void 0 : params.remoteEndpoints.some((e) => e.type === EndpointType.LangGraphPlatform))) {
2789
+ console.warn("Actions set in runtime instance will not be available for the agent");
2790
+ console.warn(`LangGraph Platform remote endpoints are deprecated in favor of the "agents" property`);
2714
2791
  }
2715
- }));
2716
- const agents = totalAgents ? json["agents"].map((agent) => ({
2717
- name: agent.name,
2718
- description: agent.description,
2719
- parameters: [],
2720
- handler: async (_args) => {
2721
- },
2722
- remoteAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName, additionalMessages = [], metaEvents }) => {
2723
- logger2.debug({
2724
- actionName: agent.name
2725
- }, "Executing remote agent");
2726
- const headers = createHeaders(onBeforeRequest, graphqlContext);
2727
- telemetry_client_default.capture("oss.runtime.remote_action_executed", {
2728
- agentExecution: true,
2729
- type: "self-hosted",
2730
- agentsAmount: json["agents"].length
2792
+ this.actions = (params == null ? void 0 : params.actions) || [];
2793
+ this.availableAgents = [];
2794
+ for (const chain of (params == null ? void 0 : params.langserve) || []) {
2795
+ const remoteChain = new RemoteChain(chain);
2796
+ this.langserve.push(remoteChain.toAction());
2797
+ }
2798
+ this.remoteEndpointDefinitions = (params == null ? void 0 : params.remoteEndpoints) ?? (params == null ? void 0 : params.remoteActions) ?? [];
2799
+ this.onBeforeRequest = (_a = params == null ? void 0 : params.middleware) == null ? void 0 : _a.onBeforeRequest;
2800
+ this.onAfterRequest = (_b = params == null ? void 0 : params.middleware) == null ? void 0 : _b.onAfterRequest;
2801
+ this.delegateAgentProcessingToServiceAdapter = (params == null ? void 0 : params.delegateAgentProcessingToServiceAdapter) || false;
2802
+ this.observability = params == null ? void 0 : params.observability_c;
2803
+ this.agents = (params == null ? void 0 : params.agents) ?? {};
2804
+ this.onError = params == null ? void 0 : params.onError;
2805
+ this.mcpServersConfig = params == null ? void 0 : params.mcpServers;
2806
+ this.createMCPClientImpl = params == null ? void 0 : params.createMCPClient;
2807
+ if (this.mcpServersConfig && this.mcpServersConfig.length > 0 && !this.createMCPClientImpl) {
2808
+ throw new CopilotKitMisuseError2({
2809
+ message: "MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`."
2731
2810
  });
2732
- let state = {};
2733
- let config = {};
2734
- if (agentStates) {
2735
- const jsonState = agentStates.find((state2) => state2.agentName === name);
2736
- if (jsonState) {
2737
- state = parseJson2(jsonState.state, {});
2738
- config = parseJson2(jsonState.config, {});
2739
- }
2740
- }
2741
- const fetchUrl = `${url}/agents/execute`;
2742
- try {
2743
- const response = await fetchWithRetry(fetchUrl, {
2744
- method: "POST",
2745
- headers,
2746
- body: JSON.stringify({
2747
- name,
2748
- threadId,
2749
- nodeName,
2750
- messages: [
2751
- ...messages,
2752
- ...additionalMessages
2753
- ],
2754
- state,
2755
- config,
2756
- properties: graphqlContext.properties,
2757
- actions: tryMap(actionInputsWithoutAgents, (action) => ({
2758
- name: action.name,
2759
- description: action.description,
2760
- parameters: JSON.parse(action.jsonSchema)
2761
- })),
2762
- metaEvents
2763
- })
2764
- }, logger2);
2765
- if (!response.ok) {
2766
- logger2.error({
2767
- url,
2768
- status: response.status,
2769
- body: await response.text()
2770
- }, "Failed to execute remote agent");
2771
- if (response.status === 404) {
2772
- throw new CopilotKitApiDiscoveryError({
2773
- url: fetchUrl
2774
- });
2811
+ }
2812
+ if ((params == null ? void 0 : params.actions) && (((_c = params == null ? void 0 : params.remoteEndpoints) == null ? void 0 : _c.some((e) => e.type === EndpointType.LangGraphPlatform)) || ((_d = this.mcpServersConfig) == null ? void 0 : _d.length))) {
2813
+ console.warn("Local 'actions' defined in CopilotRuntime might not be available to remote agents (LangGraph, MCP). Consider defining actions closer to the agent implementation if needed.");
2814
+ }
2815
+ }
2816
+ // +++ MCP Instruction Injection Method +++
2817
+ injectMCPToolInstructions(messages, currentActions) {
2818
+ const mcpActionsForRequest = currentActions.filter((action) => action._isMCPTool);
2819
+ if (!mcpActionsForRequest || mcpActionsForRequest.length === 0) {
2820
+ return messages;
2821
+ }
2822
+ const uniqueMcpTools = /* @__PURE__ */ new Map();
2823
+ mcpActionsForRequest.forEach((action) => {
2824
+ uniqueMcpTools.set(action.name, action);
2825
+ });
2826
+ const toolsMap = {};
2827
+ Array.from(uniqueMcpTools.values()).forEach((action) => {
2828
+ toolsMap[action.name] = {
2829
+ description: action.description || "",
2830
+ schema: action.parameters ? {
2831
+ parameters: {
2832
+ properties: action.parameters.reduce((acc, p) => ({
2833
+ ...acc,
2834
+ [p.name]: {
2835
+ type: p.type,
2836
+ description: p.description
2837
+ }
2838
+ }), {}),
2839
+ required: action.parameters.filter((p) => p.required).map((p) => p.name)
2775
2840
  }
2776
- throw new ResolvedCopilotKitError({
2777
- status: response.status,
2778
- url: fetchUrl,
2779
- isRemoteEndpoint: true
2780
- });
2781
- }
2782
- if (agent.type === "langgraph") {
2783
- const eventSource = new RemoteLangGraphEventSource();
2784
- writeJsonLineResponseToEventStream(response.body, eventSource.eventStream$);
2785
- return eventSource.processLangGraphEvents();
2786
- } else if (agent.type === "crewai") {
2787
- const eventStream$ = new RuntimeEventSubject();
2788
- writeJsonLineResponseToEventStream(response.body, eventStream$);
2789
- return eventStream$;
2790
- } else {
2791
- throw new Error("Unsupported agent type");
2792
- }
2793
- } catch (error) {
2794
- if (error instanceof CopilotKitError3) {
2795
- throw error;
2796
- }
2797
- throw new CopilotKitLowLevelError2({
2798
- error,
2799
- url: fetchUrl
2800
- });
2801
- }
2841
+ } : {},
2842
+ execute: async () => ({})
2843
+ };
2844
+ });
2845
+ const mcpToolInstructions = generateMcpToolInstructions(toolsMap);
2846
+ if (!mcpToolInstructions) {
2847
+ return messages;
2802
2848
  }
2803
- })) : [];
2804
- return [
2805
- ...actions,
2806
- ...agents
2807
- ];
2808
- }
2809
- __name(constructRemoteActions, "constructRemoteActions");
2810
- function createHeaders(onBeforeRequest, graphqlContext) {
2811
- const headers = {
2812
- "Content-Type": "application/json"
2813
- };
2814
- if (onBeforeRequest) {
2815
- const { headers: additionalHeaders } = onBeforeRequest({
2816
- ctx: graphqlContext
2849
+ const instructions = mcpToolInstructions + "\nUse them when appropriate to fulfill the user's request.";
2850
+ const systemMessageIndex = messages.findIndex((msg) => {
2851
+ var _a;
2852
+ return ((_a = msg.textMessage) == null ? void 0 : _a.role) === "system";
2817
2853
  });
2818
- if (additionalHeaders) {
2819
- Object.assign(headers, additionalHeaders);
2854
+ const newMessages = [
2855
+ ...messages
2856
+ ];
2857
+ if (systemMessageIndex !== -1) {
2858
+ const existingMsg = newMessages[systemMessageIndex];
2859
+ if (existingMsg.textMessage) {
2860
+ existingMsg.textMessage.content = (existingMsg.textMessage.content ? existingMsg.textMessage.content + "\n\n" : "") + instructions;
2861
+ }
2862
+ } else {
2863
+ newMessages.unshift({
2864
+ id: randomId(),
2865
+ createdAt: /* @__PURE__ */ new Date(),
2866
+ textMessage: {
2867
+ role: MessageRole.system,
2868
+ content: instructions
2869
+ },
2870
+ actionExecutionMessage: void 0,
2871
+ resultMessage: void 0,
2872
+ agentStateMessage: void 0
2873
+ });
2820
2874
  }
2875
+ return newMessages;
2821
2876
  }
2822
- return headers;
2823
- }
2824
- __name(createHeaders, "createHeaders");
2825
-
2826
- // src/lib/runtime/remote-actions.ts
2827
- import { CopilotKitLowLevelError as CopilotKitLowLevelError3, ResolvedCopilotKitError as ResolvedCopilotKitError2, CopilotKitError as CopilotKitError4 } from "@copilotkit/shared";
2828
-
2829
- // src/lib/runtime/agui-action.ts
2830
- import { parseJson as parseJson3 } from "@copilotkit/shared";
2831
- function constructAGUIRemoteAction({ logger: logger2, messages, agentStates, agent, metaEvents }) {
2832
- const action = {
2833
- name: agent.agentId,
2834
- description: agent.description,
2835
- parameters: [],
2836
- handler: async (_args) => {
2837
- },
2838
- remoteAgentHandler: async ({ actionInputsWithoutAgents, threadId }) => {
2839
- var _a;
2840
- logger2.debug({
2841
- actionName: agent.agentId
2842
- }, "Executing remote agent");
2843
- const agentWireMessages = convertMessagesToAGUIMessage(messages);
2844
- agent.messages = agentWireMessages;
2845
- agent.threadId = threadId;
2846
- telemetry_client_default.capture("oss.runtime.remote_action_executed", {
2847
- agentExecution: true,
2848
- type: "self-hosted",
2849
- agentsAmount: 1
2850
- });
2851
- let state = {};
2852
- if (agentStates) {
2853
- const jsonState = agentStates.find((state2) => state2.agentName === agent.agentId);
2854
- if (jsonState) {
2855
- state = parseJson3(jsonState.state, {});
2877
+ async processRuntimeRequest(request) {
2878
+ var _a, _b, _c, _d, _e;
2879
+ const { serviceAdapter, messages: rawMessages, actions: clientSideActionsInput, threadId, runId, outputMessagesPromise, graphqlContext, forwardedParameters, url, extensions, agentSession, agentStates, publicApiKey } = request;
2880
+ const eventSource = new RuntimeEventSource({
2881
+ errorHandler: async (error, context) => {
2882
+ await this.error("error", context, error, publicApiKey);
2883
+ },
2884
+ errorContext: {
2885
+ threadId,
2886
+ runId,
2887
+ source: "runtime",
2888
+ request: {
2889
+ operation: "processRuntimeRequest",
2890
+ method: "POST",
2891
+ url,
2892
+ startTime: Date.now()
2893
+ },
2894
+ agent: agentSession ? {
2895
+ name: agentSession.agentName
2896
+ } : void 0,
2897
+ technical: {
2898
+ environment: process.env.NODE_ENV
2856
2899
  }
2857
2900
  }
2858
- agent.state = state;
2859
- const tools = actionInputsWithoutAgents.map((input) => {
2860
- return {
2861
- name: input.name,
2862
- description: input.description,
2863
- parameters: JSON.parse(input.jsonSchema)
2901
+ });
2902
+ const requestStartTime = Date.now();
2903
+ const streamedChunks = [];
2904
+ try {
2905
+ if (Object.keys(this.agents).length && (agentSession == null ? void 0 : agentSession.agentName) && !this.delegateAgentProcessingToServiceAdapter) {
2906
+ this.agents = {
2907
+ [agentSession.agentName]: this.agents[agentSession.agentName]
2864
2908
  };
2865
- });
2866
- const forwardedProps = metaEvents.length ? {
2867
- command: {
2868
- resume: (_a = metaEvents[0]) == null ? void 0 : _a.response
2909
+ }
2910
+ if (agentSession && !this.delegateAgentProcessingToServiceAdapter) {
2911
+ return await this.processAgentRequest(request);
2912
+ }
2913
+ if (serviceAdapter instanceof EmptyAdapter) {
2914
+ throw new CopilotKitMisuseError2({
2915
+ message: `Invalid adapter configuration: EmptyAdapter is only meant to be used with agent lock mode.
2916
+ For non-agent components like useCopilotChatSuggestions, CopilotTextarea, or CopilotTask,
2917
+ please use an LLM adapter instead.`
2918
+ });
2919
+ }
2920
+ const serverSideActions = await this.getServerSideActions(request);
2921
+ const filteredRawMessages = rawMessages.filter((message) => !message.agentStateMessage);
2922
+ const messagesWithInjectedInstructions = this.injectMCPToolInstructions(filteredRawMessages, serverSideActions);
2923
+ const inputMessages = convertGqlInputToMessages(messagesWithInjectedInstructions);
2924
+ if (((_a = this.observability) == null ? void 0 : _a.enabled) && publicApiKey) {
2925
+ try {
2926
+ const requestData = {
2927
+ threadId,
2928
+ runId,
2929
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
2930
+ messages: inputMessages,
2931
+ actions: clientSideActionsInput,
2932
+ forwardedParameters,
2933
+ timestamp: requestStartTime,
2934
+ provider: this.detectProvider(serviceAdapter)
2935
+ };
2936
+ await this.observability.hooks.handleRequest(requestData);
2937
+ } catch (error) {
2938
+ console.error("Error logging LLM request:", error);
2869
2939
  }
2870
- } : void 0;
2871
- return agent.legacy_to_be_removed_runAgentBridged({
2872
- tools,
2873
- forwardedProps
2940
+ }
2941
+ const serverSideActionsInput = serverSideActions.map((action) => ({
2942
+ name: action.name,
2943
+ description: action.description,
2944
+ jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters))
2945
+ }));
2946
+ const actionInputs = flattenToolCallsNoDuplicates([
2947
+ ...serverSideActionsInput,
2948
+ ...clientSideActionsInput.filter(
2949
+ // Filter remote actions from CopilotKit core loop
2950
+ (action) => action.available !== ActionInputAvailability.remote
2951
+ )
2952
+ ]);
2953
+ await ((_b = this.onBeforeRequest) == null ? void 0 : _b.call(this, {
2954
+ threadId,
2955
+ runId,
2956
+ inputMessages,
2957
+ properties: graphqlContext.properties,
2958
+ url
2959
+ }));
2960
+ const result = await serviceAdapter.process({
2961
+ messages: inputMessages,
2962
+ actions: actionInputs,
2963
+ threadId,
2964
+ runId,
2965
+ eventSource,
2966
+ forwardedParameters,
2967
+ extensions,
2968
+ agentSession,
2969
+ agentStates
2874
2970
  });
2875
- }
2876
- };
2877
- return [
2878
- action
2879
- ];
2880
- }
2881
- __name(constructAGUIRemoteAction, "constructAGUIRemoteAction");
2882
- function convertMessagesToAGUIMessage(messages) {
2883
- const result = [];
2884
- for (const message of messages) {
2885
- if (message.isTextMessage()) {
2886
- result.push({
2887
- id: message.id,
2888
- role: message.role,
2889
- content: message.content
2971
+ const nonEmptyThreadId = threadId ?? result.threadId;
2972
+ outputMessagesPromise.then((outputMessages) => {
2973
+ var _a2;
2974
+ (_a2 = this.onAfterRequest) == null ? void 0 : _a2.call(this, {
2975
+ threadId: nonEmptyThreadId,
2976
+ runId: result.runId,
2977
+ inputMessages,
2978
+ outputMessages,
2979
+ properties: graphqlContext.properties,
2980
+ url
2981
+ });
2982
+ }).catch((_error) => {
2890
2983
  });
2891
- } else if (message.isActionExecutionMessage()) {
2892
- const toolCall = {
2893
- id: message.id,
2894
- type: "function",
2895
- function: {
2896
- name: message.name,
2897
- arguments: JSON.stringify(message.arguments)
2984
+ if (((_c = this.observability) == null ? void 0 : _c.enabled) && publicApiKey) {
2985
+ try {
2986
+ outputMessagesPromise.then((outputMessages) => {
2987
+ const responseData = {
2988
+ threadId: result.threadId,
2989
+ runId: result.runId,
2990
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
2991
+ // Use collected chunks for progressive mode or outputMessages for regular mode
2992
+ output: this.observability.progressive ? streamedChunks : outputMessages,
2993
+ latency: Date.now() - requestStartTime,
2994
+ timestamp: Date.now(),
2995
+ provider: this.detectProvider(serviceAdapter),
2996
+ // Indicate this is the final response
2997
+ isFinalResponse: true
2998
+ };
2999
+ try {
3000
+ this.observability.hooks.handleResponse(responseData);
3001
+ } catch (logError) {
3002
+ console.error("Error logging LLM response:", logError);
3003
+ }
3004
+ }).catch((error) => {
3005
+ console.error("Failed to get output messages for logging:", error);
3006
+ });
3007
+ } catch (error) {
3008
+ console.error("Error setting up logging for LLM response:", error);
2898
3009
  }
3010
+ }
3011
+ if (((_d = this.observability) == null ? void 0 : _d.enabled) && this.observability.progressive && publicApiKey) {
3012
+ const originalStream = eventSource.stream.bind(eventSource);
3013
+ eventSource.stream = async (callback) => {
3014
+ await originalStream(async (eventStream$) => {
3015
+ eventStream$.subscribe({
3016
+ next: (event) => {
3017
+ if (event.type === RuntimeEventTypes.TextMessageContent) {
3018
+ streamedChunks.push(event.content);
3019
+ try {
3020
+ const progressiveData = {
3021
+ threadId: threadId || "",
3022
+ runId,
3023
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3024
+ output: event.content,
3025
+ latency: Date.now() - requestStartTime,
3026
+ timestamp: Date.now(),
3027
+ provider: this.detectProvider(serviceAdapter),
3028
+ isProgressiveChunk: true
3029
+ };
3030
+ Promise.resolve().then(() => {
3031
+ this.observability.hooks.handleResponse(progressiveData);
3032
+ }).catch((error) => {
3033
+ console.error("Error in progressive logging:", error);
3034
+ });
3035
+ } catch (error) {
3036
+ console.error("Error preparing progressive log data:", error);
3037
+ }
3038
+ }
3039
+ }
3040
+ });
3041
+ await callback(eventStream$);
3042
+ });
3043
+ };
3044
+ }
3045
+ return {
3046
+ threadId: nonEmptyThreadId,
3047
+ runId: result.runId,
3048
+ eventSource,
3049
+ serverSideActions,
3050
+ actionInputsWithoutAgents: actionInputs.filter((action) => (
3051
+ // TODO-AGENTS: do not exclude ALL server side actions
3052
+ !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name)
3053
+ )),
3054
+ extensions: result.extensions
2899
3055
  };
2900
- if (message.parentMessageId && result.some((m) => m.id === message.parentMessageId)) {
2901
- const parentMessage = result.find((m) => m.id === message.parentMessageId);
2902
- if (parentMessage.toolCalls === void 0) {
2903
- parentMessage.toolCalls = [];
3056
+ } catch (error) {
3057
+ if (((_e = this.observability) == null ? void 0 : _e.enabled) && publicApiKey) {
3058
+ try {
3059
+ const errorData = {
3060
+ threadId,
3061
+ runId,
3062
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3063
+ error: error instanceof Error ? error : String(error),
3064
+ timestamp: Date.now(),
3065
+ latency: Date.now() - requestStartTime,
3066
+ provider: this.detectProvider(serviceAdapter)
3067
+ };
3068
+ await this.observability.hooks.handleError(errorData);
3069
+ } catch (logError) {
3070
+ console.error("Error logging LLM error:", logError);
2904
3071
  }
2905
- parentMessage.toolCalls.push(toolCall);
3072
+ }
3073
+ let structuredError;
3074
+ if (error instanceof CopilotKitError3) {
3075
+ structuredError = error;
2906
3076
  } else {
2907
- result.push({
2908
- id: message.parentMessageId ?? message.id,
2909
- role: "assistant",
2910
- toolCalls: [
2911
- toolCall
2912
- ]
2913
- });
3077
+ structuredError = ensureStructuredError2(error, (err) => this.convertStreamingErrorToStructured(err));
2914
3078
  }
2915
- } else if (message.isResultMessage()) {
2916
- result.push({
2917
- id: message.id,
2918
- role: "tool",
2919
- content: message.result,
2920
- toolCallId: message.actionExecutionId
2921
- });
2922
- }
2923
- }
2924
- return result;
2925
- }
2926
- __name(convertMessagesToAGUIMessage, "convertMessagesToAGUIMessage");
2927
-
2928
- // src/lib/runtime/remote-actions.ts
2929
- var EndpointType;
2930
- (function(EndpointType2) {
2931
- EndpointType2["CopilotKit"] = "copilotKit";
2932
- EndpointType2["LangGraphPlatform"] = "langgraph-platform";
2933
- })(EndpointType || (EndpointType = {}));
2934
- function isRemoteAgentAction(action) {
2935
- if (!action) {
2936
- return false;
2937
- }
2938
- return typeof action.remoteAgentHandler === "function";
2939
- }
2940
- __name(isRemoteAgentAction, "isRemoteAgentAction");
2941
- async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: logger2, frontendUrl }) {
2942
- logger2.debug({
2943
- url
2944
- }, "Fetching actions from url");
2945
- const headers = createHeaders(onBeforeRequest, graphqlContext);
2946
- const fetchUrl = `${url}/info`;
2947
- try {
2948
- const response = await fetch(fetchUrl, {
2949
- method: "POST",
2950
- headers,
2951
- body: JSON.stringify({
2952
- properties: graphqlContext.properties,
2953
- frontendUrl
2954
- })
2955
- });
2956
- if (!response.ok) {
2957
- logger2.error({
2958
- url,
2959
- status: response.status,
2960
- body: await response.text()
2961
- }, "Failed to fetch actions from url");
2962
- throw new ResolvedCopilotKitError2({
2963
- status: response.status,
2964
- url: fetchUrl,
2965
- isRemoteEndpoint: true
2966
- });
2967
- }
2968
- const json = await response.json();
2969
- logger2.debug({
2970
- json
2971
- }, "Fetched actions from url");
2972
- return json;
2973
- } catch (error) {
2974
- if (error instanceof CopilotKitError4) {
2975
- throw error;
3079
+ await this.error("error", {
3080
+ threadId,
3081
+ runId,
3082
+ source: "runtime",
3083
+ request: {
3084
+ operation: "processRuntimeRequest",
3085
+ method: "POST",
3086
+ url,
3087
+ startTime: requestStartTime
3088
+ },
3089
+ response: {
3090
+ endTime: Date.now(),
3091
+ latency: Date.now() - requestStartTime
3092
+ },
3093
+ agent: agentSession ? {
3094
+ name: agentSession.agentName
3095
+ } : void 0,
3096
+ technical: {
3097
+ environment: process.env.NODE_ENV,
3098
+ stackTrace: error instanceof Error ? error.stack : void 0
3099
+ }
3100
+ }, structuredError, publicApiKey);
3101
+ throw structuredError;
2976
3102
  }
2977
- throw new CopilotKitLowLevelError3({
2978
- error,
2979
- url: fetchUrl
2980
- });
2981
3103
  }
2982
- }
2983
- __name(fetchRemoteInfo, "fetchRemoteInfo");
2984
- async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, messages, agentStates, frontendUrl, agents, metaEvents }) {
2985
- const logger2 = graphqlContext.logger.child({
2986
- component: "remote-actions.fetchRemoteActions"
2987
- });
2988
- logger2.debug({
2989
- remoteEndpointDefinitions
2990
- }, "Fetching from remote endpoints");
2991
- const filtered = remoteEndpointDefinitions.filter((value, index, self) => {
2992
- if (value.type === "langgraph-platform") {
2993
- return value;
2994
- }
2995
- return index === self.findIndex((t) => t.url === value.url);
2996
- });
2997
- const result = await Promise.all(filtered.map(async (endpoint) => {
2998
- if (endpoint.type === "langgraph-platform") {
2999
- return constructLGCRemoteAction({
3000
- endpoint,
3001
- messages,
3002
- graphqlContext,
3003
- logger: logger2.child({
3004
- component: "remote-actions.constructLGCRemoteAction",
3005
- endpoint
3006
- }),
3007
- agentStates
3008
- });
3009
- }
3010
- const json = await fetchRemoteInfo({
3011
- url: endpoint.url,
3012
- onBeforeRequest: endpoint.onBeforeRequest,
3013
- graphqlContext,
3014
- logger: logger2.child({
3015
- component: "remote-actions.fetchActionsFromUrl",
3016
- endpoint
3017
- }),
3018
- frontendUrl
3019
- });
3020
- return constructRemoteActions({
3021
- json,
3022
- messages,
3023
- url: endpoint.url,
3024
- onBeforeRequest: endpoint.onBeforeRequest,
3025
- graphqlContext,
3026
- logger: logger2.child({
3027
- component: "remote-actions.constructActions",
3028
- endpoint
3029
- }),
3030
- agentStates
3031
- });
3032
- }));
3033
- for (const [key, agent] of Object.entries(agents)) {
3034
- if (agent.agentId !== void 0 && agent.agentId !== key) {
3035
- throw new CopilotKitError4({
3036
- message: `Agent ${key} has agentId ${agent.agentId} which does not match the key ${key}`,
3037
- code: CopilotKitErrorCode2.UNKNOWN
3038
- });
3039
- } else if (agent.agentId === void 0) {
3040
- agent.agentId = key;
3041
- }
3042
- result.push(constructAGUIRemoteAction({
3043
- logger: logger2,
3044
- messages,
3045
- agentStates,
3046
- agent,
3047
- metaEvents
3104
+ async getAllAgents(graphqlContext) {
3105
+ const agentsWithEndpoints = await this.discoverAgentsFromEndpoints(graphqlContext);
3106
+ const aguiAgents = this.discoverAgentsFromAgui();
3107
+ this.availableAgents = [
3108
+ ...agentsWithEndpoints,
3109
+ ...aguiAgents
3110
+ ].map((a) => ({
3111
+ name: a.name,
3112
+ id: a.id
3048
3113
  }));
3114
+ return [
3115
+ ...agentsWithEndpoints,
3116
+ ...aguiAgents
3117
+ ];
3049
3118
  }
3050
- return result.flat();
3051
- }
3052
- __name(setupRemoteActions, "setupRemoteActions");
3053
-
3054
- // src/lib/telemetry-client.ts
3055
- import { createHash as createHash3 } from "crypto";
3056
-
3057
- // src/lib/runtime/copilot-runtime.ts
3058
- 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";
3059
-
3060
- // src/service-adapters/conversion.ts
3061
- import { plainToInstance } from "class-transformer";
3062
- import { tryMap as tryMap2 } from "@copilotkit/shared";
3063
- function convertGqlInputToMessages(inputMessages) {
3064
- const messages = tryMap2(inputMessages, (message) => {
3065
- if (message.textMessage) {
3066
- return plainToInstance(TextMessage, {
3067
- id: message.id,
3068
- createdAt: message.createdAt,
3069
- role: message.textMessage.role,
3070
- content: message.textMessage.content,
3071
- parentMessageId: message.textMessage.parentMessageId
3072
- });
3073
- } else if (message.imageMessage) {
3074
- return plainToInstance(ImageMessage, {
3075
- id: message.id,
3076
- createdAt: message.createdAt,
3077
- role: message.imageMessage.role,
3078
- bytes: message.imageMessage.bytes,
3079
- format: message.imageMessage.format,
3080
- parentMessageId: message.imageMessage.parentMessageId
3081
- });
3082
- } else if (message.actionExecutionMessage) {
3083
- return plainToInstance(ActionExecutionMessage, {
3084
- id: message.id,
3085
- createdAt: message.createdAt,
3086
- name: message.actionExecutionMessage.name,
3087
- arguments: JSON.parse(message.actionExecutionMessage.arguments),
3088
- parentMessageId: message.actionExecutionMessage.parentMessageId
3089
- });
3090
- } else if (message.resultMessage) {
3091
- return plainToInstance(ResultMessage, {
3092
- id: message.id,
3093
- createdAt: message.createdAt,
3094
- actionExecutionId: message.resultMessage.actionExecutionId,
3095
- actionName: message.resultMessage.actionName,
3096
- result: message.resultMessage.result
3097
- });
3098
- } else if (message.agentStateMessage) {
3099
- return plainToInstance(AgentStateMessage, {
3100
- id: message.id,
3101
- threadId: message.agentStateMessage.threadId,
3102
- createdAt: message.createdAt,
3103
- agentName: message.agentStateMessage.agentName,
3104
- nodeName: message.agentStateMessage.nodeName,
3105
- runId: message.agentStateMessage.runId,
3106
- active: message.agentStateMessage.active,
3107
- role: message.agentStateMessage.role,
3108
- state: JSON.parse(message.agentStateMessage.state),
3109
- running: message.agentStateMessage.running
3110
- });
3111
- } else {
3112
- return null;
3113
- }
3114
- });
3115
- return messages.filter((m) => m);
3116
- }
3117
- __name(convertGqlInputToMessages, "convertGqlInputToMessages");
3118
-
3119
- // src/lib/runtime/copilot-runtime.ts
3120
- import { from } from "rxjs";
3121
- import { Client as LangGraphClient2 } from "@langchain/langgraph-sdk";
3122
-
3123
- // src/lib/runtime/mcp-tools-utils.ts
3124
- function extractParametersFromSchema(toolOrSchema) {
3125
- var _a;
3126
- const parameters = [];
3127
- const schema = "schema" in (toolOrSchema || {}) ? toolOrSchema.schema : toolOrSchema;
3128
- const toolParameters = (schema == null ? void 0 : schema.parameters) || ((_a = schema == null ? void 0 : schema.parameters) == null ? void 0 : _a.jsonSchema);
3129
- const properties = toolParameters == null ? void 0 : toolParameters.properties;
3130
- const requiredParams = new Set((toolParameters == null ? void 0 : toolParameters.required) || []);
3131
- if (!properties) {
3132
- return parameters;
3133
- }
3134
- for (const paramName in properties) {
3135
- if (Object.prototype.hasOwnProperty.call(properties, paramName)) {
3136
- const paramDef = properties[paramName];
3137
- parameters.push({
3138
- name: paramName,
3139
- // Infer type, default to string. MCP schemas might have more complex types.
3140
- // This might need refinement based on common MCP schema practices.
3141
- type: paramDef.type || "string",
3142
- description: paramDef.description,
3143
- required: requiredParams.has(paramName)
3144
- });
3145
- }
3146
- }
3147
- return parameters;
3148
- }
3149
- __name(extractParametersFromSchema, "extractParametersFromSchema");
3150
- function convertMCPToolsToActions(mcpTools, mcpEndpoint) {
3151
- const actions = [];
3152
- for (const [toolName, tool] of Object.entries(mcpTools)) {
3153
- const parameters = extractParametersFromSchema(tool);
3154
- const handler = /* @__PURE__ */ __name(async (params) => {
3155
- try {
3156
- const result = await tool.execute({
3157
- params
3119
+ async discoverAgentsFromEndpoints(graphqlContext) {
3120
+ const agents = this.remoteEndpointDefinitions.reduce(async (acc, endpoint) => {
3121
+ const agents2 = await acc;
3122
+ if (endpoint.type === EndpointType.LangGraphPlatform) {
3123
+ const propertyHeaders = graphqlContext.properties.authorization ? {
3124
+ authorization: `Bearer ${graphqlContext.properties.authorization}`
3125
+ } : null;
3126
+ const client = new LangGraphClient2({
3127
+ apiUrl: endpoint.deploymentUrl,
3128
+ apiKey: endpoint.langsmithApiKey,
3129
+ defaultHeaders: {
3130
+ ...propertyHeaders
3131
+ }
3158
3132
  });
3159
- return typeof result === "string" ? result : JSON.stringify(result);
3133
+ let data = [];
3134
+ try {
3135
+ data = await client.assistants.search();
3136
+ if (data && "detail" in data && data.detail.toLowerCase() === "not found") {
3137
+ throw new CopilotKitAgentDiscoveryError({
3138
+ availableAgents: this.availableAgents
3139
+ });
3140
+ }
3141
+ } catch (e) {
3142
+ throw new CopilotKitMisuseError2({
3143
+ message: `
3144
+ Failed to find or contact remote endpoint at url ${endpoint.deploymentUrl}.
3145
+ Make sure the API is running and that it's indeed a LangGraph platform url.
3146
+
3147
+ See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3148
+ });
3149
+ }
3150
+ const endpointAgents = data.map((entry) => ({
3151
+ name: entry.graph_id,
3152
+ id: entry.assistant_id,
3153
+ description: "",
3154
+ endpoint
3155
+ }));
3156
+ return [
3157
+ ...agents2,
3158
+ ...endpointAgents
3159
+ ];
3160
+ }
3161
+ const cpkEndpoint = endpoint;
3162
+ const fetchUrl = `${endpoint.url}/info`;
3163
+ try {
3164
+ const response = await fetchWithRetry(fetchUrl, {
3165
+ method: "POST",
3166
+ headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
3167
+ body: JSON.stringify({
3168
+ properties: graphqlContext.properties
3169
+ })
3170
+ });
3171
+ if (!response.ok) {
3172
+ if (response.status === 404) {
3173
+ throw new CopilotKitApiDiscoveryError({
3174
+ url: fetchUrl
3175
+ });
3176
+ }
3177
+ throw new ResolvedCopilotKitError({
3178
+ status: response.status,
3179
+ url: fetchUrl,
3180
+ isRemoteEndpoint: true
3181
+ });
3182
+ }
3183
+ const data = await response.json();
3184
+ const endpointAgents = ((data == null ? void 0 : data.agents) ?? []).map((agent) => ({
3185
+ name: agent.name,
3186
+ description: agent.description ?? "" ?? "",
3187
+ id: randomId(),
3188
+ endpoint
3189
+ }));
3190
+ return [
3191
+ ...agents2,
3192
+ ...endpointAgents
3193
+ ];
3160
3194
  } catch (error) {
3161
- console.error(`Error executing MCP tool '${toolName}' from endpoint ${mcpEndpoint}:`, error);
3162
- throw new Error(`Execution failed for MCP tool '${toolName}': ${error instanceof Error ? error.message : String(error)}`);
3195
+ if (error instanceof CopilotKitError3) {
3196
+ throw error;
3197
+ }
3198
+ throw new CopilotKitLowLevelError3({
3199
+ error,
3200
+ url: fetchUrl
3201
+ });
3163
3202
  }
3164
- }, "handler");
3165
- actions.push({
3166
- name: toolName,
3167
- description: tool.description || `MCP tool: ${toolName} (from ${mcpEndpoint})`,
3168
- parameters,
3169
- handler,
3170
- // Add metadata for easier identification/debugging
3171
- _isMCPTool: true,
3172
- _mcpEndpoint: mcpEndpoint
3173
- });
3203
+ }, Promise.resolve([]));
3204
+ return agents;
3174
3205
  }
3175
- return actions;
3176
- }
3177
- __name(convertMCPToolsToActions, "convertMCPToolsToActions");
3178
- function generateMcpToolInstructions(toolsMap) {
3179
- if (!toolsMap || Object.keys(toolsMap).length === 0) {
3180
- return "";
3206
+ discoverAgentsFromAgui() {
3207
+ return Object.entries(this.agents ?? []).map(([key, agent]) => ({
3208
+ name: agent.agentName ?? key,
3209
+ id: agent.agentId ?? key,
3210
+ description: agent.description ?? ""
3211
+ }));
3181
3212
  }
3182
- const toolEntries = Object.entries(toolsMap);
3183
- const toolsDoc = toolEntries.map(([name, tool]) => {
3184
- let paramsDoc = " No parameters required";
3185
- try {
3186
- if (tool.schema && typeof tool.schema === "object") {
3187
- const schema = tool.schema;
3188
- if (schema.properties) {
3189
- const requiredParams = schema.required || [];
3190
- const paramsList = Object.entries(schema.properties).map(([paramName, propSchema]) => {
3191
- const propDetails = propSchema;
3192
- const requiredMark = requiredParams.includes(paramName) ? "*" : "";
3193
- const typeInfo = propDetails.type || "any";
3194
- const description = propDetails.description ? ` - ${propDetails.description}` : "";
3195
- return ` - ${paramName}${requiredMark} (${typeInfo})${description}`;
3196
- });
3197
- if (paramsList.length > 0) {
3198
- paramsDoc = paramsList.join("\n");
3213
+ async loadAgentState(graphqlContext, threadId, agentName) {
3214
+ var _a;
3215
+ const agents = await this.getAllAgents(graphqlContext);
3216
+ const agent = agents.find((agent2) => agent2.name === agentName);
3217
+ if (!agent) {
3218
+ throw new Error("Agent not found");
3219
+ }
3220
+ if ("endpoint" in agent && (agent.endpoint.type === EndpointType.CopilotKit || !("type" in agent.endpoint))) {
3221
+ const cpkEndpoint = agent.endpoint;
3222
+ const fetchUrl = `${cpkEndpoint.url}/agents/state`;
3223
+ try {
3224
+ const response = await fetchWithRetry(fetchUrl, {
3225
+ method: "POST",
3226
+ headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
3227
+ body: JSON.stringify({
3228
+ properties: graphqlContext.properties,
3229
+ threadId,
3230
+ name: agentName
3231
+ })
3232
+ });
3233
+ if (!response.ok) {
3234
+ if (response.status === 404) {
3235
+ throw new CopilotKitApiDiscoveryError({
3236
+ url: fetchUrl
3237
+ });
3238
+ }
3239
+ let errorMessage = `HTTP ${response.status} error`;
3240
+ try {
3241
+ const errorBody = await response.text();
3242
+ const parsedError = JSON.parse(errorBody);
3243
+ if (parsedError.error && typeof parsedError.error === "string") {
3244
+ errorMessage = parsedError.error;
3245
+ }
3246
+ } catch {
3199
3247
  }
3248
+ throw new ResolvedCopilotKitError({
3249
+ status: response.status,
3250
+ url: fetchUrl,
3251
+ isRemoteEndpoint: true,
3252
+ message: errorMessage
3253
+ });
3254
+ }
3255
+ const data = await response.json();
3256
+ return {
3257
+ ...data,
3258
+ state: JSON.stringify(data.state),
3259
+ messages: JSON.stringify(data.messages)
3260
+ };
3261
+ } catch (error) {
3262
+ if (error instanceof CopilotKitError3) {
3263
+ throw error;
3200
3264
  }
3265
+ throw new CopilotKitLowLevelError3({
3266
+ error,
3267
+ url: fetchUrl
3268
+ });
3201
3269
  }
3202
- } catch (e) {
3203
- console.error(`Error parsing schema for tool ${name}:`, e);
3204
- }
3205
- return `- ${name}: ${tool.description || ""}
3206
- ${paramsDoc}`;
3207
- }).join("\n\n");
3208
- return `You have access to the following external tools provided by Model Context Protocol (MCP) servers:
3209
-
3210
- ${toolsDoc}
3211
-
3212
- When using these tools:
3213
- 1. Only provide valid parameters according to their type requirements
3214
- 2. Required parameters are marked with *
3215
- 3. Format API calls correctly with the expected parameter structure
3216
- 4. Always check tool responses to determine your next action`;
3217
- }
3218
- __name(generateMcpToolInstructions, "generateMcpToolInstructions");
3219
-
3220
- // src/lib/runtime/copilot-runtime.ts
3221
- var CopilotRuntime = class {
3222
- actions;
3223
- agents;
3224
- remoteEndpointDefinitions;
3225
- langserve = [];
3226
- onBeforeRequest;
3227
- onAfterRequest;
3228
- delegateAgentProcessingToServiceAdapter;
3229
- observability;
3230
- availableAgents;
3231
- onTrace;
3232
- hasWarnedAboutTracing = false;
3233
- // +++ MCP Properties +++
3234
- mcpServersConfig;
3235
- mcpActionCache = /* @__PURE__ */ new Map();
3236
- // --- MCP Properties ---
3237
- // +++ MCP Client Factory +++
3238
- createMCPClientImpl;
3239
- // --- MCP Client Factory ---
3240
- constructor(params) {
3241
- var _a, _b, _c, _d;
3242
- if ((params == null ? void 0 : params.actions) && (params == null ? void 0 : params.remoteEndpoints) && (params == null ? void 0 : params.remoteEndpoints.some((e) => e.type === EndpointType.LangGraphPlatform))) {
3243
- console.warn("Actions set in runtime instance will not be available for the agent");
3244
- console.warn(`LangGraph Platform remote endpoints are deprecated in favor of the "agents" property`);
3245
- }
3246
- this.actions = (params == null ? void 0 : params.actions) || [];
3247
- this.availableAgents = [];
3248
- for (const chain of (params == null ? void 0 : params.langserve) || []) {
3249
- const remoteChain = new RemoteChain(chain);
3250
- this.langserve.push(remoteChain.toAction());
3251
3270
  }
3252
- this.remoteEndpointDefinitions = (params == null ? void 0 : params.remoteEndpoints) ?? (params == null ? void 0 : params.remoteActions) ?? [];
3253
- this.onBeforeRequest = (_a = params == null ? void 0 : params.middleware) == null ? void 0 : _a.onBeforeRequest;
3254
- this.onAfterRequest = (_b = params == null ? void 0 : params.middleware) == null ? void 0 : _b.onAfterRequest;
3255
- this.delegateAgentProcessingToServiceAdapter = (params == null ? void 0 : params.delegateAgentProcessingToServiceAdapter) || false;
3256
- this.observability = params == null ? void 0 : params.observability_c;
3257
- this.agents = (params == null ? void 0 : params.agents) ?? {};
3258
- this.onTrace = params == null ? void 0 : params.onTrace;
3259
- this.mcpServersConfig = params == null ? void 0 : params.mcpServers;
3260
- this.createMCPClientImpl = params == null ? void 0 : params.createMCPClient;
3261
- if (this.mcpServersConfig && this.mcpServersConfig.length > 0 && !this.createMCPClientImpl) {
3262
- throw new CopilotKitMisuseError2({
3263
- message: "MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`."
3264
- });
3271
+ const propertyHeaders = graphqlContext.properties.authorization ? {
3272
+ authorization: `Bearer ${graphqlContext.properties.authorization}`
3273
+ } : null;
3274
+ let state = {};
3275
+ try {
3276
+ let client;
3277
+ if ("endpoint" in agent && agent.endpoint.type === EndpointType.LangGraphPlatform) {
3278
+ client = new LangGraphClient2({
3279
+ apiUrl: agent.endpoint.deploymentUrl,
3280
+ apiKey: agent.endpoint.langsmithApiKey,
3281
+ defaultHeaders: {
3282
+ ...propertyHeaders
3283
+ }
3284
+ });
3285
+ } else {
3286
+ const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name];
3287
+ if (!aguiAgent) {
3288
+ throw new Error(`Agent: ${agent.name} could not be resolved`);
3289
+ }
3290
+ client = aguiAgent.client ?? null;
3291
+ }
3292
+ state = client ? (await client.threads.getState(threadId)).values : {};
3293
+ } catch (error) {
3294
+ const errorMessage = error instanceof Error ? error.message : String(error);
3295
+ const errorStatus = ((_a = error == null ? void 0 : error.response) == null ? void 0 : _a.status) || (error == null ? void 0 : error.status);
3296
+ if (errorStatus === 404) {
3297
+ state = {};
3298
+ } else {
3299
+ console.debug(`Agent '${agentName}' configuration issue: ${errorMessage}`);
3300
+ throw new ResolvedCopilotKitError({
3301
+ status: 400,
3302
+ message: `Agent '${agentName}' failed to execute: ${errorMessage}`,
3303
+ code: CopilotKitErrorCode2.CONFIGURATION_ERROR
3304
+ });
3305
+ }
3265
3306
  }
3266
- if ((params == null ? void 0 : params.actions) && (((_c = params == null ? void 0 : params.remoteEndpoints) == null ? void 0 : _c.some((e) => e.type === EndpointType.LangGraphPlatform)) || ((_d = this.mcpServersConfig) == null ? void 0 : _d.length))) {
3267
- console.warn("Local 'actions' defined in CopilotRuntime might not be available to remote agents (LangGraph, MCP). Consider defining actions closer to the agent implementation if needed.");
3307
+ if (Object.keys(state).length === 0) {
3308
+ return {
3309
+ threadId: threadId || "",
3310
+ threadExists: false,
3311
+ state: JSON.stringify({}),
3312
+ messages: JSON.stringify([])
3313
+ };
3314
+ } else {
3315
+ const { messages, ...stateWithoutMessages } = state;
3316
+ const copilotkitMessages = langchainMessagesToCopilotKit(messages);
3317
+ return {
3318
+ threadId: threadId || "",
3319
+ threadExists: true,
3320
+ state: JSON.stringify(stateWithoutMessages),
3321
+ messages: JSON.stringify(copilotkitMessages)
3322
+ };
3268
3323
  }
3324
+ throw new Error(`Agent: ${agent.name} could not be resolved`);
3269
3325
  }
3270
- // +++ MCP Instruction Injection Method +++
3271
- injectMCPToolInstructions(messages, currentActions) {
3272
- const mcpActionsForRequest = currentActions.filter((action) => action._isMCPTool);
3273
- if (!mcpActionsForRequest || mcpActionsForRequest.length === 0) {
3274
- return messages;
3275
- }
3276
- const uniqueMcpTools = /* @__PURE__ */ new Map();
3277
- mcpActionsForRequest.forEach((action) => {
3278
- uniqueMcpTools.set(action.name, action);
3279
- });
3280
- const toolsMap = {};
3281
- Array.from(uniqueMcpTools.values()).forEach((action) => {
3282
- toolsMap[action.name] = {
3283
- description: action.description || "",
3284
- schema: action.parameters ? {
3285
- parameters: {
3286
- properties: action.parameters.reduce((acc, p) => ({
3287
- ...acc,
3288
- [p.name]: {
3289
- type: p.type,
3290
- description: p.description
3291
- }
3292
- }), {}),
3293
- required: action.parameters.filter((p) => p.required).map((p) => p.name)
3294
- }
3295
- } : {},
3296
- execute: async () => ({})
3297
- };
3298
- });
3299
- const mcpToolInstructions = generateMcpToolInstructions(toolsMap);
3300
- if (!mcpToolInstructions) {
3301
- return messages;
3302
- }
3303
- const instructions = "You have access to the following tools provided by external Model Context Protocol (MCP) servers:\n" + mcpToolInstructions + "\nUse them when appropriate to fulfill the user's request.";
3304
- const systemMessageIndex = messages.findIndex((msg) => {
3305
- var _a;
3306
- return ((_a = msg.textMessage) == null ? void 0 : _a.role) === "system";
3307
- });
3308
- const newMessages = [
3309
- ...messages
3310
- ];
3311
- if (systemMessageIndex !== -1) {
3312
- const existingMsg = newMessages[systemMessageIndex];
3313
- if (existingMsg.textMessage) {
3314
- existingMsg.textMessage.content = (existingMsg.textMessage.content ? existingMsg.textMessage.content + "\n\n" : "") + instructions;
3315
- }
3316
- } else {
3317
- newMessages.unshift({
3318
- id: randomId2(),
3319
- createdAt: /* @__PURE__ */ new Date(),
3320
- textMessage: {
3321
- role: MessageRole.system,
3322
- content: instructions
3323
- },
3324
- actionExecutionMessage: void 0,
3325
- resultMessage: void 0,
3326
- agentStateMessage: void 0
3327
- });
3328
- }
3329
- return newMessages;
3330
- }
3331
- async processRuntimeRequest(request) {
3326
+ async processAgentRequest(request) {
3332
3327
  var _a, _b, _c, _d, _e;
3333
- const { serviceAdapter, messages: rawMessages, actions: clientSideActionsInput, threadId, runId, outputMessagesPromise, graphqlContext, forwardedParameters, url, extensions, agentSession, agentStates, publicApiKey } = request;
3334
- const eventSource = new RuntimeEventSource();
3328
+ const { messages: rawMessages, outputMessagesPromise, graphqlContext, agentSession, threadId: threadIdFromRequest, metaEvents, publicApiKey, forwardedParameters } = request;
3329
+ const { agentName, nodeName } = agentSession;
3335
3330
  const requestStartTime = Date.now();
3336
3331
  const streamedChunks = [];
3337
- await this.trace("request", {
3332
+ const threadId = threadIdFromRequest ?? agentSession.threadId;
3333
+ await this.error("agent_state", {
3338
3334
  threadId,
3339
- runId,
3340
- source: "runtime",
3335
+ source: "agent",
3341
3336
  request: {
3342
- operation: "processRuntimeRequest",
3337
+ operation: "processAgentRequest",
3343
3338
  method: "POST",
3344
- url,
3345
3339
  startTime: requestStartTime
3346
3340
  },
3347
- agent: agentSession ? {
3348
- name: agentSession.agentName
3349
- } : void 0,
3341
+ agent: {
3342
+ name: agentName,
3343
+ nodeName
3344
+ },
3350
3345
  messages: {
3351
3346
  input: rawMessages,
3352
3347
  messageCount: rawMessages.length
@@ -3355,114 +3350,83 @@ var CopilotRuntime = class {
3355
3350
  environment: process.env.NODE_ENV
3356
3351
  }
3357
3352
  }, void 0, publicApiKey);
3358
- try {
3359
- if (Object.keys(this.agents).length && (agentSession == null ? void 0 : agentSession.agentName) && !this.delegateAgentProcessingToServiceAdapter) {
3360
- this.agents = {
3361
- [agentSession.agentName]: this.agents[agentSession.agentName]
3353
+ const serverSideActions = await this.getServerSideActions(request);
3354
+ const messages = convertGqlInputToMessages(rawMessages);
3355
+ const currentAgent = serverSideActions.find((action) => action.name === agentName && isRemoteAgentAction(action));
3356
+ if (!currentAgent) {
3357
+ throw new CopilotKitAgentDiscoveryError({
3358
+ agentName,
3359
+ availableAgents: this.availableAgents
3360
+ });
3361
+ }
3362
+ const availableActionsForCurrentAgent = serverSideActions.filter((action) => (
3363
+ // Case 1: Keep all regular (non-agent) actions
3364
+ !isRemoteAgentAction(action) || // Case 2: For agent actions, keep all except self (prevent infinite loops)
3365
+ isRemoteAgentAction(action) && action.name !== agentName
3366
+ )).map((action) => ({
3367
+ name: action.name,
3368
+ description: action.description,
3369
+ jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters))
3370
+ }));
3371
+ const allAvailableActions = flattenToolCallsNoDuplicates([
3372
+ ...availableActionsForCurrentAgent,
3373
+ ...request.actions
3374
+ ]);
3375
+ if (((_a = this.observability) == null ? void 0 : _a.enabled) && publicApiKey) {
3376
+ try {
3377
+ const requestData = {
3378
+ threadId,
3379
+ runId: void 0,
3380
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3381
+ messages,
3382
+ actions: allAvailableActions,
3383
+ forwardedParameters,
3384
+ timestamp: requestStartTime,
3385
+ provider: "agent",
3386
+ agentName,
3387
+ nodeName
3362
3388
  };
3389
+ await this.observability.hooks.handleRequest(requestData);
3390
+ } catch (error) {
3391
+ console.error("Error logging agent request:", error);
3363
3392
  }
3364
- if (agentSession && !this.delegateAgentProcessingToServiceAdapter) {
3365
- return await this.processAgentRequest(request);
3366
- }
3367
- if (serviceAdapter instanceof EmptyAdapter) {
3368
- throw new CopilotKitMisuseError2({
3369
- message: `Invalid adapter configuration: EmptyAdapter is only meant to be used with agent lock mode.
3370
- For non-agent components like useCopilotChatSuggestions, CopilotTextarea, or CopilotTask,
3371
- please use an LLM adapter instead.`
3372
- });
3373
- }
3374
- const serverSideActions = await this.getServerSideActions(request);
3375
- const filteredRawMessages = rawMessages.filter((message) => !message.agentStateMessage);
3376
- const messagesWithInjectedInstructions = this.injectMCPToolInstructions(filteredRawMessages, serverSideActions);
3377
- const inputMessages = convertGqlInputToMessages(messagesWithInjectedInstructions);
3378
- if (((_a = this.observability) == null ? void 0 : _a.enabled) && publicApiKey) {
3379
- try {
3380
- const requestData = {
3381
- threadId,
3382
- runId,
3383
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3384
- messages: inputMessages,
3385
- actions: clientSideActionsInput,
3386
- forwardedParameters,
3387
- timestamp: requestStartTime,
3388
- provider: this.detectProvider(serviceAdapter)
3389
- };
3390
- await this.observability.hooks.handleRequest(requestData);
3391
- } catch (error) {
3392
- console.error("Error logging LLM request:", error);
3393
+ }
3394
+ await ((_b = this.onBeforeRequest) == null ? void 0 : _b.call(this, {
3395
+ threadId,
3396
+ runId: void 0,
3397
+ inputMessages: messages,
3398
+ properties: graphqlContext.properties
3399
+ }));
3400
+ try {
3401
+ const eventSource = new RuntimeEventSource({
3402
+ errorHandler: async (error, context) => {
3403
+ await this.error("error", context, error, publicApiKey);
3404
+ },
3405
+ errorContext: {
3406
+ threadId,
3407
+ source: "agent",
3408
+ request: {
3409
+ operation: "processAgentRequest",
3410
+ method: "POST",
3411
+ startTime: requestStartTime
3412
+ },
3413
+ agent: {
3414
+ name: agentName,
3415
+ nodeName
3416
+ },
3417
+ technical: {
3418
+ environment: process.env.NODE_ENV
3419
+ }
3393
3420
  }
3394
- }
3395
- const serverSideActionsInput = serverSideActions.map((action) => ({
3396
- name: action.name,
3397
- description: action.description,
3398
- jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters))
3399
- }));
3400
- const actionInputs = flattenToolCallsNoDuplicates([
3401
- ...serverSideActionsInput,
3402
- ...clientSideActionsInput.filter(
3403
- // Filter remote actions from CopilotKit core loop
3404
- (action) => action.available !== ActionInputAvailability.remote
3405
- )
3406
- ]);
3407
- await ((_b = this.onBeforeRequest) == null ? void 0 : _b.call(this, {
3408
- threadId,
3409
- runId,
3410
- inputMessages,
3411
- properties: graphqlContext.properties,
3412
- url
3413
- }));
3414
- const result = await serviceAdapter.process({
3415
- messages: inputMessages,
3416
- actions: actionInputs,
3417
- threadId,
3418
- runId,
3419
- eventSource,
3420
- forwardedParameters,
3421
- extensions,
3422
- agentSession,
3423
- agentStates
3424
3421
  });
3425
- const nonEmptyThreadId = threadId ?? result.threadId;
3426
- outputMessagesPromise.then((outputMessages) => {
3427
- var _a2;
3428
- (_a2 = this.onAfterRequest) == null ? void 0 : _a2.call(this, {
3429
- threadId: nonEmptyThreadId,
3430
- runId: result.runId,
3431
- inputMessages,
3432
- outputMessages,
3433
- properties: graphqlContext.properties,
3434
- url
3435
- });
3436
- }).catch((_error) => {
3422
+ const stream = await currentAgent.remoteAgentHandler({
3423
+ name: agentName,
3424
+ threadId,
3425
+ nodeName,
3426
+ metaEvents,
3427
+ actionInputsWithoutAgents: allAvailableActions
3437
3428
  });
3438
- if (((_c = this.observability) == null ? void 0 : _c.enabled) && publicApiKey) {
3439
- try {
3440
- outputMessagesPromise.then((outputMessages) => {
3441
- const responseData = {
3442
- threadId: result.threadId,
3443
- runId: result.runId,
3444
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3445
- // Use collected chunks for progressive mode or outputMessages for regular mode
3446
- output: this.observability.progressive ? streamedChunks : outputMessages,
3447
- latency: Date.now() - requestStartTime,
3448
- timestamp: Date.now(),
3449
- provider: this.detectProvider(serviceAdapter),
3450
- // Indicate this is the final response
3451
- isFinalResponse: true
3452
- };
3453
- try {
3454
- this.observability.hooks.handleResponse(responseData);
3455
- } catch (logError) {
3456
- console.error("Error logging LLM response:", logError);
3457
- }
3458
- }).catch((error) => {
3459
- console.error("Failed to get output messages for logging:", error);
3460
- });
3461
- } catch (error) {
3462
- console.error("Error setting up logging for LLM response:", error);
3463
- }
3464
- }
3465
- if (((_d = this.observability) == null ? void 0 : _d.enabled) && this.observability.progressive && publicApiKey) {
3429
+ if (((_c = this.observability) == null ? void 0 : _c.enabled) && this.observability.progressive && publicApiKey) {
3466
3430
  const originalStream = eventSource.stream.bind(eventSource);
3467
3431
  eventSource.stream = async (callback) => {
3468
3432
  await originalStream(async (eventStream$) => {
@@ -3473,21 +3437,23 @@ please use an LLM adapter instead.`
3473
3437
  try {
3474
3438
  const progressiveData = {
3475
3439
  threadId: threadId || "",
3476
- runId,
3440
+ runId: void 0,
3477
3441
  model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3478
3442
  output: event.content,
3479
3443
  latency: Date.now() - requestStartTime,
3480
3444
  timestamp: Date.now(),
3481
- provider: this.detectProvider(serviceAdapter),
3482
- isProgressiveChunk: true
3445
+ provider: "agent",
3446
+ isProgressiveChunk: true,
3447
+ agentName,
3448
+ nodeName
3483
3449
  };
3484
3450
  Promise.resolve().then(() => {
3485
3451
  this.observability.hooks.handleResponse(progressiveData);
3486
3452
  }).catch((error) => {
3487
- console.error("Error in progressive logging:", error);
3453
+ console.error("Error in progressive agent logging:", error);
3488
3454
  });
3489
3455
  } catch (error) {
3490
- console.error("Error preparing progressive log data:", error);
3456
+ console.error("Error preparing progressive agent log data:", error);
3491
3457
  }
3492
3458
  }
3493
3459
  }
@@ -3496,828 +3462,1148 @@ please use an LLM adapter instead.`
3496
3462
  });
3497
3463
  };
3498
3464
  }
3499
- return {
3500
- threadId: nonEmptyThreadId,
3501
- runId: result.runId,
3502
- eventSource,
3503
- serverSideActions,
3504
- actionInputsWithoutAgents: actionInputs.filter((action) => (
3505
- // TODO-AGENTS: do not exclude ALL server side actions
3506
- !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name)
3507
- )),
3508
- extensions: result.extensions
3509
- };
3510
- } catch (error) {
3511
- if (((_e = this.observability) == null ? void 0 : _e.enabled) && publicApiKey) {
3512
- try {
3513
- const errorData = {
3514
- threadId,
3515
- runId,
3516
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3517
- error: error instanceof Error ? error : String(error),
3518
- timestamp: Date.now(),
3519
- latency: Date.now() - requestStartTime,
3520
- provider: this.detectProvider(serviceAdapter)
3521
- };
3522
- await this.observability.hooks.handleError(errorData);
3523
- } catch (logError) {
3524
- console.error("Error logging LLM error:", logError);
3525
- }
3465
+ eventSource.stream(async (eventStream$) => {
3466
+ from(stream).subscribe({
3467
+ next: (event) => eventStream$.next(event),
3468
+ error: async (err) => {
3469
+ var _a2;
3470
+ if (((_a2 = this.observability) == null ? void 0 : _a2.enabled) && publicApiKey) {
3471
+ try {
3472
+ const errorData = {
3473
+ threadId,
3474
+ runId: void 0,
3475
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3476
+ error: err instanceof Error ? err : String(err),
3477
+ timestamp: Date.now(),
3478
+ latency: Date.now() - requestStartTime,
3479
+ provider: "agent",
3480
+ agentName,
3481
+ nodeName
3482
+ };
3483
+ this.observability.hooks.handleError(errorData);
3484
+ } catch (logError) {
3485
+ console.error("Error logging agent error:", logError);
3486
+ }
3487
+ }
3488
+ const structuredError = ensureStructuredError2(err, (error) => this.convertStreamingErrorToStructured(error));
3489
+ await this.error("error", {
3490
+ threadId,
3491
+ source: "agent",
3492
+ request: {
3493
+ operation: "processAgentRequest",
3494
+ method: "POST",
3495
+ startTime: requestStartTime
3496
+ },
3497
+ response: {
3498
+ endTime: Date.now(),
3499
+ latency: Date.now() - requestStartTime
3500
+ },
3501
+ agent: {
3502
+ name: agentName,
3503
+ nodeName
3504
+ },
3505
+ technical: {
3506
+ environment: process.env.NODE_ENV,
3507
+ stackTrace: err instanceof Error ? err.stack : void 0
3508
+ }
3509
+ }, structuredError, publicApiKey);
3510
+ eventStream$.error(structuredError);
3511
+ eventStream$.complete();
3512
+ },
3513
+ complete: () => eventStream$.complete()
3514
+ });
3515
+ });
3516
+ if (((_d = this.observability) == null ? void 0 : _d.enabled) && publicApiKey) {
3517
+ outputMessagesPromise.then((outputMessages) => {
3518
+ const responseData = {
3519
+ threadId,
3520
+ runId: void 0,
3521
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3522
+ // Use collected chunks for progressive mode or outputMessages for regular mode
3523
+ output: this.observability.progressive ? streamedChunks : outputMessages,
3524
+ latency: Date.now() - requestStartTime,
3525
+ timestamp: Date.now(),
3526
+ provider: "agent",
3527
+ isFinalResponse: true,
3528
+ agentName,
3529
+ nodeName
3530
+ };
3531
+ try {
3532
+ this.observability.hooks.handleResponse(responseData);
3533
+ } catch (logError) {
3534
+ console.error("Error logging agent response:", logError);
3535
+ }
3536
+ }).catch((error) => {
3537
+ console.error("Failed to get output messages for agent logging:", error);
3538
+ });
3526
3539
  }
3527
- let structuredError;
3528
- if (error instanceof CopilotKitError5) {
3529
- structuredError = error;
3530
- } else {
3531
- console.error("Error getting response:", error);
3532
- structuredError = this.convertStreamingErrorToStructured(error);
3540
+ outputMessagesPromise.then((outputMessages) => {
3541
+ var _a2;
3542
+ (_a2 = this.onAfterRequest) == null ? void 0 : _a2.call(this, {
3543
+ threadId,
3544
+ runId: void 0,
3545
+ inputMessages: messages,
3546
+ outputMessages,
3547
+ properties: graphqlContext.properties
3548
+ });
3549
+ }).catch((_error) => {
3550
+ });
3551
+ return {
3552
+ threadId,
3553
+ runId: void 0,
3554
+ eventSource,
3555
+ serverSideActions,
3556
+ actionInputsWithoutAgents: allAvailableActions
3557
+ };
3558
+ } catch (error) {
3559
+ if (((_e = this.observability) == null ? void 0 : _e.enabled) && publicApiKey) {
3560
+ try {
3561
+ const errorData = {
3562
+ threadId,
3563
+ runId: void 0,
3564
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3565
+ error: error instanceof Error ? error : String(error),
3566
+ timestamp: Date.now(),
3567
+ latency: Date.now() - requestStartTime,
3568
+ provider: "agent",
3569
+ agentName,
3570
+ nodeName
3571
+ };
3572
+ await this.observability.hooks.handleError(errorData);
3573
+ } catch (logError) {
3574
+ console.error("Error logging agent error:", logError);
3575
+ }
3533
3576
  }
3534
- await this.trace("error", {
3577
+ const structuredError = ensureStructuredError2(error, (err) => this.convertStreamingErrorToStructured(err));
3578
+ await this.error("error", {
3535
3579
  threadId,
3536
- runId,
3537
- source: "runtime",
3580
+ source: "agent",
3538
3581
  request: {
3539
- operation: "processRuntimeRequest",
3582
+ operation: "processAgentRequest",
3540
3583
  method: "POST",
3541
- url,
3542
3584
  startTime: requestStartTime
3543
3585
  },
3544
3586
  response: {
3545
3587
  endTime: Date.now(),
3546
3588
  latency: Date.now() - requestStartTime
3547
3589
  },
3548
- agent: agentSession ? {
3549
- name: agentSession.agentName
3550
- } : void 0,
3590
+ agent: {
3591
+ name: agentName,
3592
+ nodeName
3593
+ },
3551
3594
  technical: {
3552
3595
  environment: process.env.NODE_ENV,
3553
3596
  stackTrace: error instanceof Error ? error.stack : void 0
3554
3597
  }
3555
3598
  }, structuredError, publicApiKey);
3599
+ console.error("Error getting response:", error);
3556
3600
  throw structuredError;
3557
3601
  }
3558
3602
  }
3559
- async getAllAgents(graphqlContext) {
3560
- const [agentsWithEndpoints, aguiAgents] = await Promise.all([
3561
- this.discoverAgentsFromEndpoints(graphqlContext),
3562
- this.discoverAgentsFromAgui()
3563
- ]);
3564
- this.availableAgents = [
3565
- ...agentsWithEndpoints,
3566
- ...aguiAgents
3567
- ].map((a) => ({
3568
- name: a.name,
3569
- id: a.id
3570
- }));
3571
- return [
3572
- ...agentsWithEndpoints,
3573
- ...aguiAgents
3574
- ];
3575
- }
3576
- async discoverAgentsFromEndpoints(graphqlContext) {
3577
- const agents = this.remoteEndpointDefinitions.reduce(async (acc, endpoint) => {
3578
- const agents2 = await acc;
3579
- if (endpoint.type === EndpointType.LangGraphPlatform) {
3580
- const propertyHeaders = graphqlContext.properties.authorization ? {
3581
- authorization: `Bearer ${graphqlContext.properties.authorization}`
3582
- } : null;
3583
- const client = new LangGraphClient2({
3584
- apiUrl: endpoint.deploymentUrl,
3585
- apiKey: endpoint.langsmithApiKey,
3586
- defaultHeaders: {
3587
- ...propertyHeaders
3588
- }
3589
- });
3590
- let data = [];
3591
- try {
3592
- data = await client.assistants.search();
3593
- if (data && "detail" in data && data.detail.toLowerCase() === "not found") {
3594
- throw new CopilotKitAgentDiscoveryError({
3595
- availableAgents: this.availableAgents
3596
- });
3597
- }
3598
- } catch (e) {
3599
- throw new CopilotKitMisuseError2({
3600
- message: `
3601
- Failed to find or contact remote endpoint at url ${endpoint.deploymentUrl}.
3602
- Make sure the API is running and that it's indeed a LangGraph platform url.
3603
-
3604
- See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3605
- });
3606
- }
3607
- const endpointAgents = data.map((entry) => ({
3608
- name: entry.graph_id,
3609
- id: entry.assistant_id,
3610
- description: "",
3611
- endpoint
3612
- }));
3613
- return [
3614
- ...agents2,
3615
- ...endpointAgents
3616
- ];
3617
- }
3618
- const cpkEndpoint = endpoint;
3619
- const fetchUrl = `${endpoint.url}/info`;
3603
+ async getServerSideActions(request) {
3604
+ var _a, _b, _c;
3605
+ const { graphqlContext, messages: rawMessages, agentStates, url } = request;
3606
+ const inputMessages = convertGqlInputToMessages(rawMessages);
3607
+ const langserveFunctions = [];
3608
+ for (const chainPromise of this.langserve) {
3620
3609
  try {
3621
- const response = await fetchWithRetry(fetchUrl, {
3622
- method: "POST",
3623
- headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
3624
- body: JSON.stringify({
3625
- properties: graphqlContext.properties
3626
- })
3627
- });
3628
- if (!response.ok) {
3629
- if (response.status === 404) {
3630
- throw new CopilotKitApiDiscoveryError2({
3631
- url: fetchUrl
3632
- });
3633
- }
3634
- throw new ResolvedCopilotKitError3({
3635
- status: response.status,
3636
- url: fetchUrl,
3637
- isRemoteEndpoint: true
3638
- });
3639
- }
3640
- const data = await response.json();
3641
- const endpointAgents = ((data == null ? void 0 : data.agents) ?? []).map((agent) => ({
3642
- name: agent.name,
3643
- description: agent.description ?? "" ?? "",
3644
- id: randomId2(),
3645
- endpoint
3646
- }));
3647
- return [
3648
- ...agents2,
3649
- ...endpointAgents
3650
- ];
3610
+ const chain = await chainPromise;
3611
+ langserveFunctions.push(chain);
3651
3612
  } catch (error) {
3652
- if (error instanceof CopilotKitError5) {
3653
- throw error;
3654
- }
3655
- throw new CopilotKitLowLevelError4({
3656
- error,
3657
- url: fetchUrl
3658
- });
3659
- }
3660
- }, Promise.resolve([]));
3661
- return agents;
3662
- }
3663
- async discoverAgentsFromAgui() {
3664
- const agents = Object.values(this.agents ?? []).reduce(async (acc, agent) => {
3665
- const agents2 = await acc;
3666
- const client = agent.client;
3667
- let data = [];
3668
- try {
3669
- data = await client.assistants.search();
3670
- if (data && "detail" in data && data.detail.toLowerCase() === "not found") {
3671
- throw new CopilotKitAgentDiscoveryError({
3672
- availableAgents: this.availableAgents
3673
- });
3674
- }
3675
- } catch (e) {
3676
- throw new CopilotKitMisuseError2({
3677
- message: `
3678
- Failed to find or contact agent ${agent.graphId}.
3679
- Make sure the LangGraph API is running and the agent is defined in langgraph.json
3680
-
3681
- See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3682
- });
3613
+ console.error("Error loading langserve chain:", error);
3683
3614
  }
3684
- const endpointAgents = data.map((entry) => ({
3685
- name: entry.graph_id,
3686
- id: entry.assistant_id,
3687
- description: ""
3688
- }));
3689
- return [
3690
- ...agents2,
3691
- ...endpointAgents
3692
- ];
3693
- }, Promise.resolve([]));
3694
- return agents;
3695
- }
3696
- async loadAgentState(graphqlContext, threadId, agentName) {
3697
- const agents = await this.getAllAgents(graphqlContext);
3698
- const agent = agents.find((agent2) => agent2.name === agentName);
3699
- if (!agent) {
3700
- throw new Error("Agent not found");
3701
3615
  }
3702
- if ("endpoint" in agent && (agent.endpoint.type === EndpointType.CopilotKit || !("type" in agent.endpoint))) {
3703
- const cpkEndpoint = agent.endpoint;
3704
- const fetchUrl = `${cpkEndpoint.url}/agents/state`;
3705
- try {
3706
- const response = await fetchWithRetry(fetchUrl, {
3707
- method: "POST",
3708
- headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
3709
- body: JSON.stringify({
3710
- properties: graphqlContext.properties,
3711
- threadId,
3712
- name: agentName
3713
- })
3714
- });
3715
- if (!response.ok) {
3716
- if (response.status === 404) {
3717
- throw new CopilotKitApiDiscoveryError2({
3718
- url: fetchUrl
3719
- });
3720
- }
3721
- throw new ResolvedCopilotKitError3({
3722
- status: response.status,
3723
- url: fetchUrl,
3724
- isRemoteEndpoint: true
3725
- });
3616
+ const remoteEndpointDefinitions = this.remoteEndpointDefinitions.map((endpoint) => ({
3617
+ ...endpoint,
3618
+ type: resolveEndpointType(endpoint)
3619
+ }));
3620
+ const remoteActions = await setupRemoteActions({
3621
+ remoteEndpointDefinitions,
3622
+ graphqlContext,
3623
+ messages: inputMessages,
3624
+ agentStates,
3625
+ frontendUrl: url,
3626
+ agents: this.agents,
3627
+ metaEvents: request.metaEvents,
3628
+ nodeName: (_a = request.agentSession) == null ? void 0 : _a.nodeName
3629
+ });
3630
+ const configuredActions = typeof this.actions === "function" ? this.actions({
3631
+ properties: graphqlContext.properties,
3632
+ url
3633
+ }) : this.actions;
3634
+ const requestSpecificMCPActions = [];
3635
+ if (this.createMCPClientImpl) {
3636
+ const baseEndpoints = this.mcpServersConfig || [];
3637
+ const requestEndpoints = ((_b = graphqlContext.properties) == null ? void 0 : _b.mcpServers) || ((_c = graphqlContext.properties) == null ? void 0 : _c.mcpEndpoints) || [];
3638
+ const effectiveEndpointsMap = /* @__PURE__ */ new Map();
3639
+ [
3640
+ ...baseEndpoints
3641
+ ].forEach((ep) => {
3642
+ if (ep && ep.endpoint) {
3643
+ effectiveEndpointsMap.set(ep.endpoint, ep);
3726
3644
  }
3727
- const data = await response.json();
3728
- return {
3729
- ...data,
3730
- state: JSON.stringify(data.state),
3731
- messages: JSON.stringify(data.messages)
3732
- };
3733
- } catch (error) {
3734
- if (error instanceof CopilotKitError5) {
3735
- throw error;
3645
+ });
3646
+ [
3647
+ ...requestEndpoints
3648
+ ].forEach((ep) => {
3649
+ if (ep && ep.endpoint) {
3650
+ effectiveEndpointsMap.set(ep.endpoint, ep);
3736
3651
  }
3737
- throw new CopilotKitLowLevelError4({
3738
- error,
3739
- url: fetchUrl
3740
- });
3652
+ });
3653
+ const effectiveEndpoints = Array.from(effectiveEndpointsMap.values());
3654
+ for (const config of effectiveEndpoints) {
3655
+ const endpointUrl = config.endpoint;
3656
+ let actionsForEndpoint = this.mcpActionCache.get(endpointUrl);
3657
+ if (!actionsForEndpoint) {
3658
+ let client = null;
3659
+ try {
3660
+ client = await this.createMCPClientImpl(config);
3661
+ const tools = await client.tools();
3662
+ actionsForEndpoint = convertMCPToolsToActions(tools, endpointUrl);
3663
+ this.mcpActionCache.set(endpointUrl, actionsForEndpoint);
3664
+ } catch (error) {
3665
+ console.error(`MCP: Failed to fetch tools from endpoint ${endpointUrl}. Skipping. Error:`, error);
3666
+ actionsForEndpoint = [];
3667
+ this.mcpActionCache.set(endpointUrl, actionsForEndpoint);
3668
+ }
3669
+ }
3670
+ requestSpecificMCPActions.push(...actionsForEndpoint || []);
3741
3671
  }
3742
3672
  }
3743
- const propertyHeaders = graphqlContext.properties.authorization ? {
3744
- authorization: `Bearer ${graphqlContext.properties.authorization}`
3745
- } : null;
3746
- let client;
3747
- if ("endpoint" in agent && agent.endpoint.type === EndpointType.LangGraphPlatform) {
3748
- client = new LangGraphClient2({
3749
- apiUrl: agent.endpoint.deploymentUrl,
3750
- apiKey: agent.endpoint.langsmithApiKey,
3751
- defaultHeaders: {
3752
- ...propertyHeaders
3753
- }
3673
+ return [
3674
+ ...configuredActions,
3675
+ ...langserveFunctions,
3676
+ ...remoteActions,
3677
+ ...requestSpecificMCPActions
3678
+ ];
3679
+ }
3680
+ // Add helper method to detect provider
3681
+ detectProvider(serviceAdapter) {
3682
+ const adapterName = serviceAdapter.constructor.name;
3683
+ if (adapterName.includes("OpenAI"))
3684
+ return "openai";
3685
+ if (adapterName.includes("Anthropic"))
3686
+ return "anthropic";
3687
+ if (adapterName.includes("Google"))
3688
+ return "google";
3689
+ if (adapterName.includes("Groq"))
3690
+ return "groq";
3691
+ if (adapterName.includes("LangChain"))
3692
+ return "langchain";
3693
+ return void 0;
3694
+ }
3695
+ convertStreamingErrorToStructured(error) {
3696
+ var _a, _b, _c, _d, _e, _f, _g;
3697
+ let helpfulMessage = generateHelpfulErrorMessage(error, "agent streaming connection");
3698
+ if (((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.includes("fetch failed")) || ((_b = error == null ? void 0 : error.message) == null ? void 0 : _b.includes("ECONNREFUSED")) || ((_c = error == null ? void 0 : error.message) == null ? void 0 : _c.includes("ENOTFOUND")) || ((_d = error == null ? void 0 : error.message) == null ? void 0 : _d.includes("ETIMEDOUT")) || ((_e = error == null ? void 0 : error.message) == null ? void 0 : _e.includes("terminated")) || ((_f = error == null ? void 0 : error.cause) == null ? void 0 : _f.code) === "UND_ERR_SOCKET" || ((_g = error == null ? void 0 : error.message) == null ? void 0 : _g.includes("other side closed")) || (error == null ? void 0 : error.code) === "UND_ERR_SOCKET") {
3699
+ return new CopilotKitLowLevelError3({
3700
+ error: error instanceof Error ? error : new Error(String(error)),
3701
+ url: "agent streaming connection",
3702
+ message: helpfulMessage
3754
3703
  });
3755
- } else {
3756
- const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name];
3757
- if (!aguiAgent) {
3758
- throw new Error(`Agent: ${agent.name} could not be resolved`);
3704
+ }
3705
+ return new CopilotKitError3({
3706
+ message: helpfulMessage,
3707
+ code: CopilotKitErrorCode2.UNKNOWN
3708
+ });
3709
+ }
3710
+ async error(type, context, error, publicApiKey) {
3711
+ if (!this.onError)
3712
+ return;
3713
+ if (!publicApiKey) {
3714
+ if (!this.hasWarnedAboutError) {
3715
+ console.warn("CopilotKit: onError handler provided but requires publicApiKey to be defined for error handling to work.");
3716
+ this.hasWarnedAboutError = true;
3759
3717
  }
3760
- client = aguiAgent.client;
3718
+ return;
3761
3719
  }
3762
- let state = {};
3763
3720
  try {
3764
- state = (await client.threads.getState(threadId)).values;
3765
- } catch (error) {
3766
- }
3767
- if (Object.keys(state).length === 0) {
3768
- return {
3769
- threadId: threadId || "",
3770
- threadExists: false,
3771
- state: JSON.stringify({}),
3772
- messages: JSON.stringify([])
3773
- };
3774
- } else {
3775
- const { messages, ...stateWithoutMessages } = state;
3776
- const copilotkitMessages = langchainMessagesToCopilotKit(messages);
3777
- return {
3778
- threadId: threadId || "",
3779
- threadExists: true,
3780
- state: JSON.stringify(stateWithoutMessages),
3781
- messages: JSON.stringify(copilotkitMessages)
3721
+ const errorEvent = {
3722
+ type,
3723
+ timestamp: Date.now(),
3724
+ context,
3725
+ ...error && {
3726
+ error
3727
+ }
3782
3728
  };
3729
+ await this.onError(errorEvent);
3730
+ } catch (errorHandlerError) {
3731
+ console.error("Error in onError handler:", errorHandlerError);
3783
3732
  }
3784
- throw new Error(`Agent: ${agent.name} could not be resolved`);
3785
3733
  }
3786
- async processAgentRequest(request) {
3787
- var _a, _b, _c, _d, _e;
3788
- const { messages: rawMessages, outputMessagesPromise, graphqlContext, agentSession, threadId: threadIdFromRequest, metaEvents, publicApiKey, forwardedParameters } = request;
3789
- const { agentName, nodeName } = agentSession;
3790
- const requestStartTime = Date.now();
3791
- const streamedChunks = [];
3792
- const threadId = threadIdFromRequest ?? agentSession.threadId;
3793
- await this.trace("agent_state", {
3794
- threadId,
3795
- source: "agent",
3796
- request: {
3797
- operation: "processAgentRequest",
3798
- method: "POST",
3799
- startTime: requestStartTime
3800
- },
3801
- agent: {
3802
- name: agentName,
3803
- nodeName
3804
- },
3805
- messages: {
3806
- input: rawMessages,
3807
- messageCount: rawMessages.length
3808
- },
3809
- technical: {
3810
- environment: process.env.NODE_ENV
3811
- }
3812
- }, void 0, publicApiKey);
3813
- const serverSideActions = await this.getServerSideActions(request);
3814
- const messages = convertGqlInputToMessages(rawMessages);
3815
- const currentAgent = serverSideActions.find((action) => action.name === agentName && isRemoteAgentAction(action));
3816
- if (!currentAgent) {
3817
- throw new CopilotKitAgentDiscoveryError({
3818
- agentName,
3819
- availableAgents: this.availableAgents
3734
+ /**
3735
+ * Public method to handle GraphQL validation errors
3736
+ * This allows the GraphQL resolver to send validation errors through the error system
3737
+ */
3738
+ async errorGraphQLError(error, context) {
3739
+ if (!this.onError)
3740
+ return;
3741
+ try {
3742
+ await this.onError({
3743
+ type: "error",
3744
+ timestamp: Date.now(),
3745
+ context: {
3746
+ source: "runtime",
3747
+ request: {
3748
+ operation: context.operation,
3749
+ startTime: Date.now()
3750
+ },
3751
+ technical: {
3752
+ environment: process.env.NODE_ENV
3753
+ },
3754
+ metadata: {
3755
+ errorType: "GraphQLValidationError",
3756
+ cloudConfigPresent: context.cloudConfigPresent,
3757
+ guardrailsEnabled: context.guardrailsEnabled
3758
+ }
3759
+ },
3760
+ error
3820
3761
  });
3762
+ } catch (errorHandlerError) {
3763
+ console.error("Error in onError handler:", errorHandlerError);
3821
3764
  }
3822
- const availableActionsForCurrentAgent = serverSideActions.filter((action) => (
3823
- // Case 1: Keep all regular (non-agent) actions
3824
- !isRemoteAgentAction(action) || // Case 2: For agent actions, keep all except self (prevent infinite loops)
3825
- isRemoteAgentAction(action) && action.name !== agentName
3826
- )).map((action) => ({
3827
- name: action.name,
3828
- description: action.description,
3829
- jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters))
3830
- }));
3831
- const allAvailableActions = flattenToolCallsNoDuplicates([
3832
- ...availableActionsForCurrentAgent,
3833
- ...request.actions
3834
- ]);
3835
- if (((_a = this.observability) == null ? void 0 : _a.enabled) && publicApiKey) {
3836
- try {
3837
- const requestData = {
3838
- threadId,
3839
- runId: void 0,
3840
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3841
- messages,
3842
- actions: allAvailableActions,
3843
- forwardedParameters,
3844
- timestamp: requestStartTime,
3845
- provider: "agent",
3846
- agentName,
3847
- nodeName
3848
- };
3849
- await this.observability.hooks.handleRequest(requestData);
3850
- } catch (error) {
3851
- console.error("Error logging agent request:", error);
3852
- }
3765
+ }
3766
+ };
3767
+ __name(CopilotRuntime, "CopilotRuntime");
3768
+ function flattenToolCallsNoDuplicates(toolsByPriority) {
3769
+ let allTools = [];
3770
+ const allToolNames = [];
3771
+ for (const tool of toolsByPriority) {
3772
+ if (!allToolNames.includes(tool.name)) {
3773
+ allTools.push(tool);
3774
+ allToolNames.push(tool.name);
3853
3775
  }
3854
- await ((_b = this.onBeforeRequest) == null ? void 0 : _b.call(this, {
3855
- threadId,
3856
- runId: void 0,
3857
- inputMessages: messages,
3858
- properties: graphqlContext.properties
3859
- }));
3860
- try {
3861
- const eventSource = new RuntimeEventSource();
3862
- const stream = await currentAgent.remoteAgentHandler({
3863
- name: agentName,
3864
- threadId,
3865
- nodeName,
3866
- metaEvents,
3867
- actionInputsWithoutAgents: allAvailableActions
3868
- });
3869
- if (((_c = this.observability) == null ? void 0 : _c.enabled) && this.observability.progressive && publicApiKey) {
3870
- const originalStream = eventSource.stream.bind(eventSource);
3871
- eventSource.stream = async (callback) => {
3872
- await originalStream(async (eventStream$) => {
3873
- eventStream$.subscribe({
3874
- next: (event) => {
3875
- if (event.type === RuntimeEventTypes.TextMessageContent) {
3876
- streamedChunks.push(event.content);
3877
- try {
3878
- const progressiveData = {
3879
- threadId: threadId || "",
3880
- runId: void 0,
3881
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3882
- output: event.content,
3883
- latency: Date.now() - requestStartTime,
3884
- timestamp: Date.now(),
3885
- provider: "agent",
3886
- isProgressiveChunk: true,
3887
- agentName,
3888
- nodeName
3889
- };
3890
- Promise.resolve().then(() => {
3891
- this.observability.hooks.handleResponse(progressiveData);
3892
- }).catch((error) => {
3893
- console.error("Error in progressive agent logging:", error);
3894
- });
3895
- } catch (error) {
3896
- console.error("Error preparing progressive agent log data:", error);
3897
- }
3898
- }
3899
- }
3900
- });
3901
- await callback(eventStream$);
3902
- });
3903
- };
3776
+ }
3777
+ return allTools;
3778
+ }
3779
+ __name(flattenToolCallsNoDuplicates, "flattenToolCallsNoDuplicates");
3780
+ function copilotKitEndpoint(config) {
3781
+ return {
3782
+ ...config,
3783
+ type: EndpointType.CopilotKit
3784
+ };
3785
+ }
3786
+ __name(copilotKitEndpoint, "copilotKitEndpoint");
3787
+ function langGraphPlatformEndpoint(config) {
3788
+ return {
3789
+ ...config,
3790
+ type: EndpointType.LangGraphPlatform
3791
+ };
3792
+ }
3793
+ __name(langGraphPlatformEndpoint, "langGraphPlatformEndpoint");
3794
+ function resolveEndpointType(endpoint) {
3795
+ if (!endpoint.type) {
3796
+ if ("deploymentUrl" in endpoint && "agents" in endpoint) {
3797
+ return EndpointType.LangGraphPlatform;
3798
+ } else {
3799
+ return EndpointType.CopilotKit;
3800
+ }
3801
+ }
3802
+ return endpoint.type;
3803
+ }
3804
+ __name(resolveEndpointType, "resolveEndpointType");
3805
+
3806
+ // src/lib/telemetry-client.ts
3807
+ var packageJson = require_package();
3808
+ var telemetryClient = new TelemetryClient({
3809
+ packageName: packageJson.name,
3810
+ packageVersion: packageJson.version
3811
+ });
3812
+ function getRuntimeInstanceTelemetryInfo(options) {
3813
+ var _a, _b;
3814
+ const runtime = options.runtime;
3815
+ const endpointsInfo = runtime.remoteEndpointDefinitions.reduce((acc, endpoint) => {
3816
+ let info = {
3817
+ ...acc
3818
+ };
3819
+ const endpointType = resolveEndpointType(endpoint);
3820
+ if (!info.endpointTypes.includes(endpointType)) {
3821
+ info = {
3822
+ ...info,
3823
+ endpointTypes: [
3824
+ ...info.endpointTypes,
3825
+ endpointType
3826
+ ]
3827
+ };
3828
+ }
3829
+ if (endpointType === EndpointType.LangGraphPlatform) {
3830
+ const ep = endpoint;
3831
+ info = {
3832
+ ...info,
3833
+ agentsAmount: ep.agents.length,
3834
+ hashedKey: ep.langsmithApiKey ? createHash2("sha256").update(ep.langsmithApiKey).digest("hex") : null
3835
+ };
3836
+ }
3837
+ return info;
3838
+ }, {
3839
+ endpointTypes: [],
3840
+ agentsAmount: null,
3841
+ hashedKey: null
3842
+ });
3843
+ const publicApiKey = (_a = options.cloud) == null ? void 0 : _a.publicApiKey;
3844
+ const apiKeyProvided = !!publicApiKey && publicApiKey.trim().length > 0;
3845
+ return {
3846
+ actionsAmount: runtime.actions.length,
3847
+ endpointsAmount: runtime.remoteEndpointDefinitions.length,
3848
+ endpointTypes: endpointsInfo.endpointTypes,
3849
+ agentsAmount: endpointsInfo.agentsAmount,
3850
+ hashedLgcKey: endpointsInfo.hashedKey,
3851
+ "cloud.api_key_provided": apiKeyProvided,
3852
+ ...apiKeyProvided ? {
3853
+ "cloud.public_api_key": publicApiKey
3854
+ } : {},
3855
+ ...((_b = options.cloud) == null ? void 0 : _b.baseUrl) ? {
3856
+ "cloud.base_url": options.cloud.baseUrl
3857
+ } : {}
3858
+ };
3859
+ }
3860
+ __name(getRuntimeInstanceTelemetryInfo, "getRuntimeInstanceTelemetryInfo");
3861
+ var telemetry_client_default = telemetryClient;
3862
+
3863
+ // src/agents/langgraph/event-source.ts
3864
+ import { CopilotKitLowLevelError as CopilotKitLowLevelError4, isStructuredCopilotKitError } from "@copilotkit/shared";
3865
+ import { catchError, mergeMap, ReplaySubject, scan } from "rxjs";
3866
+ var RemoteLangGraphEventSource = class {
3867
+ eventStream$ = new ReplaySubject();
3868
+ shouldEmitToolCall(shouldEmitToolCalls, toolCallName) {
3869
+ if (typeof shouldEmitToolCalls === "boolean") {
3870
+ return shouldEmitToolCalls;
3871
+ }
3872
+ if (Array.isArray(shouldEmitToolCalls)) {
3873
+ return shouldEmitToolCalls.includes(toolCallName);
3874
+ }
3875
+ return shouldEmitToolCalls === toolCallName;
3876
+ }
3877
+ getCurrentContent(event) {
3878
+ var _a, _b, _c, _d, _e;
3879
+ const content = ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.content) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.content);
3880
+ if (!content) {
3881
+ const toolCallChunks = this.getCurrentToolCallChunks(event) ?? [];
3882
+ for (const chunk of toolCallChunks) {
3883
+ if (chunk.args) {
3884
+ return chunk.args;
3885
+ }
3904
3886
  }
3905
- eventSource.stream(async (eventStream$) => {
3906
- from(stream).subscribe({
3907
- next: (event) => eventStream$.next(event),
3908
- error: async (err) => {
3909
- var _a2;
3910
- console.error("Error in stream", err);
3911
- if (((_a2 = this.observability) == null ? void 0 : _a2.enabled) && publicApiKey) {
3912
- try {
3913
- const errorData = {
3914
- threadId,
3915
- runId: void 0,
3916
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3917
- error: err instanceof Error ? err : String(err),
3918
- timestamp: Date.now(),
3919
- latency: Date.now() - requestStartTime,
3920
- provider: "agent",
3921
- agentName,
3922
- nodeName
3923
- };
3924
- this.observability.hooks.handleError(errorData);
3925
- } catch (logError) {
3926
- console.error("Error logging agent error:", logError);
3927
- }
3928
- }
3929
- const structuredError = this.convertStreamingErrorToStructured(err);
3930
- await this.trace("error", {
3931
- threadId,
3932
- source: "agent",
3933
- request: {
3934
- operation: "processAgentRequest",
3935
- method: "POST",
3936
- startTime: requestStartTime
3937
- },
3938
- response: {
3939
- endTime: Date.now(),
3940
- latency: Date.now() - requestStartTime
3941
- },
3942
- agent: {
3943
- name: agentName,
3944
- nodeName
3945
- },
3946
- technical: {
3947
- environment: process.env.NODE_ENV,
3948
- stackTrace: err instanceof Error ? err.stack : void 0
3949
- }
3950
- }, structuredError, publicApiKey);
3951
- eventStream$.error(structuredError);
3952
- eventStream$.complete();
3953
- },
3954
- complete: () => eventStream$.complete()
3887
+ }
3888
+ if (typeof content === "string") {
3889
+ return content;
3890
+ } else if (Array.isArray(content) && content.length > 0) {
3891
+ return content[0].text;
3892
+ }
3893
+ return null;
3894
+ }
3895
+ getCurrentMessageId(event) {
3896
+ var _a, _b, _c, _d, _e;
3897
+ return ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.id) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.id);
3898
+ }
3899
+ getCurrentToolCallChunks(event) {
3900
+ var _a, _b, _c, _d, _e;
3901
+ return ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.tool_call_chunks) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.tool_call_chunks);
3902
+ }
3903
+ getResponseMetadata(event) {
3904
+ var _a, _b, _c, _d, _e;
3905
+ return ((_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.response_metadata) ?? ((_e = (_d = event.data) == null ? void 0 : _d.chunk) == null ? void 0 : _e.response_metadata);
3906
+ }
3907
+ processLangGraphEvents() {
3908
+ let lastEventWithState = null;
3909
+ return this.eventStream$.pipe(scan((acc, event) => {
3910
+ if (event.event === LangGraphEventTypes.OnChatModelStream) {
3911
+ const prevMessageId = acc.lastMessageId;
3912
+ acc.currentContent = this.getCurrentContent(event);
3913
+ acc.lastMessageId = this.getCurrentMessageId(event) ?? acc.lastMessageId;
3914
+ const toolCallChunks = this.getCurrentToolCallChunks(event) ?? [];
3915
+ const responseMetadata = this.getResponseMetadata(event);
3916
+ const toolCallCheck = toolCallChunks && toolCallChunks.length > 0;
3917
+ let isToolCallEnd = (responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "tool_calls";
3918
+ acc.isToolCallStart = toolCallChunks.some((chunk) => chunk.name && chunk.id);
3919
+ acc.isMessageStart = prevMessageId !== acc.lastMessageId && !acc.isToolCallStart;
3920
+ let previousRoundHadToolCall = acc.isToolCall;
3921
+ acc.isToolCall = toolCallCheck;
3922
+ if (previousRoundHadToolCall && !toolCallCheck) {
3923
+ isToolCallEnd = true;
3924
+ }
3925
+ acc.isToolCallEnd = isToolCallEnd;
3926
+ acc.isMessageEnd = (responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "stop";
3927
+ ({ name: acc.lastToolCallName, id: acc.lastToolCallId } = toolCallChunks.find((chunk) => chunk.name && chunk.id) ?? {
3928
+ name: acc.lastToolCallName,
3929
+ id: acc.lastToolCallId
3955
3930
  });
3956
- });
3957
- if (((_d = this.observability) == null ? void 0 : _d.enabled) && publicApiKey) {
3958
- outputMessagesPromise.then((outputMessages) => {
3959
- const responseData = {
3960
- threadId,
3961
- runId: void 0,
3962
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3963
- // Use collected chunks for progressive mode or outputMessages for regular mode
3964
- output: this.observability.progressive ? streamedChunks : outputMessages,
3965
- latency: Date.now() - requestStartTime,
3966
- timestamp: Date.now(),
3967
- provider: "agent",
3968
- isFinalResponse: true,
3969
- agentName,
3970
- nodeName
3971
- };
3972
- try {
3973
- this.observability.hooks.handleResponse(responseData);
3974
- } catch (logError) {
3975
- console.error("Error logging agent response:", logError);
3931
+ }
3932
+ acc.event = event;
3933
+ lastEventWithState = acc;
3934
+ return acc;
3935
+ }, {
3936
+ event: null,
3937
+ isMessageStart: false,
3938
+ isMessageEnd: false,
3939
+ isToolCallStart: false,
3940
+ isToolCallEnd: false,
3941
+ isToolCall: false,
3942
+ lastMessageId: null,
3943
+ lastToolCallId: null,
3944
+ lastToolCallName: null,
3945
+ currentContent: null,
3946
+ processedToolCallIds: /* @__PURE__ */ new Set()
3947
+ }), mergeMap((acc) => {
3948
+ const events = [];
3949
+ let shouldEmitMessages = true;
3950
+ let shouldEmitToolCalls = true;
3951
+ if (acc.event.event == LangGraphEventTypes.OnChatModelStream) {
3952
+ if ("copilotkit:emit-tool-calls" in (acc.event.metadata || {})) {
3953
+ shouldEmitToolCalls = acc.event.metadata["copilotkit:emit-tool-calls"];
3954
+ }
3955
+ if ("copilotkit:emit-messages" in (acc.event.metadata || {})) {
3956
+ shouldEmitMessages = acc.event.metadata["copilotkit:emit-messages"];
3957
+ }
3958
+ }
3959
+ if (acc.event.event === LangGraphEventTypes.OnInterrupt) {
3960
+ events.push({
3961
+ type: RuntimeEventTypes.MetaEvent,
3962
+ name: RuntimeMetaEventName.LangGraphInterruptEvent,
3963
+ value: acc.event.value
3964
+ });
3965
+ }
3966
+ if (acc.event.event === LangGraphEventTypes.OnCopilotKitInterrupt) {
3967
+ events.push({
3968
+ type: RuntimeEventTypes.MetaEvent,
3969
+ name: RuntimeMetaEventName.CopilotKitLangGraphInterruptEvent,
3970
+ data: acc.event.data
3971
+ });
3972
+ }
3973
+ if (acc.event.event === LangGraphEventTypes.OnCopilotKitError) {
3974
+ const errorData = acc.event.data.error;
3975
+ const preservedError = new CopilotKitLowLevelError4({
3976
+ error: new Error(errorData.message),
3977
+ url: "langgraph agent",
3978
+ message: `${errorData.type}: ${errorData.message}`
3979
+ });
3980
+ if (errorData.status_code) {
3981
+ preservedError.statusCode = errorData.status_code;
3982
+ }
3983
+ if (errorData.response_data) {
3984
+ preservedError.responseData = errorData.response_data;
3985
+ }
3986
+ preservedError.agentName = errorData.agent_name;
3987
+ preservedError.originalErrorType = errorData.type;
3988
+ throw preservedError;
3989
+ }
3990
+ const responseMetadata = this.getResponseMetadata(acc.event);
3991
+ if (acc.isToolCallEnd && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName) && acc.lastToolCallId && !acc.processedToolCallIds.has(acc.lastToolCallId)) {
3992
+ acc.processedToolCallIds.add(acc.lastToolCallId);
3993
+ events.push({
3994
+ type: RuntimeEventTypes.ActionExecutionEnd,
3995
+ actionExecutionId: acc.lastToolCallId
3996
+ });
3997
+ } else if ((responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "stop" && shouldEmitMessages) {
3998
+ events.push({
3999
+ type: RuntimeEventTypes.TextMessageEnd,
4000
+ messageId: acc.lastMessageId
4001
+ });
4002
+ }
4003
+ switch (acc.event.event) {
4004
+ case LangGraphEventTypes.OnCustomEvent:
4005
+ if (acc.event.name === CustomEventNames.CopilotKitManuallyEmitMessage) {
4006
+ events.push({
4007
+ type: RuntimeEventTypes.TextMessageStart,
4008
+ messageId: acc.event.data.message_id
4009
+ });
4010
+ events.push({
4011
+ type: RuntimeEventTypes.TextMessageContent,
4012
+ messageId: acc.event.data.message_id,
4013
+ content: acc.event.data.message
4014
+ });
4015
+ events.push({
4016
+ type: RuntimeEventTypes.TextMessageEnd,
4017
+ messageId: acc.event.data.message_id
4018
+ });
4019
+ } else if (acc.event.name === CustomEventNames.CopilotKitManuallyEmitToolCall) {
4020
+ events.push({
4021
+ type: RuntimeEventTypes.ActionExecutionStart,
4022
+ actionExecutionId: acc.event.data.id,
4023
+ actionName: acc.event.data.name,
4024
+ parentMessageId: acc.event.data.id
4025
+ });
4026
+ events.push({
4027
+ type: RuntimeEventTypes.ActionExecutionArgs,
4028
+ actionExecutionId: acc.event.data.id,
4029
+ args: JSON.stringify(acc.event.data.args)
4030
+ });
4031
+ events.push({
4032
+ type: RuntimeEventTypes.ActionExecutionEnd,
4033
+ actionExecutionId: acc.event.data.id
4034
+ });
4035
+ }
4036
+ break;
4037
+ case LangGraphEventTypes.OnCopilotKitStateSync:
4038
+ events.push({
4039
+ type: RuntimeEventTypes.AgentStateMessage,
4040
+ threadId: acc.event.thread_id,
4041
+ role: acc.event.role,
4042
+ agentName: acc.event.agent_name,
4043
+ nodeName: acc.event.node_name,
4044
+ runId: acc.event.run_id,
4045
+ active: acc.event.active,
4046
+ state: JSON.stringify(acc.event.state),
4047
+ running: acc.event.running
4048
+ });
4049
+ break;
4050
+ case LangGraphEventTypes.OnChatModelStream:
4051
+ if (acc.isToolCallStart && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName)) {
4052
+ events.push({
4053
+ type: RuntimeEventTypes.ActionExecutionStart,
4054
+ actionExecutionId: acc.lastToolCallId,
4055
+ actionName: acc.lastToolCallName,
4056
+ parentMessageId: acc.lastMessageId
4057
+ });
4058
+ } else if (acc.isMessageStart && shouldEmitMessages) {
4059
+ acc.processedToolCallIds.clear();
4060
+ events.push({
4061
+ type: RuntimeEventTypes.TextMessageStart,
4062
+ messageId: acc.lastMessageId
4063
+ });
4064
+ }
4065
+ if (acc.isToolCall && acc.currentContent && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName)) {
4066
+ events.push({
4067
+ type: RuntimeEventTypes.ActionExecutionArgs,
4068
+ actionExecutionId: acc.lastToolCallId,
4069
+ args: acc.currentContent
4070
+ });
4071
+ } else if (!acc.isToolCall && acc.currentContent && shouldEmitMessages) {
4072
+ events.push({
4073
+ type: RuntimeEventTypes.TextMessageContent,
4074
+ messageId: acc.lastMessageId,
4075
+ content: acc.currentContent
4076
+ });
3976
4077
  }
3977
- }).catch((error) => {
3978
- console.error("Failed to get output messages for agent logging:", error);
3979
- });
4078
+ break;
3980
4079
  }
3981
- outputMessagesPromise.then((outputMessages) => {
3982
- var _a2;
3983
- (_a2 = this.onAfterRequest) == null ? void 0 : _a2.call(this, {
4080
+ return events;
4081
+ }), catchError((error) => {
4082
+ if (isStructuredCopilotKitError(error)) {
4083
+ throw error;
4084
+ }
4085
+ let helpfulMessage = generateHelpfulErrorMessage(error, "LangGraph agent connection");
4086
+ throw new CopilotKitLowLevelError4({
4087
+ error: error instanceof Error ? error : new Error(String(error)),
4088
+ url: "langgraph event stream",
4089
+ message: helpfulMessage
4090
+ });
4091
+ }));
4092
+ }
4093
+ };
4094
+ __name(RemoteLangGraphEventSource, "RemoteLangGraphEventSource");
4095
+
4096
+ // src/lib/runtime/remote-action-constructors.ts
4097
+ import { CopilotKitError as CopilotKitError4, CopilotKitLowLevelError as CopilotKitLowLevelError5 } from "@copilotkit/shared";
4098
+ import { CopilotKitApiDiscoveryError as CopilotKitApiDiscoveryError2, ResolvedCopilotKitError as ResolvedCopilotKitError2 } from "@copilotkit/shared";
4099
+ import { parseJson as parseJson2, tryMap as tryMap2 } from "@copilotkit/shared";
4100
+ function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, messages, agentStates }) {
4101
+ const agents = endpoint.agents.map((agent) => ({
4102
+ name: agent.name,
4103
+ description: agent.description,
4104
+ parameters: [],
4105
+ handler: async (_args) => {
4106
+ },
4107
+ remoteAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName, additionalMessages = [], metaEvents }) => {
4108
+ logger2.debug({
4109
+ actionName: agent.name
4110
+ }, "Executing LangGraph Platform agent");
4111
+ telemetry_client_default.capture("oss.runtime.remote_action_executed", {
4112
+ agentExecution: true,
4113
+ type: "langgraph-platform",
4114
+ agentsAmount: endpoint.agents.length,
4115
+ hashedLgcKey: endpoint.langsmithApiKey ? createHash3("sha256").update(endpoint.langsmithApiKey).digest("hex") : null
4116
+ });
4117
+ let state = {};
4118
+ let config = {};
4119
+ if (agentStates) {
4120
+ const jsonState = agentStates.find((state2) => state2.agentName === name);
4121
+ if (jsonState) {
4122
+ state = parseJson2(jsonState.state, {});
4123
+ config = parseJson2(jsonState.config, {});
4124
+ }
4125
+ }
4126
+ try {
4127
+ const response = await execute({
4128
+ logger: logger2.child({
4129
+ component: "remote-actions.remote-lg-action.streamEvents"
4130
+ }),
4131
+ deploymentUrl: endpoint.deploymentUrl,
4132
+ langsmithApiKey: endpoint.langsmithApiKey,
4133
+ agent,
3984
4134
  threadId,
3985
- runId: void 0,
3986
- inputMessages: messages,
3987
- outputMessages,
3988
- properties: graphqlContext.properties
4135
+ nodeName,
4136
+ messages: [
4137
+ ...messages,
4138
+ ...additionalMessages
4139
+ ],
4140
+ state,
4141
+ config,
4142
+ properties: graphqlContext.properties,
4143
+ actions: tryMap2(actionInputsWithoutAgents, (action) => ({
4144
+ name: action.name,
4145
+ description: action.description,
4146
+ parameters: JSON.parse(action.jsonSchema)
4147
+ })),
4148
+ metaEvents
3989
4149
  });
3990
- }).catch((_error) => {
4150
+ const eventSource = new RemoteLangGraphEventSource();
4151
+ writeJsonLineResponseToEventStream(response, eventSource.eventStream$);
4152
+ return eventSource.processLangGraphEvents();
4153
+ } catch (error) {
4154
+ if (error instanceof CopilotKitError4 || error instanceof CopilotKitLowLevelError5) {
4155
+ if (isUserConfigurationError(error)) {
4156
+ logger2.debug({
4157
+ url: endpoint.deploymentUrl,
4158
+ error: error.message,
4159
+ code: error.code
4160
+ }, "User configuration error in LangGraph Platform agent");
4161
+ } else {
4162
+ logger2.error({
4163
+ url: endpoint.deploymentUrl,
4164
+ error: error.message,
4165
+ type: error.constructor.name
4166
+ }, "LangGraph Platform agent error");
4167
+ }
4168
+ throw error;
4169
+ }
4170
+ logger2.error({
4171
+ url: endpoint.deploymentUrl,
4172
+ status: 500,
4173
+ body: error.message
4174
+ }, "Failed to execute LangGraph Platform agent");
4175
+ throw new CopilotKitLowLevelError5({
4176
+ error: error instanceof Error ? error : new Error(String(error)),
4177
+ url: endpoint.deploymentUrl,
4178
+ message: "Failed to execute LangGraph Platform agent"
4179
+ });
4180
+ }
4181
+ }
4182
+ }));
4183
+ return [
4184
+ ...agents
4185
+ ];
4186
+ }
4187
+ __name(constructLGCRemoteAction, "constructLGCRemoteAction");
4188
+ var RemoteAgentType;
4189
+ (function(RemoteAgentType2) {
4190
+ RemoteAgentType2["LangGraph"] = "langgraph";
4191
+ RemoteAgentType2["CrewAI"] = "crewai";
4192
+ })(RemoteAgentType || (RemoteAgentType = {}));
4193
+ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, logger: logger2, messages, agentStates }) {
4194
+ const totalAgents = Array.isArray(json["agents"]) ? json["agents"].length : 0;
4195
+ const actions = json["actions"].map((action) => ({
4196
+ name: action.name,
4197
+ description: action.description,
4198
+ parameters: action.parameters,
4199
+ handler: async (args) => {
4200
+ logger2.debug({
4201
+ actionName: action.name,
4202
+ args
4203
+ }, "Executing remote action");
4204
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
4205
+ telemetry_client_default.capture("oss.runtime.remote_action_executed", {
4206
+ agentExecution: false,
4207
+ type: "self-hosted",
4208
+ agentsAmount: totalAgents
3991
4209
  });
3992
- return {
3993
- threadId,
3994
- runId: void 0,
3995
- eventSource,
3996
- serverSideActions,
3997
- actionInputsWithoutAgents: allAvailableActions
3998
- };
3999
- } catch (error) {
4000
- if (((_e = this.observability) == null ? void 0 : _e.enabled) && publicApiKey) {
4001
- try {
4002
- const errorData = {
4003
- threadId,
4004
- runId: void 0,
4005
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
4006
- error: error instanceof Error ? error : String(error),
4007
- timestamp: Date.now(),
4008
- latency: Date.now() - requestStartTime,
4009
- provider: "agent",
4010
- agentName,
4011
- nodeName
4012
- };
4013
- await this.observability.hooks.handleError(errorData);
4014
- } catch (logError) {
4015
- console.error("Error logging agent error:", logError);
4210
+ const fetchUrl = `${url}/actions/execute`;
4211
+ try {
4212
+ const response = await fetchWithRetry(fetchUrl, {
4213
+ method: "POST",
4214
+ headers,
4215
+ body: JSON.stringify({
4216
+ name: action.name,
4217
+ arguments: args,
4218
+ properties: graphqlContext.properties
4219
+ })
4220
+ }, logger2);
4221
+ if (!response.ok) {
4222
+ logger2.error({
4223
+ url,
4224
+ status: response.status,
4225
+ body: await response.text()
4226
+ }, "Failed to execute remote action");
4227
+ if (response.status === 404) {
4228
+ throw new CopilotKitApiDiscoveryError2({
4229
+ url: fetchUrl
4230
+ });
4231
+ }
4232
+ throw new ResolvedCopilotKitError2({
4233
+ status: response.status,
4234
+ url: fetchUrl,
4235
+ isRemoteEndpoint: true
4236
+ });
4237
+ }
4238
+ const requestResult = await response.json();
4239
+ const result = requestResult["result"];
4240
+ logger2.debug({
4241
+ actionName: action.name,
4242
+ result
4243
+ }, "Executed remote action");
4244
+ return result;
4245
+ } catch (error) {
4246
+ if (error instanceof CopilotKitError4 || error instanceof CopilotKitLowLevelError5) {
4247
+ throw error;
4016
4248
  }
4249
+ throw new CopilotKitLowLevelError5({
4250
+ error,
4251
+ url: fetchUrl
4252
+ });
4017
4253
  }
4018
- let structuredError;
4019
- if (error instanceof CopilotKitError5) {
4020
- structuredError = error;
4021
- } else {
4022
- structuredError = this.convertStreamingErrorToStructured(error);
4254
+ }
4255
+ }));
4256
+ const agents = totalAgents ? json["agents"].map((agent) => ({
4257
+ name: agent.name,
4258
+ description: agent.description,
4259
+ parameters: [],
4260
+ handler: async (_args) => {
4261
+ },
4262
+ remoteAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName, additionalMessages = [], metaEvents }) => {
4263
+ logger2.debug({
4264
+ actionName: agent.name
4265
+ }, "Executing remote agent");
4266
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
4267
+ telemetry_client_default.capture("oss.runtime.remote_action_executed", {
4268
+ agentExecution: true,
4269
+ type: "self-hosted",
4270
+ agentsAmount: json["agents"].length
4271
+ });
4272
+ let state = {};
4273
+ let config = {};
4274
+ if (agentStates) {
4275
+ const jsonState = agentStates.find((state2) => state2.agentName === name);
4276
+ if (jsonState) {
4277
+ state = parseJson2(jsonState.state, {});
4278
+ config = parseJson2(jsonState.config, {});
4279
+ }
4023
4280
  }
4024
- await this.trace("error", {
4025
- threadId,
4026
- source: "agent",
4027
- request: {
4028
- operation: "processAgentRequest",
4281
+ const fetchUrl = `${url}/agents/execute`;
4282
+ try {
4283
+ const response = await fetchWithRetry(fetchUrl, {
4029
4284
  method: "POST",
4030
- startTime: requestStartTime
4031
- },
4032
- response: {
4033
- endTime: Date.now(),
4034
- latency: Date.now() - requestStartTime
4035
- },
4036
- agent: {
4037
- name: agentName,
4038
- nodeName
4039
- },
4040
- technical: {
4041
- environment: process.env.NODE_ENV,
4042
- stackTrace: error instanceof Error ? error.stack : void 0
4285
+ headers,
4286
+ body: JSON.stringify({
4287
+ name,
4288
+ threadId,
4289
+ nodeName,
4290
+ messages: [
4291
+ ...messages,
4292
+ ...additionalMessages
4293
+ ],
4294
+ state,
4295
+ config,
4296
+ properties: graphqlContext.properties,
4297
+ actions: tryMap2(actionInputsWithoutAgents, (action) => ({
4298
+ name: action.name,
4299
+ description: action.description,
4300
+ parameters: JSON.parse(action.jsonSchema)
4301
+ })),
4302
+ metaEvents
4303
+ })
4304
+ }, logger2);
4305
+ if (!response.ok) {
4306
+ logger2.error({
4307
+ url,
4308
+ status: response.status,
4309
+ body: await response.text()
4310
+ }, "Failed to execute remote agent");
4311
+ if (response.status === 404) {
4312
+ throw new CopilotKitApiDiscoveryError2({
4313
+ url: fetchUrl
4314
+ });
4315
+ }
4316
+ throw new ResolvedCopilotKitError2({
4317
+ status: response.status,
4318
+ url: fetchUrl,
4319
+ isRemoteEndpoint: true
4320
+ });
4321
+ }
4322
+ if (agent.type === "langgraph") {
4323
+ const eventSource = new RemoteLangGraphEventSource();
4324
+ writeJsonLineResponseToEventStream(response.body, eventSource.eventStream$);
4325
+ return eventSource.processLangGraphEvents();
4326
+ } else if (agent.type === "crewai") {
4327
+ const eventStream$ = new RuntimeEventSubject();
4328
+ writeJsonLineResponseToEventStream(response.body, eventStream$);
4329
+ return eventStream$;
4330
+ } else {
4331
+ throw new Error("Unsupported agent type");
4043
4332
  }
4044
- }, structuredError, publicApiKey);
4045
- console.error("Error getting response:", error);
4046
- throw structuredError;
4047
- }
4048
- }
4049
- async getServerSideActions(request) {
4050
- var _a, _b;
4051
- const { graphqlContext, messages: rawMessages, agentStates, url } = request;
4052
- const inputMessages = convertGqlInputToMessages(rawMessages);
4053
- const langserveFunctions = [];
4054
- for (const chainPromise of this.langserve) {
4055
- try {
4056
- const chain = await chainPromise;
4057
- langserveFunctions.push(chain);
4058
4333
  } catch (error) {
4059
- console.error("Error loading langserve chain:", error);
4334
+ if (error instanceof CopilotKitError4 || error instanceof CopilotKitLowLevelError5) {
4335
+ throw error;
4336
+ }
4337
+ throw new CopilotKitLowLevelError5({
4338
+ error,
4339
+ url: fetchUrl
4340
+ });
4060
4341
  }
4061
4342
  }
4062
- const remoteEndpointDefinitions = this.remoteEndpointDefinitions.map((endpoint) => ({
4063
- ...endpoint,
4064
- type: resolveEndpointType(endpoint)
4065
- }));
4066
- const remoteActions = await setupRemoteActions({
4067
- remoteEndpointDefinitions,
4068
- graphqlContext,
4069
- messages: inputMessages,
4070
- agentStates,
4071
- frontendUrl: url,
4072
- agents: this.agents,
4073
- metaEvents: request.metaEvents
4343
+ })) : [];
4344
+ return [
4345
+ ...actions,
4346
+ ...agents
4347
+ ];
4348
+ }
4349
+ __name(constructRemoteActions, "constructRemoteActions");
4350
+ function createHeaders(onBeforeRequest, graphqlContext) {
4351
+ const headers = {
4352
+ "Content-Type": "application/json"
4353
+ };
4354
+ if (onBeforeRequest) {
4355
+ const { headers: additionalHeaders } = onBeforeRequest({
4356
+ ctx: graphqlContext
4074
4357
  });
4075
- const configuredActions = typeof this.actions === "function" ? this.actions({
4076
- properties: graphqlContext.properties,
4077
- url
4078
- }) : this.actions;
4079
- const requestSpecificMCPActions = [];
4080
- if (this.createMCPClientImpl) {
4081
- const baseEndpoints = this.mcpServersConfig || [];
4082
- const requestEndpoints = ((_a = graphqlContext.properties) == null ? void 0 : _a.mcpServers) || ((_b = graphqlContext.properties) == null ? void 0 : _b.mcpEndpoints) || [];
4083
- const effectiveEndpointsMap = /* @__PURE__ */ new Map();
4084
- [
4085
- ...baseEndpoints
4086
- ].forEach((ep) => {
4087
- if (ep && ep.endpoint) {
4088
- effectiveEndpointsMap.set(ep.endpoint, ep);
4089
- }
4090
- });
4091
- [
4092
- ...requestEndpoints
4093
- ].forEach((ep) => {
4094
- if (ep && ep.endpoint) {
4095
- effectiveEndpointsMap.set(ep.endpoint, ep);
4096
- }
4358
+ if (additionalHeaders) {
4359
+ Object.assign(headers, additionalHeaders);
4360
+ }
4361
+ }
4362
+ return headers;
4363
+ }
4364
+ __name(createHeaders, "createHeaders");
4365
+
4366
+ // src/lib/runtime/remote-actions.ts
4367
+ import { CopilotKitLowLevelError as CopilotKitLowLevelError6, ResolvedCopilotKitError as ResolvedCopilotKitError3, CopilotKitError as CopilotKitError5 } from "@copilotkit/shared";
4368
+
4369
+ // src/lib/runtime/agui-action.ts
4370
+ import { parseJson as parseJson3 } from "@copilotkit/shared";
4371
+ function constructAGUIRemoteAction({ logger: logger2, messages, agentStates, agent, metaEvents, threadMetadata, nodeName }) {
4372
+ const action = {
4373
+ name: agent.agentId,
4374
+ description: agent.description,
4375
+ parameters: [],
4376
+ handler: async (_args) => {
4377
+ },
4378
+ remoteAgentHandler: async ({ actionInputsWithoutAgents, threadId }) => {
4379
+ var _a;
4380
+ logger2.debug({
4381
+ actionName: agent.agentId
4382
+ }, "Executing remote agent");
4383
+ const agentWireMessages = convertMessagesToAGUIMessage(messages);
4384
+ agent.messages = agentWireMessages;
4385
+ agent.threadId = threadId;
4386
+ telemetry_client_default.capture("oss.runtime.remote_action_executed", {
4387
+ agentExecution: true,
4388
+ type: "self-hosted",
4389
+ agentsAmount: 1
4097
4390
  });
4098
- const effectiveEndpoints = Array.from(effectiveEndpointsMap.values());
4099
- for (const config of effectiveEndpoints) {
4100
- const endpointUrl = config.endpoint;
4101
- let actionsForEndpoint = this.mcpActionCache.get(endpointUrl);
4102
- if (!actionsForEndpoint) {
4103
- let client = null;
4104
- try {
4105
- client = await this.createMCPClientImpl(config);
4106
- const tools = await client.tools();
4107
- actionsForEndpoint = convertMCPToolsToActions(tools, endpointUrl);
4108
- this.mcpActionCache.set(endpointUrl, actionsForEndpoint);
4109
- } catch (error) {
4110
- console.error(`MCP: Failed to fetch tools from endpoint ${endpointUrl}. Skipping. Error:`, error);
4111
- actionsForEndpoint = [];
4112
- this.mcpActionCache.set(endpointUrl, actionsForEndpoint);
4113
- }
4391
+ let state = {};
4392
+ if (agentStates) {
4393
+ const jsonState = agentStates.find((state2) => state2.agentName === agent.agentId);
4394
+ if (jsonState) {
4395
+ state = parseJson3(jsonState.state, {});
4114
4396
  }
4115
- requestSpecificMCPActions.push(...actionsForEndpoint || []);
4116
4397
  }
4117
- }
4118
- return [
4119
- ...configuredActions,
4120
- ...langserveFunctions,
4121
- ...remoteActions,
4122
- ...requestSpecificMCPActions
4123
- ];
4124
- }
4125
- // Add helper method to detect provider
4126
- detectProvider(serviceAdapter) {
4127
- const adapterName = serviceAdapter.constructor.name;
4128
- if (adapterName.includes("OpenAI"))
4129
- return "openai";
4130
- if (adapterName.includes("Anthropic"))
4131
- return "anthropic";
4132
- if (adapterName.includes("Google"))
4133
- return "google";
4134
- if (adapterName.includes("Groq"))
4135
- return "groq";
4136
- if (adapterName.includes("LangChain"))
4137
- return "langchain";
4138
- return void 0;
4139
- }
4140
- convertStreamingErrorToStructured(error) {
4141
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
4142
- 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") {
4143
- return new CopilotKitError5({
4144
- message: "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
4145
- code: CopilotKitErrorCode3.NETWORK_ERROR
4398
+ agent.state = state;
4399
+ const tools = actionInputsWithoutAgents.map((input) => {
4400
+ return {
4401
+ name: input.name,
4402
+ description: input.description,
4403
+ parameters: JSON.parse(input.jsonSchema)
4404
+ };
4146
4405
  });
4147
- }
4148
- 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"))) {
4149
- return new CopilotKitLowLevelError4({
4150
- error: error instanceof Error ? error : new Error(String(error)),
4151
- url: "agent streaming connection",
4152
- message: "Network error occurred during agent streaming. Please check your connection and try again."
4406
+ const forwardedProps = {
4407
+ ...(metaEvents == null ? void 0 : metaEvents.length) ? {
4408
+ command: {
4409
+ resume: (_a = metaEvents[0]) == null ? void 0 : _a.response
4410
+ }
4411
+ } : {},
4412
+ ...threadMetadata ? {
4413
+ threadMetadata
4414
+ } : {},
4415
+ ...nodeName ? {
4416
+ nodeName
4417
+ } : {}
4418
+ };
4419
+ return agent.legacy_to_be_removed_runAgentBridged({
4420
+ tools,
4421
+ forwardedProps
4153
4422
  });
4154
4423
  }
4155
- 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"))) {
4156
- return new CopilotKitError5({
4157
- message: "Agent request was cancelled",
4158
- code: CopilotKitErrorCode3.UNKNOWN
4424
+ };
4425
+ return [
4426
+ action
4427
+ ];
4428
+ }
4429
+ __name(constructAGUIRemoteAction, "constructAGUIRemoteAction");
4430
+ function convertMessagesToAGUIMessage(messages) {
4431
+ const result = [];
4432
+ for (const message of messages) {
4433
+ if (message.isTextMessage()) {
4434
+ result.push({
4435
+ id: message.id,
4436
+ role: message.role,
4437
+ content: message.content
4159
4438
  });
4160
- }
4161
- return new CopilotKitError5({
4162
- message: `Agent streaming error: ${(error == null ? void 0 : error.message) || String(error)}`,
4163
- code: CopilotKitErrorCode3.UNKNOWN
4164
- });
4165
- }
4166
- async trace(type, context, error, publicApiKey) {
4167
- if (!this.onTrace)
4168
- return;
4169
- if (!publicApiKey) {
4170
- if (!this.hasWarnedAboutTracing) {
4171
- console.warn("CopilotKit: onTrace handler provided but requires publicApiKey for tracing to work. This is a CopilotKit Cloud feature. See: https://docs.copilotkit.ai/cloud");
4172
- this.hasWarnedAboutTracing = true;
4173
- }
4174
- return;
4175
- }
4176
- try {
4177
- const traceEvent = {
4178
- type,
4179
- timestamp: Date.now(),
4180
- context,
4181
- ...error && {
4182
- error
4439
+ } else if (message.isActionExecutionMessage()) {
4440
+ const toolCall = {
4441
+ id: message.id,
4442
+ type: "function",
4443
+ function: {
4444
+ name: message.name,
4445
+ arguments: JSON.stringify(message.arguments)
4183
4446
  }
4184
4447
  };
4185
- await this.onTrace(traceEvent);
4186
- } catch (traceError) {
4187
- console.error("Error in onTrace handler:", traceError);
4188
- }
4189
- }
4190
- /**
4191
- * Public method to trace GraphQL validation errors
4192
- * This allows the GraphQL resolver to send validation errors through the trace system
4193
- */
4194
- async traceGraphQLError(error, context) {
4195
- if (!this.onTrace)
4196
- return;
4197
- try {
4198
- await this.onTrace({
4199
- type: "error",
4200
- timestamp: Date.now(),
4201
- context: {
4202
- source: "runtime",
4203
- request: {
4204
- operation: context.operation,
4205
- startTime: Date.now()
4206
- },
4207
- technical: {
4208
- environment: process.env.NODE_ENV
4209
- },
4210
- metadata: {
4211
- errorType: "GraphQLValidationError",
4212
- cloudConfigPresent: context.cloudConfigPresent,
4213
- guardrailsEnabled: context.guardrailsEnabled
4214
- }
4215
- },
4216
- error
4448
+ if (message.parentMessageId && result.some((m) => m.id === message.parentMessageId)) {
4449
+ const parentMessage = result.find((m) => m.id === message.parentMessageId);
4450
+ if (parentMessage.toolCalls === void 0) {
4451
+ parentMessage.toolCalls = [];
4452
+ }
4453
+ parentMessage.toolCalls.push(toolCall);
4454
+ } else {
4455
+ result.push({
4456
+ id: message.parentMessageId ?? message.id,
4457
+ role: "assistant",
4458
+ toolCalls: [
4459
+ toolCall
4460
+ ]
4461
+ });
4462
+ }
4463
+ } else if (message.isResultMessage()) {
4464
+ result.push({
4465
+ id: message.id,
4466
+ role: "tool",
4467
+ content: message.result,
4468
+ toolCallId: message.actionExecutionId
4217
4469
  });
4218
- } catch (traceError) {
4219
- console.error("Error in onTrace handler:", traceError);
4220
- }
4221
- }
4222
- };
4223
- __name(CopilotRuntime, "CopilotRuntime");
4224
- function flattenToolCallsNoDuplicates(toolsByPriority) {
4225
- let allTools = [];
4226
- const allToolNames = [];
4227
- for (const tool of toolsByPriority) {
4228
- if (!allToolNames.includes(tool.name)) {
4229
- allTools.push(tool);
4230
- allToolNames.push(tool.name);
4231
4470
  }
4232
4471
  }
4233
- return allTools;
4234
- }
4235
- __name(flattenToolCallsNoDuplicates, "flattenToolCallsNoDuplicates");
4236
- function copilotKitEndpoint(config) {
4237
- return {
4238
- ...config,
4239
- type: EndpointType.CopilotKit
4240
- };
4472
+ return result;
4241
4473
  }
4242
- __name(copilotKitEndpoint, "copilotKitEndpoint");
4243
- function langGraphPlatformEndpoint(config) {
4244
- return {
4245
- ...config,
4246
- type: EndpointType.LangGraphPlatform
4247
- };
4474
+ __name(convertMessagesToAGUIMessage, "convertMessagesToAGUIMessage");
4475
+
4476
+ // src/lib/runtime/remote-actions.ts
4477
+ var EndpointType;
4478
+ (function(EndpointType2) {
4479
+ EndpointType2["CopilotKit"] = "copilotKit";
4480
+ EndpointType2["LangGraphPlatform"] = "langgraph-platform";
4481
+ })(EndpointType || (EndpointType = {}));
4482
+ function isRemoteAgentAction(action) {
4483
+ if (!action) {
4484
+ return false;
4485
+ }
4486
+ return typeof action.remoteAgentHandler === "function";
4248
4487
  }
4249
- __name(langGraphPlatformEndpoint, "langGraphPlatformEndpoint");
4250
- function resolveEndpointType(endpoint) {
4251
- if (!endpoint.type) {
4252
- if ("deploymentUrl" in endpoint && "agents" in endpoint) {
4253
- return EndpointType.LangGraphPlatform;
4254
- } else {
4255
- return EndpointType.CopilotKit;
4488
+ __name(isRemoteAgentAction, "isRemoteAgentAction");
4489
+ async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: logger2, frontendUrl }) {
4490
+ logger2.debug({
4491
+ url
4492
+ }, "Fetching actions from url");
4493
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
4494
+ const fetchUrl = `${url}/info`;
4495
+ try {
4496
+ const response = await fetch(fetchUrl, {
4497
+ method: "POST",
4498
+ headers,
4499
+ body: JSON.stringify({
4500
+ properties: graphqlContext.properties,
4501
+ frontendUrl
4502
+ })
4503
+ });
4504
+ if (!response.ok) {
4505
+ logger2.error({
4506
+ url,
4507
+ status: response.status,
4508
+ body: await response.text()
4509
+ }, "Failed to fetch actions from url");
4510
+ throw new ResolvedCopilotKitError3({
4511
+ status: response.status,
4512
+ url: fetchUrl,
4513
+ isRemoteEndpoint: true
4514
+ });
4515
+ }
4516
+ const json = await response.json();
4517
+ logger2.debug({
4518
+ json
4519
+ }, "Fetched actions from url");
4520
+ return json;
4521
+ } catch (error) {
4522
+ if (error instanceof CopilotKitError5) {
4523
+ throw error;
4256
4524
  }
4525
+ throw new CopilotKitLowLevelError6({
4526
+ error,
4527
+ url: fetchUrl
4528
+ });
4257
4529
  }
4258
- return endpoint.type;
4259
4530
  }
4260
- __name(resolveEndpointType, "resolveEndpointType");
4261
-
4262
- // src/lib/telemetry-client.ts
4263
- var packageJson = require_package();
4264
- var telemetryClient = new TelemetryClient({
4265
- packageName: packageJson.name,
4266
- packageVersion: packageJson.version
4267
- });
4268
- function getRuntimeInstanceTelemetryInfo(options) {
4269
- var _a, _b;
4270
- const runtime = options.runtime;
4271
- const endpointsInfo = runtime.remoteEndpointDefinitions.reduce((acc, endpoint) => {
4272
- let info = {
4273
- ...acc
4274
- };
4275
- const endpointType = resolveEndpointType(endpoint);
4276
- if (!info.endpointTypes.includes(endpointType)) {
4277
- info = {
4278
- ...info,
4279
- endpointTypes: [
4280
- ...info.endpointTypes,
4281
- endpointType
4282
- ]
4283
- };
4284
- }
4285
- if (endpointType === EndpointType.LangGraphPlatform) {
4286
- const ep = endpoint;
4287
- info = {
4288
- ...info,
4289
- agentsAmount: ep.agents.length,
4290
- hashedKey: ep.langsmithApiKey ? createHash3("sha256").update(ep.langsmithApiKey).digest("hex") : null
4291
- };
4531
+ __name(fetchRemoteInfo, "fetchRemoteInfo");
4532
+ async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, messages, agentStates, frontendUrl, agents, metaEvents, nodeName }) {
4533
+ var _a;
4534
+ const logger2 = graphqlContext.logger.child({
4535
+ component: "remote-actions.fetchRemoteActions"
4536
+ });
4537
+ logger2.debug({
4538
+ remoteEndpointDefinitions
4539
+ }, "Fetching from remote endpoints");
4540
+ const threadMetadata = ((_a = graphqlContext.properties) == null ? void 0 : _a.threadMetadata) || {};
4541
+ const filtered = remoteEndpointDefinitions.filter((value, index, self) => {
4542
+ if (value.type === "langgraph-platform") {
4543
+ return value;
4292
4544
  }
4293
- return info;
4294
- }, {
4295
- endpointTypes: [],
4296
- agentsAmount: null,
4297
- hashedKey: null
4545
+ return index === self.findIndex((t) => t.url === value.url);
4298
4546
  });
4299
- const publicApiKey = (_a = options.cloud) == null ? void 0 : _a.publicApiKey;
4300
- const apiKeyProvided = !!publicApiKey && publicApiKey.trim().length > 0;
4301
- return {
4302
- actionsAmount: runtime.actions.length,
4303
- endpointsAmount: runtime.remoteEndpointDefinitions.length,
4304
- endpointTypes: endpointsInfo.endpointTypes,
4305
- agentsAmount: endpointsInfo.agentsAmount,
4306
- hashedLgcKey: endpointsInfo.hashedKey,
4307
- "cloud.api_key_provided": apiKeyProvided,
4308
- ...apiKeyProvided ? {
4309
- "cloud.public_api_key": publicApiKey
4310
- } : {},
4311
- ...((_b = options.cloud) == null ? void 0 : _b.baseUrl) ? {
4312
- "cloud.base_url": options.cloud.baseUrl
4313
- } : {}
4314
- };
4547
+ const result = await Promise.all(filtered.map(async (endpoint) => {
4548
+ if (endpoint.type === "langgraph-platform") {
4549
+ return constructLGCRemoteAction({
4550
+ endpoint,
4551
+ messages,
4552
+ graphqlContext,
4553
+ logger: logger2.child({
4554
+ component: "remote-actions.constructLGCRemoteAction",
4555
+ endpoint
4556
+ }),
4557
+ agentStates
4558
+ });
4559
+ }
4560
+ const json = await fetchRemoteInfo({
4561
+ url: endpoint.url,
4562
+ onBeforeRequest: endpoint.onBeforeRequest,
4563
+ graphqlContext,
4564
+ logger: logger2.child({
4565
+ component: "remote-actions.fetchActionsFromUrl",
4566
+ endpoint
4567
+ }),
4568
+ frontendUrl
4569
+ });
4570
+ return constructRemoteActions({
4571
+ json,
4572
+ messages,
4573
+ url: endpoint.url,
4574
+ onBeforeRequest: endpoint.onBeforeRequest,
4575
+ graphqlContext,
4576
+ logger: logger2.child({
4577
+ component: "remote-actions.constructActions",
4578
+ endpoint
4579
+ }),
4580
+ agentStates
4581
+ });
4582
+ }));
4583
+ for (const [key, agent] of Object.entries(agents)) {
4584
+ if (agent.agentId !== void 0 && agent.agentId !== key) {
4585
+ throw new CopilotKitError5({
4586
+ message: `Agent ${key} has agentId ${agent.agentId} which does not match the key ${key}`,
4587
+ code: CopilotKitErrorCode3.UNKNOWN
4588
+ });
4589
+ } else if (agent.agentId === void 0) {
4590
+ agent.agentId = key;
4591
+ }
4592
+ result.push(constructAGUIRemoteAction({
4593
+ logger: logger2,
4594
+ messages,
4595
+ agentStates,
4596
+ agent,
4597
+ metaEvents,
4598
+ threadMetadata,
4599
+ nodeName
4600
+ }));
4601
+ }
4602
+ return result.flat();
4315
4603
  }
4316
- __name(getRuntimeInstanceTelemetryInfo, "getRuntimeInstanceTelemetryInfo");
4317
- var telemetry_client_default = telemetryClient;
4604
+ __name(setupRemoteActions, "setupRemoteActions");
4318
4605
 
4319
4606
  // src/service-adapters/events.ts
4320
- import { plainToInstance as plainToInstance2 } from "class-transformer";
4321
4607
  var RuntimeEventTypes;
4322
4608
  (function(RuntimeEventTypes2) {
4323
4609
  RuntimeEventTypes2["TextMessageStart"] = "TextMessageStart";
@@ -4433,6 +4719,12 @@ __name(RuntimeEventSubject, "RuntimeEventSubject");
4433
4719
  var RuntimeEventSource = class {
4434
4720
  eventStream$ = new RuntimeEventSubject();
4435
4721
  callback;
4722
+ errorHandler;
4723
+ errorContext;
4724
+ constructor(params) {
4725
+ this.errorHandler = params == null ? void 0 : params.errorHandler;
4726
+ this.errorContext = params == null ? void 0 : params.errorContext;
4727
+ }
4436
4728
  async stream(callback) {
4437
4729
  this.callback = callback;
4438
4730
  }
@@ -4440,16 +4732,22 @@ var RuntimeEventSource = class {
4440
4732
  const errorMessage = `\u274C ${message}`;
4441
4733
  if (!this.callback) {
4442
4734
  this.stream(async (eventStream$) => {
4443
- eventStream$.sendTextMessage(randomId3(), errorMessage);
4735
+ eventStream$.sendTextMessage(randomId2(), errorMessage);
4444
4736
  });
4445
4737
  } else {
4446
- this.eventStream$.sendTextMessage(randomId3(), errorMessage);
4738
+ this.eventStream$.sendTextMessage(randomId2(), errorMessage);
4447
4739
  }
4448
4740
  }
4449
4741
  processRuntimeEvents({ serverSideActions, guardrailsResult$, actionInputsWithoutAgents, threadId }) {
4450
- this.callback(this.eventStream$).catch((error) => {
4451
- console.error("Error in event source callback", error);
4452
- const structuredError = convertStreamingErrorToStructured2(error);
4742
+ this.callback(this.eventStream$).catch(async (error) => {
4743
+ const structuredError = ensureStructuredError3(error, convertStreamingErrorToStructured2);
4744
+ if (this.errorHandler && this.errorContext) {
4745
+ try {
4746
+ await this.errorHandler(structuredError, this.errorContext);
4747
+ } catch (errorHandlerError) {
4748
+ console.error("Error in streaming error handler:", errorHandlerError);
4749
+ }
4750
+ }
4453
4751
  this.eventStream$.error(structuredError);
4454
4752
  this.eventStream$.complete();
4455
4753
  });
@@ -4484,12 +4782,23 @@ var RuntimeEventSource = class {
4484
4782
  if (eventWithState.event.type === "ActionExecutionEnd" && eventWithState.callActionServerSide) {
4485
4783
  const toolCallEventStream$ = new RuntimeEventSubject();
4486
4784
  executeAction(toolCallEventStream$, guardrailsResult$ ? guardrailsResult$ : null, eventWithState.action, eventWithState.args, eventWithState.actionExecutionParentMessageId, eventWithState.actionExecutionId, actionInputsWithoutAgents, threadId).catch((error) => {
4487
- console.error(error);
4488
4785
  });
4489
4786
  telemetry_client_default.capture("oss.runtime.server_action_executed", {});
4490
4787
  return concat(of(eventWithState.event), toolCallEventStream$).pipe(catchError2((error) => {
4491
- console.error("Error in tool call stream", error);
4492
- const structuredError = convertStreamingErrorToStructured2(error);
4788
+ const structuredError = ensureStructuredError3(error, convertStreamingErrorToStructured2);
4789
+ if (this.errorHandler && this.errorContext) {
4790
+ from2(this.errorHandler(structuredError, {
4791
+ ...this.errorContext,
4792
+ action: {
4793
+ name: eventWithState.action.name,
4794
+ executionId: eventWithState.actionExecutionId
4795
+ }
4796
+ })).subscribe({
4797
+ error: (errorHandlerError) => {
4798
+ console.error("Error in action execution error handler:", errorHandlerError);
4799
+ }
4800
+ });
4801
+ }
4493
4802
  toolCallEventStream$.sendActionExecutionResult({
4494
4803
  actionExecutionId: eventWithState.actionExecutionId,
4495
4804
  actionName: eventWithState.action.name,
@@ -4569,8 +4878,7 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
4569
4878
  from2(stream).subscribe({
4570
4879
  next: (event) => eventStream$.next(event),
4571
4880
  error: (err) => {
4572
- console.error("Error in stream", err);
4573
- const structuredError = convertStreamingErrorToStructured2(err);
4881
+ const structuredError = ensureStructuredError3(err, convertStreamingErrorToStructured2);
4574
4882
  eventStream$.sendActionExecutionResult({
4575
4883
  actionExecutionId,
4576
4884
  actionName: action.name,
@@ -4610,36 +4918,19 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
4610
4918
  }
4611
4919
  __name(executeAction, "executeAction");
4612
4920
  function convertStreamingErrorToStructured2(error) {
4613
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
4614
- 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") {
4615
- return new CopilotKitError6({
4616
- message: "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
4617
- code: CopilotKitErrorCode4.NETWORK_ERROR
4618
- });
4619
- }
4620
- 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"))) {
4621
- return new CopilotKitLowLevelError5({
4921
+ var _a, _b, _c, _d, _e, _f, _g;
4922
+ let helpfulMessage = generateHelpfulErrorMessage(error, "event streaming connection");
4923
+ if (((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.includes("fetch failed")) || ((_b = error == null ? void 0 : error.message) == null ? void 0 : _b.includes("ECONNREFUSED")) || ((_c = error == null ? void 0 : error.message) == null ? void 0 : _c.includes("ENOTFOUND")) || ((_d = error == null ? void 0 : error.message) == null ? void 0 : _d.includes("ETIMEDOUT")) || ((_e = error == null ? void 0 : error.message) == null ? void 0 : _e.includes("terminated")) || ((_f = error == null ? void 0 : error.cause) == null ? void 0 : _f.code) === "UND_ERR_SOCKET" || ((_g = error == null ? void 0 : error.message) == null ? void 0 : _g.includes("other side closed")) || (error == null ? void 0 : error.code) === "UND_ERR_SOCKET") {
4924
+ return new CopilotKitLowLevelError7({
4622
4925
  error: error instanceof Error ? error : new Error(String(error)),
4623
4926
  url: "event streaming connection",
4624
- message: "Network error occurred during event streaming. Please check your connection and try again."
4625
- });
4626
- }
4627
- 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"))) {
4628
- return new CopilotKitError6({
4629
- message: "Request was cancelled",
4630
- code: CopilotKitErrorCode4.UNKNOWN
4631
- });
4632
- }
4633
- const errorMessage = (error == null ? void 0 : error.message) || String(error);
4634
- if (errorMessage.includes("401") || errorMessage.toLowerCase().includes("api key") || errorMessage.toLowerCase().includes("unauthorized") || errorMessage.toLowerCase().includes("authentication") || errorMessage.toLowerCase().includes("incorrect api key")) {
4635
- return new CopilotKitError6({
4636
- message: `Event streaming error: ${errorMessage}`,
4637
- code: CopilotKitErrorCode4.MISSING_PUBLIC_API_KEY_ERROR
4927
+ message: helpfulMessage
4638
4928
  });
4639
4929
  }
4640
4930
  return new CopilotKitError6({
4641
- message: `Event streaming error: ${errorMessage}`,
4642
- code: CopilotKitErrorCode4.UNKNOWN
4931
+ message: helpfulMessage,
4932
+ code: CopilotKitErrorCode4.UNKNOWN,
4933
+ severity: Severity.CRITICAL
4643
4934
  });
4644
4935
  }
4645
4936
  __name(convertStreamingErrorToStructured2, "convertStreamingErrorToStructured");
@@ -4648,7 +4939,7 @@ __name(convertStreamingErrorToStructured2, "convertStreamingErrorToStructured");
4648
4939
  import { GraphQLJSONObject } from "graphql-scalars";
4649
4940
  import { plainToInstance as plainToInstance3 } from "class-transformer";
4650
4941
  import { GraphQLError } from "graphql";
4651
- import { randomId as randomId4 } from "@copilotkit/shared";
4942
+ import { randomId as randomId3 } from "@copilotkit/shared";
4652
4943
 
4653
4944
  // src/graphql/types/agents-response.type.ts
4654
4945
  import { Field as Field16, ObjectType as ObjectType5 } from "type-graphql";
@@ -4704,7 +4995,7 @@ AgentsResponse = _ts_decorate16([
4704
4995
  ], AgentsResponse);
4705
4996
 
4706
4997
  // src/graphql/resolvers/copilot.resolver.ts
4707
- import { CopilotKitError as CopilotKitError7 } from "@copilotkit/shared";
4998
+ import { CopilotKitError as CopilotKitError7, CopilotKitLowLevelError as CopilotKitLowLevelError8, isStructuredCopilotKitError as isStructuredCopilotKitError2 } from "@copilotkit/shared";
4708
4999
  function _ts_decorate17(decorators, target, key, desc) {
4709
5000
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4710
5001
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -4774,7 +5065,7 @@ var CopilotResolver = class {
4774
5065
  };
4775
5066
  }
4776
5067
  async generateCopilotResponse(ctx, data, properties) {
4777
- var _a, _b, _c, _d, _e;
5068
+ var _a, _b, _c, _d, _e, _f, _g;
4778
5069
  telemetry_client_default.capture("oss.runtime.copilot_request_created", {
4779
5070
  "cloud.guardrails.enabled": ((_a = data.cloud) == null ? void 0 : _a.guardrails) !== void 0,
4780
5071
  requestType: data.metadata.requestType,
@@ -4816,7 +5107,7 @@ var CopilotResolver = class {
4816
5107
  logger2.debug("Cloud configuration provided, checking for public API key in headers");
4817
5108
  if (!copilotCloudPublicApiKey) {
4818
5109
  logger2.error("Public API key not found in headers");
4819
- await copilotRuntime.traceGraphQLError({
5110
+ await copilotRuntime.errorGraphQLError({
4820
5111
  message: "X-CopilotCloud-Public-API-Key header is required",
4821
5112
  code: "MISSING_PUBLIC_API_KEY",
4822
5113
  type: "GraphQLError"
@@ -4853,26 +5144,41 @@ var CopilotResolver = class {
4853
5144
  ctx.properties["copilotCloudPublicApiKey"] = copilotCloudPublicApiKey;
4854
5145
  }
4855
5146
  logger2.debug("Processing");
4856
- const { eventSource, threadId = randomId4(), runId, serverSideActions, actionInputsWithoutAgents, extensions } = await copilotRuntime.processRuntimeRequest({
4857
- serviceAdapter,
4858
- messages: data.messages,
4859
- actions: data.frontend.actions.filter((action) => action.available !== ActionInputAvailability.disabled),
4860
- threadId: data.threadId,
4861
- runId: data.runId,
4862
- publicApiKey: copilotCloudPublicApiKey,
4863
- outputMessagesPromise,
4864
- graphqlContext: ctx,
4865
- forwardedParameters: data.forwardedParameters,
4866
- agentSession: data.agentSession,
4867
- agentStates: data.agentStates,
4868
- url: data.frontend.url,
4869
- extensions: data.extensions,
4870
- metaEvents: data.metaEvents
4871
- });
5147
+ let runtimeResponse;
5148
+ try {
5149
+ runtimeResponse = await copilotRuntime.processRuntimeRequest({
5150
+ serviceAdapter,
5151
+ messages: data.messages,
5152
+ actions: data.frontend.actions.filter((action) => action.available !== ActionInputAvailability.disabled),
5153
+ threadId: data.threadId,
5154
+ runId: data.runId,
5155
+ publicApiKey: copilotCloudPublicApiKey,
5156
+ outputMessagesPromise,
5157
+ graphqlContext: ctx,
5158
+ forwardedParameters: data.forwardedParameters,
5159
+ agentSession: data.agentSession,
5160
+ agentStates: data.agentStates,
5161
+ url: data.frontend.url,
5162
+ extensions: data.extensions,
5163
+ metaEvents: data.metaEvents
5164
+ });
5165
+ } catch (error) {
5166
+ if (isStructuredCopilotKitError2(error) || ((_e = error == null ? void 0 : error.extensions) == null ? void 0 : _e.visibility)) {
5167
+ throw new GraphQLError(error.message || "Agent error occurred", {
5168
+ extensions: {
5169
+ ...error.extensions,
5170
+ code: error.code || ((_f = error.extensions) == null ? void 0 : _f.code) || "AGENT_ERROR",
5171
+ originalError: error
5172
+ }
5173
+ });
5174
+ }
5175
+ throw error;
5176
+ }
5177
+ const { eventSource, threadId = randomId3(), runId, serverSideActions, actionInputsWithoutAgents, extensions } = runtimeResponse;
4872
5178
  logger2.debug("Event source created, creating response");
4873
5179
  const eventStream = eventSource.processRuntimeEvents({
4874
5180
  serverSideActions,
4875
- guardrailsResult$: ((_e = data.cloud) == null ? void 0 : _e.guardrails) ? guardrailsResult$ : null,
5181
+ guardrailsResult$: ((_g = data.cloud) == null ? void 0 : _g.guardrails) ? guardrailsResult$ : null,
4876
5182
  actionInputsWithoutAgents: actionInputsWithoutAgents.filter(
4877
5183
  // TODO-AGENTS: do not exclude ALL server side actions
4878
5184
  (action) => !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name)
@@ -4953,12 +5259,16 @@ var CopilotResolver = class {
4953
5259
  }
4954
5260
  },
4955
5261
  error: (err) => {
4956
- logger2.error({
4957
- err
4958
- }, "Error in meta events stream");
4959
- responseStatus$.next(new UnknownErrorResponse({
4960
- description: `An unknown error has occurred in the event stream`
4961
- }));
5262
+ var _a2, _b2;
5263
+ if (((_a2 = err == null ? void 0 : err.name) == null ? void 0 : _a2.includes("CopilotKit")) || ((_b2 = err == null ? void 0 : err.extensions) == null ? void 0 : _b2.visibility)) {
5264
+ responseStatus$.next(new UnknownErrorResponse({
5265
+ description: err.message || "Agent error occurred"
5266
+ }));
5267
+ } else {
5268
+ responseStatus$.next(new UnknownErrorResponse({
5269
+ description: `An unknown error has occurred in the event stream`
5270
+ }));
5271
+ }
4962
5272
  eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
4963
5273
  stop();
4964
5274
  },
@@ -4996,7 +5306,7 @@ var CopilotResolver = class {
4996
5306
  });
4997
5307
  outputMessages = [
4998
5308
  plainToInstance3(TextMessage, {
4999
- id: randomId4(),
5309
+ id: randomId3(),
5000
5310
  createdAt: /* @__PURE__ */ new Date(),
5001
5311
  content: result.reason,
5002
5312
  role: MessageRole.assistant
@@ -5174,7 +5484,7 @@ var CopilotResolver = class {
5174
5484
  event
5175
5485
  }, "Agent message event received");
5176
5486
  pushMessage({
5177
- id: randomId4(),
5487
+ id: randomId3(),
5178
5488
  status: new SuccessMessageStatus(),
5179
5489
  threadId: event.threadId,
5180
5490
  agentName: event.agentName,
@@ -5187,7 +5497,7 @@ var CopilotResolver = class {
5187
5497
  createdAt: /* @__PURE__ */ new Date()
5188
5498
  });
5189
5499
  outputMessages.push(plainToInstance3(AgentStateMessage, {
5190
- id: randomId4(),
5500
+ id: randomId3(),
5191
5501
  threadId: event.threadId,
5192
5502
  agentName: event.agentName,
5193
5503
  nodeName: event.nodeName,
@@ -5202,13 +5512,23 @@ var CopilotResolver = class {
5202
5512
  }
5203
5513
  },
5204
5514
  error: (err) => {
5205
- logger2.error({
5206
- err
5207
- }, "Error in event stream");
5208
- if (err instanceof CopilotKitError7 || err instanceof Error && err.name && err.name.includes("CopilotKit")) {
5515
+ var _a3, _b2, _c2, _d2, _e2, _f2;
5516
+ if (err instanceof CopilotKitError7 || err instanceof CopilotKitLowLevelError8 || err instanceof Error && err.name && err.name.includes("CopilotKit") || ((_a3 = err == null ? void 0 : err.extensions) == null ? void 0 : _a3.visibility)) {
5517
+ responseStatus$.next(new UnknownErrorResponse({
5518
+ description: err.message || "Agent error occurred",
5519
+ // Include original error information for frontend to extract
5520
+ originalError: {
5521
+ code: err.code || ((_b2 = err.extensions) == null ? void 0 : _b2.code),
5522
+ statusCode: err.statusCode || ((_c2 = err.extensions) == null ? void 0 : _c2.statusCode),
5523
+ severity: err.severity || ((_d2 = err.extensions) == null ? void 0 : _d2.severity),
5524
+ visibility: err.visibility || ((_e2 = err.extensions) == null ? void 0 : _e2.visibility),
5525
+ originalErrorType: err.originalErrorType || ((_f2 = err.extensions) == null ? void 0 : _f2.originalErrorType),
5526
+ extensions: err.extensions
5527
+ }
5528
+ }));
5209
5529
  eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
5210
5530
  rejectOutputMessagesPromise(err);
5211
- stopStreamingMessages(err);
5531
+ stopStreamingMessages();
5212
5532
  return;
5213
5533
  }
5214
5534
  responseStatus$.next(new UnknownErrorResponse({
@@ -5446,6 +5766,7 @@ StateResolver = _ts_decorate20([
5446
5766
 
5447
5767
  // src/lib/integrations/shared.ts
5448
5768
  var packageJson2 = __toESM(require_package());
5769
+ import { CopilotKitError as CopilotKitError8, CopilotKitErrorCode as CopilotKitErrorCode5 } from "@copilotkit/shared";
5449
5770
  var logger = createLogger();
5450
5771
  var addCustomHeaderPlugin = {
5451
5772
  onResponse({ response }) {
@@ -5510,6 +5831,13 @@ function getCommonConfig(options) {
5510
5831
  serviceAdapter: options.serviceAdapter.constructor.name
5511
5832
  }
5512
5833
  });
5834
+ const userErrorCodes = [
5835
+ CopilotKitErrorCode5.AGENT_NOT_FOUND,
5836
+ CopilotKitErrorCode5.API_NOT_FOUND,
5837
+ CopilotKitErrorCode5.REMOTE_ENDPOINT_NOT_FOUND,
5838
+ CopilotKitErrorCode5.CONFIGURATION_ERROR,
5839
+ CopilotKitErrorCode5.MISSING_PUBLIC_API_KEY_ERROR
5840
+ ];
5513
5841
  return {
5514
5842
  logging: createLogger({
5515
5843
  component: "Yoga GraphQL",
@@ -5520,7 +5848,25 @@ function getCommonConfig(options) {
5520
5848
  useDeferStream(),
5521
5849
  addCustomHeaderPlugin
5522
5850
  ],
5523
- context: (ctx) => createContext(ctx, options, contextLogger, options.properties)
5851
+ context: (ctx) => createContext(ctx, options, contextLogger, options.properties),
5852
+ // Suppress logging for user configuration errors
5853
+ maskedErrors: {
5854
+ maskError: (error, message, isDev) => {
5855
+ const originalError = error.originalError || error;
5856
+ const extensions = error.extensions;
5857
+ const errorCode = extensions == null ? void 0 : extensions.code;
5858
+ if (errorCode && userErrorCodes.includes(errorCode)) {
5859
+ console.debug("User configuration error:", error.message);
5860
+ return error;
5861
+ }
5862
+ if (originalError instanceof CopilotKitError8 && userErrorCodes.includes(originalError.code)) {
5863
+ console.debug("User configuration error:", error.message);
5864
+ return error;
5865
+ }
5866
+ console.error("Application error:", error);
5867
+ return error;
5868
+ }
5869
+ }
5524
5870
  };
5525
5871
  }
5526
5872
  __name(getCommonConfig, "getCommonConfig");
@@ -5569,4 +5915,4 @@ export {
5569
5915
  getCommonConfig,
5570
5916
  copilotRuntimeNodeHttpEndpoint
5571
5917
  };
5572
- //# sourceMappingURL=chunk-WIXS6EG7.mjs.map
5918
+ //# sourceMappingURL=chunk-TE5QWP4H.mjs.map