@copilotkit/runtime 1.9.2-next.0 → 1.9.2-next.10

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 (84) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/dist/{chunk-O6KXX5R5.mjs → chunk-5OK4GLKL.mjs} +19 -2
  3. package/dist/chunk-5OK4GLKL.mjs.map +1 -0
  4. package/dist/{chunk-44FYLJJJ.mjs → chunk-6RUTA76W.mjs} +2 -2
  5. package/dist/chunk-AMUJQ6IR.mjs +50 -0
  6. package/dist/chunk-AMUJQ6IR.mjs.map +1 -0
  7. package/dist/{chunk-IIXJVVTV.mjs → chunk-GS7DO47Q.mjs} +155 -78
  8. package/dist/chunk-GS7DO47Q.mjs.map +1 -0
  9. package/dist/{chunk-YMIOUUPV.mjs → chunk-PMIAGZGS.mjs} +2374 -1855
  10. package/dist/chunk-PMIAGZGS.mjs.map +1 -0
  11. package/dist/{chunk-ESXPDYNT.mjs → chunk-TOBFVWZU.mjs} +2 -2
  12. package/dist/{chunk-YXL4PSJM.mjs → chunk-VBXBFZEL.mjs} +2 -2
  13. package/dist/{chunk-5BIEM2UU.mjs → chunk-XWBDEXDA.mjs} +4 -3
  14. package/dist/{chunk-5BIEM2UU.mjs.map → chunk-XWBDEXDA.mjs.map} +1 -1
  15. package/dist/{groq-adapter-25a2bd35.d.ts → groq-adapter-172a2ca4.d.ts} +1 -1
  16. package/dist/index.d.ts +4 -3
  17. package/dist/index.js +3765 -3108
  18. package/dist/index.js.map +1 -1
  19. package/dist/index.mjs +12 -8
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/lib/index.d.ts +7 -133
  22. package/dist/lib/index.js +3357 -2743
  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 +162 -98
  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 +162 -98
  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 +162 -98
  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 +162 -98
  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 +225 -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-e272b15a.d.ts → shared-bd953ebf.d.ts} +45 -5
  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 +4 -4
  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 +108 -45
  59. package/src/graphql/resolvers/state.resolver.ts +3 -3
  60. package/src/lib/error-messages.ts +200 -0
  61. package/src/lib/integrations/shared.ts +43 -0
  62. package/src/lib/runtime/__tests__/copilot-runtime-trace.test.ts +169 -0
  63. package/src/lib/runtime/copilot-runtime.ts +420 -83
  64. package/src/lib/runtime/langgraph/langgraph-agent.ts +12 -0
  65. package/src/lib/runtime/remote-action-constructors.ts +28 -3
  66. package/src/lib/runtime/remote-lg-action.ts +130 -40
  67. package/src/lib/streaming.ts +125 -36
  68. package/src/service-adapters/anthropic/anthropic-adapter.ts +67 -8
  69. package/src/service-adapters/anthropic/utils.ts +3 -8
  70. package/src/service-adapters/events.ts +37 -81
  71. package/src/service-adapters/groq/groq-adapter.ts +66 -56
  72. package/src/service-adapters/index.ts +1 -0
  73. package/src/service-adapters/openai/openai-adapter.ts +18 -3
  74. package/src/service-adapters/shared/error-utils.ts +61 -0
  75. package/src/service-adapters/shared/index.ts +1 -0
  76. package/src/utils/failed-response-status-reasons.ts +23 -1
  77. package/tests/service-adapters/anthropic/anthropic-adapter.test.ts +172 -387
  78. package/dist/chunk-IIXJVVTV.mjs.map +0 -1
  79. package/dist/chunk-O6KXX5R5.mjs.map +0 -1
  80. package/dist/chunk-YMIOUUPV.mjs.map +0 -1
  81. package/dist/{chunk-44FYLJJJ.mjs.map → chunk-6RUTA76W.mjs.map} +0 -0
  82. package/dist/{chunk-ESXPDYNT.mjs.map → chunk-TOBFVWZU.mjs.map} +0 -0
  83. package/dist/{chunk-YXL4PSJM.mjs.map → chunk-VBXBFZEL.mjs.map} +0 -0
  84. package/dist/{langserve-4a5c9217.d.ts → langserve-fc5cac89.d.ts} +7 -7
@@ -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-GS7DO47Q.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.0",
43
+ version: "1.9.2-next.10",
44
44
  sideEffects: false,
45
45
  main: "./dist/index.js",
46
46
  module: "./dist/index.mjs",
@@ -81,7 +81,7 @@ var require_package = __commonJS({
81
81
  "@ag-ui/client": "0.0.28",
82
82
  "@ag-ui/core": "0.0.28",
83
83
  "@ag-ui/encoder": "0.0.28",
84
- "@ag-ui/langgraph": "0.0.3",
84
+ "@ag-ui/langgraph": "0.0.4",
85
85
  "@ag-ui/proto": "0.0.28",
86
86
  "@anthropic-ai/sdk": "^0.27.3",
87
87
  "@copilotkit/shared": "workspace:*",
@@ -105,7 +105,7 @@ var require_package = __commonJS({
105
105
  pino: "^9.2.0",
106
106
  "pino-pretty": "^11.2.1",
107
107
  "reflect-metadata": "^0.2.2",
108
- rxjs: "^7.8.1",
108
+ rxjs: "7.8.1",
109
109
  "type-graphql": "2.0.0-rc.1",
110
110
  zod: "^3.23.3"
111
111
  },
@@ -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,327 +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
1854
- var activeInterruptEvent = false;
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");
1855
1949
  async function execute(args) {
1856
1950
  return new ReadableStream({
1857
1951
  async start(controller) {
@@ -1882,6 +1976,9 @@ async function execute(args) {
1882
1976
  See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
1883
1977
  });
1884
1978
  } else {
1979
+ if (lastError instanceof CopilotKitError2 || lastError instanceof CopilotKitLowLevelError2 || lastError instanceof Error && lastError.name && lastError.name.includes("CopilotKit")) {
1980
+ throw lastError;
1981
+ }
1885
1982
  throw new CopilotKitMisuseError({
1886
1983
  message: `
1887
1984
  The LangGraph client threw unhandled error ${lastError}.
@@ -1894,7 +1991,7 @@ async function execute(args) {
1894
1991
  }
1895
1992
  __name(execute, "execute");
1896
1993
  async function streamEvents(controller, args) {
1897
- var _a, _b, _c, _d, _e, _f, _g, _h;
1994
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
1898
1995
  const { deploymentUrl, langsmithApiKey, threadId: argsInitialThreadId, agent, nodeName: initialNodeName, state: initialState, config: explicitConfig, messages, actions, logger: logger2, properties, metaEvents } = args;
1899
1996
  let nodeName = initialNodeName;
1900
1997
  let state = initialState;
@@ -1952,18 +2049,14 @@ async function streamEvents(controller, args) {
1952
2049
  command: void 0
1953
2050
  };
1954
2051
  const lgInterruptMetaEvent = metaEvents == null ? void 0 : metaEvents.find((ev) => ev.name === MetaEventName.LangGraphInterruptEvent);
1955
- if (activeInterruptEvent && !lgInterruptMetaEvent) {
1956
- payload.command = {
1957
- resume: state.messages
1958
- };
1959
- }
1960
2052
  if (lgInterruptMetaEvent == null ? void 0 : lgInterruptMetaEvent.response) {
1961
2053
  let response = lgInterruptMetaEvent.response;
1962
2054
  payload.command = {
1963
2055
  resume: parseJson(response, response)
1964
2056
  };
1965
2057
  }
1966
- if (mode === "continue" && !activeInterruptEvent) {
2058
+ const interrupts = ((_b = (_a = agentState.tasks) == null ? void 0 : _a[0]) == null ? void 0 : _b.interrupts) ?? [];
2059
+ if (mode === "continue" && !interrupts.length) {
1967
2060
  await client.threads.updateState(threadId, {
1968
2061
  values: state,
1969
2062
  asNode: nodeName
@@ -2025,12 +2118,23 @@ async function streamEvents(controller, args) {
2025
2118
  let emitIntermediateStateUntilEnd = null;
2026
2119
  let shouldExit = false;
2027
2120
  let externalRunId = null;
2028
- const streamResponse = client.runs.stream(threadId, assistantId, payload);
2029
2121
  const emit = /* @__PURE__ */ __name((message) => controller.enqueue(new TextEncoder().encode(message)), "emit");
2122
+ if ((interrupts == null ? void 0 : interrupts.length) && !((_c = payload.command) == null ? void 0 : _c.resume)) {
2123
+ if (!lgInterruptMetaEvent) {
2124
+ payload.command = {
2125
+ resume: state.messages
2126
+ };
2127
+ } else {
2128
+ interrupts.forEach((interrupt) => {
2129
+ emitInterrupt(interrupt.value, emit);
2130
+ });
2131
+ return Promise.resolve();
2132
+ }
2133
+ }
2134
+ const streamResponse = client.runs.stream(threadId, assistantId, payload);
2030
2135
  let latestStateValues = {};
2031
2136
  let updatedState = state;
2032
2137
  let manuallyEmittedState = null;
2033
- activeInterruptEvent = false;
2034
2138
  try {
2035
2139
  telemetry_client_default.capture("oss.runtime.agent_execution_stream_started", {
2036
2140
  hashedLgcKey: streamInfo.hashedLgcKey
@@ -2044,28 +2148,36 @@ async function streamEvents(controller, args) {
2044
2148
  ].includes(streamResponseChunk.event))
2045
2149
  continue;
2046
2150
  if (streamResponseChunk.event === "error") {
2047
- 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
+ });
2048
2175
  }
2049
2176
  const chunk = streamResponseChunk;
2050
2177
  const interruptEvents = chunk.data.__interrupt__;
2051
2178
  if (interruptEvents == null ? void 0 : interruptEvents.length) {
2052
- activeInterruptEvent = true;
2053
2179
  const interruptValue = interruptEvents == null ? void 0 : interruptEvents[0].value;
2054
- if (typeof interruptValue != "string" && "__copilotkit_interrupt_value__" in interruptValue) {
2055
- const evValue = interruptValue.__copilotkit_interrupt_value__;
2056
- emit(JSON.stringify({
2057
- event: LangGraphEventTypes.OnCopilotKitInterrupt,
2058
- data: {
2059
- value: typeof evValue === "string" ? evValue : JSON.stringify(evValue),
2060
- messages: langchainMessagesToCopilotKit(interruptValue.__copilotkit_messages__)
2061
- }
2062
- }) + "\n");
2063
- } else {
2064
- emit(JSON.stringify({
2065
- event: LangGraphEventTypes.OnInterrupt,
2066
- value: typeof interruptValue === "string" ? interruptValue : JSON.stringify(interruptValue)
2067
- }) + "\n");
2068
- }
2180
+ emitInterrupt(interruptValue, emit);
2069
2181
  continue;
2070
2182
  }
2071
2183
  if (streamResponseChunk.event === "updates")
@@ -2080,8 +2192,8 @@ async function streamEvents(controller, args) {
2080
2192
  const runId = chunkData.metadata.run_id;
2081
2193
  externalRunId = runId;
2082
2194
  const metadata = chunkData.metadata;
2083
- if (((_b = (_a = chunkData.data) == null ? void 0 : _a.output) == null ? void 0 : _b.model) != null && ((_d = (_c = chunkData.data) == null ? void 0 : _c.output) == null ? void 0 : _d.model) != "") {
2084
- streamInfo.provider = (_f = (_e = chunkData.data) == null ? void 0 : _e.output) == null ? void 0 : _f.model;
2195
+ if (((_e = (_d = chunkData.data) == null ? void 0 : _d.output) == null ? void 0 : _e.model) != null && ((_g = (_f = chunkData.data) == null ? void 0 : _f.output) == null ? void 0 : _g.model) != "") {
2196
+ streamInfo.provider = (_i = (_h = chunkData.data) == null ? void 0 : _h.output) == null ? void 0 : _i.model;
2085
2197
  }
2086
2198
  if (metadata.langgraph_host != null && metadata.langgraph_host != "") {
2087
2199
  streamInfo.langGraphHost = metadata.langgraph_host;
@@ -2152,9 +2264,9 @@ async function streamEvents(controller, args) {
2152
2264
  emit(JSON.stringify(chunkData) + "\n");
2153
2265
  }
2154
2266
  state = await client.threads.getState(threadId);
2155
- const interrupts = (_h = (_g = state.tasks) == null ? void 0 : _g[0]) == null ? void 0 : _h.interrupts;
2156
- nodeName = interrupts ? nodeName : Object.keys(state.metadata.writes)[0];
2157
- const isEndNode = state.next.length === 0 && !interrupts;
2267
+ const interrupts2 = (_k = (_j = state.tasks) == null ? void 0 : _j[0]) == null ? void 0 : _k.interrupts;
2268
+ nodeName = interrupts2 ? nodeName : Object.keys(state.metadata.writes)[0];
2269
+ const isEndNode = state.next.length === 0 && !interrupts2;
2158
2270
  telemetry_client_default.capture("oss.runtime.agent_execution_stream_ended", streamInfo);
2159
2271
  emit(getStateSyncEvent({
2160
2272
  threadId,
@@ -2169,11 +2281,21 @@ async function streamEvents(controller, args) {
2169
2281
  }));
2170
2282
  return Promise.resolve();
2171
2283
  } catch (e) {
2172
- 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
+ }
2173
2292
  telemetry_client_default.capture("oss.runtime.agent_execution_stream_errored", {
2174
2293
  ...streamInfo,
2175
2294
  error: e.message
2176
2295
  });
2296
+ if (e instanceof CopilotKitError2 || e instanceof CopilotKitLowLevelError2 || e instanceof Error && e.name && e.name.includes("CopilotKit")) {
2297
+ throw e;
2298
+ }
2177
2299
  return Promise.resolve();
2178
2300
  }
2179
2301
  }
@@ -2486,195 +2608,530 @@ function filterObjectBySchemaKeys(obj, schemaKeys) {
2486
2608
  return Object.fromEntries(Object.entries(obj).filter(([key]) => schemaKeys.includes(key)));
2487
2609
  }
2488
2610
  __name(filterObjectBySchemaKeys, "filterObjectBySchemaKeys");
2489
-
2490
- // src/lib/runtime/remote-action-constructors.ts
2491
- import { CopilotKitError as CopilotKitError3, CopilotKitLowLevelError as CopilotKitLowLevelError2 } from "@copilotkit/shared";
2492
-
2493
- // src/lib/streaming.ts
2494
- import { CopilotKitLowLevelError, CopilotKitError as CopilotKitError2, CopilotKitErrorCode } from "@copilotkit/shared";
2495
- async function writeJsonLineResponseToEventStream(response, eventStream$) {
2496
- const reader = response.getReader();
2497
- const decoder = new TextDecoder();
2498
- let buffer = [];
2499
- function flushBuffer() {
2500
- const currentBuffer = buffer.join("");
2501
- if (currentBuffer.trim().length === 0) {
2502
- return;
2503
- }
2504
- const parts = currentBuffer.split("\n");
2505
- if (parts.length === 0) {
2506
- return;
2507
- }
2508
- const lastPartIsComplete = currentBuffer.endsWith("\n");
2509
- buffer = [];
2510
- if (!lastPartIsComplete) {
2511
- buffer.push(parts.pop());
2512
- }
2513
- parts.map((part) => part.trim()).filter((part) => part != "").forEach((part) => {
2514
- eventStream$.next(JSON.parse(part));
2515
- });
2516
- }
2517
- __name(flushBuffer, "flushBuffer");
2518
- try {
2519
- while (true) {
2520
- const { done, value } = await reader.read();
2521
- if (!done) {
2522
- buffer.push(decoder.decode(value, {
2523
- stream: true
2524
- }));
2525
- }
2526
- flushBuffer();
2527
- if (done) {
2528
- break;
2611
+ function emitInterrupt(interruptValue, emit) {
2612
+ if (typeof interruptValue != "string" && "__copilotkit_interrupt_value__" in interruptValue) {
2613
+ const evValue = interruptValue.__copilotkit_interrupt_value__;
2614
+ emit(JSON.stringify({
2615
+ event: LangGraphEventTypes.OnCopilotKitInterrupt,
2616
+ data: {
2617
+ value: typeof evValue === "string" ? evValue : JSON.stringify(evValue),
2618
+ messages: langchainMessagesToCopilotKit(interruptValue.__copilotkit_messages__)
2529
2619
  }
2530
- }
2531
- } catch (error) {
2532
- console.error("Error in stream", error);
2533
- const structuredError = convertStreamingErrorToStructured(error);
2534
- eventStream$.error(structuredError);
2535
- return;
2620
+ }) + "\n");
2621
+ } else {
2622
+ emit(JSON.stringify({
2623
+ event: LangGraphEventTypes.OnInterrupt,
2624
+ value: typeof interruptValue === "string" ? interruptValue : JSON.stringify(interruptValue)
2625
+ }) + "\n");
2536
2626
  }
2537
- eventStream$.complete();
2538
2627
  }
2539
- __name(writeJsonLineResponseToEventStream, "writeJsonLineResponseToEventStream");
2540
- function convertStreamingErrorToStructured(error) {
2541
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2542
- if (((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.includes("terminated")) || ((_b = error == null ? void 0 : error.cause) == null ? void 0 : _b.code) === "UND_ERR_SOCKET" || ((_c = error == null ? void 0 : error.message) == null ? void 0 : _c.includes("other side closed")) || (error == null ? void 0 : error.code) === "UND_ERR_SOCKET") {
2543
- return new CopilotKitError2({
2544
- message: "Connection to agent was unexpectedly terminated. This is likely due to the agent service being down or experiencing issues. Please check your agent logs and try again.",
2545
- code: CopilotKitErrorCode.NETWORK_ERROR
2546
- });
2547
- }
2548
- if (((_d = error == null ? void 0 : error.message) == null ? void 0 : _d.includes("fetch failed")) || ((_e = error == null ? void 0 : error.message) == null ? void 0 : _e.includes("ECONNREFUSED")) || ((_f = error == null ? void 0 : error.message) == null ? void 0 : _f.includes("ENOTFOUND")) || ((_g = error == null ? void 0 : error.message) == null ? void 0 : _g.includes("ETIMEDOUT"))) {
2549
- return new CopilotKitLowLevelError({
2550
- error: error instanceof Error ? error : new Error(String(error)),
2551
- url: "streaming connection",
2552
- message: "Network error occurred during streaming. Please check your connection and try again."
2553
- });
2628
+ __name(emitInterrupt, "emitInterrupt");
2629
+
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 = (schema == null ? void 0 : schema.parameters) || ((_a = schema == null ? void 0 : schema.parameters) == null ? void 0 : _a.jsonSchema);
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;
2554
2640
  }
2555
- if (((_h = error == null ? void 0 : error.message) == null ? void 0 : _h.includes("aborted")) || ((_i = error == null ? void 0 : error.message) == null ? void 0 : _i.includes("canceled")) || ((_j = error == null ? void 0 : error.message) == null ? void 0 : _j.includes("signal is aborted"))) {
2556
- return new CopilotKitError2({
2557
- message: "Request was cancelled",
2558
- code: CopilotKitErrorCode.UNKNOWN
2559
- });
2641
+ for (const paramName in properties) {
2642
+ if (Object.prototype.hasOwnProperty.call(properties, paramName)) {
2643
+ const paramDef = properties[paramName];
2644
+ parameters.push({
2645
+ name: paramName,
2646
+ // Infer type, default to string. MCP schemas might have more complex types.
2647
+ // This might need refinement based on common MCP schema practices.
2648
+ type: paramDef.type || "string",
2649
+ description: paramDef.description,
2650
+ required: requiredParams.has(paramName)
2651
+ });
2652
+ }
2560
2653
  }
2561
- return new CopilotKitError2({
2562
- message: `Streaming error: ${(error == null ? void 0 : error.message) || String(error)}`,
2563
- code: CopilotKitErrorCode.UNKNOWN
2564
- });
2654
+ return parameters;
2565
2655
  }
2566
- __name(convertStreamingErrorToStructured, "convertStreamingErrorToStructured");
2567
-
2568
- // src/lib/runtime/remote-action-constructors.ts
2569
- import { CopilotKitApiDiscoveryError, ResolvedCopilotKitError } from "@copilotkit/shared";
2570
- import { parseJson as parseJson2, tryMap } from "@copilotkit/shared";
2571
- function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, messages, agentStates }) {
2572
- const agents = endpoint.agents.map((agent) => ({
2573
- name: agent.name,
2574
- description: agent.description,
2575
- parameters: [],
2576
- handler: async (_args) => {
2577
- },
2578
- remoteAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName, additionalMessages = [], metaEvents }) => {
2579
- logger2.debug({
2580
- actionName: agent.name
2581
- }, "Executing LangGraph Platform agent");
2582
- telemetry_client_default.capture("oss.runtime.remote_action_executed", {
2583
- agentExecution: true,
2584
- type: "langgraph-platform",
2585
- agentsAmount: endpoint.agents.length,
2586
- hashedLgcKey: endpoint.langsmithApiKey ? createHash2("sha256").update(endpoint.langsmithApiKey).digest("hex") : null
2587
- });
2588
- let state = {};
2589
- let config = {};
2590
- if (agentStates) {
2591
- const jsonState = agentStates.find((state2) => state2.agentName === name);
2592
- if (jsonState) {
2593
- state = parseJson2(jsonState.state, {});
2594
- config = parseJson2(jsonState.config, {});
2595
- }
2596
- }
2656
+ __name(extractParametersFromSchema, "extractParametersFromSchema");
2657
+ function convertMCPToolsToActions(mcpTools, mcpEndpoint) {
2658
+ const actions = [];
2659
+ for (const [toolName, tool] of Object.entries(mcpTools)) {
2660
+ const parameters = extractParametersFromSchema(tool);
2661
+ const handler = /* @__PURE__ */ __name(async (params) => {
2597
2662
  try {
2598
- const response = await execute({
2599
- logger: logger2.child({
2600
- component: "remote-actions.remote-lg-action.streamEvents"
2601
- }),
2602
- deploymentUrl: endpoint.deploymentUrl,
2603
- langsmithApiKey: endpoint.langsmithApiKey,
2604
- agent,
2605
- threadId,
2606
- nodeName,
2607
- messages: [
2608
- ...messages,
2609
- ...additionalMessages
2610
- ],
2611
- state,
2612
- config,
2613
- properties: graphqlContext.properties,
2614
- actions: tryMap(actionInputsWithoutAgents, (action) => ({
2615
- name: action.name,
2616
- description: action.description,
2617
- parameters: JSON.parse(action.jsonSchema)
2618
- })),
2619
- metaEvents
2663
+ const result = await tool.execute({
2664
+ params
2620
2665
  });
2621
- const eventSource = new RemoteLangGraphEventSource();
2622
- writeJsonLineResponseToEventStream(response, eventSource.eventStream$);
2623
- return eventSource.processLangGraphEvents();
2666
+ return typeof result === "string" ? result : JSON.stringify(result);
2624
2667
  } catch (error) {
2625
- logger2.error({
2626
- url: endpoint.deploymentUrl,
2627
- status: 500,
2628
- body: error.message
2629
- }, "Failed to execute LangGraph Platform agent");
2630
- throw new Error("Failed to execute LangGraph Platform agent");
2668
+ console.error(`Error executing MCP tool '${toolName}' from endpoint ${mcpEndpoint}:`, error);
2669
+ throw new Error(`Execution failed for MCP tool '${toolName}': ${error instanceof Error ? error.message : String(error)}`);
2670
+ }
2671
+ }, "handler");
2672
+ actions.push({
2673
+ name: toolName,
2674
+ description: tool.description || `MCP tool: ${toolName} (from ${mcpEndpoint})`,
2675
+ parameters,
2676
+ handler,
2677
+ // Add metadata for easier identification/debugging
2678
+ _isMCPTool: true,
2679
+ _mcpEndpoint: mcpEndpoint
2680
+ });
2681
+ }
2682
+ return actions;
2683
+ }
2684
+ __name(convertMCPToolsToActions, "convertMCPToolsToActions");
2685
+ function generateMcpToolInstructions(toolsMap) {
2686
+ if (!toolsMap || Object.keys(toolsMap).length === 0) {
2687
+ return "";
2688
+ }
2689
+ const toolEntries = Object.entries(toolsMap);
2690
+ const toolsDoc = toolEntries.map(([name, tool]) => {
2691
+ let paramsDoc = " No parameters required";
2692
+ try {
2693
+ if (tool.schema && typeof tool.schema === "object") {
2694
+ const schema = tool.schema;
2695
+ if (schema.properties) {
2696
+ const requiredParams = schema.required || [];
2697
+ const paramsList = Object.entries(schema.properties).map(([paramName, propSchema]) => {
2698
+ const propDetails = propSchema;
2699
+ const requiredMark = requiredParams.includes(paramName) ? "*" : "";
2700
+ const typeInfo = propDetails.type || "any";
2701
+ const description = propDetails.description ? ` - ${propDetails.description}` : "";
2702
+ return ` - ${paramName}${requiredMark} (${typeInfo})${description}`;
2703
+ });
2704
+ if (paramsList.length > 0) {
2705
+ paramsDoc = paramsList.join("\n");
2706
+ }
2707
+ }
2631
2708
  }
2709
+ } catch (e) {
2710
+ console.error(`Error parsing schema for tool ${name}:`, e);
2632
2711
  }
2633
- }));
2634
- return [
2635
- ...agents
2636
- ];
2712
+ return `- ${name}: ${tool.description || ""}
2713
+ ${paramsDoc}`;
2714
+ }).join("\n\n");
2715
+ return `You have access to the following external tools provided by Model Context Protocol (MCP) servers:
2716
+
2717
+ ${toolsDoc}
2718
+
2719
+ When using these tools:
2720
+ 1. Only provide valid parameters according to their type requirements
2721
+ 2. Required parameters are marked with *
2722
+ 3. Format API calls correctly with the expected parameter structure
2723
+ 4. Always check tool responses to determine your next action`;
2637
2724
  }
2638
- __name(constructLGCRemoteAction, "constructLGCRemoteAction");
2639
- var RemoteAgentType;
2640
- (function(RemoteAgentType2) {
2641
- RemoteAgentType2["LangGraph"] = "langgraph";
2642
- RemoteAgentType2["CrewAI"] = "crewai";
2643
- })(RemoteAgentType || (RemoteAgentType = {}));
2644
- function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, logger: logger2, messages, agentStates }) {
2645
- const totalAgents = Array.isArray(json["agents"]) ? json["agents"].length : 0;
2646
- const actions = json["actions"].map((action) => ({
2647
- name: action.name,
2648
- description: action.description,
2649
- parameters: action.parameters,
2650
- handler: async (args) => {
2651
- logger2.debug({
2652
- actionName: action.name,
2653
- args
2654
- }, "Executing remote action");
2655
- const headers = createHeaders(onBeforeRequest, graphqlContext);
2656
- telemetry_client_default.capture("oss.runtime.remote_action_executed", {
2657
- agentExecution: false,
2658
- type: "self-hosted",
2659
- agentsAmount: totalAgents
2725
+ __name(generateMcpToolInstructions, "generateMcpToolInstructions");
2726
+
2727
+ // src/lib/runtime/copilot-runtime.ts
2728
+ var CopilotRuntime = class {
2729
+ actions;
2730
+ agents;
2731
+ remoteEndpointDefinitions;
2732
+ langserve = [];
2733
+ onBeforeRequest;
2734
+ onAfterRequest;
2735
+ delegateAgentProcessingToServiceAdapter;
2736
+ observability;
2737
+ availableAgents;
2738
+ onTrace;
2739
+ hasWarnedAboutTracing = false;
2740
+ // +++ MCP Properties +++
2741
+ mcpServersConfig;
2742
+ mcpActionCache = /* @__PURE__ */ new Map();
2743
+ // --- MCP Properties ---
2744
+ // +++ MCP Client Factory +++
2745
+ createMCPClientImpl;
2746
+ // --- MCP Client Factory ---
2747
+ constructor(params) {
2748
+ var _a, _b, _c, _d;
2749
+ 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))) {
2750
+ console.warn("Actions set in runtime instance will not be available for the agent");
2751
+ console.warn(`LangGraph Platform remote endpoints are deprecated in favor of the "agents" property`);
2752
+ }
2753
+ this.actions = (params == null ? void 0 : params.actions) || [];
2754
+ this.availableAgents = [];
2755
+ for (const chain of (params == null ? void 0 : params.langserve) || []) {
2756
+ const remoteChain = new RemoteChain(chain);
2757
+ this.langserve.push(remoteChain.toAction());
2758
+ }
2759
+ this.remoteEndpointDefinitions = (params == null ? void 0 : params.remoteEndpoints) ?? (params == null ? void 0 : params.remoteActions) ?? [];
2760
+ this.onBeforeRequest = (_a = params == null ? void 0 : params.middleware) == null ? void 0 : _a.onBeforeRequest;
2761
+ this.onAfterRequest = (_b = params == null ? void 0 : params.middleware) == null ? void 0 : _b.onAfterRequest;
2762
+ this.delegateAgentProcessingToServiceAdapter = (params == null ? void 0 : params.delegateAgentProcessingToServiceAdapter) || false;
2763
+ this.observability = params == null ? void 0 : params.observability_c;
2764
+ this.agents = (params == null ? void 0 : params.agents) ?? {};
2765
+ this.onTrace = params == null ? void 0 : params.onTrace;
2766
+ this.mcpServersConfig = params == null ? void 0 : params.mcpServers;
2767
+ this.createMCPClientImpl = params == null ? void 0 : params.createMCPClient;
2768
+ if (this.mcpServersConfig && this.mcpServersConfig.length > 0 && !this.createMCPClientImpl) {
2769
+ throw new CopilotKitMisuseError2({
2770
+ message: "MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`."
2660
2771
  });
2661
- const fetchUrl = `${url}/actions/execute`;
2772
+ }
2773
+ 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))) {
2774
+ 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.");
2775
+ }
2776
+ }
2777
+ // +++ MCP Instruction Injection Method +++
2778
+ injectMCPToolInstructions(messages, currentActions) {
2779
+ const mcpActionsForRequest = currentActions.filter((action) => action._isMCPTool);
2780
+ if (!mcpActionsForRequest || mcpActionsForRequest.length === 0) {
2781
+ return messages;
2782
+ }
2783
+ const uniqueMcpTools = /* @__PURE__ */ new Map();
2784
+ mcpActionsForRequest.forEach((action) => {
2785
+ uniqueMcpTools.set(action.name, action);
2786
+ });
2787
+ const toolsMap = {};
2788
+ Array.from(uniqueMcpTools.values()).forEach((action) => {
2789
+ toolsMap[action.name] = {
2790
+ description: action.description || "",
2791
+ schema: action.parameters ? {
2792
+ parameters: {
2793
+ properties: action.parameters.reduce((acc, p) => ({
2794
+ ...acc,
2795
+ [p.name]: {
2796
+ type: p.type,
2797
+ description: p.description
2798
+ }
2799
+ }), {}),
2800
+ required: action.parameters.filter((p) => p.required).map((p) => p.name)
2801
+ }
2802
+ } : {},
2803
+ execute: async () => ({})
2804
+ };
2805
+ });
2806
+ const mcpToolInstructions = generateMcpToolInstructions(toolsMap);
2807
+ if (!mcpToolInstructions) {
2808
+ return messages;
2809
+ }
2810
+ 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.";
2811
+ const systemMessageIndex = messages.findIndex((msg) => {
2812
+ var _a;
2813
+ return ((_a = msg.textMessage) == null ? void 0 : _a.role) === "system";
2814
+ });
2815
+ const newMessages = [
2816
+ ...messages
2817
+ ];
2818
+ if (systemMessageIndex !== -1) {
2819
+ const existingMsg = newMessages[systemMessageIndex];
2820
+ if (existingMsg.textMessage) {
2821
+ existingMsg.textMessage.content = (existingMsg.textMessage.content ? existingMsg.textMessage.content + "\n\n" : "") + instructions;
2822
+ }
2823
+ } else {
2824
+ newMessages.unshift({
2825
+ id: randomId(),
2826
+ createdAt: /* @__PURE__ */ new Date(),
2827
+ textMessage: {
2828
+ role: MessageRole.system,
2829
+ content: instructions
2830
+ },
2831
+ actionExecutionMessage: void 0,
2832
+ resultMessage: void 0,
2833
+ agentStateMessage: void 0
2834
+ });
2835
+ }
2836
+ return newMessages;
2837
+ }
2838
+ async processRuntimeRequest(request) {
2839
+ var _a, _b, _c, _d, _e;
2840
+ const { serviceAdapter, messages: rawMessages, actions: clientSideActionsInput, threadId, runId, outputMessagesPromise, graphqlContext, forwardedParameters, url, extensions, agentSession, agentStates, publicApiKey } = request;
2841
+ const eventSource = new RuntimeEventSource();
2842
+ const requestStartTime = Date.now();
2843
+ const streamedChunks = [];
2844
+ await this.trace("request", {
2845
+ threadId,
2846
+ runId,
2847
+ source: "runtime",
2848
+ request: {
2849
+ operation: "processRuntimeRequest",
2850
+ method: "POST",
2851
+ url,
2852
+ startTime: requestStartTime
2853
+ },
2854
+ agent: agentSession ? {
2855
+ name: agentSession.agentName
2856
+ } : void 0,
2857
+ messages: {
2858
+ input: rawMessages,
2859
+ messageCount: rawMessages.length
2860
+ },
2861
+ technical: {
2862
+ environment: process.env.NODE_ENV
2863
+ }
2864
+ }, void 0, publicApiKey);
2865
+ try {
2866
+ if (Object.keys(this.agents).length && (agentSession == null ? void 0 : agentSession.agentName) && !this.delegateAgentProcessingToServiceAdapter) {
2867
+ this.agents = {
2868
+ [agentSession.agentName]: this.agents[agentSession.agentName]
2869
+ };
2870
+ }
2871
+ if (agentSession && !this.delegateAgentProcessingToServiceAdapter) {
2872
+ return await this.processAgentRequest(request);
2873
+ }
2874
+ if (serviceAdapter instanceof EmptyAdapter) {
2875
+ throw new CopilotKitMisuseError2({
2876
+ message: `Invalid adapter configuration: EmptyAdapter is only meant to be used with agent lock mode.
2877
+ For non-agent components like useCopilotChatSuggestions, CopilotTextarea, or CopilotTask,
2878
+ please use an LLM adapter instead.`
2879
+ });
2880
+ }
2881
+ const serverSideActions = await this.getServerSideActions(request);
2882
+ const filteredRawMessages = rawMessages.filter((message) => !message.agentStateMessage);
2883
+ const messagesWithInjectedInstructions = this.injectMCPToolInstructions(filteredRawMessages, serverSideActions);
2884
+ const inputMessages = convertGqlInputToMessages(messagesWithInjectedInstructions);
2885
+ if (((_a = this.observability) == null ? void 0 : _a.enabled) && publicApiKey) {
2886
+ try {
2887
+ const requestData = {
2888
+ threadId,
2889
+ runId,
2890
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
2891
+ messages: inputMessages,
2892
+ actions: clientSideActionsInput,
2893
+ forwardedParameters,
2894
+ timestamp: requestStartTime,
2895
+ provider: this.detectProvider(serviceAdapter)
2896
+ };
2897
+ await this.observability.hooks.handleRequest(requestData);
2898
+ } catch (error) {
2899
+ console.error("Error logging LLM request:", error);
2900
+ }
2901
+ }
2902
+ const serverSideActionsInput = serverSideActions.map((action) => ({
2903
+ name: action.name,
2904
+ description: action.description,
2905
+ jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters))
2906
+ }));
2907
+ const actionInputs = flattenToolCallsNoDuplicates([
2908
+ ...serverSideActionsInput,
2909
+ ...clientSideActionsInput.filter(
2910
+ // Filter remote actions from CopilotKit core loop
2911
+ (action) => action.available !== ActionInputAvailability.remote
2912
+ )
2913
+ ]);
2914
+ await ((_b = this.onBeforeRequest) == null ? void 0 : _b.call(this, {
2915
+ threadId,
2916
+ runId,
2917
+ inputMessages,
2918
+ properties: graphqlContext.properties,
2919
+ url
2920
+ }));
2921
+ const result = await serviceAdapter.process({
2922
+ messages: inputMessages,
2923
+ actions: actionInputs,
2924
+ threadId,
2925
+ runId,
2926
+ eventSource,
2927
+ forwardedParameters,
2928
+ extensions,
2929
+ agentSession,
2930
+ agentStates
2931
+ });
2932
+ const nonEmptyThreadId = threadId ?? result.threadId;
2933
+ outputMessagesPromise.then((outputMessages) => {
2934
+ var _a2;
2935
+ (_a2 = this.onAfterRequest) == null ? void 0 : _a2.call(this, {
2936
+ threadId: nonEmptyThreadId,
2937
+ runId: result.runId,
2938
+ inputMessages,
2939
+ outputMessages,
2940
+ properties: graphqlContext.properties,
2941
+ url
2942
+ });
2943
+ }).catch((_error) => {
2944
+ });
2945
+ if (((_c = this.observability) == null ? void 0 : _c.enabled) && publicApiKey) {
2946
+ try {
2947
+ outputMessagesPromise.then((outputMessages) => {
2948
+ const responseData = {
2949
+ threadId: result.threadId,
2950
+ runId: result.runId,
2951
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
2952
+ // Use collected chunks for progressive mode or outputMessages for regular mode
2953
+ output: this.observability.progressive ? streamedChunks : outputMessages,
2954
+ latency: Date.now() - requestStartTime,
2955
+ timestamp: Date.now(),
2956
+ provider: this.detectProvider(serviceAdapter),
2957
+ // Indicate this is the final response
2958
+ isFinalResponse: true
2959
+ };
2960
+ try {
2961
+ this.observability.hooks.handleResponse(responseData);
2962
+ } catch (logError) {
2963
+ console.error("Error logging LLM response:", logError);
2964
+ }
2965
+ }).catch((error) => {
2966
+ console.error("Failed to get output messages for logging:", error);
2967
+ });
2968
+ } catch (error) {
2969
+ console.error("Error setting up logging for LLM response:", error);
2970
+ }
2971
+ }
2972
+ if (((_d = this.observability) == null ? void 0 : _d.enabled) && this.observability.progressive && publicApiKey) {
2973
+ const originalStream = eventSource.stream.bind(eventSource);
2974
+ eventSource.stream = async (callback) => {
2975
+ await originalStream(async (eventStream$) => {
2976
+ eventStream$.subscribe({
2977
+ next: (event) => {
2978
+ if (event.type === RuntimeEventTypes.TextMessageContent) {
2979
+ streamedChunks.push(event.content);
2980
+ try {
2981
+ const progressiveData = {
2982
+ threadId: threadId || "",
2983
+ runId,
2984
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
2985
+ output: event.content,
2986
+ latency: Date.now() - requestStartTime,
2987
+ timestamp: Date.now(),
2988
+ provider: this.detectProvider(serviceAdapter),
2989
+ isProgressiveChunk: true
2990
+ };
2991
+ Promise.resolve().then(() => {
2992
+ this.observability.hooks.handleResponse(progressiveData);
2993
+ }).catch((error) => {
2994
+ console.error("Error in progressive logging:", error);
2995
+ });
2996
+ } catch (error) {
2997
+ console.error("Error preparing progressive log data:", error);
2998
+ }
2999
+ }
3000
+ }
3001
+ });
3002
+ await callback(eventStream$);
3003
+ });
3004
+ };
3005
+ }
3006
+ return {
3007
+ threadId: nonEmptyThreadId,
3008
+ runId: result.runId,
3009
+ eventSource,
3010
+ serverSideActions,
3011
+ actionInputsWithoutAgents: actionInputs.filter((action) => (
3012
+ // TODO-AGENTS: do not exclude ALL server side actions
3013
+ !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name)
3014
+ )),
3015
+ extensions: result.extensions
3016
+ };
3017
+ } catch (error) {
3018
+ if (((_e = this.observability) == null ? void 0 : _e.enabled) && publicApiKey) {
3019
+ try {
3020
+ const errorData = {
3021
+ threadId,
3022
+ runId,
3023
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3024
+ error: error instanceof Error ? error : String(error),
3025
+ timestamp: Date.now(),
3026
+ latency: Date.now() - requestStartTime,
3027
+ provider: this.detectProvider(serviceAdapter)
3028
+ };
3029
+ await this.observability.hooks.handleError(errorData);
3030
+ } catch (logError) {
3031
+ console.error("Error logging LLM error:", logError);
3032
+ }
3033
+ }
3034
+ let structuredError;
3035
+ if (error instanceof CopilotKitError3) {
3036
+ structuredError = error;
3037
+ } else {
3038
+ structuredError = ensureStructuredError2(error, (err) => this.convertStreamingErrorToStructured(err));
3039
+ }
3040
+ await this.trace("error", {
3041
+ threadId,
3042
+ runId,
3043
+ source: "runtime",
3044
+ request: {
3045
+ operation: "processRuntimeRequest",
3046
+ method: "POST",
3047
+ url,
3048
+ startTime: requestStartTime
3049
+ },
3050
+ response: {
3051
+ endTime: Date.now(),
3052
+ latency: Date.now() - requestStartTime
3053
+ },
3054
+ agent: agentSession ? {
3055
+ name: agentSession.agentName
3056
+ } : void 0,
3057
+ technical: {
3058
+ environment: process.env.NODE_ENV,
3059
+ stackTrace: error instanceof Error ? error.stack : void 0
3060
+ }
3061
+ }, structuredError, publicApiKey);
3062
+ throw structuredError;
3063
+ }
3064
+ }
3065
+ async getAllAgents(graphqlContext) {
3066
+ const [agentsWithEndpoints, aguiAgents] = await Promise.all([
3067
+ this.discoverAgentsFromEndpoints(graphqlContext),
3068
+ this.discoverAgentsFromAgui()
3069
+ ]);
3070
+ this.availableAgents = [
3071
+ ...agentsWithEndpoints,
3072
+ ...aguiAgents
3073
+ ].map((a) => ({
3074
+ name: a.name,
3075
+ id: a.id
3076
+ }));
3077
+ return [
3078
+ ...agentsWithEndpoints,
3079
+ ...aguiAgents
3080
+ ];
3081
+ }
3082
+ async discoverAgentsFromEndpoints(graphqlContext) {
3083
+ const agents = this.remoteEndpointDefinitions.reduce(async (acc, endpoint) => {
3084
+ const agents2 = await acc;
3085
+ if (endpoint.type === EndpointType.LangGraphPlatform) {
3086
+ const propertyHeaders = graphqlContext.properties.authorization ? {
3087
+ authorization: `Bearer ${graphqlContext.properties.authorization}`
3088
+ } : null;
3089
+ const client = new LangGraphClient2({
3090
+ apiUrl: endpoint.deploymentUrl,
3091
+ apiKey: endpoint.langsmithApiKey,
3092
+ defaultHeaders: {
3093
+ ...propertyHeaders
3094
+ }
3095
+ });
3096
+ let data = [];
3097
+ try {
3098
+ data = await client.assistants.search();
3099
+ if (data && "detail" in data && data.detail.toLowerCase() === "not found") {
3100
+ throw new CopilotKitAgentDiscoveryError({
3101
+ availableAgents: this.availableAgents
3102
+ });
3103
+ }
3104
+ } catch (e) {
3105
+ throw new CopilotKitMisuseError2({
3106
+ message: `
3107
+ Failed to find or contact remote endpoint at url ${endpoint.deploymentUrl}.
3108
+ Make sure the API is running and that it's indeed a LangGraph platform url.
3109
+
3110
+ See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3111
+ });
3112
+ }
3113
+ const endpointAgents = data.map((entry) => ({
3114
+ name: entry.graph_id,
3115
+ id: entry.assistant_id,
3116
+ description: "",
3117
+ endpoint
3118
+ }));
3119
+ return [
3120
+ ...agents2,
3121
+ ...endpointAgents
3122
+ ];
3123
+ }
3124
+ const cpkEndpoint = endpoint;
3125
+ const fetchUrl = `${endpoint.url}/info`;
2662
3126
  try {
2663
3127
  const response = await fetchWithRetry(fetchUrl, {
2664
3128
  method: "POST",
2665
- headers,
3129
+ headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
2666
3130
  body: JSON.stringify({
2667
- name: action.name,
2668
- arguments: args,
2669
3131
  properties: graphqlContext.properties
2670
3132
  })
2671
- }, logger2);
3133
+ });
2672
3134
  if (!response.ok) {
2673
- logger2.error({
2674
- url,
2675
- status: response.status,
2676
- body: await response.text()
2677
- }, "Failed to execute remote action");
2678
3135
  if (response.status === 404) {
2679
3136
  throw new CopilotKitApiDiscoveryError({
2680
3137
  url: fetchUrl
@@ -2686,1398 +3143,1417 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
2686
3143
  isRemoteEndpoint: true
2687
3144
  });
2688
3145
  }
2689
- const requestResult = await response.json();
2690
- const result = requestResult["result"];
2691
- logger2.debug({
2692
- actionName: action.name,
2693
- result
2694
- }, "Executed remote action");
2695
- return result;
3146
+ const data = await response.json();
3147
+ const endpointAgents = ((data == null ? void 0 : data.agents) ?? []).map((agent) => ({
3148
+ name: agent.name,
3149
+ description: agent.description ?? "" ?? "",
3150
+ id: randomId(),
3151
+ endpoint
3152
+ }));
3153
+ return [
3154
+ ...agents2,
3155
+ ...endpointAgents
3156
+ ];
2696
3157
  } catch (error) {
2697
3158
  if (error instanceof CopilotKitError3) {
2698
3159
  throw error;
2699
3160
  }
2700
- throw new CopilotKitLowLevelError2({
3161
+ throw new CopilotKitLowLevelError3({
2701
3162
  error,
2702
3163
  url: fetchUrl
2703
3164
  });
2704
3165
  }
2705
- }
2706
- }));
2707
- const agents = totalAgents ? json["agents"].map((agent) => ({
2708
- name: agent.name,
2709
- description: agent.description,
2710
- parameters: [],
2711
- handler: async (_args) => {
2712
- },
2713
- remoteAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName, additionalMessages = [], metaEvents }) => {
2714
- logger2.debug({
2715
- actionName: agent.name
2716
- }, "Executing remote agent");
2717
- const headers = createHeaders(onBeforeRequest, graphqlContext);
2718
- telemetry_client_default.capture("oss.runtime.remote_action_executed", {
2719
- agentExecution: true,
2720
- type: "self-hosted",
2721
- agentsAmount: json["agents"].length
2722
- });
2723
- let state = {};
2724
- let config = {};
2725
- if (agentStates) {
2726
- const jsonState = agentStates.find((state2) => state2.agentName === name);
2727
- if (jsonState) {
2728
- state = parseJson2(jsonState.state, {});
2729
- config = parseJson2(jsonState.config, {});
3166
+ }, Promise.resolve([]));
3167
+ return agents;
3168
+ }
3169
+ async discoverAgentsFromAgui() {
3170
+ const agents = Object.values(this.agents ?? []).reduce(async (acc, agent) => {
3171
+ const agents2 = await acc;
3172
+ const client = agent.client;
3173
+ let data = [];
3174
+ try {
3175
+ data = await client.assistants.search();
3176
+ if (data && "detail" in data && data.detail.toLowerCase() === "not found") {
3177
+ throw new CopilotKitAgentDiscoveryError({
3178
+ availableAgents: this.availableAgents
3179
+ });
2730
3180
  }
3181
+ } catch (e) {
3182
+ throw new CopilotKitMisuseError2({
3183
+ message: `
3184
+ Failed to find or contact agent ${agent.graphId}.
3185
+ Make sure the LangGraph API is running and the agent is defined in langgraph.json
3186
+
3187
+ See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3188
+ });
2731
3189
  }
2732
- const fetchUrl = `${url}/agents/execute`;
3190
+ const endpointAgents = data.map((entry) => ({
3191
+ name: entry.graph_id,
3192
+ id: entry.assistant_id,
3193
+ description: ""
3194
+ }));
3195
+ return [
3196
+ ...agents2,
3197
+ ...endpointAgents
3198
+ ];
3199
+ }, Promise.resolve([]));
3200
+ return agents;
3201
+ }
3202
+ async loadAgentState(graphqlContext, threadId, agentName) {
3203
+ const agents = await this.getAllAgents(graphqlContext);
3204
+ const agent = agents.find((agent2) => agent2.name === agentName);
3205
+ if (!agent) {
3206
+ throw new Error("Agent not found");
3207
+ }
3208
+ if ("endpoint" in agent && (agent.endpoint.type === EndpointType.CopilotKit || !("type" in agent.endpoint))) {
3209
+ const cpkEndpoint = agent.endpoint;
3210
+ const fetchUrl = `${cpkEndpoint.url}/agents/state`;
2733
3211
  try {
2734
3212
  const response = await fetchWithRetry(fetchUrl, {
2735
3213
  method: "POST",
2736
- headers,
3214
+ headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
2737
3215
  body: JSON.stringify({
2738
- name,
2739
- threadId,
2740
- nodeName,
2741
- messages: [
2742
- ...messages,
2743
- ...additionalMessages
2744
- ],
2745
- state,
2746
- config,
2747
3216
  properties: graphqlContext.properties,
2748
- actions: tryMap(actionInputsWithoutAgents, (action) => ({
2749
- name: action.name,
2750
- description: action.description,
2751
- parameters: JSON.parse(action.jsonSchema)
2752
- })),
2753
- metaEvents
3217
+ threadId,
3218
+ name: agentName
2754
3219
  })
2755
- }, logger2);
3220
+ });
2756
3221
  if (!response.ok) {
2757
- logger2.error({
2758
- url,
2759
- status: response.status,
2760
- body: await response.text()
2761
- }, "Failed to execute remote agent");
2762
3222
  if (response.status === 404) {
2763
3223
  throw new CopilotKitApiDiscoveryError({
2764
3224
  url: fetchUrl
2765
3225
  });
2766
3226
  }
3227
+ let errorMessage = `HTTP ${response.status} error`;
3228
+ try {
3229
+ const errorBody = await response.text();
3230
+ const parsedError = JSON.parse(errorBody);
3231
+ if (parsedError.error && typeof parsedError.error === "string") {
3232
+ errorMessage = parsedError.error;
3233
+ }
3234
+ } catch {
3235
+ }
2767
3236
  throw new ResolvedCopilotKitError({
2768
3237
  status: response.status,
2769
3238
  url: fetchUrl,
2770
- isRemoteEndpoint: true
3239
+ isRemoteEndpoint: true,
3240
+ message: errorMessage
2771
3241
  });
2772
3242
  }
2773
- if (agent.type === "langgraph") {
2774
- const eventSource = new RemoteLangGraphEventSource();
2775
- writeJsonLineResponseToEventStream(response.body, eventSource.eventStream$);
2776
- return eventSource.processLangGraphEvents();
2777
- } else if (agent.type === "crewai") {
2778
- const eventStream$ = new RuntimeEventSubject();
2779
- writeJsonLineResponseToEventStream(response.body, eventStream$);
2780
- return eventStream$;
2781
- } else {
2782
- throw new Error("Unsupported agent type");
2783
- }
3243
+ const data = await response.json();
3244
+ return {
3245
+ ...data,
3246
+ state: JSON.stringify(data.state),
3247
+ messages: JSON.stringify(data.messages)
3248
+ };
2784
3249
  } catch (error) {
2785
3250
  if (error instanceof CopilotKitError3) {
2786
3251
  throw error;
2787
3252
  }
2788
- throw new CopilotKitLowLevelError2({
3253
+ throw new CopilotKitLowLevelError3({
2789
3254
  error,
2790
3255
  url: fetchUrl
2791
- });
2792
- }
2793
- }
2794
- })) : [];
2795
- return [
2796
- ...actions,
2797
- ...agents
2798
- ];
2799
- }
2800
- __name(constructRemoteActions, "constructRemoteActions");
2801
- function createHeaders(onBeforeRequest, graphqlContext) {
2802
- const headers = {
2803
- "Content-Type": "application/json"
2804
- };
2805
- if (onBeforeRequest) {
2806
- const { headers: additionalHeaders } = onBeforeRequest({
2807
- ctx: graphqlContext
2808
- });
2809
- if (additionalHeaders) {
2810
- Object.assign(headers, additionalHeaders);
2811
- }
2812
- }
2813
- return headers;
2814
- }
2815
- __name(createHeaders, "createHeaders");
2816
-
2817
- // src/lib/runtime/remote-actions.ts
2818
- import { CopilotKitLowLevelError as CopilotKitLowLevelError3, ResolvedCopilotKitError as ResolvedCopilotKitError2, CopilotKitError as CopilotKitError4 } from "@copilotkit/shared";
2819
-
2820
- // src/lib/runtime/agui-action.ts
2821
- import { parseJson as parseJson3 } from "@copilotkit/shared";
2822
- function constructAGUIRemoteAction({ logger: logger2, messages, agentStates, agent, metaEvents }) {
2823
- const action = {
2824
- name: agent.agentId,
2825
- description: agent.description,
2826
- parameters: [],
2827
- handler: async (_args) => {
2828
- },
2829
- remoteAgentHandler: async ({ actionInputsWithoutAgents, threadId }) => {
2830
- var _a;
2831
- logger2.debug({
2832
- actionName: agent.agentId
2833
- }, "Executing remote agent");
2834
- const agentWireMessages = convertMessagesToAGUIMessage(messages);
2835
- agent.messages = agentWireMessages;
2836
- agent.threadId = threadId;
2837
- telemetry_client_default.capture("oss.runtime.remote_action_executed", {
2838
- agentExecution: true,
2839
- type: "self-hosted",
2840
- agentsAmount: 1
2841
- });
2842
- let state = {};
2843
- if (agentStates) {
2844
- const jsonState = agentStates.find((state2) => state2.agentName === agent.agentId);
2845
- if (jsonState) {
2846
- state = parseJson3(jsonState.state, {});
2847
- }
2848
- }
2849
- agent.state = state;
2850
- const tools = actionInputsWithoutAgents.map((input) => {
2851
- return {
2852
- name: input.name,
2853
- description: input.description,
2854
- parameters: JSON.parse(input.jsonSchema)
2855
- };
2856
- });
2857
- const forwardedProps = metaEvents.length ? {
2858
- command: {
2859
- resume: (_a = metaEvents[0]) == null ? void 0 : _a.response
2860
- }
2861
- } : void 0;
2862
- return agent.legacy_to_be_removed_runAgentBridged({
2863
- tools,
2864
- forwardedProps
2865
- });
2866
- }
2867
- };
2868
- return [
2869
- action
2870
- ];
2871
- }
2872
- __name(constructAGUIRemoteAction, "constructAGUIRemoteAction");
2873
- function convertMessagesToAGUIMessage(messages) {
2874
- const result = [];
2875
- for (const message of messages) {
2876
- if (message.isTextMessage()) {
2877
- result.push({
2878
- id: message.id,
2879
- role: message.role,
2880
- content: message.content
2881
- });
2882
- } else if (message.isActionExecutionMessage()) {
2883
- const toolCall = {
2884
- id: message.id,
2885
- type: "function",
2886
- function: {
2887
- name: message.name,
2888
- arguments: JSON.stringify(message.arguments)
2889
- }
2890
- };
2891
- if (message.parentMessageId && result.some((m) => m.id === message.parentMessageId)) {
2892
- const parentMessage = result.find((m) => m.id === message.parentMessageId);
2893
- if (parentMessage.toolCalls === void 0) {
2894
- parentMessage.toolCalls = [];
2895
- }
2896
- parentMessage.toolCalls.push(toolCall);
2897
- } else {
2898
- result.push({
2899
- id: message.parentMessageId ?? message.id,
2900
- role: "assistant",
2901
- toolCalls: [
2902
- toolCall
2903
- ]
2904
- });
2905
- }
2906
- } else if (message.isResultMessage()) {
2907
- result.push({
2908
- id: message.id,
2909
- role: "tool",
2910
- content: message.result,
2911
- toolCallId: message.actionExecutionId
3256
+ });
3257
+ }
3258
+ }
3259
+ const propertyHeaders = graphqlContext.properties.authorization ? {
3260
+ authorization: `Bearer ${graphqlContext.properties.authorization}`
3261
+ } : null;
3262
+ let client;
3263
+ if ("endpoint" in agent && agent.endpoint.type === EndpointType.LangGraphPlatform) {
3264
+ client = new LangGraphClient2({
3265
+ apiUrl: agent.endpoint.deploymentUrl,
3266
+ apiKey: agent.endpoint.langsmithApiKey,
3267
+ defaultHeaders: {
3268
+ ...propertyHeaders
3269
+ }
2912
3270
  });
3271
+ } else {
3272
+ const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name];
3273
+ if (!aguiAgent) {
3274
+ throw new Error(`Agent: ${agent.name} could not be resolved`);
3275
+ }
3276
+ client = aguiAgent.client;
2913
3277
  }
2914
- }
2915
- return result;
2916
- }
2917
- __name(convertMessagesToAGUIMessage, "convertMessagesToAGUIMessage");
2918
-
2919
- // src/lib/runtime/remote-actions.ts
2920
- var EndpointType;
2921
- (function(EndpointType2) {
2922
- EndpointType2["CopilotKit"] = "copilotKit";
2923
- EndpointType2["LangGraphPlatform"] = "langgraph-platform";
2924
- })(EndpointType || (EndpointType = {}));
2925
- function isRemoteAgentAction(action) {
2926
- if (!action) {
2927
- return false;
2928
- }
2929
- return typeof action.remoteAgentHandler === "function";
2930
- }
2931
- __name(isRemoteAgentAction, "isRemoteAgentAction");
2932
- async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: logger2, frontendUrl }) {
2933
- logger2.debug({
2934
- url
2935
- }, "Fetching actions from url");
2936
- const headers = createHeaders(onBeforeRequest, graphqlContext);
2937
- const fetchUrl = `${url}/info`;
2938
- try {
2939
- const response = await fetch(fetchUrl, {
2940
- method: "POST",
2941
- headers,
2942
- body: JSON.stringify({
2943
- properties: graphqlContext.properties,
2944
- frontendUrl
2945
- })
2946
- });
2947
- if (!response.ok) {
2948
- logger2.error({
2949
- url,
2950
- status: response.status,
2951
- body: await response.text()
2952
- }, "Failed to fetch actions from url");
2953
- throw new ResolvedCopilotKitError2({
2954
- status: response.status,
2955
- url: fetchUrl,
2956
- isRemoteEndpoint: true
3278
+ let state = {};
3279
+ try {
3280
+ state = (await client.threads.getState(threadId)).values;
3281
+ } catch (error) {
3282
+ const errorMessage = error instanceof Error ? error.message : String(error);
3283
+ console.debug(`Agent '${agentName}' configuration issue: ${errorMessage}`);
3284
+ throw new ResolvedCopilotKitError({
3285
+ status: 400,
3286
+ message: `Agent '${agentName}' failed to execute: ${errorMessage}`,
3287
+ code: CopilotKitErrorCode2.CONFIGURATION_ERROR
2957
3288
  });
2958
3289
  }
2959
- const json = await response.json();
2960
- logger2.debug({
2961
- json
2962
- }, "Fetched actions from url");
2963
- return json;
2964
- } catch (error) {
2965
- if (error instanceof CopilotKitError4) {
2966
- throw error;
3290
+ if (Object.keys(state).length === 0) {
3291
+ return {
3292
+ threadId: threadId || "",
3293
+ threadExists: false,
3294
+ state: JSON.stringify({}),
3295
+ messages: JSON.stringify([])
3296
+ };
3297
+ } else {
3298
+ const { messages, ...stateWithoutMessages } = state;
3299
+ const copilotkitMessages = langchainMessagesToCopilotKit(messages);
3300
+ return {
3301
+ threadId: threadId || "",
3302
+ threadExists: true,
3303
+ state: JSON.stringify(stateWithoutMessages),
3304
+ messages: JSON.stringify(copilotkitMessages)
3305
+ };
2967
3306
  }
2968
- throw new CopilotKitLowLevelError3({
2969
- error,
2970
- url: fetchUrl
2971
- });
3307
+ throw new Error(`Agent: ${agent.name} could not be resolved`);
2972
3308
  }
2973
- }
2974
- __name(fetchRemoteInfo, "fetchRemoteInfo");
2975
- async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, messages, agentStates, frontendUrl, agents, metaEvents }) {
2976
- const logger2 = graphqlContext.logger.child({
2977
- component: "remote-actions.fetchRemoteActions"
2978
- });
2979
- logger2.debug({
2980
- remoteEndpointDefinitions
2981
- }, "Fetching from remote endpoints");
2982
- const filtered = remoteEndpointDefinitions.filter((value, index, self) => {
2983
- if (value.type === "langgraph-platform") {
2984
- return value;
2985
- }
2986
- return index === self.findIndex((t) => t.url === value.url);
2987
- });
2988
- const result = await Promise.all(filtered.map(async (endpoint) => {
2989
- if (endpoint.type === "langgraph-platform") {
2990
- return constructLGCRemoteAction({
2991
- endpoint,
2992
- messages,
2993
- graphqlContext,
2994
- logger: logger2.child({
2995
- component: "remote-actions.constructLGCRemoteAction",
2996
- endpoint
2997
- }),
2998
- agentStates
3309
+ async processAgentRequest(request) {
3310
+ var _a, _b, _c, _d, _e;
3311
+ const { messages: rawMessages, outputMessagesPromise, graphqlContext, agentSession, threadId: threadIdFromRequest, metaEvents, publicApiKey, forwardedParameters } = request;
3312
+ const { agentName, nodeName } = agentSession;
3313
+ const requestStartTime = Date.now();
3314
+ const streamedChunks = [];
3315
+ const threadId = threadIdFromRequest ?? agentSession.threadId;
3316
+ await this.trace("agent_state", {
3317
+ threadId,
3318
+ source: "agent",
3319
+ request: {
3320
+ operation: "processAgentRequest",
3321
+ method: "POST",
3322
+ startTime: requestStartTime
3323
+ },
3324
+ agent: {
3325
+ name: agentName,
3326
+ nodeName
3327
+ },
3328
+ messages: {
3329
+ input: rawMessages,
3330
+ messageCount: rawMessages.length
3331
+ },
3332
+ technical: {
3333
+ environment: process.env.NODE_ENV
3334
+ }
3335
+ }, void 0, publicApiKey);
3336
+ const serverSideActions = await this.getServerSideActions(request);
3337
+ const messages = convertGqlInputToMessages(rawMessages);
3338
+ const currentAgent = serverSideActions.find((action) => action.name === agentName && isRemoteAgentAction(action));
3339
+ if (!currentAgent) {
3340
+ throw new CopilotKitAgentDiscoveryError({
3341
+ agentName,
3342
+ availableAgents: this.availableAgents
2999
3343
  });
3000
3344
  }
3001
- const json = await fetchRemoteInfo({
3002
- url: endpoint.url,
3003
- onBeforeRequest: endpoint.onBeforeRequest,
3004
- graphqlContext,
3005
- logger: logger2.child({
3006
- component: "remote-actions.fetchActionsFromUrl",
3007
- endpoint
3008
- }),
3009
- frontendUrl
3010
- });
3011
- return constructRemoteActions({
3012
- json,
3013
- messages,
3014
- url: endpoint.url,
3015
- onBeforeRequest: endpoint.onBeforeRequest,
3016
- graphqlContext,
3017
- logger: logger2.child({
3018
- component: "remote-actions.constructActions",
3019
- endpoint
3020
- }),
3021
- agentStates
3022
- });
3023
- }));
3024
- for (const [key, agent] of Object.entries(agents)) {
3025
- if (agent.agentId !== void 0 && agent.agentId !== key) {
3026
- throw new CopilotKitError4({
3027
- message: `Agent ${key} has agentId ${agent.agentId} which does not match the key ${key}`,
3028
- code: CopilotKitErrorCode2.UNKNOWN
3029
- });
3030
- } else if (agent.agentId === void 0) {
3031
- agent.agentId = key;
3345
+ const availableActionsForCurrentAgent = serverSideActions.filter((action) => (
3346
+ // Case 1: Keep all regular (non-agent) actions
3347
+ !isRemoteAgentAction(action) || // Case 2: For agent actions, keep all except self (prevent infinite loops)
3348
+ isRemoteAgentAction(action) && action.name !== agentName
3349
+ )).map((action) => ({
3350
+ name: action.name,
3351
+ description: action.description,
3352
+ jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters))
3353
+ }));
3354
+ const allAvailableActions = flattenToolCallsNoDuplicates([
3355
+ ...availableActionsForCurrentAgent,
3356
+ ...request.actions
3357
+ ]);
3358
+ if (((_a = this.observability) == null ? void 0 : _a.enabled) && publicApiKey) {
3359
+ try {
3360
+ const requestData = {
3361
+ threadId,
3362
+ runId: void 0,
3363
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3364
+ messages,
3365
+ actions: allAvailableActions,
3366
+ forwardedParameters,
3367
+ timestamp: requestStartTime,
3368
+ provider: "agent",
3369
+ agentName,
3370
+ nodeName
3371
+ };
3372
+ await this.observability.hooks.handleRequest(requestData);
3373
+ } catch (error) {
3374
+ console.error("Error logging agent request:", error);
3375
+ }
3032
3376
  }
3033
- result.push(constructAGUIRemoteAction({
3034
- logger: logger2,
3035
- messages,
3036
- agentStates,
3037
- agent,
3038
- metaEvents
3377
+ await ((_b = this.onBeforeRequest) == null ? void 0 : _b.call(this, {
3378
+ threadId,
3379
+ runId: void 0,
3380
+ inputMessages: messages,
3381
+ properties: graphqlContext.properties
3039
3382
  }));
3040
- }
3041
- return result.flat();
3042
- }
3043
- __name(setupRemoteActions, "setupRemoteActions");
3044
-
3045
- // src/lib/telemetry-client.ts
3046
- import { createHash as createHash3 } from "crypto";
3047
-
3048
- // src/lib/runtime/copilot-runtime.ts
3049
- import { actionParametersToJsonSchema, ResolvedCopilotKitError as ResolvedCopilotKitError3, CopilotKitApiDiscoveryError as CopilotKitApiDiscoveryError2, randomId as randomId2, CopilotKitError as CopilotKitError5, CopilotKitAgentDiscoveryError, CopilotKitMisuseError as CopilotKitMisuseError2, CopilotKitErrorCode as CopilotKitErrorCode3, CopilotKitLowLevelError as CopilotKitLowLevelError4 } from "@copilotkit/shared";
3050
-
3051
- // src/service-adapters/conversion.ts
3052
- import { plainToInstance } from "class-transformer";
3053
- import { tryMap as tryMap2 } from "@copilotkit/shared";
3054
- function convertGqlInputToMessages(inputMessages) {
3055
- const messages = tryMap2(inputMessages, (message) => {
3056
- if (message.textMessage) {
3057
- return plainToInstance(TextMessage, {
3058
- id: message.id,
3059
- createdAt: message.createdAt,
3060
- role: message.textMessage.role,
3061
- content: message.textMessage.content,
3062
- parentMessageId: message.textMessage.parentMessageId
3063
- });
3064
- } else if (message.imageMessage) {
3065
- return plainToInstance(ImageMessage, {
3066
- id: message.id,
3067
- createdAt: message.createdAt,
3068
- role: message.imageMessage.role,
3069
- bytes: message.imageMessage.bytes,
3070
- format: message.imageMessage.format,
3071
- parentMessageId: message.imageMessage.parentMessageId
3072
- });
3073
- } else if (message.actionExecutionMessage) {
3074
- return plainToInstance(ActionExecutionMessage, {
3075
- id: message.id,
3076
- createdAt: message.createdAt,
3077
- name: message.actionExecutionMessage.name,
3078
- arguments: JSON.parse(message.actionExecutionMessage.arguments),
3079
- parentMessageId: message.actionExecutionMessage.parentMessageId
3080
- });
3081
- } else if (message.resultMessage) {
3082
- return plainToInstance(ResultMessage, {
3083
- id: message.id,
3084
- createdAt: message.createdAt,
3085
- actionExecutionId: message.resultMessage.actionExecutionId,
3086
- actionName: message.resultMessage.actionName,
3087
- result: message.resultMessage.result
3383
+ try {
3384
+ const eventSource = new RuntimeEventSource();
3385
+ const stream = await currentAgent.remoteAgentHandler({
3386
+ name: agentName,
3387
+ threadId,
3388
+ nodeName,
3389
+ metaEvents,
3390
+ actionInputsWithoutAgents: allAvailableActions
3088
3391
  });
3089
- } else if (message.agentStateMessage) {
3090
- return plainToInstance(AgentStateMessage, {
3091
- id: message.id,
3092
- threadId: message.agentStateMessage.threadId,
3093
- createdAt: message.createdAt,
3094
- agentName: message.agentStateMessage.agentName,
3095
- nodeName: message.agentStateMessage.nodeName,
3096
- runId: message.agentStateMessage.runId,
3097
- active: message.agentStateMessage.active,
3098
- role: message.agentStateMessage.role,
3099
- state: JSON.parse(message.agentStateMessage.state),
3100
- running: message.agentStateMessage.running
3392
+ if (((_c = this.observability) == null ? void 0 : _c.enabled) && this.observability.progressive && publicApiKey) {
3393
+ const originalStream = eventSource.stream.bind(eventSource);
3394
+ eventSource.stream = async (callback) => {
3395
+ await originalStream(async (eventStream$) => {
3396
+ eventStream$.subscribe({
3397
+ next: (event) => {
3398
+ if (event.type === RuntimeEventTypes.TextMessageContent) {
3399
+ streamedChunks.push(event.content);
3400
+ try {
3401
+ const progressiveData = {
3402
+ threadId: threadId || "",
3403
+ runId: void 0,
3404
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3405
+ output: event.content,
3406
+ latency: Date.now() - requestStartTime,
3407
+ timestamp: Date.now(),
3408
+ provider: "agent",
3409
+ isProgressiveChunk: true,
3410
+ agentName,
3411
+ nodeName
3412
+ };
3413
+ Promise.resolve().then(() => {
3414
+ this.observability.hooks.handleResponse(progressiveData);
3415
+ }).catch((error) => {
3416
+ console.error("Error in progressive agent logging:", error);
3417
+ });
3418
+ } catch (error) {
3419
+ console.error("Error preparing progressive agent log data:", error);
3420
+ }
3421
+ }
3422
+ }
3423
+ });
3424
+ await callback(eventStream$);
3425
+ });
3426
+ };
3427
+ }
3428
+ eventSource.stream(async (eventStream$) => {
3429
+ from(stream).subscribe({
3430
+ next: (event) => eventStream$.next(event),
3431
+ error: async (err) => {
3432
+ var _a2;
3433
+ if (((_a2 = this.observability) == null ? void 0 : _a2.enabled) && publicApiKey) {
3434
+ try {
3435
+ const errorData = {
3436
+ threadId,
3437
+ runId: void 0,
3438
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3439
+ error: err instanceof Error ? err : String(err),
3440
+ timestamp: Date.now(),
3441
+ latency: Date.now() - requestStartTime,
3442
+ provider: "agent",
3443
+ agentName,
3444
+ nodeName
3445
+ };
3446
+ this.observability.hooks.handleError(errorData);
3447
+ } catch (logError) {
3448
+ console.error("Error logging agent error:", logError);
3449
+ }
3450
+ }
3451
+ const structuredError = ensureStructuredError2(err, (error) => this.convertStreamingErrorToStructured(error));
3452
+ await this.trace("error", {
3453
+ threadId,
3454
+ source: "agent",
3455
+ request: {
3456
+ operation: "processAgentRequest",
3457
+ method: "POST",
3458
+ startTime: requestStartTime
3459
+ },
3460
+ response: {
3461
+ endTime: Date.now(),
3462
+ latency: Date.now() - requestStartTime
3463
+ },
3464
+ agent: {
3465
+ name: agentName,
3466
+ nodeName
3467
+ },
3468
+ technical: {
3469
+ environment: process.env.NODE_ENV,
3470
+ stackTrace: err instanceof Error ? err.stack : void 0
3471
+ }
3472
+ }, structuredError, publicApiKey);
3473
+ eventStream$.error(structuredError);
3474
+ eventStream$.complete();
3475
+ },
3476
+ complete: () => eventStream$.complete()
3477
+ });
3101
3478
  });
3102
- } else {
3103
- return null;
3104
- }
3105
- });
3106
- return messages.filter((m) => m);
3107
- }
3108
- __name(convertGqlInputToMessages, "convertGqlInputToMessages");
3109
-
3110
- // src/lib/runtime/copilot-runtime.ts
3111
- import { from } from "rxjs";
3112
- import { Client as LangGraphClient2 } from "@langchain/langgraph-sdk";
3113
-
3114
- // src/lib/runtime/mcp-tools-utils.ts
3115
- function extractParametersFromSchema(toolOrSchema) {
3116
- var _a;
3117
- const parameters = [];
3118
- const schema = "schema" in (toolOrSchema || {}) ? toolOrSchema.schema : toolOrSchema;
3119
- const toolParameters = (schema == null ? void 0 : schema.parameters) || ((_a = schema == null ? void 0 : schema.parameters) == null ? void 0 : _a.jsonSchema);
3120
- const properties = toolParameters == null ? void 0 : toolParameters.properties;
3121
- const requiredParams = new Set((toolParameters == null ? void 0 : toolParameters.required) || []);
3122
- if (!properties) {
3123
- return parameters;
3124
- }
3125
- for (const paramName in properties) {
3126
- if (Object.prototype.hasOwnProperty.call(properties, paramName)) {
3127
- const paramDef = properties[paramName];
3128
- parameters.push({
3129
- name: paramName,
3130
- // Infer type, default to string. MCP schemas might have more complex types.
3131
- // This might need refinement based on common MCP schema practices.
3132
- type: paramDef.type || "string",
3133
- description: paramDef.description,
3134
- required: requiredParams.has(paramName)
3479
+ if (((_d = this.observability) == null ? void 0 : _d.enabled) && publicApiKey) {
3480
+ outputMessagesPromise.then((outputMessages) => {
3481
+ const responseData = {
3482
+ threadId,
3483
+ runId: void 0,
3484
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3485
+ // Use collected chunks for progressive mode or outputMessages for regular mode
3486
+ output: this.observability.progressive ? streamedChunks : outputMessages,
3487
+ latency: Date.now() - requestStartTime,
3488
+ timestamp: Date.now(),
3489
+ provider: "agent",
3490
+ isFinalResponse: true,
3491
+ agentName,
3492
+ nodeName
3493
+ };
3494
+ try {
3495
+ this.observability.hooks.handleResponse(responseData);
3496
+ } catch (logError) {
3497
+ console.error("Error logging agent response:", logError);
3498
+ }
3499
+ }).catch((error) => {
3500
+ console.error("Failed to get output messages for agent logging:", error);
3501
+ });
3502
+ }
3503
+ outputMessagesPromise.then((outputMessages) => {
3504
+ var _a2;
3505
+ (_a2 = this.onAfterRequest) == null ? void 0 : _a2.call(this, {
3506
+ threadId,
3507
+ runId: void 0,
3508
+ inputMessages: messages,
3509
+ outputMessages,
3510
+ properties: graphqlContext.properties
3511
+ });
3512
+ }).catch((_error) => {
3135
3513
  });
3514
+ return {
3515
+ threadId,
3516
+ runId: void 0,
3517
+ eventSource,
3518
+ serverSideActions,
3519
+ actionInputsWithoutAgents: allAvailableActions
3520
+ };
3521
+ } catch (error) {
3522
+ if (((_e = this.observability) == null ? void 0 : _e.enabled) && publicApiKey) {
3523
+ try {
3524
+ const errorData = {
3525
+ threadId,
3526
+ runId: void 0,
3527
+ model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3528
+ error: error instanceof Error ? error : String(error),
3529
+ timestamp: Date.now(),
3530
+ latency: Date.now() - requestStartTime,
3531
+ provider: "agent",
3532
+ agentName,
3533
+ nodeName
3534
+ };
3535
+ await this.observability.hooks.handleError(errorData);
3536
+ } catch (logError) {
3537
+ console.error("Error logging agent error:", logError);
3538
+ }
3539
+ }
3540
+ const structuredError = ensureStructuredError2(error, (err) => this.convertStreamingErrorToStructured(err));
3541
+ await this.trace("error", {
3542
+ threadId,
3543
+ source: "agent",
3544
+ request: {
3545
+ operation: "processAgentRequest",
3546
+ method: "POST",
3547
+ startTime: requestStartTime
3548
+ },
3549
+ response: {
3550
+ endTime: Date.now(),
3551
+ latency: Date.now() - requestStartTime
3552
+ },
3553
+ agent: {
3554
+ name: agentName,
3555
+ nodeName
3556
+ },
3557
+ technical: {
3558
+ environment: process.env.NODE_ENV,
3559
+ stackTrace: error instanceof Error ? error.stack : void 0
3560
+ }
3561
+ }, structuredError, publicApiKey);
3562
+ console.error("Error getting response:", error);
3563
+ throw structuredError;
3136
3564
  }
3137
3565
  }
3138
- return parameters;
3139
- }
3140
- __name(extractParametersFromSchema, "extractParametersFromSchema");
3141
- function convertMCPToolsToActions(mcpTools, mcpEndpoint) {
3142
- const actions = [];
3143
- for (const [toolName, tool] of Object.entries(mcpTools)) {
3144
- const parameters = extractParametersFromSchema(tool);
3145
- const handler = /* @__PURE__ */ __name(async (params) => {
3566
+ async getServerSideActions(request) {
3567
+ var _a, _b;
3568
+ const { graphqlContext, messages: rawMessages, agentStates, url } = request;
3569
+ const inputMessages = convertGqlInputToMessages(rawMessages);
3570
+ const langserveFunctions = [];
3571
+ for (const chainPromise of this.langserve) {
3146
3572
  try {
3147
- const result = await tool.execute({
3148
- params
3149
- });
3150
- return typeof result === "string" ? result : JSON.stringify(result);
3573
+ const chain = await chainPromise;
3574
+ langserveFunctions.push(chain);
3151
3575
  } catch (error) {
3152
- console.error(`Error executing MCP tool '${toolName}' from endpoint ${mcpEndpoint}:`, error);
3153
- throw new Error(`Execution failed for MCP tool '${toolName}': ${error instanceof Error ? error.message : String(error)}`);
3576
+ console.error("Error loading langserve chain:", error);
3154
3577
  }
3155
- }, "handler");
3156
- actions.push({
3157
- name: toolName,
3158
- description: tool.description || `MCP tool: ${toolName} (from ${mcpEndpoint})`,
3159
- parameters,
3160
- handler,
3161
- // Add metadata for easier identification/debugging
3162
- _isMCPTool: true,
3163
- _mcpEndpoint: mcpEndpoint
3578
+ }
3579
+ const remoteEndpointDefinitions = this.remoteEndpointDefinitions.map((endpoint) => ({
3580
+ ...endpoint,
3581
+ type: resolveEndpointType(endpoint)
3582
+ }));
3583
+ const remoteActions = await setupRemoteActions({
3584
+ remoteEndpointDefinitions,
3585
+ graphqlContext,
3586
+ messages: inputMessages,
3587
+ agentStates,
3588
+ frontendUrl: url,
3589
+ agents: this.agents,
3590
+ metaEvents: request.metaEvents
3164
3591
  });
3165
- }
3166
- return actions;
3167
- }
3168
- __name(convertMCPToolsToActions, "convertMCPToolsToActions");
3169
- function generateMcpToolInstructions(toolsMap) {
3170
- if (!toolsMap || Object.keys(toolsMap).length === 0) {
3171
- return "";
3172
- }
3173
- const toolEntries = Object.entries(toolsMap);
3174
- const toolsDoc = toolEntries.map(([name, tool]) => {
3175
- let paramsDoc = " No parameters required";
3176
- try {
3177
- if (tool.schema && typeof tool.schema === "object") {
3178
- const schema = tool.schema;
3179
- if (schema.properties) {
3180
- const requiredParams = schema.required || [];
3181
- const paramsList = Object.entries(schema.properties).map(([paramName, propSchema]) => {
3182
- const propDetails = propSchema;
3183
- const requiredMark = requiredParams.includes(paramName) ? "*" : "";
3184
- const typeInfo = propDetails.type || "any";
3185
- const description = propDetails.description ? ` - ${propDetails.description}` : "";
3186
- return ` - ${paramName}${requiredMark} (${typeInfo})${description}`;
3187
- });
3188
- if (paramsList.length > 0) {
3189
- paramsDoc = paramsList.join("\n");
3592
+ const configuredActions = typeof this.actions === "function" ? this.actions({
3593
+ properties: graphqlContext.properties,
3594
+ url
3595
+ }) : this.actions;
3596
+ const requestSpecificMCPActions = [];
3597
+ if (this.createMCPClientImpl) {
3598
+ const baseEndpoints = this.mcpServersConfig || [];
3599
+ const requestEndpoints = ((_a = graphqlContext.properties) == null ? void 0 : _a.mcpServers) || ((_b = graphqlContext.properties) == null ? void 0 : _b.mcpEndpoints) || [];
3600
+ const effectiveEndpointsMap = /* @__PURE__ */ new Map();
3601
+ [
3602
+ ...baseEndpoints
3603
+ ].forEach((ep) => {
3604
+ if (ep && ep.endpoint) {
3605
+ effectiveEndpointsMap.set(ep.endpoint, ep);
3606
+ }
3607
+ });
3608
+ [
3609
+ ...requestEndpoints
3610
+ ].forEach((ep) => {
3611
+ if (ep && ep.endpoint) {
3612
+ effectiveEndpointsMap.set(ep.endpoint, ep);
3613
+ }
3614
+ });
3615
+ const effectiveEndpoints = Array.from(effectiveEndpointsMap.values());
3616
+ for (const config of effectiveEndpoints) {
3617
+ const endpointUrl = config.endpoint;
3618
+ let actionsForEndpoint = this.mcpActionCache.get(endpointUrl);
3619
+ if (!actionsForEndpoint) {
3620
+ let client = null;
3621
+ try {
3622
+ client = await this.createMCPClientImpl(config);
3623
+ const tools = await client.tools();
3624
+ actionsForEndpoint = convertMCPToolsToActions(tools, endpointUrl);
3625
+ this.mcpActionCache.set(endpointUrl, actionsForEndpoint);
3626
+ } catch (error) {
3627
+ console.error(`MCP: Failed to fetch tools from endpoint ${endpointUrl}. Skipping. Error:`, error);
3628
+ actionsForEndpoint = [];
3629
+ this.mcpActionCache.set(endpointUrl, actionsForEndpoint);
3190
3630
  }
3191
3631
  }
3632
+ requestSpecificMCPActions.push(...actionsForEndpoint || []);
3192
3633
  }
3193
- } catch (e) {
3194
- console.error(`Error parsing schema for tool ${name}:`, e);
3195
3634
  }
3196
- return `- ${name}: ${tool.description || ""}
3197
- ${paramsDoc}`;
3198
- }).join("\n\n");
3199
- return `You have access to the following external tools provided by Model Context Protocol (MCP) servers:
3200
-
3201
- ${toolsDoc}
3202
-
3203
- When using these tools:
3204
- 1. Only provide valid parameters according to their type requirements
3205
- 2. Required parameters are marked with *
3206
- 3. Format API calls correctly with the expected parameter structure
3207
- 4. Always check tool responses to determine your next action`;
3208
- }
3209
- __name(generateMcpToolInstructions, "generateMcpToolInstructions");
3210
-
3211
- // src/lib/runtime/copilot-runtime.ts
3212
- var CopilotRuntime = class {
3213
- actions;
3214
- agents;
3215
- remoteEndpointDefinitions;
3216
- langserve = [];
3217
- onBeforeRequest;
3218
- onAfterRequest;
3219
- delegateAgentProcessingToServiceAdapter;
3220
- observability;
3221
- availableAgents;
3222
- // +++ MCP Properties +++
3223
- mcpServersConfig;
3224
- mcpActionCache = /* @__PURE__ */ new Map();
3225
- // --- MCP Properties ---
3226
- // +++ MCP Client Factory +++
3227
- createMCPClientImpl;
3228
- // --- MCP Client Factory ---
3229
- constructor(params) {
3230
- var _a, _b, _c, _d;
3231
- 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))) {
3232
- console.warn("Actions set in runtime instance will not be available for the agent");
3635
+ return [
3636
+ ...configuredActions,
3637
+ ...langserveFunctions,
3638
+ ...remoteActions,
3639
+ ...requestSpecificMCPActions
3640
+ ];
3641
+ }
3642
+ // Add helper method to detect provider
3643
+ detectProvider(serviceAdapter) {
3644
+ const adapterName = serviceAdapter.constructor.name;
3645
+ if (adapterName.includes("OpenAI"))
3646
+ return "openai";
3647
+ if (adapterName.includes("Anthropic"))
3648
+ return "anthropic";
3649
+ if (adapterName.includes("Google"))
3650
+ return "google";
3651
+ if (adapterName.includes("Groq"))
3652
+ return "groq";
3653
+ if (adapterName.includes("LangChain"))
3654
+ return "langchain";
3655
+ return void 0;
3656
+ }
3657
+ convertStreamingErrorToStructured(error) {
3658
+ var _a, _b, _c, _d, _e, _f, _g;
3659
+ let helpfulMessage = generateHelpfulErrorMessage(error, "agent streaming connection");
3660
+ 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") {
3661
+ return new CopilotKitLowLevelError3({
3662
+ error: error instanceof Error ? error : new Error(String(error)),
3663
+ url: "agent streaming connection",
3664
+ message: helpfulMessage
3665
+ });
3233
3666
  }
3234
- this.actions = (params == null ? void 0 : params.actions) || [];
3235
- this.availableAgents = [];
3236
- for (const chain of (params == null ? void 0 : params.langserve) || []) {
3237
- const remoteChain = new RemoteChain(chain);
3238
- this.langserve.push(remoteChain.toAction());
3667
+ return new CopilotKitError3({
3668
+ message: helpfulMessage,
3669
+ code: CopilotKitErrorCode2.UNKNOWN
3670
+ });
3671
+ }
3672
+ async trace(type, context, error, publicApiKey) {
3673
+ if (!this.onTrace)
3674
+ return;
3675
+ if (!publicApiKey) {
3676
+ if (!this.hasWarnedAboutTracing) {
3677
+ console.warn("CopilotKit: onTrace handler provided but requires publicApiKey to be defined for tracing to work.");
3678
+ this.hasWarnedAboutTracing = true;
3679
+ }
3680
+ return;
3239
3681
  }
3240
- this.remoteEndpointDefinitions = (params == null ? void 0 : params.remoteEndpoints) ?? (params == null ? void 0 : params.remoteActions) ?? [];
3241
- this.onBeforeRequest = (_a = params == null ? void 0 : params.middleware) == null ? void 0 : _a.onBeforeRequest;
3242
- this.onAfterRequest = (_b = params == null ? void 0 : params.middleware) == null ? void 0 : _b.onAfterRequest;
3243
- this.delegateAgentProcessingToServiceAdapter = (params == null ? void 0 : params.delegateAgentProcessingToServiceAdapter) || false;
3244
- this.observability = params == null ? void 0 : params.observability_c;
3245
- this.agents = (params == null ? void 0 : params.agents) ?? {};
3246
- this.mcpServersConfig = params == null ? void 0 : params.mcpServers;
3247
- this.createMCPClientImpl = params == null ? void 0 : params.createMCPClient;
3248
- if (this.mcpServersConfig && this.mcpServersConfig.length > 0 && !this.createMCPClientImpl) {
3249
- throw new CopilotKitMisuseError2({
3250
- message: "MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`."
3682
+ try {
3683
+ const traceEvent = {
3684
+ type,
3685
+ timestamp: Date.now(),
3686
+ context,
3687
+ ...error && {
3688
+ error
3689
+ }
3690
+ };
3691
+ await this.onTrace(traceEvent);
3692
+ } catch (traceError) {
3693
+ console.error("Error in onTrace handler:", traceError);
3694
+ }
3695
+ }
3696
+ /**
3697
+ * Public method to trace GraphQL validation errors
3698
+ * This allows the GraphQL resolver to send validation errors through the trace system
3699
+ */
3700
+ async traceGraphQLError(error, context) {
3701
+ if (!this.onTrace)
3702
+ return;
3703
+ try {
3704
+ await this.onTrace({
3705
+ type: "error",
3706
+ timestamp: Date.now(),
3707
+ context: {
3708
+ source: "runtime",
3709
+ request: {
3710
+ operation: context.operation,
3711
+ startTime: Date.now()
3712
+ },
3713
+ technical: {
3714
+ environment: process.env.NODE_ENV
3715
+ },
3716
+ metadata: {
3717
+ errorType: "GraphQLValidationError",
3718
+ cloudConfigPresent: context.cloudConfigPresent,
3719
+ guardrailsEnabled: context.guardrailsEnabled
3720
+ }
3721
+ },
3722
+ error
3251
3723
  });
3724
+ } catch (traceError) {
3725
+ console.error("Error in onTrace handler:", traceError);
3252
3726
  }
3253
- 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))) {
3254
- 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.");
3727
+ }
3728
+ };
3729
+ __name(CopilotRuntime, "CopilotRuntime");
3730
+ function flattenToolCallsNoDuplicates(toolsByPriority) {
3731
+ let allTools = [];
3732
+ const allToolNames = [];
3733
+ for (const tool of toolsByPriority) {
3734
+ if (!allToolNames.includes(tool.name)) {
3735
+ allTools.push(tool);
3736
+ allToolNames.push(tool.name);
3255
3737
  }
3256
3738
  }
3257
- // +++ MCP Instruction Injection Method +++
3258
- injectMCPToolInstructions(messages, currentActions) {
3259
- const mcpActionsForRequest = currentActions.filter((action) => action._isMCPTool);
3260
- if (!mcpActionsForRequest || mcpActionsForRequest.length === 0) {
3261
- return messages;
3739
+ return allTools;
3740
+ }
3741
+ __name(flattenToolCallsNoDuplicates, "flattenToolCallsNoDuplicates");
3742
+ function copilotKitEndpoint(config) {
3743
+ return {
3744
+ ...config,
3745
+ type: EndpointType.CopilotKit
3746
+ };
3747
+ }
3748
+ __name(copilotKitEndpoint, "copilotKitEndpoint");
3749
+ function langGraphPlatformEndpoint(config) {
3750
+ return {
3751
+ ...config,
3752
+ type: EndpointType.LangGraphPlatform
3753
+ };
3754
+ }
3755
+ __name(langGraphPlatformEndpoint, "langGraphPlatformEndpoint");
3756
+ function resolveEndpointType(endpoint) {
3757
+ if (!endpoint.type) {
3758
+ if ("deploymentUrl" in endpoint && "agents" in endpoint) {
3759
+ return EndpointType.LangGraphPlatform;
3760
+ } else {
3761
+ return EndpointType.CopilotKit;
3262
3762
  }
3263
- const uniqueMcpTools = /* @__PURE__ */ new Map();
3264
- mcpActionsForRequest.forEach((action) => {
3265
- uniqueMcpTools.set(action.name, action);
3266
- });
3267
- const toolsMap = {};
3268
- Array.from(uniqueMcpTools.values()).forEach((action) => {
3269
- toolsMap[action.name] = {
3270
- description: action.description || "",
3271
- schema: action.parameters ? {
3272
- parameters: {
3273
- properties: action.parameters.reduce((acc, p) => ({
3274
- ...acc,
3275
- [p.name]: {
3276
- type: p.type,
3277
- description: p.description
3278
- }
3279
- }), {}),
3280
- required: action.parameters.filter((p) => p.required).map((p) => p.name)
3281
- }
3282
- } : {},
3283
- execute: async () => ({})
3763
+ }
3764
+ return endpoint.type;
3765
+ }
3766
+ __name(resolveEndpointType, "resolveEndpointType");
3767
+
3768
+ // src/lib/telemetry-client.ts
3769
+ var packageJson = require_package();
3770
+ var telemetryClient = new TelemetryClient({
3771
+ packageName: packageJson.name,
3772
+ packageVersion: packageJson.version
3773
+ });
3774
+ function getRuntimeInstanceTelemetryInfo(options) {
3775
+ var _a, _b;
3776
+ const runtime = options.runtime;
3777
+ const endpointsInfo = runtime.remoteEndpointDefinitions.reduce((acc, endpoint) => {
3778
+ let info = {
3779
+ ...acc
3780
+ };
3781
+ const endpointType = resolveEndpointType(endpoint);
3782
+ if (!info.endpointTypes.includes(endpointType)) {
3783
+ info = {
3784
+ ...info,
3785
+ endpointTypes: [
3786
+ ...info.endpointTypes,
3787
+ endpointType
3788
+ ]
3284
3789
  };
3285
- });
3286
- const mcpToolInstructions = generateMcpToolInstructions(toolsMap);
3287
- if (!mcpToolInstructions) {
3288
- return messages;
3289
3790
  }
3290
- 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.";
3291
- const systemMessageIndex = messages.findIndex((msg) => {
3292
- var _a;
3293
- return ((_a = msg.textMessage) == null ? void 0 : _a.role) === "system";
3294
- });
3295
- const newMessages = [
3296
- ...messages
3297
- ];
3298
- if (systemMessageIndex !== -1) {
3299
- const existingMsg = newMessages[systemMessageIndex];
3300
- if (existingMsg.textMessage) {
3301
- existingMsg.textMessage.content = (existingMsg.textMessage.content ? existingMsg.textMessage.content + "\n\n" : "") + instructions;
3302
- }
3303
- } else {
3304
- newMessages.unshift({
3305
- id: randomId2(),
3306
- createdAt: /* @__PURE__ */ new Date(),
3307
- textMessage: {
3308
- role: MessageRole.system,
3309
- content: instructions
3310
- },
3311
- actionExecutionMessage: void 0,
3312
- resultMessage: void 0,
3313
- agentStateMessage: void 0
3314
- });
3791
+ if (endpointType === EndpointType.LangGraphPlatform) {
3792
+ const ep = endpoint;
3793
+ info = {
3794
+ ...info,
3795
+ agentsAmount: ep.agents.length,
3796
+ hashedKey: ep.langsmithApiKey ? createHash2("sha256").update(ep.langsmithApiKey).digest("hex") : null
3797
+ };
3798
+ }
3799
+ return info;
3800
+ }, {
3801
+ endpointTypes: [],
3802
+ agentsAmount: null,
3803
+ hashedKey: null
3804
+ });
3805
+ const publicApiKey = (_a = options.cloud) == null ? void 0 : _a.publicApiKey;
3806
+ const apiKeyProvided = !!publicApiKey && publicApiKey.trim().length > 0;
3807
+ return {
3808
+ actionsAmount: runtime.actions.length,
3809
+ endpointsAmount: runtime.remoteEndpointDefinitions.length,
3810
+ endpointTypes: endpointsInfo.endpointTypes,
3811
+ agentsAmount: endpointsInfo.agentsAmount,
3812
+ hashedLgcKey: endpointsInfo.hashedKey,
3813
+ "cloud.api_key_provided": apiKeyProvided,
3814
+ ...apiKeyProvided ? {
3815
+ "cloud.public_api_key": publicApiKey
3816
+ } : {},
3817
+ ...((_b = options.cloud) == null ? void 0 : _b.baseUrl) ? {
3818
+ "cloud.base_url": options.cloud.baseUrl
3819
+ } : {}
3820
+ };
3821
+ }
3822
+ __name(getRuntimeInstanceTelemetryInfo, "getRuntimeInstanceTelemetryInfo");
3823
+ var telemetry_client_default = telemetryClient;
3824
+
3825
+ // src/agents/langgraph/event-source.ts
3826
+ import { CopilotKitLowLevelError as CopilotKitLowLevelError4, isStructuredCopilotKitError } from "@copilotkit/shared";
3827
+ import { catchError, mergeMap, ReplaySubject, scan } from "rxjs";
3828
+ var RemoteLangGraphEventSource = class {
3829
+ eventStream$ = new ReplaySubject();
3830
+ shouldEmitToolCall(shouldEmitToolCalls, toolCallName) {
3831
+ if (typeof shouldEmitToolCalls === "boolean") {
3832
+ return shouldEmitToolCalls;
3315
3833
  }
3316
- return newMessages;
3834
+ if (Array.isArray(shouldEmitToolCalls)) {
3835
+ return shouldEmitToolCalls.includes(toolCallName);
3836
+ }
3837
+ return shouldEmitToolCalls === toolCallName;
3317
3838
  }
3318
- async processRuntimeRequest(request) {
3839
+ getCurrentContent(event) {
3319
3840
  var _a, _b, _c, _d, _e;
3320
- const { serviceAdapter, messages: rawMessages, actions: clientSideActionsInput, threadId, runId, outputMessagesPromise, graphqlContext, forwardedParameters, url, extensions, agentSession, agentStates, publicApiKey } = request;
3321
- const eventSource = new RuntimeEventSource();
3322
- const requestStartTime = Date.now();
3323
- const streamedChunks = [];
3324
- try {
3325
- if (agentSession && !this.delegateAgentProcessingToServiceAdapter) {
3326
- return await this.processAgentRequest(request);
3841
+ 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);
3842
+ if (!content) {
3843
+ const toolCallChunks = this.getCurrentToolCallChunks(event) ?? [];
3844
+ for (const chunk of toolCallChunks) {
3845
+ if (chunk.args) {
3846
+ return chunk.args;
3847
+ }
3327
3848
  }
3328
- if (serviceAdapter instanceof EmptyAdapter) {
3329
- throw new CopilotKitMisuseError2({
3330
- message: `Invalid adapter configuration: EmptyAdapter is only meant to be used with agent lock mode.
3331
- For non-agent components like useCopilotChatSuggestions, CopilotTextarea, or CopilotTask,
3332
- please use an LLM adapter instead.`
3849
+ }
3850
+ if (typeof content === "string") {
3851
+ return content;
3852
+ } else if (Array.isArray(content) && content.length > 0) {
3853
+ return content[0].text;
3854
+ }
3855
+ return null;
3856
+ }
3857
+ getCurrentMessageId(event) {
3858
+ var _a, _b, _c, _d, _e;
3859
+ 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);
3860
+ }
3861
+ getCurrentToolCallChunks(event) {
3862
+ var _a, _b, _c, _d, _e;
3863
+ 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);
3864
+ }
3865
+ getResponseMetadata(event) {
3866
+ var _a, _b, _c, _d, _e;
3867
+ 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);
3868
+ }
3869
+ processLangGraphEvents() {
3870
+ let lastEventWithState = null;
3871
+ return this.eventStream$.pipe(scan((acc, event) => {
3872
+ if (event.event === LangGraphEventTypes.OnChatModelStream) {
3873
+ const prevMessageId = acc.lastMessageId;
3874
+ acc.currentContent = this.getCurrentContent(event);
3875
+ acc.lastMessageId = this.getCurrentMessageId(event) ?? acc.lastMessageId;
3876
+ const toolCallChunks = this.getCurrentToolCallChunks(event) ?? [];
3877
+ const responseMetadata = this.getResponseMetadata(event);
3878
+ const toolCallCheck = toolCallChunks && toolCallChunks.length > 0;
3879
+ let isToolCallEnd = (responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "tool_calls";
3880
+ acc.isToolCallStart = toolCallChunks.some((chunk) => chunk.name && chunk.id);
3881
+ acc.isMessageStart = prevMessageId !== acc.lastMessageId && !acc.isToolCallStart;
3882
+ let previousRoundHadToolCall = acc.isToolCall;
3883
+ acc.isToolCall = toolCallCheck;
3884
+ if (previousRoundHadToolCall && !toolCallCheck) {
3885
+ isToolCallEnd = true;
3886
+ }
3887
+ acc.isToolCallEnd = isToolCallEnd;
3888
+ acc.isMessageEnd = (responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "stop";
3889
+ ({ name: acc.lastToolCallName, id: acc.lastToolCallId } = toolCallChunks.find((chunk) => chunk.name && chunk.id) ?? {
3890
+ name: acc.lastToolCallName,
3891
+ id: acc.lastToolCallId
3333
3892
  });
3334
3893
  }
3335
- const serverSideActions = await this.getServerSideActions(request);
3336
- const filteredRawMessages = rawMessages.filter((message) => !message.agentStateMessage);
3337
- const messagesWithInjectedInstructions = this.injectMCPToolInstructions(filteredRawMessages, serverSideActions);
3338
- const inputMessages = convertGqlInputToMessages(messagesWithInjectedInstructions);
3339
- if (((_a = this.observability) == null ? void 0 : _a.enabled) && publicApiKey) {
3340
- try {
3341
- const requestData = {
3342
- threadId,
3343
- runId,
3344
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3345
- messages: inputMessages,
3346
- actions: clientSideActionsInput,
3347
- forwardedParameters,
3348
- timestamp: requestStartTime,
3349
- provider: this.detectProvider(serviceAdapter)
3350
- };
3351
- await this.observability.hooks.handleRequest(requestData);
3352
- } catch (error) {
3353
- console.error("Error logging LLM request:", error);
3894
+ acc.event = event;
3895
+ lastEventWithState = acc;
3896
+ return acc;
3897
+ }, {
3898
+ event: null,
3899
+ isMessageStart: false,
3900
+ isMessageEnd: false,
3901
+ isToolCallStart: false,
3902
+ isToolCallEnd: false,
3903
+ isToolCall: false,
3904
+ lastMessageId: null,
3905
+ lastToolCallId: null,
3906
+ lastToolCallName: null,
3907
+ currentContent: null,
3908
+ processedToolCallIds: /* @__PURE__ */ new Set()
3909
+ }), mergeMap((acc) => {
3910
+ const events = [];
3911
+ let shouldEmitMessages = true;
3912
+ let shouldEmitToolCalls = true;
3913
+ if (acc.event.event == LangGraphEventTypes.OnChatModelStream) {
3914
+ if ("copilotkit:emit-tool-calls" in (acc.event.metadata || {})) {
3915
+ shouldEmitToolCalls = acc.event.metadata["copilotkit:emit-tool-calls"];
3354
3916
  }
3355
- }
3356
- const serverSideActionsInput = serverSideActions.map((action) => ({
3357
- name: action.name,
3358
- description: action.description,
3359
- jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters))
3360
- }));
3361
- const actionInputs = flattenToolCallsNoDuplicates([
3362
- ...serverSideActionsInput,
3363
- ...clientSideActionsInput.filter(
3364
- // Filter remote actions from CopilotKit core loop
3365
- (action) => action.available !== ActionInputAvailability.remote
3366
- )
3367
- ]);
3368
- await ((_b = this.onBeforeRequest) == null ? void 0 : _b.call(this, {
3369
- threadId,
3370
- runId,
3371
- inputMessages,
3372
- properties: graphqlContext.properties,
3373
- url
3374
- }));
3375
- const result = await serviceAdapter.process({
3376
- messages: inputMessages,
3377
- actions: actionInputs,
3378
- threadId,
3379
- runId,
3380
- eventSource,
3381
- forwardedParameters,
3382
- extensions,
3383
- agentSession,
3384
- agentStates
3385
- });
3386
- const nonEmptyThreadId = threadId ?? result.threadId;
3387
- outputMessagesPromise.then((outputMessages) => {
3388
- var _a2;
3389
- (_a2 = this.onAfterRequest) == null ? void 0 : _a2.call(this, {
3390
- threadId: nonEmptyThreadId,
3391
- runId: result.runId,
3392
- inputMessages,
3393
- outputMessages,
3394
- properties: graphqlContext.properties,
3395
- url
3396
- });
3397
- }).catch((_error) => {
3398
- });
3399
- if (((_c = this.observability) == null ? void 0 : _c.enabled) && publicApiKey) {
3400
- try {
3401
- outputMessagesPromise.then((outputMessages) => {
3402
- const responseData = {
3403
- threadId: result.threadId,
3404
- runId: result.runId,
3405
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3406
- // Use collected chunks for progressive mode or outputMessages for regular mode
3407
- output: this.observability.progressive ? streamedChunks : outputMessages,
3408
- latency: Date.now() - requestStartTime,
3409
- timestamp: Date.now(),
3410
- provider: this.detectProvider(serviceAdapter),
3411
- // Indicate this is the final response
3412
- isFinalResponse: true
3413
- };
3414
- try {
3415
- this.observability.hooks.handleResponse(responseData);
3416
- } catch (logError) {
3417
- console.error("Error logging LLM response:", logError);
3418
- }
3419
- }).catch((error) => {
3420
- console.error("Failed to get output messages for logging:", error);
3421
- });
3422
- } catch (error) {
3423
- console.error("Error setting up logging for LLM response:", error);
3917
+ if ("copilotkit:emit-messages" in (acc.event.metadata || {})) {
3918
+ shouldEmitMessages = acc.event.metadata["copilotkit:emit-messages"];
3424
3919
  }
3425
3920
  }
3426
- if (((_d = this.observability) == null ? void 0 : _d.enabled) && this.observability.progressive && publicApiKey) {
3427
- const originalStream = eventSource.stream.bind(eventSource);
3428
- eventSource.stream = async (callback) => {
3429
- await originalStream(async (eventStream$) => {
3430
- eventStream$.subscribe({
3431
- next: (event) => {
3432
- if (event.type === RuntimeEventTypes.TextMessageContent) {
3433
- streamedChunks.push(event.content);
3434
- try {
3435
- const progressiveData = {
3436
- threadId: threadId || "",
3437
- runId,
3438
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3439
- output: event.content,
3440
- latency: Date.now() - requestStartTime,
3441
- timestamp: Date.now(),
3442
- provider: this.detectProvider(serviceAdapter),
3443
- isProgressiveChunk: true
3444
- };
3445
- Promise.resolve().then(() => {
3446
- this.observability.hooks.handleResponse(progressiveData);
3447
- }).catch((error) => {
3448
- console.error("Error in progressive logging:", error);
3449
- });
3450
- } catch (error) {
3451
- console.error("Error preparing progressive log data:", error);
3452
- }
3453
- }
3454
- }
3455
- });
3456
- await callback(eventStream$);
3457
- });
3458
- };
3921
+ if (acc.event.event === LangGraphEventTypes.OnInterrupt) {
3922
+ events.push({
3923
+ type: RuntimeEventTypes.MetaEvent,
3924
+ name: RuntimeMetaEventName.LangGraphInterruptEvent,
3925
+ value: acc.event.value
3926
+ });
3459
3927
  }
3460
- return {
3461
- threadId: nonEmptyThreadId,
3462
- runId: result.runId,
3463
- eventSource,
3464
- serverSideActions,
3465
- actionInputsWithoutAgents: actionInputs.filter((action) => (
3466
- // TODO-AGENTS: do not exclude ALL server side actions
3467
- !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name)
3468
- )),
3469
- extensions: result.extensions
3470
- };
3471
- } catch (error) {
3472
- if (((_e = this.observability) == null ? void 0 : _e.enabled) && publicApiKey) {
3473
- try {
3474
- const errorData = {
3475
- threadId,
3476
- runId,
3477
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3478
- error: error instanceof Error ? error : String(error),
3479
- timestamp: Date.now(),
3480
- latency: Date.now() - requestStartTime,
3481
- provider: this.detectProvider(serviceAdapter)
3482
- };
3483
- await this.observability.hooks.handleError(errorData);
3484
- } catch (logError) {
3485
- console.error("Error logging LLM error:", logError);
3486
- }
3928
+ if (acc.event.event === LangGraphEventTypes.OnCopilotKitInterrupt) {
3929
+ events.push({
3930
+ type: RuntimeEventTypes.MetaEvent,
3931
+ name: RuntimeMetaEventName.CopilotKitLangGraphInterruptEvent,
3932
+ data: acc.event.data
3933
+ });
3487
3934
  }
3488
- if (error instanceof CopilotKitError5) {
3489
- throw error;
3935
+ if (acc.event.event === LangGraphEventTypes.OnCopilotKitError) {
3936
+ const errorData = acc.event.data.error;
3937
+ const preservedError = new CopilotKitLowLevelError4({
3938
+ error: new Error(errorData.message),
3939
+ url: "langgraph agent",
3940
+ message: `${errorData.type}: ${errorData.message}`
3941
+ });
3942
+ if (errorData.status_code) {
3943
+ preservedError.statusCode = errorData.status_code;
3944
+ }
3945
+ if (errorData.response_data) {
3946
+ preservedError.responseData = errorData.response_data;
3947
+ }
3948
+ preservedError.agentName = errorData.agent_name;
3949
+ preservedError.originalErrorType = errorData.type;
3950
+ throw preservedError;
3490
3951
  }
3491
- console.error("Error getting response:", error);
3492
- const structuredError = this.convertStreamingErrorToStructured(error);
3493
- throw structuredError;
3494
- }
3495
- }
3496
- async discoverAgentsFromEndpoints(graphqlContext) {
3497
- const agents = this.remoteEndpointDefinitions.reduce(async (acc, endpoint) => {
3498
- const agents2 = await acc;
3499
- if (endpoint.type === EndpointType.LangGraphPlatform) {
3500
- const propertyHeaders = graphqlContext.properties.authorization ? {
3501
- authorization: `Bearer ${graphqlContext.properties.authorization}`
3502
- } : null;
3503
- const client = new LangGraphClient2({
3504
- apiUrl: endpoint.deploymentUrl,
3505
- apiKey: endpoint.langsmithApiKey,
3506
- defaultHeaders: {
3507
- ...propertyHeaders
3508
- }
3952
+ const responseMetadata = this.getResponseMetadata(acc.event);
3953
+ if (acc.isToolCallEnd && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName) && acc.lastToolCallId && !acc.processedToolCallIds.has(acc.lastToolCallId)) {
3954
+ acc.processedToolCallIds.add(acc.lastToolCallId);
3955
+ events.push({
3956
+ type: RuntimeEventTypes.ActionExecutionEnd,
3957
+ actionExecutionId: acc.lastToolCallId
3509
3958
  });
3510
- let data = [];
3511
- try {
3512
- data = await client.assistants.search();
3513
- if (data && "detail" in data && data.detail.toLowerCase() === "not found") {
3514
- throw new CopilotKitAgentDiscoveryError({
3515
- availableAgents: this.availableAgents
3959
+ } else if ((responseMetadata == null ? void 0 : responseMetadata.finish_reason) === "stop" && shouldEmitMessages) {
3960
+ events.push({
3961
+ type: RuntimeEventTypes.TextMessageEnd,
3962
+ messageId: acc.lastMessageId
3963
+ });
3964
+ }
3965
+ switch (acc.event.event) {
3966
+ case LangGraphEventTypes.OnCustomEvent:
3967
+ if (acc.event.name === CustomEventNames.CopilotKitManuallyEmitMessage) {
3968
+ events.push({
3969
+ type: RuntimeEventTypes.TextMessageStart,
3970
+ messageId: acc.event.data.message_id
3971
+ });
3972
+ events.push({
3973
+ type: RuntimeEventTypes.TextMessageContent,
3974
+ messageId: acc.event.data.message_id,
3975
+ content: acc.event.data.message
3976
+ });
3977
+ events.push({
3978
+ type: RuntimeEventTypes.TextMessageEnd,
3979
+ messageId: acc.event.data.message_id
3980
+ });
3981
+ } else if (acc.event.name === CustomEventNames.CopilotKitManuallyEmitToolCall) {
3982
+ events.push({
3983
+ type: RuntimeEventTypes.ActionExecutionStart,
3984
+ actionExecutionId: acc.event.data.id,
3985
+ actionName: acc.event.data.name,
3986
+ parentMessageId: acc.event.data.id
3987
+ });
3988
+ events.push({
3989
+ type: RuntimeEventTypes.ActionExecutionArgs,
3990
+ actionExecutionId: acc.event.data.id,
3991
+ args: JSON.stringify(acc.event.data.args)
3992
+ });
3993
+ events.push({
3994
+ type: RuntimeEventTypes.ActionExecutionEnd,
3995
+ actionExecutionId: acc.event.data.id
3516
3996
  });
3517
3997
  }
3518
- } catch (e) {
3519
- throw new CopilotKitMisuseError2({
3520
- message: `
3521
- Failed to find or contact remote endpoint at url ${endpoint.deploymentUrl}.
3522
- Make sure the API is running and that it's indeed a LangGraph platform url.
3523
-
3524
- See more: https://docs.copilotkit.ai/troubleshooting/common-issues`
3998
+ break;
3999
+ case LangGraphEventTypes.OnCopilotKitStateSync:
4000
+ events.push({
4001
+ type: RuntimeEventTypes.AgentStateMessage,
4002
+ threadId: acc.event.thread_id,
4003
+ role: acc.event.role,
4004
+ agentName: acc.event.agent_name,
4005
+ nodeName: acc.event.node_name,
4006
+ runId: acc.event.run_id,
4007
+ active: acc.event.active,
4008
+ state: JSON.stringify(acc.event.state),
4009
+ running: acc.event.running
3525
4010
  });
4011
+ break;
4012
+ case LangGraphEventTypes.OnChatModelStream:
4013
+ if (acc.isToolCallStart && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName)) {
4014
+ events.push({
4015
+ type: RuntimeEventTypes.ActionExecutionStart,
4016
+ actionExecutionId: acc.lastToolCallId,
4017
+ actionName: acc.lastToolCallName,
4018
+ parentMessageId: acc.lastMessageId
4019
+ });
4020
+ } else if (acc.isMessageStart && shouldEmitMessages) {
4021
+ acc.processedToolCallIds.clear();
4022
+ events.push({
4023
+ type: RuntimeEventTypes.TextMessageStart,
4024
+ messageId: acc.lastMessageId
4025
+ });
4026
+ }
4027
+ if (acc.isToolCall && acc.currentContent && this.shouldEmitToolCall(shouldEmitToolCalls, acc.lastToolCallName)) {
4028
+ events.push({
4029
+ type: RuntimeEventTypes.ActionExecutionArgs,
4030
+ actionExecutionId: acc.lastToolCallId,
4031
+ args: acc.currentContent
4032
+ });
4033
+ } else if (!acc.isToolCall && acc.currentContent && shouldEmitMessages) {
4034
+ events.push({
4035
+ type: RuntimeEventTypes.TextMessageContent,
4036
+ messageId: acc.lastMessageId,
4037
+ content: acc.currentContent
4038
+ });
4039
+ }
4040
+ break;
4041
+ }
4042
+ return events;
4043
+ }), catchError((error) => {
4044
+ if (isStructuredCopilotKitError(error)) {
4045
+ throw error;
4046
+ }
4047
+ let helpfulMessage = generateHelpfulErrorMessage(error, "LangGraph agent connection");
4048
+ throw new CopilotKitLowLevelError4({
4049
+ error: error instanceof Error ? error : new Error(String(error)),
4050
+ url: "langgraph event stream",
4051
+ message: helpfulMessage
4052
+ });
4053
+ }));
4054
+ }
4055
+ };
4056
+ __name(RemoteLangGraphEventSource, "RemoteLangGraphEventSource");
4057
+
4058
+ // src/lib/runtime/remote-action-constructors.ts
4059
+ import { CopilotKitError as CopilotKitError4, CopilotKitLowLevelError as CopilotKitLowLevelError5 } from "@copilotkit/shared";
4060
+ import { CopilotKitApiDiscoveryError as CopilotKitApiDiscoveryError2, ResolvedCopilotKitError as ResolvedCopilotKitError2 } from "@copilotkit/shared";
4061
+ import { parseJson as parseJson2, tryMap as tryMap2 } from "@copilotkit/shared";
4062
+ function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, messages, agentStates }) {
4063
+ const agents = endpoint.agents.map((agent) => ({
4064
+ name: agent.name,
4065
+ description: agent.description,
4066
+ parameters: [],
4067
+ handler: async (_args) => {
4068
+ },
4069
+ remoteAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName, additionalMessages = [], metaEvents }) => {
4070
+ logger2.debug({
4071
+ actionName: agent.name
4072
+ }, "Executing LangGraph Platform agent");
4073
+ telemetry_client_default.capture("oss.runtime.remote_action_executed", {
4074
+ agentExecution: true,
4075
+ type: "langgraph-platform",
4076
+ agentsAmount: endpoint.agents.length,
4077
+ hashedLgcKey: endpoint.langsmithApiKey ? createHash3("sha256").update(endpoint.langsmithApiKey).digest("hex") : null
4078
+ });
4079
+ let state = {};
4080
+ let config = {};
4081
+ if (agentStates) {
4082
+ const jsonState = agentStates.find((state2) => state2.agentName === name);
4083
+ if (jsonState) {
4084
+ state = parseJson2(jsonState.state, {});
4085
+ config = parseJson2(jsonState.config, {});
3526
4086
  }
3527
- const endpointAgents = data.map((entry) => ({
3528
- name: entry.graph_id,
3529
- id: entry.assistant_id,
3530
- description: "",
3531
- endpoint
3532
- }));
3533
- return [
3534
- ...agents2,
3535
- ...endpointAgents
3536
- ];
3537
4087
  }
3538
- const cpkEndpoint = endpoint;
3539
- const fetchUrl = `${endpoint.url}/info`;
3540
4088
  try {
3541
- const response = await fetchWithRetry(fetchUrl, {
3542
- method: "POST",
3543
- headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
3544
- body: JSON.stringify({
3545
- properties: graphqlContext.properties
3546
- })
4089
+ const response = await execute({
4090
+ logger: logger2.child({
4091
+ component: "remote-actions.remote-lg-action.streamEvents"
4092
+ }),
4093
+ deploymentUrl: endpoint.deploymentUrl,
4094
+ langsmithApiKey: endpoint.langsmithApiKey,
4095
+ agent,
4096
+ threadId,
4097
+ nodeName,
4098
+ messages: [
4099
+ ...messages,
4100
+ ...additionalMessages
4101
+ ],
4102
+ state,
4103
+ config,
4104
+ properties: graphqlContext.properties,
4105
+ actions: tryMap2(actionInputsWithoutAgents, (action) => ({
4106
+ name: action.name,
4107
+ description: action.description,
4108
+ parameters: JSON.parse(action.jsonSchema)
4109
+ })),
4110
+ metaEvents
3547
4111
  });
3548
- if (!response.ok) {
3549
- if (response.status === 404) {
3550
- throw new CopilotKitApiDiscoveryError2({
3551
- url: fetchUrl
3552
- });
3553
- }
3554
- throw new ResolvedCopilotKitError3({
3555
- status: response.status,
3556
- url: fetchUrl,
3557
- isRemoteEndpoint: true
3558
- });
3559
- }
3560
- const data = await response.json();
3561
- const endpointAgents = ((data == null ? void 0 : data.agents) ?? []).map((agent) => ({
3562
- name: agent.name,
3563
- description: agent.description ?? "" ?? "",
3564
- id: randomId2(),
3565
- endpoint
3566
- }));
3567
- return [
3568
- ...agents2,
3569
- ...endpointAgents
3570
- ];
4112
+ const eventSource = new RemoteLangGraphEventSource();
4113
+ writeJsonLineResponseToEventStream(response, eventSource.eventStream$);
4114
+ return eventSource.processLangGraphEvents();
3571
4115
  } catch (error) {
3572
- if (error instanceof CopilotKitError5) {
4116
+ if (error instanceof CopilotKitError4 || error instanceof CopilotKitLowLevelError5) {
4117
+ if (isUserConfigurationError(error)) {
4118
+ logger2.debug({
4119
+ url: endpoint.deploymentUrl,
4120
+ error: error.message,
4121
+ code: error.code
4122
+ }, "User configuration error in LangGraph Platform agent");
4123
+ } else {
4124
+ logger2.error({
4125
+ url: endpoint.deploymentUrl,
4126
+ error: error.message,
4127
+ type: error.constructor.name
4128
+ }, "LangGraph Platform agent error");
4129
+ }
3573
4130
  throw error;
3574
4131
  }
3575
- throw new CopilotKitLowLevelError4({
3576
- error,
3577
- url: fetchUrl
4132
+ logger2.error({
4133
+ url: endpoint.deploymentUrl,
4134
+ status: 500,
4135
+ body: error.message
4136
+ }, "Failed to execute LangGraph Platform agent");
4137
+ throw new CopilotKitLowLevelError5({
4138
+ error: error instanceof Error ? error : new Error(String(error)),
4139
+ url: endpoint.deploymentUrl,
4140
+ message: "Failed to execute LangGraph Platform agent"
3578
4141
  });
3579
4142
  }
3580
- }, Promise.resolve([]));
3581
- this.availableAgents = (await agents ?? []).map((a) => ({
3582
- name: a.name,
3583
- id: a.id
3584
- }));
3585
- return agents;
3586
- }
3587
- async loadAgentState(graphqlContext, threadId, agentName) {
3588
- const agentsWithEndpoints = await this.discoverAgentsFromEndpoints(graphqlContext);
3589
- const agentWithEndpoint = agentsWithEndpoints.find((agent) => agent.name === agentName);
3590
- if (!agentWithEndpoint) {
3591
- throw new Error("Agent not found");
3592
4143
  }
3593
- if (agentWithEndpoint.endpoint.type === EndpointType.LangGraphPlatform) {
3594
- const propertyHeaders = graphqlContext.properties.authorization ? {
3595
- authorization: `Bearer ${graphqlContext.properties.authorization}`
3596
- } : null;
3597
- const client = new LangGraphClient2({
3598
- apiUrl: agentWithEndpoint.endpoint.deploymentUrl,
3599
- apiKey: agentWithEndpoint.endpoint.langsmithApiKey,
3600
- defaultHeaders: {
3601
- ...propertyHeaders
3602
- }
4144
+ }));
4145
+ return [
4146
+ ...agents
4147
+ ];
4148
+ }
4149
+ __name(constructLGCRemoteAction, "constructLGCRemoteAction");
4150
+ var RemoteAgentType;
4151
+ (function(RemoteAgentType2) {
4152
+ RemoteAgentType2["LangGraph"] = "langgraph";
4153
+ RemoteAgentType2["CrewAI"] = "crewai";
4154
+ })(RemoteAgentType || (RemoteAgentType = {}));
4155
+ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, logger: logger2, messages, agentStates }) {
4156
+ const totalAgents = Array.isArray(json["agents"]) ? json["agents"].length : 0;
4157
+ const actions = json["actions"].map((action) => ({
4158
+ name: action.name,
4159
+ description: action.description,
4160
+ parameters: action.parameters,
4161
+ handler: async (args) => {
4162
+ logger2.debug({
4163
+ actionName: action.name,
4164
+ args
4165
+ }, "Executing remote action");
4166
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
4167
+ telemetry_client_default.capture("oss.runtime.remote_action_executed", {
4168
+ agentExecution: false,
4169
+ type: "self-hosted",
4170
+ agentsAmount: totalAgents
3603
4171
  });
3604
- let state = {};
3605
- try {
3606
- state = (await client.threads.getState(threadId)).values;
3607
- } catch (error) {
3608
- }
3609
- if (Object.keys(state).length === 0) {
3610
- return {
3611
- threadId: threadId || "",
3612
- threadExists: false,
3613
- state: JSON.stringify({}),
3614
- messages: JSON.stringify([])
3615
- };
3616
- } else {
3617
- const { messages, ...stateWithoutMessages } = state;
3618
- const copilotkitMessages = langchainMessagesToCopilotKit(messages);
3619
- return {
3620
- threadId: threadId || "",
3621
- threadExists: true,
3622
- state: JSON.stringify(stateWithoutMessages),
3623
- messages: JSON.stringify(copilotkitMessages)
3624
- };
3625
- }
3626
- } else if (agentWithEndpoint.endpoint.type === EndpointType.CopilotKit || !("type" in agentWithEndpoint.endpoint)) {
3627
- const cpkEndpoint = agentWithEndpoint.endpoint;
3628
- const fetchUrl = `${cpkEndpoint.url}/agents/state`;
4172
+ const fetchUrl = `${url}/actions/execute`;
3629
4173
  try {
3630
4174
  const response = await fetchWithRetry(fetchUrl, {
3631
4175
  method: "POST",
3632
- headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),
4176
+ headers,
3633
4177
  body: JSON.stringify({
3634
- properties: graphqlContext.properties,
3635
- threadId,
3636
- name: agentName
4178
+ name: action.name,
4179
+ arguments: args,
4180
+ properties: graphqlContext.properties
3637
4181
  })
3638
- });
4182
+ }, logger2);
3639
4183
  if (!response.ok) {
4184
+ logger2.error({
4185
+ url,
4186
+ status: response.status,
4187
+ body: await response.text()
4188
+ }, "Failed to execute remote action");
3640
4189
  if (response.status === 404) {
3641
4190
  throw new CopilotKitApiDiscoveryError2({
3642
4191
  url: fetchUrl
3643
4192
  });
3644
4193
  }
3645
- throw new ResolvedCopilotKitError3({
4194
+ throw new ResolvedCopilotKitError2({
3646
4195
  status: response.status,
3647
4196
  url: fetchUrl,
3648
4197
  isRemoteEndpoint: true
3649
4198
  });
3650
4199
  }
3651
- const data = await response.json();
3652
- return {
3653
- ...data,
3654
- state: JSON.stringify(data.state),
3655
- messages: JSON.stringify(data.messages)
3656
- };
4200
+ const requestResult = await response.json();
4201
+ const result = requestResult["result"];
4202
+ logger2.debug({
4203
+ actionName: action.name,
4204
+ result
4205
+ }, "Executed remote action");
4206
+ return result;
3657
4207
  } catch (error) {
3658
- if (error instanceof CopilotKitError5) {
4208
+ if (error instanceof CopilotKitError4 || error instanceof CopilotKitLowLevelError5) {
3659
4209
  throw error;
3660
4210
  }
3661
- throw new CopilotKitLowLevelError4({
4211
+ throw new CopilotKitLowLevelError5({
3662
4212
  error,
3663
4213
  url: fetchUrl
3664
4214
  });
3665
4215
  }
3666
- } else {
3667
- throw new Error(`Unknown endpoint type: ${agentWithEndpoint.endpoint.type}`);
3668
- }
3669
- }
3670
- async processAgentRequest(request) {
3671
- var _a, _b, _c, _d, _e;
3672
- const { messages: rawMessages, outputMessagesPromise, graphqlContext, agentSession, threadId: threadIdFromRequest, metaEvents, publicApiKey, forwardedParameters } = request;
3673
- const { agentName, nodeName } = agentSession;
3674
- const requestStartTime = Date.now();
3675
- const streamedChunks = [];
3676
- const threadId = threadIdFromRequest ?? agentSession.threadId;
3677
- const serverSideActions = await this.getServerSideActions(request);
3678
- const messages = convertGqlInputToMessages(rawMessages);
3679
- const currentAgent = serverSideActions.find((action) => action.name === agentName && isRemoteAgentAction(action));
3680
- if (!currentAgent) {
3681
- throw new CopilotKitAgentDiscoveryError({
3682
- agentName,
3683
- availableAgents: this.availableAgents
3684
- });
3685
- }
3686
- const availableActionsForCurrentAgent = serverSideActions.filter((action) => (
3687
- // Case 1: Keep all regular (non-agent) actions
3688
- !isRemoteAgentAction(action) || // Case 2: For agent actions, keep all except self (prevent infinite loops)
3689
- isRemoteAgentAction(action) && action.name !== agentName
3690
- )).map((action) => ({
3691
- name: action.name,
3692
- description: action.description,
3693
- jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters))
3694
- }));
3695
- const allAvailableActions = flattenToolCallsNoDuplicates([
3696
- ...availableActionsForCurrentAgent,
3697
- ...request.actions
3698
- ]);
3699
- if (((_a = this.observability) == null ? void 0 : _a.enabled) && publicApiKey) {
3700
- try {
3701
- const requestData = {
3702
- threadId,
3703
- runId: void 0,
3704
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3705
- messages,
3706
- actions: allAvailableActions,
3707
- forwardedParameters,
3708
- timestamp: requestStartTime,
3709
- provider: "agent",
3710
- agentName,
3711
- nodeName
3712
- };
3713
- await this.observability.hooks.handleRequest(requestData);
3714
- } catch (error) {
3715
- console.error("Error logging agent request:", error);
3716
- }
3717
4216
  }
3718
- await ((_b = this.onBeforeRequest) == null ? void 0 : _b.call(this, {
3719
- threadId,
3720
- runId: void 0,
3721
- inputMessages: messages,
3722
- properties: graphqlContext.properties
3723
- }));
3724
- try {
3725
- const eventSource = new RuntimeEventSource();
3726
- const stream = await currentAgent.remoteAgentHandler({
3727
- name: agentName,
3728
- threadId,
3729
- nodeName,
3730
- metaEvents,
3731
- actionInputsWithoutAgents: allAvailableActions
3732
- });
3733
- if (((_c = this.observability) == null ? void 0 : _c.enabled) && this.observability.progressive && publicApiKey) {
3734
- const originalStream = eventSource.stream.bind(eventSource);
3735
- eventSource.stream = async (callback) => {
3736
- await originalStream(async (eventStream$) => {
3737
- eventStream$.subscribe({
3738
- next: (event) => {
3739
- if (event.type === RuntimeEventTypes.TextMessageContent) {
3740
- streamedChunks.push(event.content);
3741
- try {
3742
- const progressiveData = {
3743
- threadId: threadId || "",
3744
- runId: void 0,
3745
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3746
- output: event.content,
3747
- latency: Date.now() - requestStartTime,
3748
- timestamp: Date.now(),
3749
- provider: "agent",
3750
- isProgressiveChunk: true,
3751
- agentName,
3752
- nodeName
3753
- };
3754
- Promise.resolve().then(() => {
3755
- this.observability.hooks.handleResponse(progressiveData);
3756
- }).catch((error) => {
3757
- console.error("Error in progressive agent logging:", error);
3758
- });
3759
- } catch (error) {
3760
- console.error("Error preparing progressive agent log data:", error);
3761
- }
3762
- }
3763
- }
3764
- });
3765
- await callback(eventStream$);
3766
- });
3767
- };
3768
- }
3769
- eventSource.stream(async (eventStream$) => {
3770
- from(stream).subscribe({
3771
- next: (event) => eventStream$.next(event),
3772
- error: (err) => {
3773
- var _a2;
3774
- console.error("Error in stream", err);
3775
- if (((_a2 = this.observability) == null ? void 0 : _a2.enabled) && publicApiKey) {
3776
- try {
3777
- const errorData = {
3778
- threadId,
3779
- runId: void 0,
3780
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3781
- error: err instanceof Error ? err : String(err),
3782
- timestamp: Date.now(),
3783
- latency: Date.now() - requestStartTime,
3784
- provider: "agent",
3785
- agentName,
3786
- nodeName
3787
- };
3788
- this.observability.hooks.handleError(errorData);
3789
- } catch (logError) {
3790
- console.error("Error logging agent error:", logError);
3791
- }
3792
- }
3793
- const structuredError = this.convertStreamingErrorToStructured(err);
3794
- eventStream$.error(structuredError);
3795
- eventStream$.complete();
3796
- },
3797
- complete: () => eventStream$.complete()
3798
- });
3799
- });
3800
- if (((_d = this.observability) == null ? void 0 : _d.enabled) && publicApiKey) {
3801
- outputMessagesPromise.then((outputMessages) => {
3802
- const responseData = {
3803
- threadId,
3804
- runId: void 0,
3805
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3806
- // Use collected chunks for progressive mode or outputMessages for regular mode
3807
- output: this.observability.progressive ? streamedChunks : outputMessages,
3808
- latency: Date.now() - requestStartTime,
3809
- timestamp: Date.now(),
3810
- provider: "agent",
3811
- isFinalResponse: true,
3812
- agentName,
3813
- nodeName
3814
- };
3815
- try {
3816
- this.observability.hooks.handleResponse(responseData);
3817
- } catch (logError) {
3818
- console.error("Error logging agent response:", logError);
3819
- }
3820
- }).catch((error) => {
3821
- console.error("Failed to get output messages for agent logging:", error);
3822
- });
3823
- }
3824
- outputMessagesPromise.then((outputMessages) => {
3825
- var _a2;
3826
- (_a2 = this.onAfterRequest) == null ? void 0 : _a2.call(this, {
3827
- threadId,
3828
- runId: void 0,
3829
- inputMessages: messages,
3830
- outputMessages,
3831
- properties: graphqlContext.properties
3832
- });
3833
- }).catch((_error) => {
3834
- });
3835
- return {
3836
- threadId,
3837
- runId: void 0,
3838
- eventSource,
3839
- serverSideActions,
3840
- actionInputsWithoutAgents: allAvailableActions
3841
- };
3842
- } catch (error) {
3843
- if (((_e = this.observability) == null ? void 0 : _e.enabled) && publicApiKey) {
3844
- try {
3845
- const errorData = {
3846
- threadId,
3847
- runId: void 0,
3848
- model: forwardedParameters == null ? void 0 : forwardedParameters.model,
3849
- error: error instanceof Error ? error : String(error),
3850
- timestamp: Date.now(),
3851
- latency: Date.now() - requestStartTime,
3852
- provider: "agent",
3853
- agentName,
3854
- nodeName
3855
- };
3856
- await this.observability.hooks.handleError(errorData);
3857
- } catch (logError) {
3858
- console.error("Error logging agent error:", logError);
4217
+ }));
4218
+ const agents = totalAgents ? json["agents"].map((agent) => ({
4219
+ name: agent.name,
4220
+ description: agent.description,
4221
+ parameters: [],
4222
+ handler: async (_args) => {
4223
+ },
4224
+ remoteAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName, additionalMessages = [], metaEvents }) => {
4225
+ logger2.debug({
4226
+ actionName: agent.name
4227
+ }, "Executing remote agent");
4228
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
4229
+ telemetry_client_default.capture("oss.runtime.remote_action_executed", {
4230
+ agentExecution: true,
4231
+ type: "self-hosted",
4232
+ agentsAmount: json["agents"].length
4233
+ });
4234
+ let state = {};
4235
+ let config = {};
4236
+ if (agentStates) {
4237
+ const jsonState = agentStates.find((state2) => state2.agentName === name);
4238
+ if (jsonState) {
4239
+ state = parseJson2(jsonState.state, {});
4240
+ config = parseJson2(jsonState.config, {});
3859
4241
  }
3860
4242
  }
3861
- console.error("Error getting response:", error);
3862
- throw error;
3863
- }
3864
- }
3865
- async getServerSideActions(request) {
3866
- var _a, _b;
3867
- const { graphqlContext, messages: rawMessages, agentStates, url } = request;
3868
- const inputMessages = convertGqlInputToMessages(rawMessages);
3869
- const langserveFunctions = [];
3870
- for (const chainPromise of this.langserve) {
4243
+ const fetchUrl = `${url}/agents/execute`;
3871
4244
  try {
3872
- const chain = await chainPromise;
3873
- langserveFunctions.push(chain);
4245
+ const response = await fetchWithRetry(fetchUrl, {
4246
+ method: "POST",
4247
+ headers,
4248
+ body: JSON.stringify({
4249
+ name,
4250
+ threadId,
4251
+ nodeName,
4252
+ messages: [
4253
+ ...messages,
4254
+ ...additionalMessages
4255
+ ],
4256
+ state,
4257
+ config,
4258
+ properties: graphqlContext.properties,
4259
+ actions: tryMap2(actionInputsWithoutAgents, (action) => ({
4260
+ name: action.name,
4261
+ description: action.description,
4262
+ parameters: JSON.parse(action.jsonSchema)
4263
+ })),
4264
+ metaEvents
4265
+ })
4266
+ }, logger2);
4267
+ if (!response.ok) {
4268
+ logger2.error({
4269
+ url,
4270
+ status: response.status,
4271
+ body: await response.text()
4272
+ }, "Failed to execute remote agent");
4273
+ if (response.status === 404) {
4274
+ throw new CopilotKitApiDiscoveryError2({
4275
+ url: fetchUrl
4276
+ });
4277
+ }
4278
+ throw new ResolvedCopilotKitError2({
4279
+ status: response.status,
4280
+ url: fetchUrl,
4281
+ isRemoteEndpoint: true
4282
+ });
4283
+ }
4284
+ if (agent.type === "langgraph") {
4285
+ const eventSource = new RemoteLangGraphEventSource();
4286
+ writeJsonLineResponseToEventStream(response.body, eventSource.eventStream$);
4287
+ return eventSource.processLangGraphEvents();
4288
+ } else if (agent.type === "crewai") {
4289
+ const eventStream$ = new RuntimeEventSubject();
4290
+ writeJsonLineResponseToEventStream(response.body, eventStream$);
4291
+ return eventStream$;
4292
+ } else {
4293
+ throw new Error("Unsupported agent type");
4294
+ }
3874
4295
  } catch (error) {
3875
- console.error("Error loading langserve chain:", error);
4296
+ if (error instanceof CopilotKitError4 || error instanceof CopilotKitLowLevelError5) {
4297
+ throw error;
4298
+ }
4299
+ throw new CopilotKitLowLevelError5({
4300
+ error,
4301
+ url: fetchUrl
4302
+ });
3876
4303
  }
3877
4304
  }
3878
- const remoteEndpointDefinitions = this.remoteEndpointDefinitions.map((endpoint) => ({
3879
- ...endpoint,
3880
- type: resolveEndpointType(endpoint)
3881
- }));
3882
- const remoteActions = await setupRemoteActions({
3883
- remoteEndpointDefinitions,
3884
- graphqlContext,
3885
- messages: inputMessages,
3886
- agentStates,
3887
- frontendUrl: url,
3888
- agents: this.agents,
3889
- metaEvents: request.metaEvents
4305
+ })) : [];
4306
+ return [
4307
+ ...actions,
4308
+ ...agents
4309
+ ];
4310
+ }
4311
+ __name(constructRemoteActions, "constructRemoteActions");
4312
+ function createHeaders(onBeforeRequest, graphqlContext) {
4313
+ const headers = {
4314
+ "Content-Type": "application/json"
4315
+ };
4316
+ if (onBeforeRequest) {
4317
+ const { headers: additionalHeaders } = onBeforeRequest({
4318
+ ctx: graphqlContext
3890
4319
  });
3891
- const configuredActions = typeof this.actions === "function" ? this.actions({
3892
- properties: graphqlContext.properties,
3893
- url
3894
- }) : this.actions;
3895
- const requestSpecificMCPActions = [];
3896
- if (this.createMCPClientImpl) {
3897
- const baseEndpoints = this.mcpServersConfig || [];
3898
- const requestEndpoints = ((_a = graphqlContext.properties) == null ? void 0 : _a.mcpServers) || ((_b = graphqlContext.properties) == null ? void 0 : _b.mcpEndpoints) || [];
3899
- const effectiveEndpointsMap = /* @__PURE__ */ new Map();
3900
- [
3901
- ...baseEndpoints
3902
- ].forEach((ep) => {
3903
- if (ep && ep.endpoint) {
3904
- effectiveEndpointsMap.set(ep.endpoint, ep);
3905
- }
4320
+ if (additionalHeaders) {
4321
+ Object.assign(headers, additionalHeaders);
4322
+ }
4323
+ }
4324
+ return headers;
4325
+ }
4326
+ __name(createHeaders, "createHeaders");
4327
+
4328
+ // src/lib/runtime/remote-actions.ts
4329
+ import { CopilotKitLowLevelError as CopilotKitLowLevelError6, ResolvedCopilotKitError as ResolvedCopilotKitError3, CopilotKitError as CopilotKitError5 } from "@copilotkit/shared";
4330
+
4331
+ // src/lib/runtime/agui-action.ts
4332
+ import { parseJson as parseJson3 } from "@copilotkit/shared";
4333
+ function constructAGUIRemoteAction({ logger: logger2, messages, agentStates, agent, metaEvents }) {
4334
+ const action = {
4335
+ name: agent.agentId,
4336
+ description: agent.description,
4337
+ parameters: [],
4338
+ handler: async (_args) => {
4339
+ },
4340
+ remoteAgentHandler: async ({ actionInputsWithoutAgents, threadId }) => {
4341
+ var _a;
4342
+ logger2.debug({
4343
+ actionName: agent.agentId
4344
+ }, "Executing remote agent");
4345
+ const agentWireMessages = convertMessagesToAGUIMessage(messages);
4346
+ agent.messages = agentWireMessages;
4347
+ agent.threadId = threadId;
4348
+ telemetry_client_default.capture("oss.runtime.remote_action_executed", {
4349
+ agentExecution: true,
4350
+ type: "self-hosted",
4351
+ agentsAmount: 1
3906
4352
  });
3907
- [
3908
- ...requestEndpoints
3909
- ].forEach((ep) => {
3910
- if (ep && ep.endpoint) {
3911
- effectiveEndpointsMap.set(ep.endpoint, ep);
4353
+ let state = {};
4354
+ if (agentStates) {
4355
+ const jsonState = agentStates.find((state2) => state2.agentName === agent.agentId);
4356
+ if (jsonState) {
4357
+ state = parseJson3(jsonState.state, {});
3912
4358
  }
4359
+ }
4360
+ agent.state = state;
4361
+ const tools = actionInputsWithoutAgents.map((input) => {
4362
+ return {
4363
+ name: input.name,
4364
+ description: input.description,
4365
+ parameters: JSON.parse(input.jsonSchema)
4366
+ };
3913
4367
  });
3914
- const effectiveEndpoints = Array.from(effectiveEndpointsMap.values());
3915
- for (const config of effectiveEndpoints) {
3916
- const endpointUrl = config.endpoint;
3917
- let actionsForEndpoint = this.mcpActionCache.get(endpointUrl);
3918
- if (!actionsForEndpoint) {
3919
- let client = null;
3920
- try {
3921
- client = await this.createMCPClientImpl(config);
3922
- const tools = await client.tools();
3923
- actionsForEndpoint = convertMCPToolsToActions(tools, endpointUrl);
3924
- this.mcpActionCache.set(endpointUrl, actionsForEndpoint);
3925
- } catch (error) {
3926
- console.error(`MCP: Failed to fetch tools from endpoint ${endpointUrl}. Skipping. Error:`, error);
3927
- actionsForEndpoint = [];
3928
- this.mcpActionCache.set(endpointUrl, actionsForEndpoint);
3929
- }
4368
+ const forwardedProps = metaEvents.length ? {
4369
+ command: {
4370
+ resume: (_a = metaEvents[0]) == null ? void 0 : _a.response
3930
4371
  }
3931
- requestSpecificMCPActions.push(...actionsForEndpoint || []);
3932
- }
4372
+ } : void 0;
4373
+ return agent.legacy_to_be_removed_runAgentBridged({
4374
+ tools,
4375
+ forwardedProps
4376
+ });
3933
4377
  }
3934
- return [
3935
- ...configuredActions,
3936
- ...langserveFunctions,
3937
- ...remoteActions,
3938
- ...requestSpecificMCPActions
3939
- ];
3940
- }
3941
- // Add helper method to detect provider
3942
- detectProvider(serviceAdapter) {
3943
- const adapterName = serviceAdapter.constructor.name;
3944
- if (adapterName.includes("OpenAI"))
3945
- return "openai";
3946
- if (adapterName.includes("Anthropic"))
3947
- return "anthropic";
3948
- if (adapterName.includes("Google"))
3949
- return "google";
3950
- if (adapterName.includes("Groq"))
3951
- return "groq";
3952
- if (adapterName.includes("LangChain"))
3953
- return "langchain";
3954
- return void 0;
3955
- }
3956
- convertStreamingErrorToStructured(error) {
3957
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
3958
- if (((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.includes("terminated")) || ((_b = error == null ? void 0 : error.cause) == null ? void 0 : _b.code) === "UND_ERR_SOCKET" || ((_c = error == null ? void 0 : error.message) == null ? void 0 : _c.includes("other side closed")) || (error == null ? void 0 : error.code) === "UND_ERR_SOCKET") {
3959
- return new CopilotKitError5({
3960
- message: "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
3961
- code: CopilotKitErrorCode3.NETWORK_ERROR
4378
+ };
4379
+ return [
4380
+ action
4381
+ ];
4382
+ }
4383
+ __name(constructAGUIRemoteAction, "constructAGUIRemoteAction");
4384
+ function convertMessagesToAGUIMessage(messages) {
4385
+ const result = [];
4386
+ for (const message of messages) {
4387
+ if (message.isTextMessage()) {
4388
+ result.push({
4389
+ id: message.id,
4390
+ role: message.role,
4391
+ content: message.content
4392
+ });
4393
+ } else if (message.isActionExecutionMessage()) {
4394
+ const toolCall = {
4395
+ id: message.id,
4396
+ type: "function",
4397
+ function: {
4398
+ name: message.name,
4399
+ arguments: JSON.stringify(message.arguments)
4400
+ }
4401
+ };
4402
+ if (message.parentMessageId && result.some((m) => m.id === message.parentMessageId)) {
4403
+ const parentMessage = result.find((m) => m.id === message.parentMessageId);
4404
+ if (parentMessage.toolCalls === void 0) {
4405
+ parentMessage.toolCalls = [];
4406
+ }
4407
+ parentMessage.toolCalls.push(toolCall);
4408
+ } else {
4409
+ result.push({
4410
+ id: message.parentMessageId ?? message.id,
4411
+ role: "assistant",
4412
+ toolCalls: [
4413
+ toolCall
4414
+ ]
4415
+ });
4416
+ }
4417
+ } else if (message.isResultMessage()) {
4418
+ result.push({
4419
+ id: message.id,
4420
+ role: "tool",
4421
+ content: message.result,
4422
+ toolCallId: message.actionExecutionId
3962
4423
  });
3963
4424
  }
3964
- if (((_d = error == null ? void 0 : error.message) == null ? void 0 : _d.includes("fetch failed")) || ((_e = error == null ? void 0 : error.message) == null ? void 0 : _e.includes("ECONNREFUSED")) || ((_f = error == null ? void 0 : error.message) == null ? void 0 : _f.includes("ENOTFOUND")) || ((_g = error == null ? void 0 : error.message) == null ? void 0 : _g.includes("ETIMEDOUT"))) {
3965
- return new CopilotKitLowLevelError4({
3966
- error: error instanceof Error ? error : new Error(String(error)),
3967
- url: "agent streaming connection",
3968
- message: "Network error occurred during agent streaming. Please check your connection and try again."
4425
+ }
4426
+ return result;
4427
+ }
4428
+ __name(convertMessagesToAGUIMessage, "convertMessagesToAGUIMessage");
4429
+
4430
+ // src/lib/runtime/remote-actions.ts
4431
+ var EndpointType;
4432
+ (function(EndpointType2) {
4433
+ EndpointType2["CopilotKit"] = "copilotKit";
4434
+ EndpointType2["LangGraphPlatform"] = "langgraph-platform";
4435
+ })(EndpointType || (EndpointType = {}));
4436
+ function isRemoteAgentAction(action) {
4437
+ if (!action) {
4438
+ return false;
4439
+ }
4440
+ return typeof action.remoteAgentHandler === "function";
4441
+ }
4442
+ __name(isRemoteAgentAction, "isRemoteAgentAction");
4443
+ async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: logger2, frontendUrl }) {
4444
+ logger2.debug({
4445
+ url
4446
+ }, "Fetching actions from url");
4447
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
4448
+ const fetchUrl = `${url}/info`;
4449
+ try {
4450
+ const response = await fetch(fetchUrl, {
4451
+ method: "POST",
4452
+ headers,
4453
+ body: JSON.stringify({
4454
+ properties: graphqlContext.properties,
4455
+ frontendUrl
4456
+ })
4457
+ });
4458
+ if (!response.ok) {
4459
+ logger2.error({
4460
+ url,
4461
+ status: response.status,
4462
+ body: await response.text()
4463
+ }, "Failed to fetch actions from url");
4464
+ throw new ResolvedCopilotKitError3({
4465
+ status: response.status,
4466
+ url: fetchUrl,
4467
+ isRemoteEndpoint: true
3969
4468
  });
3970
4469
  }
3971
- if (((_h = error == null ? void 0 : error.message) == null ? void 0 : _h.includes("aborted")) || ((_i = error == null ? void 0 : error.message) == null ? void 0 : _i.includes("canceled")) || ((_j = error == null ? void 0 : error.message) == null ? void 0 : _j.includes("signal is aborted"))) {
3972
- return new CopilotKitError5({
3973
- message: "Agent request was cancelled",
3974
- code: CopilotKitErrorCode3.UNKNOWN
3975
- });
4470
+ const json = await response.json();
4471
+ logger2.debug({
4472
+ json
4473
+ }, "Fetched actions from url");
4474
+ return json;
4475
+ } catch (error) {
4476
+ if (error instanceof CopilotKitError5) {
4477
+ throw error;
3976
4478
  }
3977
- return new CopilotKitError5({
3978
- message: `Agent streaming error: ${(error == null ? void 0 : error.message) || String(error)}`,
3979
- code: CopilotKitErrorCode3.UNKNOWN
4479
+ throw new CopilotKitLowLevelError6({
4480
+ error,
4481
+ url: fetchUrl
3980
4482
  });
3981
4483
  }
3982
- };
3983
- __name(CopilotRuntime, "CopilotRuntime");
3984
- function flattenToolCallsNoDuplicates(toolsByPriority) {
3985
- let allTools = [];
3986
- const allToolNames = [];
3987
- for (const tool of toolsByPriority) {
3988
- if (!allToolNames.includes(tool.name)) {
3989
- allTools.push(tool);
3990
- allToolNames.push(tool.name);
3991
- }
3992
- }
3993
- return allTools;
3994
- }
3995
- __name(flattenToolCallsNoDuplicates, "flattenToolCallsNoDuplicates");
3996
- function copilotKitEndpoint(config) {
3997
- return {
3998
- ...config,
3999
- type: EndpointType.CopilotKit
4000
- };
4001
- }
4002
- __name(copilotKitEndpoint, "copilotKitEndpoint");
4003
- function langGraphPlatformEndpoint(config) {
4004
- return {
4005
- ...config,
4006
- type: EndpointType.LangGraphPlatform
4007
- };
4008
4484
  }
4009
- __name(langGraphPlatformEndpoint, "langGraphPlatformEndpoint");
4010
- function resolveEndpointType(endpoint) {
4011
- if (!endpoint.type) {
4012
- if ("deploymentUrl" in endpoint && "agents" in endpoint) {
4013
- return EndpointType.LangGraphPlatform;
4014
- } else {
4015
- return EndpointType.CopilotKit;
4485
+ __name(fetchRemoteInfo, "fetchRemoteInfo");
4486
+ async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, messages, agentStates, frontendUrl, agents, metaEvents }) {
4487
+ const logger2 = graphqlContext.logger.child({
4488
+ component: "remote-actions.fetchRemoteActions"
4489
+ });
4490
+ logger2.debug({
4491
+ remoteEndpointDefinitions
4492
+ }, "Fetching from remote endpoints");
4493
+ const filtered = remoteEndpointDefinitions.filter((value, index, self) => {
4494
+ if (value.type === "langgraph-platform") {
4495
+ return value;
4016
4496
  }
4017
- }
4018
- return endpoint.type;
4019
- }
4020
- __name(resolveEndpointType, "resolveEndpointType");
4021
-
4022
- // src/lib/telemetry-client.ts
4023
- var packageJson = require_package();
4024
- var telemetryClient = new TelemetryClient({
4025
- packageName: packageJson.name,
4026
- packageVersion: packageJson.version
4027
- });
4028
- function getRuntimeInstanceTelemetryInfo(options) {
4029
- var _a, _b;
4030
- const runtime = options.runtime;
4031
- const endpointsInfo = runtime.remoteEndpointDefinitions.reduce((acc, endpoint) => {
4032
- let info = {
4033
- ...acc
4034
- };
4035
- const endpointType = resolveEndpointType(endpoint);
4036
- if (!info.endpointTypes.includes(endpointType)) {
4037
- info = {
4038
- ...info,
4039
- endpointTypes: [
4040
- ...info.endpointTypes,
4041
- endpointType
4042
- ]
4043
- };
4497
+ return index === self.findIndex((t) => t.url === value.url);
4498
+ });
4499
+ const result = await Promise.all(filtered.map(async (endpoint) => {
4500
+ if (endpoint.type === "langgraph-platform") {
4501
+ return constructLGCRemoteAction({
4502
+ endpoint,
4503
+ messages,
4504
+ graphqlContext,
4505
+ logger: logger2.child({
4506
+ component: "remote-actions.constructLGCRemoteAction",
4507
+ endpoint
4508
+ }),
4509
+ agentStates
4510
+ });
4044
4511
  }
4045
- if (endpointType === EndpointType.LangGraphPlatform) {
4046
- const ep = endpoint;
4047
- info = {
4048
- ...info,
4049
- agentsAmount: ep.agents.length,
4050
- hashedKey: ep.langsmithApiKey ? createHash3("sha256").update(ep.langsmithApiKey).digest("hex") : null
4051
- };
4512
+ const json = await fetchRemoteInfo({
4513
+ url: endpoint.url,
4514
+ onBeforeRequest: endpoint.onBeforeRequest,
4515
+ graphqlContext,
4516
+ logger: logger2.child({
4517
+ component: "remote-actions.fetchActionsFromUrl",
4518
+ endpoint
4519
+ }),
4520
+ frontendUrl
4521
+ });
4522
+ return constructRemoteActions({
4523
+ json,
4524
+ messages,
4525
+ url: endpoint.url,
4526
+ onBeforeRequest: endpoint.onBeforeRequest,
4527
+ graphqlContext,
4528
+ logger: logger2.child({
4529
+ component: "remote-actions.constructActions",
4530
+ endpoint
4531
+ }),
4532
+ agentStates
4533
+ });
4534
+ }));
4535
+ for (const [key, agent] of Object.entries(agents)) {
4536
+ if (agent.agentId !== void 0 && agent.agentId !== key) {
4537
+ throw new CopilotKitError5({
4538
+ message: `Agent ${key} has agentId ${agent.agentId} which does not match the key ${key}`,
4539
+ code: CopilotKitErrorCode3.UNKNOWN
4540
+ });
4541
+ } else if (agent.agentId === void 0) {
4542
+ agent.agentId = key;
4052
4543
  }
4053
- return info;
4054
- }, {
4055
- endpointTypes: [],
4056
- agentsAmount: null,
4057
- hashedKey: null
4058
- });
4059
- const publicApiKey = (_a = options.cloud) == null ? void 0 : _a.publicApiKey;
4060
- const apiKeyProvided = !!publicApiKey && publicApiKey.trim().length > 0;
4061
- return {
4062
- actionsAmount: runtime.actions.length,
4063
- endpointsAmount: runtime.remoteEndpointDefinitions.length,
4064
- endpointTypes: endpointsInfo.endpointTypes,
4065
- agentsAmount: endpointsInfo.agentsAmount,
4066
- hashedLgcKey: endpointsInfo.hashedKey,
4067
- "cloud.api_key_provided": apiKeyProvided,
4068
- ...apiKeyProvided ? {
4069
- "cloud.public_api_key": publicApiKey
4070
- } : {},
4071
- ...((_b = options.cloud) == null ? void 0 : _b.baseUrl) ? {
4072
- "cloud.base_url": options.cloud.baseUrl
4073
- } : {}
4074
- };
4544
+ result.push(constructAGUIRemoteAction({
4545
+ logger: logger2,
4546
+ messages,
4547
+ agentStates,
4548
+ agent,
4549
+ metaEvents
4550
+ }));
4551
+ }
4552
+ return result.flat();
4075
4553
  }
4076
- __name(getRuntimeInstanceTelemetryInfo, "getRuntimeInstanceTelemetryInfo");
4077
- var telemetry_client_default = telemetryClient;
4554
+ __name(setupRemoteActions, "setupRemoteActions");
4078
4555
 
4079
4556
  // src/service-adapters/events.ts
4080
- import { plainToInstance as plainToInstance2 } from "class-transformer";
4081
4557
  var RuntimeEventTypes;
4082
4558
  (function(RuntimeEventTypes2) {
4083
4559
  RuntimeEventTypes2["TextMessageStart"] = "TextMessageStart";
@@ -4200,16 +4676,15 @@ var RuntimeEventSource = class {
4200
4676
  const errorMessage = `\u274C ${message}`;
4201
4677
  if (!this.callback) {
4202
4678
  this.stream(async (eventStream$) => {
4203
- eventStream$.sendTextMessage(randomId3(), errorMessage);
4679
+ eventStream$.sendTextMessage(randomId2(), errorMessage);
4204
4680
  });
4205
4681
  } else {
4206
- this.eventStream$.sendTextMessage(randomId3(), errorMessage);
4682
+ this.eventStream$.sendTextMessage(randomId2(), errorMessage);
4207
4683
  }
4208
4684
  }
4209
4685
  processRuntimeEvents({ serverSideActions, guardrailsResult$, actionInputsWithoutAgents, threadId }) {
4210
4686
  this.callback(this.eventStream$).catch((error) => {
4211
- console.error("Error in event source callback", error);
4212
- const structuredError = convertStreamingErrorToStructured2(error);
4687
+ const structuredError = ensureStructuredError3(error, convertStreamingErrorToStructured2);
4213
4688
  this.eventStream$.error(structuredError);
4214
4689
  this.eventStream$.complete();
4215
4690
  });
@@ -4244,12 +4719,10 @@ var RuntimeEventSource = class {
4244
4719
  if (eventWithState.event.type === "ActionExecutionEnd" && eventWithState.callActionServerSide) {
4245
4720
  const toolCallEventStream$ = new RuntimeEventSubject();
4246
4721
  executeAction(toolCallEventStream$, guardrailsResult$ ? guardrailsResult$ : null, eventWithState.action, eventWithState.args, eventWithState.actionExecutionParentMessageId, eventWithState.actionExecutionId, actionInputsWithoutAgents, threadId).catch((error) => {
4247
- console.error(error);
4248
4722
  });
4249
4723
  telemetry_client_default.capture("oss.runtime.server_action_executed", {});
4250
4724
  return concat(of(eventWithState.event), toolCallEventStream$).pipe(catchError2((error) => {
4251
- console.error("Error in tool call stream", error);
4252
- const structuredError = convertStreamingErrorToStructured2(error);
4725
+ const structuredError = ensureStructuredError3(error, convertStreamingErrorToStructured2);
4253
4726
  toolCallEventStream$.sendActionExecutionResult({
4254
4727
  actionExecutionId: eventWithState.actionExecutionId,
4255
4728
  actionName: eventWithState.action.name,
@@ -4329,8 +4802,7 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
4329
4802
  from2(stream).subscribe({
4330
4803
  next: (event) => eventStream$.next(event),
4331
4804
  error: (err) => {
4332
- console.error("Error in stream", err);
4333
- const structuredError = convertStreamingErrorToStructured2(err);
4805
+ const structuredError = ensureStructuredError3(err, convertStreamingErrorToStructured2);
4334
4806
  eventStream$.sendActionExecutionResult({
4335
4807
  actionExecutionId,
4336
4808
  actionName: action.name,
@@ -4370,36 +4842,19 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
4370
4842
  }
4371
4843
  __name(executeAction, "executeAction");
4372
4844
  function convertStreamingErrorToStructured2(error) {
4373
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
4374
- if (((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.includes("terminated")) || ((_b = error == null ? void 0 : error.cause) == null ? void 0 : _b.code) === "UND_ERR_SOCKET" || ((_c = error == null ? void 0 : error.message) == null ? void 0 : _c.includes("other side closed")) || (error == null ? void 0 : error.code) === "UND_ERR_SOCKET") {
4375
- return new CopilotKitError6({
4376
- message: "Connection to agent was unexpectedly terminated. This may be due to the agent service being restarted or network issues. Please try again.",
4377
- code: CopilotKitErrorCode4.NETWORK_ERROR
4378
- });
4379
- }
4380
- if (((_d = error == null ? void 0 : error.message) == null ? void 0 : _d.includes("fetch failed")) || ((_e = error == null ? void 0 : error.message) == null ? void 0 : _e.includes("ECONNREFUSED")) || ((_f = error == null ? void 0 : error.message) == null ? void 0 : _f.includes("ENOTFOUND")) || ((_g = error == null ? void 0 : error.message) == null ? void 0 : _g.includes("ETIMEDOUT"))) {
4381
- return new CopilotKitLowLevelError5({
4845
+ var _a, _b, _c, _d, _e, _f, _g;
4846
+ let helpfulMessage = generateHelpfulErrorMessage(error, "event streaming connection");
4847
+ 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") {
4848
+ return new CopilotKitLowLevelError7({
4382
4849
  error: error instanceof Error ? error : new Error(String(error)),
4383
4850
  url: "event streaming connection",
4384
- message: "Network error occurred during event streaming. Please check your connection and try again."
4385
- });
4386
- }
4387
- if (((_h = error == null ? void 0 : error.message) == null ? void 0 : _h.includes("aborted")) || ((_i = error == null ? void 0 : error.message) == null ? void 0 : _i.includes("canceled")) || ((_j = error == null ? void 0 : error.message) == null ? void 0 : _j.includes("signal is aborted"))) {
4388
- return new CopilotKitError6({
4389
- message: "Request was cancelled",
4390
- code: CopilotKitErrorCode4.UNKNOWN
4391
- });
4392
- }
4393
- const errorMessage = (error == null ? void 0 : error.message) || String(error);
4394
- if (errorMessage.includes("401") || errorMessage.toLowerCase().includes("api key") || errorMessage.toLowerCase().includes("unauthorized") || errorMessage.toLowerCase().includes("authentication") || errorMessage.toLowerCase().includes("incorrect api key")) {
4395
- return new CopilotKitError6({
4396
- message: `Event streaming error: ${errorMessage}`,
4397
- code: CopilotKitErrorCode4.MISSING_PUBLIC_API_KEY_ERROR
4851
+ message: helpfulMessage
4398
4852
  });
4399
4853
  }
4400
4854
  return new CopilotKitError6({
4401
- message: `Event streaming error: ${errorMessage}`,
4402
- code: CopilotKitErrorCode4.UNKNOWN
4855
+ message: helpfulMessage,
4856
+ code: CopilotKitErrorCode4.UNKNOWN,
4857
+ severity: Severity.CRITICAL
4403
4858
  });
4404
4859
  }
4405
4860
  __name(convertStreamingErrorToStructured2, "convertStreamingErrorToStructured");
@@ -4408,7 +4863,7 @@ __name(convertStreamingErrorToStructured2, "convertStreamingErrorToStructured");
4408
4863
  import { GraphQLJSONObject } from "graphql-scalars";
4409
4864
  import { plainToInstance as plainToInstance3 } from "class-transformer";
4410
4865
  import { GraphQLError } from "graphql";
4411
- import { randomId as randomId4 } from "@copilotkit/shared";
4866
+ import { randomId as randomId3 } from "@copilotkit/shared";
4412
4867
 
4413
4868
  // src/graphql/types/agents-response.type.ts
4414
4869
  import { Field as Field16, ObjectType as ObjectType5 } from "type-graphql";
@@ -4464,7 +4919,7 @@ AgentsResponse = _ts_decorate16([
4464
4919
  ], AgentsResponse);
4465
4920
 
4466
4921
  // src/graphql/resolvers/copilot.resolver.ts
4467
- import { CopilotKitError as CopilotKitError7 } from "@copilotkit/shared";
4922
+ import { CopilotKitError as CopilotKitError7, CopilotKitLowLevelError as CopilotKitLowLevelError8, isStructuredCopilotKitError as isStructuredCopilotKitError2 } from "@copilotkit/shared";
4468
4923
  function _ts_decorate17(decorators, target, key, desc) {
4469
4924
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4470
4925
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -4534,7 +4989,7 @@ var CopilotResolver = class {
4534
4989
  };
4535
4990
  }
4536
4991
  async generateCopilotResponse(ctx, data, properties) {
4537
- var _a, _b, _c, _d;
4992
+ var _a, _b, _c, _d, _e, _f, _g;
4538
4993
  telemetry_client_default.capture("oss.runtime.copilot_request_created", {
4539
4994
  "cloud.guardrails.enabled": ((_a = data.cloud) == null ? void 0 : _a.guardrails) !== void 0,
4540
4995
  requestType: data.metadata.requestType,
@@ -4565,23 +5020,32 @@ var CopilotResolver = class {
4565
5020
  const serviceAdapter = ctx._copilotkit.serviceAdapter;
4566
5021
  let copilotCloudPublicApiKey = null;
4567
5022
  let copilotCloudBaseUrl;
5023
+ const publicApiKeyFromHeaders = ctx.request.headers.get("x-copilotcloud-public-api-key");
5024
+ if (publicApiKeyFromHeaders) {
5025
+ copilotCloudPublicApiKey = publicApiKeyFromHeaders;
5026
+ }
4568
5027
  if (data.cloud) {
4569
5028
  logger2 = logger2.child({
4570
5029
  cloud: true
4571
5030
  });
4572
5031
  logger2.debug("Cloud configuration provided, checking for public API key in headers");
4573
- const key = ctx.request.headers.get("x-copilotcloud-public-api-key");
4574
- if (key) {
4575
- logger2.debug("Public API key found in headers");
4576
- copilotCloudPublicApiKey = key;
4577
- } else {
5032
+ if (!copilotCloudPublicApiKey) {
4578
5033
  logger2.error("Public API key not found in headers");
5034
+ await copilotRuntime.traceGraphQLError({
5035
+ message: "X-CopilotCloud-Public-API-Key header is required",
5036
+ code: "MISSING_PUBLIC_API_KEY",
5037
+ type: "GraphQLError"
5038
+ }, {
5039
+ operation: "generateCopilotResponse",
5040
+ cloudConfigPresent: Boolean(data.cloud),
5041
+ guardrailsEnabled: Boolean((_b = data.cloud) == null ? void 0 : _b.guardrails)
5042
+ });
4579
5043
  throw new GraphQLError("X-CopilotCloud-Public-API-Key header is required");
4580
5044
  }
4581
5045
  if (process.env.COPILOT_CLOUD_BASE_URL) {
4582
5046
  copilotCloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL;
4583
- } else if ((_b = ctx._copilotkit.cloud) == null ? void 0 : _b.baseUrl) {
4584
- copilotCloudBaseUrl = (_c = ctx._copilotkit.cloud) == null ? void 0 : _c.baseUrl;
5047
+ } else if ((_c = ctx._copilotkit.cloud) == null ? void 0 : _c.baseUrl) {
5048
+ copilotCloudBaseUrl = (_d = ctx._copilotkit.cloud) == null ? void 0 : _d.baseUrl;
4585
5049
  } else {
4586
5050
  copilotCloudBaseUrl = "https://api.cloud.copilotkit.ai";
4587
5051
  }
@@ -4604,26 +5068,41 @@ var CopilotResolver = class {
4604
5068
  ctx.properties["copilotCloudPublicApiKey"] = copilotCloudPublicApiKey;
4605
5069
  }
4606
5070
  logger2.debug("Processing");
4607
- const { eventSource, threadId = randomId4(), runId, serverSideActions, actionInputsWithoutAgents, extensions } = await copilotRuntime.processRuntimeRequest({
4608
- serviceAdapter,
4609
- messages: data.messages,
4610
- actions: data.frontend.actions.filter((action) => action.available !== ActionInputAvailability.disabled),
4611
- threadId: data.threadId,
4612
- runId: data.runId,
4613
- publicApiKey: copilotCloudPublicApiKey,
4614
- outputMessagesPromise,
4615
- graphqlContext: ctx,
4616
- forwardedParameters: data.forwardedParameters,
4617
- agentSession: data.agentSession,
4618
- agentStates: data.agentStates,
4619
- url: data.frontend.url,
4620
- extensions: data.extensions,
4621
- metaEvents: data.metaEvents
4622
- });
5071
+ let runtimeResponse;
5072
+ try {
5073
+ runtimeResponse = await copilotRuntime.processRuntimeRequest({
5074
+ serviceAdapter,
5075
+ messages: data.messages,
5076
+ actions: data.frontend.actions.filter((action) => action.available !== ActionInputAvailability.disabled),
5077
+ threadId: data.threadId,
5078
+ runId: data.runId,
5079
+ publicApiKey: copilotCloudPublicApiKey,
5080
+ outputMessagesPromise,
5081
+ graphqlContext: ctx,
5082
+ forwardedParameters: data.forwardedParameters,
5083
+ agentSession: data.agentSession,
5084
+ agentStates: data.agentStates,
5085
+ url: data.frontend.url,
5086
+ extensions: data.extensions,
5087
+ metaEvents: data.metaEvents
5088
+ });
5089
+ } catch (error) {
5090
+ if (isStructuredCopilotKitError2(error) || ((_e = error == null ? void 0 : error.extensions) == null ? void 0 : _e.visibility)) {
5091
+ throw new GraphQLError(error.message || "Agent error occurred", {
5092
+ extensions: {
5093
+ ...error.extensions,
5094
+ code: error.code || ((_f = error.extensions) == null ? void 0 : _f.code) || "AGENT_ERROR",
5095
+ originalError: error
5096
+ }
5097
+ });
5098
+ }
5099
+ throw error;
5100
+ }
5101
+ const { eventSource, threadId = randomId3(), runId, serverSideActions, actionInputsWithoutAgents, extensions } = runtimeResponse;
4623
5102
  logger2.debug("Event source created, creating response");
4624
5103
  const eventStream = eventSource.processRuntimeEvents({
4625
5104
  serverSideActions,
4626
- guardrailsResult$: ((_d = data.cloud) == null ? void 0 : _d.guardrails) ? guardrailsResult$ : null,
5105
+ guardrailsResult$: ((_g = data.cloud) == null ? void 0 : _g.guardrails) ? guardrailsResult$ : null,
4627
5106
  actionInputsWithoutAgents: actionInputsWithoutAgents.filter(
4628
5107
  // TODO-AGENTS: do not exclude ALL server side actions
4629
5108
  (action) => !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name)
@@ -4704,12 +5183,16 @@ var CopilotResolver = class {
4704
5183
  }
4705
5184
  },
4706
5185
  error: (err) => {
4707
- logger2.error({
4708
- err
4709
- }, "Error in meta events stream");
4710
- responseStatus$.next(new UnknownErrorResponse({
4711
- description: `An unknown error has occurred in the event stream`
4712
- }));
5186
+ var _a2, _b2;
5187
+ 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)) {
5188
+ responseStatus$.next(new UnknownErrorResponse({
5189
+ description: err.message || "Agent error occurred"
5190
+ }));
5191
+ } else {
5192
+ responseStatus$.next(new UnknownErrorResponse({
5193
+ description: `An unknown error has occurred in the event stream`
5194
+ }));
5195
+ }
4713
5196
  eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
4714
5197
  stop();
4715
5198
  },
@@ -4747,7 +5230,7 @@ var CopilotResolver = class {
4747
5230
  });
4748
5231
  outputMessages = [
4749
5232
  plainToInstance3(TextMessage, {
4750
- id: randomId4(),
5233
+ id: randomId3(),
4751
5234
  createdAt: /* @__PURE__ */ new Date(),
4752
5235
  content: result.reason,
4753
5236
  role: MessageRole.assistant
@@ -4925,7 +5408,7 @@ var CopilotResolver = class {
4925
5408
  event
4926
5409
  }, "Agent message event received");
4927
5410
  pushMessage({
4928
- id: randomId4(),
5411
+ id: randomId3(),
4929
5412
  status: new SuccessMessageStatus(),
4930
5413
  threadId: event.threadId,
4931
5414
  agentName: event.agentName,
@@ -4938,7 +5421,7 @@ var CopilotResolver = class {
4938
5421
  createdAt: /* @__PURE__ */ new Date()
4939
5422
  });
4940
5423
  outputMessages.push(plainToInstance3(AgentStateMessage, {
4941
- id: randomId4(),
5424
+ id: randomId3(),
4942
5425
  threadId: event.threadId,
4943
5426
  agentName: event.agentName,
4944
5427
  nodeName: event.nodeName,
@@ -4953,13 +5436,23 @@ var CopilotResolver = class {
4953
5436
  }
4954
5437
  },
4955
5438
  error: (err) => {
4956
- logger2.error({
4957
- err
4958
- }, "Error in event stream");
4959
- if (err instanceof CopilotKitError7 || err instanceof Error && err.name && err.name.includes("CopilotKit")) {
5439
+ var _a3, _b2, _c2, _d2, _e2, _f2;
5440
+ 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)) {
5441
+ responseStatus$.next(new UnknownErrorResponse({
5442
+ description: err.message || "Agent error occurred",
5443
+ // Include original error information for frontend to extract
5444
+ originalError: {
5445
+ code: err.code || ((_b2 = err.extensions) == null ? void 0 : _b2.code),
5446
+ statusCode: err.statusCode || ((_c2 = err.extensions) == null ? void 0 : _c2.statusCode),
5447
+ severity: err.severity || ((_d2 = err.extensions) == null ? void 0 : _d2.severity),
5448
+ visibility: err.visibility || ((_e2 = err.extensions) == null ? void 0 : _e2.visibility),
5449
+ originalErrorType: err.originalErrorType || ((_f2 = err.extensions) == null ? void 0 : _f2.originalErrorType),
5450
+ extensions: err.extensions
5451
+ }
5452
+ }));
4960
5453
  eventStreamSubscription == null ? void 0 : eventStreamSubscription.unsubscribe();
4961
5454
  rejectOutputMessagesPromise(err);
4962
- stopStreamingMessages(err);
5455
+ stopStreamingMessages();
4963
5456
  return;
4964
5457
  }
4965
5458
  responseStatus$.next(new UnknownErrorResponse({
@@ -5164,9 +5657,9 @@ function _ts_param2(paramIndex, decorator) {
5164
5657
  __name(_ts_param2, "_ts_param");
5165
5658
  var StateResolver = class {
5166
5659
  async loadAgentState(ctx, data) {
5167
- const agents = await ctx._copilotkit.runtime.discoverAgentsFromEndpoints(ctx);
5168
- const agent = agents.find((agent2) => agent2.name === data.agentName);
5169
- if (!agent) {
5660
+ const agents = await ctx._copilotkit.runtime.getAllAgents(ctx);
5661
+ const hasAgent = agents.some((agent) => agent.name === data.agentName);
5662
+ if (!hasAgent) {
5170
5663
  throw new CopilotKitAgentDiscoveryError2({
5171
5664
  agentName: data.agentName,
5172
5665
  availableAgents: agents.map((a) => ({
@@ -5197,6 +5690,7 @@ StateResolver = _ts_decorate20([
5197
5690
 
5198
5691
  // src/lib/integrations/shared.ts
5199
5692
  var packageJson2 = __toESM(require_package());
5693
+ import { CopilotKitError as CopilotKitError8, CopilotKitErrorCode as CopilotKitErrorCode5 } from "@copilotkit/shared";
5200
5694
  var logger = createLogger();
5201
5695
  var addCustomHeaderPlugin = {
5202
5696
  onResponse({ response }) {
@@ -5261,6 +5755,13 @@ function getCommonConfig(options) {
5261
5755
  serviceAdapter: options.serviceAdapter.constructor.name
5262
5756
  }
5263
5757
  });
5758
+ const userErrorCodes = [
5759
+ CopilotKitErrorCode5.AGENT_NOT_FOUND,
5760
+ CopilotKitErrorCode5.API_NOT_FOUND,
5761
+ CopilotKitErrorCode5.REMOTE_ENDPOINT_NOT_FOUND,
5762
+ CopilotKitErrorCode5.CONFIGURATION_ERROR,
5763
+ CopilotKitErrorCode5.MISSING_PUBLIC_API_KEY_ERROR
5764
+ ];
5264
5765
  return {
5265
5766
  logging: createLogger({
5266
5767
  component: "Yoga GraphQL",
@@ -5271,7 +5772,25 @@ function getCommonConfig(options) {
5271
5772
  useDeferStream(),
5272
5773
  addCustomHeaderPlugin
5273
5774
  ],
5274
- context: (ctx) => createContext(ctx, options, contextLogger, options.properties)
5775
+ context: (ctx) => createContext(ctx, options, contextLogger, options.properties),
5776
+ // Suppress logging for user configuration errors
5777
+ maskedErrors: {
5778
+ maskError: (error, message, isDev) => {
5779
+ const originalError = error.originalError || error;
5780
+ const extensions = error.extensions;
5781
+ const errorCode = extensions == null ? void 0 : extensions.code;
5782
+ if (errorCode && userErrorCodes.includes(errorCode)) {
5783
+ console.debug("User configuration error:", error.message);
5784
+ return error;
5785
+ }
5786
+ if (originalError instanceof CopilotKitError8 && userErrorCodes.includes(originalError.code)) {
5787
+ console.debug("User configuration error:", error.message);
5788
+ return error;
5789
+ }
5790
+ console.error("Application error:", error);
5791
+ return error;
5792
+ }
5793
+ }
5275
5794
  };
5276
5795
  }
5277
5796
  __name(getCommonConfig, "getCommonConfig");
@@ -5320,4 +5839,4 @@ export {
5320
5839
  getCommonConfig,
5321
5840
  copilotRuntimeNodeHttpEndpoint
5322
5841
  };
5323
- //# sourceMappingURL=chunk-YMIOUUPV.mjs.map
5842
+ //# sourceMappingURL=chunk-PMIAGZGS.mjs.map