@copilotkit/react-core 1.51.3-next.6 → 1.51.3-next.7

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 (97) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/chunk-77IVITG3.mjs +158 -0
  3. package/dist/chunk-77IVITG3.mjs.map +1 -0
  4. package/dist/chunk-BKMJ4LC7.mjs +119 -0
  5. package/dist/chunk-BKMJ4LC7.mjs.map +1 -0
  6. package/dist/chunk-C3YJYDK4.mjs +189 -0
  7. package/dist/chunk-C3YJYDK4.mjs.map +1 -0
  8. package/dist/{chunk-GIU66J37.mjs → chunk-DQXCQWSG.mjs} +47 -5
  9. package/dist/chunk-DQXCQWSG.mjs.map +1 -0
  10. package/dist/{chunk-HBMPXNW2.mjs → chunk-LO4RRITI.mjs} +71 -18
  11. package/dist/chunk-LO4RRITI.mjs.map +1 -0
  12. package/dist/{chunk-3G4VFRVV.mjs → chunk-NXHQDCZF.mjs} +2 -2
  13. package/dist/{chunk-FDOMAPJY.mjs → chunk-QD7EID4N.mjs} +1 -1
  14. package/dist/chunk-QD7EID4N.mjs.map +1 -0
  15. package/dist/{chunk-YTQHRJUA.mjs → chunk-VKNLTZJE.mjs} +2 -2
  16. package/dist/{chunk-4RRUJHCI.mjs → chunk-VP43SLSZ.mjs} +2 -2
  17. package/dist/{chunk-MF2ZSLBV.mjs → chunk-XZFIJ7XF.mjs} +2 -2
  18. package/dist/components/copilot-provider/copilotkit.js +437 -150
  19. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  20. package/dist/components/copilot-provider/copilotkit.mjs +5 -3
  21. package/dist/components/copilot-provider/index.js +437 -150
  22. package/dist/components/copilot-provider/index.js.map +1 -1
  23. package/dist/components/copilot-provider/index.mjs +5 -3
  24. package/dist/components/index.js +437 -150
  25. package/dist/components/index.js.map +1 -1
  26. package/dist/components/index.mjs +5 -3
  27. package/dist/context/coagent-state-renders-context.d.ts +1 -0
  28. package/dist/context/coagent-state-renders-context.js.map +1 -1
  29. package/dist/context/coagent-state-renders-context.mjs +1 -1
  30. package/dist/context/index.js.map +1 -1
  31. package/dist/context/index.mjs +1 -1
  32. package/dist/hooks/index.js +512 -212
  33. package/dist/hooks/index.js.map +1 -1
  34. package/dist/hooks/index.mjs +19 -17
  35. package/dist/hooks/use-coagent-state-render-bridge.helpers.d.ts +92 -0
  36. package/dist/hooks/use-coagent-state-render-bridge.helpers.js +231 -0
  37. package/dist/hooks/use-coagent-state-render-bridge.helpers.js.map +1 -0
  38. package/dist/hooks/use-coagent-state-render-bridge.helpers.mjs +24 -0
  39. package/dist/hooks/use-coagent-state-render-bridge.helpers.mjs.map +1 -0
  40. package/dist/hooks/use-coagent-state-render-bridge.js +334 -72
  41. package/dist/hooks/use-coagent-state-render-bridge.js.map +1 -1
  42. package/dist/hooks/use-coagent-state-render-bridge.mjs +4 -2
  43. package/dist/hooks/use-coagent-state-render-registry.d.ts +25 -0
  44. package/dist/hooks/use-coagent-state-render-registry.js +358 -0
  45. package/dist/hooks/use-coagent-state-render-registry.js.map +1 -0
  46. package/dist/hooks/use-coagent-state-render-registry.mjs +9 -0
  47. package/dist/hooks/use-coagent-state-render-registry.mjs.map +1 -0
  48. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  49. package/dist/hooks/use-coagent-state-render.mjs +2 -2
  50. package/dist/hooks/use-copilot-chat-headless_c.js +414 -114
  51. package/dist/hooks/use-copilot-chat-headless_c.js.map +1 -1
  52. package/dist/hooks/use-copilot-chat-headless_c.mjs +7 -5
  53. package/dist/hooks/use-copilot-chat.js +406 -106
  54. package/dist/hooks/use-copilot-chat.js.map +1 -1
  55. package/dist/hooks/use-copilot-chat.mjs +7 -5
  56. package/dist/hooks/use-copilot-chat_internal.js +406 -106
  57. package/dist/hooks/use-copilot-chat_internal.js.map +1 -1
  58. package/dist/hooks/use-copilot-chat_internal.mjs +6 -4
  59. package/dist/hooks/use-langgraph-interrupt-render.mjs +1 -1
  60. package/dist/index.js +651 -311
  61. package/dist/index.js.map +1 -1
  62. package/dist/index.mjs +22 -20
  63. package/dist/lib/copilot-task.js.map +1 -1
  64. package/dist/lib/copilot-task.mjs +6 -4
  65. package/dist/lib/index.js.map +1 -1
  66. package/dist/lib/index.mjs +6 -4
  67. package/dist/setupTests.js +1 -0
  68. package/dist/setupTests.js.map +1 -1
  69. package/dist/setupTests.mjs +1 -0
  70. package/dist/setupTests.mjs.map +1 -1
  71. package/dist/test-helpers/copilot-context.d.ts +14 -0
  72. package/dist/test-helpers/copilot-context.js +128 -0
  73. package/dist/test-helpers/copilot-context.js.map +1 -0
  74. package/dist/test-helpers/copilot-context.mjs +74 -0
  75. package/dist/test-helpers/copilot-context.mjs.map +1 -0
  76. package/dist/types/index.mjs +1 -1
  77. package/package.json +5 -5
  78. package/src/components/copilot-provider/copilotkit.tsx +56 -0
  79. package/src/context/coagent-state-renders-context.tsx +1 -0
  80. package/src/hooks/__tests__/use-coagent-state-render-bridge.helpers.test.ts +100 -0
  81. package/src/hooks/__tests__/use-coagent-state-render.e2e.test.tsx +892 -37
  82. package/src/hooks/__tests__/use-coagent-state-render.test.tsx +334 -0
  83. package/src/hooks/use-coagent-state-render-bridge.helpers.ts +311 -0
  84. package/src/hooks/use-coagent-state-render-bridge.tsx +25 -120
  85. package/src/hooks/use-coagent-state-render-registry.ts +215 -0
  86. package/src/hooks/use-copilot-chat_internal.ts +93 -34
  87. package/src/setupTests.ts +1 -0
  88. package/src/test-helpers/copilot-context.ts +91 -0
  89. package/dist/chunk-3X3I7OJV.mjs +0 -172
  90. package/dist/chunk-3X3I7OJV.mjs.map +0 -1
  91. package/dist/chunk-FDOMAPJY.mjs.map +0 -1
  92. package/dist/chunk-GIU66J37.mjs.map +0 -1
  93. package/dist/chunk-HBMPXNW2.mjs.map +0 -1
  94. /package/dist/{chunk-3G4VFRVV.mjs.map → chunk-NXHQDCZF.mjs.map} +0 -0
  95. /package/dist/{chunk-YTQHRJUA.mjs.map → chunk-VKNLTZJE.mjs.map} +0 -0
  96. /package/dist/{chunk-4RRUJHCI.mjs.map → chunk-VP43SLSZ.mjs.map} +0 -0
  97. /package/dist/{chunk-MF2ZSLBV.mjs.map → chunk-XZFIJ7XF.mjs.map} +0 -0
package/dist/index.js CHANGED
@@ -119,8 +119,8 @@ __export(src_exports, {
119
119
  module.exports = __toCommonJS(src_exports);
120
120
 
121
121
  // src/components/copilot-provider/copilotkit.tsx
122
- var import_react15 = require("react");
123
- var import_react16 = require("@copilotkitnext/react");
122
+ var import_react16 = require("react");
123
+ var import_react17 = require("@copilotkitnext/react");
124
124
 
125
125
  // src/context/copilot-context.tsx
126
126
  var import_react = __toESM(require("react"));
@@ -359,7 +359,7 @@ function setsHaveIntersection(setA, setB) {
359
359
 
360
360
  // src/components/copilot-provider/copilotkit.tsx
361
361
  var import_react_dom = require("react-dom");
362
- var import_shared12 = require("@copilotkit/shared");
362
+ var import_shared13 = require("@copilotkit/shared");
363
363
 
364
364
  // src/hooks/use-flat-category-store.ts
365
365
  var import_react3 = require("react");
@@ -1392,8 +1392,8 @@ function useCoAgentStateRenders() {
1392
1392
  }
1393
1393
 
1394
1394
  // src/hooks/use-coagent-state-render-bridge.tsx
1395
- var import_react11 = require("@copilotkitnext/react");
1396
- var import_react12 = require("react");
1395
+ var import_react12 = require("@copilotkitnext/react");
1396
+ var import_react13 = require("react");
1397
1397
 
1398
1398
  // src/context/threads-context.tsx
1399
1399
  var import_react10 = require("react");
@@ -1423,6 +1423,9 @@ function useThreads() {
1423
1423
  }
1424
1424
 
1425
1425
  // src/hooks/use-coagent-state-render-bridge.tsx
1426
+ var import_shared10 = require("@copilotkit/shared");
1427
+
1428
+ // src/hooks/use-coagent-state-render-bridge.helpers.ts
1426
1429
  var import_shared9 = require("@copilotkit/shared");
1427
1430
  function getStateWithoutConstantKeys(state) {
1428
1431
  if (!state)
@@ -1445,16 +1448,294 @@ function areStatesEquals(a, b) {
1445
1448
  ]);
1446
1449
  return JSON.stringify(aWithoutConstantKeys) === JSON.stringify(bWithoutConstantKeys);
1447
1450
  }
1451
+ function isPlaceholderMessageId(messageId) {
1452
+ return !!messageId && messageId.startsWith("coagent-state-render-");
1453
+ }
1454
+ function isPlaceholderMessageName(messageName) {
1455
+ return messageName === "coagent-state-render";
1456
+ }
1457
+ function readCachedMessageEntry(entry) {
1458
+ if (!entry || typeof entry !== "object") {
1459
+ return { snapshot: entry, runId: void 0 };
1460
+ }
1461
+ const snapshot = "snapshot" in entry ? entry.snapshot : entry;
1462
+ const runId = "runId" in entry ? entry.runId : void 0;
1463
+ return { snapshot, runId };
1464
+ }
1465
+ function getEffectiveRunId({
1466
+ existingClaimRunId,
1467
+ cachedMessageRunId,
1468
+ runId
1469
+ }) {
1470
+ return existingClaimRunId || cachedMessageRunId || runId || "pending";
1471
+ }
1472
+ function resolveClaim({
1473
+ claims,
1474
+ context,
1475
+ stateSnapshot
1476
+ }) {
1477
+ const { messageId, stateRenderId, runId, messageIndex } = context;
1478
+ const existing = claims[messageId];
1479
+ if (existing) {
1480
+ const canRender = existing.stateRenderId === stateRenderId;
1481
+ const shouldUpdateRunId = canRender && runId && (!existing.runId || existing.runId === "pending");
1482
+ return {
1483
+ canRender,
1484
+ action: canRender ? "existing" /* Existing */ : "block" /* Block */,
1485
+ updateRunId: shouldUpdateRunId ? runId : void 0
1486
+ };
1487
+ }
1488
+ const normalizedRunId = runId != null ? runId : "pending";
1489
+ const renderClaimedByOtherMessageEntry = Object.entries(claims).find(
1490
+ ([, claim]) => {
1491
+ var _a;
1492
+ return claim.stateRenderId === stateRenderId && ((_a = claim.runId) != null ? _a : "pending") === normalizedRunId && (0, import_shared9.dataToUUID)(getStateWithoutConstantKeys(claim.stateSnapshot)) === (0, import_shared9.dataToUUID)(getStateWithoutConstantKeys(stateSnapshot));
1493
+ }
1494
+ );
1495
+ const renderClaimedByOtherMessage = renderClaimedByOtherMessageEntry == null ? void 0 : renderClaimedByOtherMessageEntry[1];
1496
+ const claimedMessageId = renderClaimedByOtherMessageEntry == null ? void 0 : renderClaimedByOtherMessageEntry[0];
1497
+ if (renderClaimedByOtherMessage) {
1498
+ if (messageIndex !== void 0 && renderClaimedByOtherMessage.messageIndex !== void 0 && messageIndex > renderClaimedByOtherMessage.messageIndex) {
1499
+ return {
1500
+ canRender: true,
1501
+ action: "override" /* Override */,
1502
+ nextClaim: { stateRenderId, runId, messageIndex },
1503
+ lockOthers: runId === renderClaimedByOtherMessage.runId || isPlaceholderMessageId(claimedMessageId)
1504
+ };
1505
+ }
1506
+ if (runId && renderClaimedByOtherMessage.runId && runId !== renderClaimedByOtherMessage.runId) {
1507
+ return {
1508
+ canRender: true,
1509
+ action: "override" /* Override */,
1510
+ nextClaim: { stateRenderId, runId, messageIndex },
1511
+ lockOthers: isPlaceholderMessageId(claimedMessageId)
1512
+ };
1513
+ }
1514
+ if (isPlaceholderMessageId(claimedMessageId)) {
1515
+ return {
1516
+ canRender: true,
1517
+ action: "override" /* Override */,
1518
+ nextClaim: { stateRenderId, runId, messageIndex },
1519
+ lockOthers: true
1520
+ };
1521
+ }
1522
+ if (stateSnapshot && renderClaimedByOtherMessage.stateSnapshot && !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, stateSnapshot)) {
1523
+ return {
1524
+ canRender: true,
1525
+ action: "override" /* Override */,
1526
+ nextClaim: { stateRenderId, runId }
1527
+ };
1528
+ }
1529
+ return { canRender: false, action: "block" /* Block */ };
1530
+ }
1531
+ if (!runId) {
1532
+ return { canRender: false, action: "block" /* Block */ };
1533
+ }
1534
+ return {
1535
+ canRender: true,
1536
+ action: "create" /* Create */,
1537
+ nextClaim: { stateRenderId, runId, messageIndex }
1538
+ };
1539
+ }
1540
+ function selectSnapshot({
1541
+ messageId,
1542
+ messageName,
1543
+ allowLiveState,
1544
+ skipLatestCache,
1545
+ stateRenderId,
1546
+ effectiveRunId,
1547
+ stateSnapshotProp,
1548
+ agentState,
1549
+ agentMessages,
1550
+ existingClaim,
1551
+ caches
1552
+ }) {
1553
+ var _a, _b, _c, _d, _e, _f;
1554
+ const lastAssistantId = agentMessages ? (_a = [...agentMessages].reverse().find((msg) => msg.role === "assistant")) == null ? void 0 : _a.id : void 0;
1555
+ const latestSnapshot = stateRenderId !== void 0 ? caches.byStateRenderAndRun[`${stateRenderId}::latest`] : void 0;
1556
+ const messageIndex = agentMessages ? agentMessages.findIndex((msg) => msg.id === messageId) : -1;
1557
+ const messageRole = messageIndex >= 0 && agentMessages ? (_b = agentMessages[messageIndex]) == null ? void 0 : _b.role : void 0;
1558
+ let previousUserMessageId;
1559
+ if (messageIndex > 0 && agentMessages) {
1560
+ for (let i = messageIndex - 1; i >= 0; i -= 1) {
1561
+ if (((_c = agentMessages[i]) == null ? void 0 : _c.role) === "user") {
1562
+ previousUserMessageId = (_d = agentMessages[i]) == null ? void 0 : _d.id;
1563
+ break;
1564
+ }
1565
+ }
1566
+ }
1567
+ const liveStateIsStale = stateSnapshotProp === void 0 && latestSnapshot !== void 0 && agentState !== void 0 && areStatesEquals(latestSnapshot, agentState);
1568
+ const shouldUseLiveState = (Boolean(allowLiveState) || !lastAssistantId || messageId === lastAssistantId) && !liveStateIsStale;
1569
+ const snapshot = stateSnapshotProp ? (0, import_shared9.parseJson)(stateSnapshotProp, stateSnapshotProp) : shouldUseLiveState ? agentState : void 0;
1570
+ const hasSnapshotKeys = !!(snapshot && Object.keys(snapshot).length > 0);
1571
+ const allowEmptySnapshot = snapshot !== void 0 && !hasSnapshotKeys && (stateSnapshotProp !== void 0 || shouldUseLiveState);
1572
+ const messageCacheEntry = caches.byMessageId[messageId];
1573
+ const cachedMessageSnapshot = readCachedMessageEntry(messageCacheEntry).snapshot;
1574
+ const cacheKey = stateRenderId !== void 0 ? `${stateRenderId}::${effectiveRunId}` : void 0;
1575
+ let cachedSnapshot = cachedMessageSnapshot != null ? cachedMessageSnapshot : caches.byMessageId[messageId];
1576
+ if (cachedSnapshot === void 0 && cacheKey && caches.byStateRenderAndRun[cacheKey] !== void 0) {
1577
+ cachedSnapshot = caches.byStateRenderAndRun[cacheKey];
1578
+ }
1579
+ if (cachedSnapshot === void 0 && stateRenderId && previousUserMessageId && caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`] !== void 0) {
1580
+ cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`];
1581
+ }
1582
+ if (cachedSnapshot === void 0 && !skipLatestCache && stateRenderId && messageRole !== "assistant" && (stateSnapshotProp !== void 0 || agentState && Object.keys(agentState).length > 0)) {
1583
+ cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::latest`];
1584
+ }
1585
+ const snapshotForClaim = (existingClaim == null ? void 0 : existingClaim.locked) ? (_e = existingClaim.stateSnapshot) != null ? _e : cachedSnapshot : hasSnapshotKeys ? snapshot : (_f = existingClaim == null ? void 0 : existingClaim.stateSnapshot) != null ? _f : cachedSnapshot;
1586
+ return { snapshot, hasSnapshotKeys, cachedSnapshot, allowEmptySnapshot, snapshotForClaim };
1587
+ }
1588
+
1589
+ // src/hooks/use-coagent-state-render-registry.ts
1590
+ var import_react11 = require("react");
1591
+ var LAST_SNAPSHOTS_BY_RENDER_AND_RUN = "__lastSnapshotsByStateRenderIdAndRun";
1592
+ var LAST_SNAPSHOTS_BY_MESSAGE = "__lastSnapshotsByMessageId";
1593
+ function getClaimsStore(claimsRef) {
1594
+ return claimsRef.current;
1595
+ }
1596
+ function getSnapshotCaches(claimsRef) {
1597
+ var _a, _b;
1598
+ const store = getClaimsStore(claimsRef);
1599
+ return {
1600
+ byStateRenderAndRun: (_a = store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN]) != null ? _a : {},
1601
+ byMessageId: (_b = store[LAST_SNAPSHOTS_BY_MESSAGE]) != null ? _b : {}
1602
+ };
1603
+ }
1604
+ function useStateRenderRegistry({
1605
+ agentId,
1606
+ stateRenderId,
1607
+ message,
1608
+ messageIndex,
1609
+ stateSnapshot,
1610
+ agentState,
1611
+ agentMessages,
1612
+ claimsRef
1613
+ }) {
1614
+ var _a, _b, _c, _d, _e, _f;
1615
+ const store = getClaimsStore(claimsRef);
1616
+ const runId = message.runId;
1617
+ const cachedMessageEntry = (_a = store[LAST_SNAPSHOTS_BY_MESSAGE]) == null ? void 0 : _a[message.id];
1618
+ const { runId: cachedMessageRunId } = readCachedMessageEntry(cachedMessageEntry);
1619
+ const existingClaimRunId = (_b = claimsRef.current[message.id]) == null ? void 0 : _b.runId;
1620
+ const effectiveRunId = getEffectiveRunId({
1621
+ existingClaimRunId,
1622
+ cachedMessageRunId,
1623
+ runId
1624
+ });
1625
+ (0, import_react11.useEffect)(() => {
1626
+ return () => {
1627
+ var _a2, _b2, _c2, _d2;
1628
+ const existingClaim2 = claimsRef.current[message.id];
1629
+ if ((existingClaim2 == null ? void 0 : existingClaim2.stateSnapshot) && Object.keys(existingClaim2.stateSnapshot).length > 0) {
1630
+ const snapshotCache = __spreadValues({}, (_a2 = store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN]) != null ? _a2 : {});
1631
+ const cacheKey = `${existingClaim2.stateRenderId}::${(_b2 = existingClaim2.runId) != null ? _b2 : "pending"}`;
1632
+ snapshotCache[cacheKey] = existingClaim2.stateSnapshot;
1633
+ snapshotCache[`${existingClaim2.stateRenderId}::latest`] = existingClaim2.stateSnapshot;
1634
+ store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
1635
+ const messageCache = __spreadValues({}, (_c2 = store[LAST_SNAPSHOTS_BY_MESSAGE]) != null ? _c2 : {});
1636
+ messageCache[message.id] = {
1637
+ snapshot: existingClaim2.stateSnapshot,
1638
+ runId: (_d2 = existingClaim2.runId) != null ? _d2 : effectiveRunId
1639
+ };
1640
+ store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
1641
+ }
1642
+ delete claimsRef.current[message.id];
1643
+ };
1644
+ }, [claimsRef, effectiveRunId, message.id]);
1645
+ if (!stateRenderId) {
1646
+ return { canRender: false };
1647
+ }
1648
+ const caches = getSnapshotCaches(claimsRef);
1649
+ const existingClaim = claimsRef.current[message.id];
1650
+ const { snapshot, hasSnapshotKeys, allowEmptySnapshot, snapshotForClaim } = selectSnapshot({
1651
+ messageId: message.id,
1652
+ messageName: message.name,
1653
+ allowLiveState: isPlaceholderMessageName(message.name) || isPlaceholderMessageId(message.id),
1654
+ skipLatestCache: isPlaceholderMessageName(message.name) || isPlaceholderMessageId(message.id),
1655
+ stateRenderId,
1656
+ effectiveRunId,
1657
+ stateSnapshotProp: stateSnapshot,
1658
+ agentState,
1659
+ agentMessages,
1660
+ existingClaim,
1661
+ caches
1662
+ });
1663
+ const resolution = resolveClaim({
1664
+ claims: claimsRef.current,
1665
+ context: {
1666
+ agentId,
1667
+ messageId: message.id,
1668
+ stateRenderId,
1669
+ runId: effectiveRunId,
1670
+ messageIndex
1671
+ },
1672
+ stateSnapshot: snapshotForClaim
1673
+ });
1674
+ if (resolution.action === "block" /* Block */) {
1675
+ return { canRender: false };
1676
+ }
1677
+ if (resolution.updateRunId && claimsRef.current[message.id]) {
1678
+ claimsRef.current[message.id].runId = resolution.updateRunId;
1679
+ }
1680
+ if (resolution.nextClaim) {
1681
+ claimsRef.current[message.id] = resolution.nextClaim;
1682
+ }
1683
+ if (resolution.lockOthers) {
1684
+ Object.entries(claimsRef.current).forEach(([id, claim]) => {
1685
+ if (id !== message.id && claim.stateRenderId === stateRenderId) {
1686
+ claim.locked = true;
1687
+ }
1688
+ });
1689
+ }
1690
+ if (existingClaim && !existingClaim.locked && (agentMessages == null ? void 0 : agentMessages.length)) {
1691
+ const indexInAgentMessages = agentMessages.findIndex((msg) => msg.id === message.id);
1692
+ if (indexInAgentMessages >= 0 && indexInAgentMessages < agentMessages.length - 1) {
1693
+ existingClaim.locked = true;
1694
+ }
1695
+ }
1696
+ const existingSnapshot = claimsRef.current[message.id].stateSnapshot;
1697
+ const snapshotChanged = stateSnapshot && existingSnapshot !== void 0 && !areStatesEquals(existingSnapshot, snapshot);
1698
+ if (snapshot && (stateSnapshot || hasSnapshotKeys || allowEmptySnapshot) && (!claimsRef.current[message.id].locked || snapshotChanged)) {
1699
+ if (!claimsRef.current[message.id].locked || snapshotChanged) {
1700
+ claimsRef.current[message.id].stateSnapshot = snapshot;
1701
+ const snapshotCache = __spreadValues({}, (_c = store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN]) != null ? _c : {});
1702
+ const cacheKey = `${stateRenderId}::${effectiveRunId}`;
1703
+ snapshotCache[cacheKey] = snapshot;
1704
+ snapshotCache[`${stateRenderId}::latest`] = snapshot;
1705
+ store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
1706
+ const messageCache = __spreadValues({}, (_d = store[LAST_SNAPSHOTS_BY_MESSAGE]) != null ? _d : {});
1707
+ messageCache[message.id] = { snapshot, runId: effectiveRunId };
1708
+ store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
1709
+ if (stateSnapshot) {
1710
+ claimsRef.current[message.id].locked = true;
1711
+ }
1712
+ }
1713
+ } else if (snapshotForClaim) {
1714
+ const existingSnapshot2 = claimsRef.current[message.id].stateSnapshot;
1715
+ if (!existingSnapshot2) {
1716
+ claimsRef.current[message.id].stateSnapshot = snapshotForClaim;
1717
+ const snapshotCache = __spreadValues({}, (_e = store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN]) != null ? _e : {});
1718
+ const cacheKey = `${stateRenderId}::${effectiveRunId}`;
1719
+ snapshotCache[cacheKey] = snapshotForClaim;
1720
+ snapshotCache[`${stateRenderId}::latest`] = snapshotForClaim;
1721
+ store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
1722
+ const messageCache = __spreadValues({}, (_f = store[LAST_SNAPSHOTS_BY_MESSAGE]) != null ? _f : {});
1723
+ messageCache[message.id] = { snapshot: snapshotForClaim, runId: effectiveRunId };
1724
+ store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
1725
+ }
1726
+ }
1727
+ return { canRender: true };
1728
+ }
1729
+
1730
+ // src/hooks/use-coagent-state-render-bridge.tsx
1448
1731
  function useCoagentStateRenderBridge(agentId, props) {
1449
1732
  var _a;
1450
- const { stateSnapshot, messageIndexInRun, message } = props;
1733
+ const { stateSnapshot, message } = props;
1451
1734
  const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();
1452
- const { agent } = (0, import_react11.useAgent)({ agentId });
1453
- const [nodeName, setNodeName] = (0, import_react12.useState)(void 0);
1454
- const [, forceUpdate] = (0, import_react12.useState)(0);
1455
- const runId = (_a = props.runId) != null ? _a : message.runId;
1456
- const effectiveRunId = runId || "pending";
1457
- (0, import_react12.useEffect)(() => {
1735
+ const { agent } = (0, import_react12.useAgent)({ agentId });
1736
+ const [nodeName, setNodeName] = (0, import_react13.useState)(void 0);
1737
+ const [, forceUpdate] = (0, import_react13.useState)(0);
1738
+ (0, import_react13.useEffect)(() => {
1458
1739
  if (!agent)
1459
1740
  return;
1460
1741
  const subscriber = {
@@ -1477,103 +1758,69 @@ function useCoagentStateRenderBridge(agentId, props) {
1477
1758
  unsubscribe();
1478
1759
  };
1479
1760
  }, [agentId, nodeName]);
1480
- const getStateRender = (0, import_react12.useCallback)(
1761
+ const getStateRender = (0, import_react13.useCallback)(
1481
1762
  (messageId) => {
1482
- return Object.entries(coAgentStateRenders).find(([stateRenderId, stateRender]) => {
1763
+ return Object.entries(coAgentStateRenders).find(([stateRenderId2, stateRender2]) => {
1483
1764
  if (claimsRef.current[messageId]) {
1484
- return stateRenderId === claimsRef.current[messageId].stateRenderId;
1765
+ return stateRenderId2 === claimsRef.current[messageId].stateRenderId;
1485
1766
  }
1486
- const matchingAgentName = stateRender.name === agentId;
1487
- const matchesNodeContext = stateRender.nodeName ? stateRender.nodeName === nodeName : true;
1767
+ const matchingAgentName = stateRender2.name === agentId;
1768
+ const matchesNodeContext = stateRender2.nodeName ? stateRender2.nodeName === nodeName : true;
1488
1769
  return matchingAgentName && matchesNodeContext;
1489
1770
  });
1490
1771
  },
1491
1772
  [coAgentStateRenders, nodeName, agentId]
1492
1773
  );
1493
- const handleRenderRequest = ({
1774
+ const stateRenderEntry = (0, import_react13.useMemo)(() => getStateRender(message.id), [getStateRender, message.id]);
1775
+ const stateRenderId = stateRenderEntry == null ? void 0 : stateRenderEntry[0];
1776
+ const stateRender = stateRenderEntry == null ? void 0 : stateRenderEntry[1];
1777
+ const registryMessage = __spreadProps(__spreadValues({}, message), {
1778
+ runId: (_a = props.runId) != null ? _a : message.runId
1779
+ });
1780
+ const { canRender } = useStateRenderRegistry({
1781
+ agentId,
1494
1782
  stateRenderId,
1495
- messageId,
1496
- runId: runId2,
1497
- stateSnapshot: renderSnapshot
1498
- }) => {
1499
- if (claimsRef.current[messageId]) {
1500
- const canRender = claimsRef.current[messageId].stateRenderId === stateRenderId;
1501
- if (canRender && runId2 && (!claimsRef.current[messageId].runId || claimsRef.current[messageId].runId === "pending")) {
1502
- claimsRef.current[messageId].runId = runId2;
1503
- }
1504
- return canRender;
1505
- }
1506
- const renderClaimedByOtherMessage = Object.values(claimsRef.current).find(
1507
- (c) => c.stateRenderId === stateRenderId && (0, import_shared9.dataToUUID)(getStateWithoutConstantKeys(c.stateSnapshot)) === (0, import_shared9.dataToUUID)(getStateWithoutConstantKeys(renderSnapshot))
1508
- );
1509
- if (renderClaimedByOtherMessage) {
1510
- if (renderSnapshot && renderClaimedByOtherMessage.stateSnapshot && !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, renderSnapshot)) {
1511
- claimsRef.current[messageId] = { stateRenderId, runId: runId2 };
1512
- return true;
1513
- }
1514
- return false;
1515
- }
1516
- if (!runId2) {
1517
- return false;
1518
- }
1519
- claimsRef.current[messageId] = { stateRenderId, runId: runId2 };
1520
- return true;
1521
- };
1522
- return (0, import_react12.useMemo)(() => {
1523
- var _a2, _b, _c;
1524
- if (messageIndexInRun !== 0) {
1525
- return null;
1526
- }
1527
- const [stateRenderId, stateRender] = (_a2 = getStateRender(message.id)) != null ? _a2 : [];
1783
+ message: registryMessage,
1784
+ messageIndex: props.messageIndex,
1785
+ stateSnapshot,
1786
+ agentState: agent == null ? void 0 : agent.state,
1787
+ agentMessages: agent == null ? void 0 : agent.messages,
1788
+ claimsRef
1789
+ });
1790
+ return (0, import_react13.useMemo)(() => {
1791
+ var _a2, _b;
1528
1792
  if (!stateRender || !stateRenderId) {
1529
1793
  return null;
1530
1794
  }
1531
- const snapshot = stateSnapshot ? (0, import_shared9.parseJson)(stateSnapshot, stateSnapshot) : agent == null ? void 0 : agent.state;
1532
- const canRender = handleRenderRequest({
1533
- stateRenderId,
1534
- messageId: message.id,
1535
- runId: effectiveRunId,
1536
- stateSnapshot: snapshot
1537
- });
1538
1795
  if (!canRender) {
1539
1796
  return null;
1540
1797
  }
1541
- if (snapshot) {
1542
- const existingSnapshot = claimsRef.current[message.id].stateSnapshot;
1543
- const snapshotChanged = stateSnapshot && existingSnapshot !== void 0 && !areStatesEquals(existingSnapshot, snapshot);
1544
- if (!claimsRef.current[message.id].locked || snapshotChanged) {
1545
- claimsRef.current[message.id].stateSnapshot = snapshot;
1546
- if (stateSnapshot) {
1547
- claimsRef.current[message.id].locked = true;
1548
- }
1549
- }
1550
- }
1551
1798
  if (stateRender.handler) {
1552
1799
  stateRender.handler({
1553
- state: stateSnapshot ? (0, import_shared9.parseJson)(stateSnapshot, stateSnapshot) : (_b = agent == null ? void 0 : agent.state) != null ? _b : {},
1800
+ state: stateSnapshot ? (0, import_shared10.parseJson)(stateSnapshot, stateSnapshot) : (_a2 = agent == null ? void 0 : agent.state) != null ? _a2 : {},
1554
1801
  nodeName: nodeName != null ? nodeName : ""
1555
1802
  });
1556
1803
  }
1557
1804
  if (stateRender.render) {
1558
- const status = (agent == null ? void 0 : agent.isRunning) ? "inProgress" : "complete";
1805
+ const status = (agent == null ? void 0 : agent.isRunning) ? "inProgress" /* InProgress */ : "complete" /* Complete */;
1559
1806
  if (typeof stateRender.render === "string")
1560
1807
  return stateRender.render;
1561
1808
  return stateRender.render({
1562
1809
  status,
1563
1810
  // Always use state from claim, to make sure the state does not seem "wiped" for a fraction of a second
1564
- state: (_c = claimsRef.current[message.id].stateSnapshot) != null ? _c : {},
1811
+ state: (_b = claimsRef.current[message.id].stateSnapshot) != null ? _b : {},
1565
1812
  nodeName: nodeName != null ? nodeName : ""
1566
1813
  });
1567
1814
  }
1568
1815
  }, [
1569
- getStateRender,
1570
- stateSnapshot,
1816
+ stateRender,
1817
+ stateRenderId,
1571
1818
  agent == null ? void 0 : agent.state,
1572
1819
  agent == null ? void 0 : agent.isRunning,
1573
1820
  nodeName,
1574
- effectiveRunId,
1575
1821
  message.id,
1576
- messageIndexInRun
1822
+ stateSnapshot,
1823
+ canRender
1577
1824
  ]);
1578
1825
  }
1579
1826
  function CoAgentStateRenderBridge(props) {
@@ -1581,13 +1828,13 @@ function CoAgentStateRenderBridge(props) {
1581
1828
  }
1582
1829
 
1583
1830
  // src/components/CopilotListeners.tsx
1584
- var import_react13 = require("react");
1585
- var import_react14 = require("@copilotkitnext/react");
1586
- var import_shared10 = require("@copilotkit/shared");
1831
+ var import_react14 = require("react");
1832
+ var import_react15 = require("@copilotkitnext/react");
1587
1833
  var import_shared11 = require("@copilotkit/shared");
1834
+ var import_shared12 = require("@copilotkit/shared");
1588
1835
  var usePredictStateSubscription = (agent) => {
1589
- const predictStateToolsRef = (0, import_react13.useRef)([]);
1590
- const getSubscriber = (0, import_react13.useCallback)(
1836
+ const predictStateToolsRef = (0, import_react14.useRef)([]);
1837
+ const getSubscriber = (0, import_react14.useCallback)(
1591
1838
  (agent2) => ({
1592
1839
  onCustomEvent: ({ event }) => {
1593
1840
  if (event.name === "PredictState") {
@@ -1598,7 +1845,7 @@ var usePredictStateSubscription = (agent) => {
1598
1845
  predictStateToolsRef.current.forEach((t) => {
1599
1846
  if ((t == null ? void 0 : t.tool) !== toolCallName)
1600
1847
  return;
1601
- const emittedState = typeof partialToolCallArgs === "string" ? (0, import_shared10.parseJson)(partialToolCallArgs, partialToolCallArgs) : partialToolCallArgs;
1848
+ const emittedState = typeof partialToolCallArgs === "string" ? (0, import_shared11.parseJson)(partialToolCallArgs, partialToolCallArgs) : partialToolCallArgs;
1602
1849
  agent2.setState({
1603
1850
  [t.state_key]: emittedState[t.state_key]
1604
1851
  });
@@ -1607,7 +1854,7 @@ var usePredictStateSubscription = (agent) => {
1607
1854
  }),
1608
1855
  []
1609
1856
  );
1610
- (0, import_react13.useEffect)(() => {
1857
+ (0, import_react14.useEffect)(() => {
1611
1858
  if (!agent)
1612
1859
  return;
1613
1860
  const subscriber = getSubscriber(agent);
@@ -1618,16 +1865,16 @@ var usePredictStateSubscription = (agent) => {
1618
1865
  }, [agent, getSubscriber]);
1619
1866
  };
1620
1867
  function CopilotListeners() {
1621
- const { copilotkit } = (0, import_react14.useCopilotKit)();
1622
- const existingConfig = (0, import_react14.useCopilotChatConfiguration)();
1868
+ const { copilotkit } = (0, import_react15.useCopilotKit)();
1869
+ const existingConfig = (0, import_react15.useCopilotChatConfiguration)();
1623
1870
  const resolvedAgentId = existingConfig == null ? void 0 : existingConfig.agentId;
1624
1871
  const { setBannerError } = useToast();
1625
- const { agent } = (0, import_react14.useAgent)({ agentId: resolvedAgentId });
1872
+ const { agent } = (0, import_react15.useAgent)({ agentId: resolvedAgentId });
1626
1873
  usePredictStateSubscription(agent);
1627
- (0, import_react13.useEffect)(() => {
1874
+ (0, import_react14.useEffect)(() => {
1628
1875
  const subscriber = {
1629
1876
  onError: ({ error }) => {
1630
- setBannerError(new import_shared11.CopilotKitLowLevelError({ error, message: error.message }));
1877
+ setBannerError(new import_shared12.CopilotKitLowLevelError({ error, message: error.message }));
1631
1878
  }
1632
1879
  };
1633
1880
  const subscription = copilotkit.subscribe(subscriber);
@@ -1645,9 +1892,9 @@ function CopilotKit(_a) {
1645
1892
  const enabled = shouldShowDevConsole(props.showDevConsole);
1646
1893
  const showInspector = shouldShowDevConsole(props.enableInspector);
1647
1894
  const publicApiKey = props.publicApiKey || props.publicLicenseKey;
1648
- const renderArr = (0, import_react15.useMemo)(() => [{ render: CoAgentStateRenderBridge }], []);
1895
+ const renderArr = (0, import_react16.useMemo)(() => [{ render: CoAgentStateRenderBridge }], []);
1649
1896
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(ToastProvider, { enabled, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(CopilotErrorBoundary, { publicApiKey, showUsageBanner: enabled, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(ThreadsProvider, { threadId: props.threadId, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
1650
- import_react16.CopilotKitProvider,
1897
+ import_react17.CopilotKitProvider,
1651
1898
  __spreadProps(__spreadValues({}, props), {
1652
1899
  showDevConsole: showInspector,
1653
1900
  renderCustomMessages: renderArr,
@@ -1656,44 +1903,83 @@ function CopilotKit(_a) {
1656
1903
  })
1657
1904
  ) }) }) });
1658
1905
  }
1906
+ function CopilotKitErrorBridge() {
1907
+ const { copilotkit } = (0, import_react17.useCopilotKit)();
1908
+ const { onError, copilotApiConfig } = useCopilotContext();
1909
+ (0, import_react16.useEffect)(() => {
1910
+ if (!copilotkit)
1911
+ return;
1912
+ const subscription = copilotkit.subscribe({
1913
+ onError: (event) => __async(this, null, function* () {
1914
+ const errorEvent = {
1915
+ type: "error",
1916
+ timestamp: Date.now(),
1917
+ context: __spreadValues({
1918
+ source: "agent",
1919
+ request: {
1920
+ operation: event.code || "unknown",
1921
+ url: copilotApiConfig == null ? void 0 : copilotApiConfig.chatApiEndpoint,
1922
+ startTime: Date.now()
1923
+ },
1924
+ technical: {
1925
+ environment: "browser",
1926
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
1927
+ stackTrace: event.error.stack
1928
+ }
1929
+ }, event.context),
1930
+ error: event.error
1931
+ };
1932
+ try {
1933
+ yield onError(errorEvent);
1934
+ } catch (handlerError) {
1935
+ console.error("Error in onError handler:", handlerError);
1936
+ }
1937
+ })
1938
+ });
1939
+ return () => {
1940
+ subscription.unsubscribe();
1941
+ };
1942
+ }, [copilotkit, onError, copilotApiConfig]);
1943
+ return null;
1944
+ }
1659
1945
  function CopilotKitInternal(cpkProps) {
1660
1946
  var _b;
1661
1947
  const _a = cpkProps, { children } = _a, props = __objRest(_a, ["children"]);
1662
1948
  validateProps(cpkProps);
1663
1949
  const publicApiKey = props.publicLicenseKey || props.publicApiKey;
1664
- const chatApiEndpoint = props.runtimeUrl || import_shared12.COPILOT_CLOUD_CHAT_URL;
1665
- const [actions, setActions] = (0, import_react15.useState)({});
1666
- const [registeredActionConfigs, setRegisteredActionConfigs] = (0, import_react15.useState)(/* @__PURE__ */ new Map());
1667
- const chatComponentsCache = (0, import_react15.useRef)({
1950
+ const chatApiEndpoint = props.runtimeUrl || import_shared13.COPILOT_CLOUD_CHAT_URL;
1951
+ const [actions, setActions] = (0, import_react16.useState)({});
1952
+ const [registeredActionConfigs, setRegisteredActionConfigs] = (0, import_react16.useState)(/* @__PURE__ */ new Map());
1953
+ const chatComponentsCache = (0, import_react16.useRef)({
1668
1954
  actions: {},
1669
1955
  coAgentStateRenders: {}
1670
1956
  });
1671
1957
  const { addElement, removeElement, printTree, getAllElements } = use_tree_default();
1672
- const [isLoading, setIsLoading] = (0, import_react15.useState)(false);
1673
- const [chatInstructions, setChatInstructions] = (0, import_react15.useState)("");
1674
- const [authStates, setAuthStates] = (0, import_react15.useState)({});
1675
- const [extensions, setExtensions] = (0, import_react15.useState)({});
1676
- const [additionalInstructions, setAdditionalInstructions] = (0, import_react15.useState)([]);
1958
+ const [isLoading, setIsLoading] = (0, import_react16.useState)(false);
1959
+ const [chatInstructions, setChatInstructions] = (0, import_react16.useState)("");
1960
+ const [authStates, setAuthStates] = (0, import_react16.useState)({});
1961
+ const [extensions, setExtensions] = (0, import_react16.useState)({});
1962
+ const [additionalInstructions, setAdditionalInstructions] = (0, import_react16.useState)([]);
1677
1963
  const {
1678
1964
  addElement: addDocument,
1679
1965
  removeElement: removeDocument,
1680
1966
  allElements: allDocuments
1681
1967
  } = use_flat_category_store_default();
1682
- const setAction = (0, import_react15.useCallback)((id, action) => {
1968
+ const setAction = (0, import_react16.useCallback)((id, action) => {
1683
1969
  setActions((prevPoints) => {
1684
1970
  return __spreadProps(__spreadValues({}, prevPoints), {
1685
1971
  [id]: action
1686
1972
  });
1687
1973
  });
1688
1974
  }, []);
1689
- const removeAction = (0, import_react15.useCallback)((id) => {
1975
+ const removeAction = (0, import_react16.useCallback)((id) => {
1690
1976
  setActions((prevPoints) => {
1691
1977
  const newPoints = __spreadValues({}, prevPoints);
1692
1978
  delete newPoints[id];
1693
1979
  return newPoints;
1694
1980
  });
1695
1981
  }, []);
1696
- const getContextString = (0, import_react15.useCallback)(
1982
+ const getContextString = (0, import_react16.useCallback)(
1697
1983
  (documents, categories) => {
1698
1984
  const documentsString = documents.map((document) => {
1699
1985
  return `${document.name} (${document.sourceApplication}):
@@ -1706,46 +1992,46 @@ ${nonDocumentStrings}`;
1706
1992
  },
1707
1993
  [printTree]
1708
1994
  );
1709
- const addContext = (0, import_react15.useCallback)(
1995
+ const addContext = (0, import_react16.useCallback)(
1710
1996
  (context, parentId, categories = defaultCopilotContextCategories) => {
1711
1997
  return addElement(context, categories, parentId);
1712
1998
  },
1713
1999
  [addElement]
1714
2000
  );
1715
- const removeContext = (0, import_react15.useCallback)(
2001
+ const removeContext = (0, import_react16.useCallback)(
1716
2002
  (id) => {
1717
2003
  removeElement(id);
1718
2004
  },
1719
2005
  [removeElement]
1720
2006
  );
1721
- const getAllContext = (0, import_react15.useCallback)(() => {
2007
+ const getAllContext = (0, import_react16.useCallback)(() => {
1722
2008
  return getAllElements();
1723
2009
  }, [getAllElements]);
1724
- const getFunctionCallHandler = (0, import_react15.useCallback)(
2010
+ const getFunctionCallHandler = (0, import_react16.useCallback)(
1725
2011
  (customEntryPoints) => {
1726
2012
  return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));
1727
2013
  },
1728
2014
  [actions]
1729
2015
  );
1730
- const getDocumentsContext = (0, import_react15.useCallback)(
2016
+ const getDocumentsContext = (0, import_react16.useCallback)(
1731
2017
  (categories) => {
1732
2018
  return allDocuments(categories);
1733
2019
  },
1734
2020
  [allDocuments]
1735
2021
  );
1736
- const addDocumentContext = (0, import_react15.useCallback)(
2022
+ const addDocumentContext = (0, import_react16.useCallback)(
1737
2023
  (documentPointer, categories = defaultCopilotContextCategories) => {
1738
2024
  return addDocument(documentPointer, categories);
1739
2025
  },
1740
2026
  [addDocument]
1741
2027
  );
1742
- const removeDocumentContext = (0, import_react15.useCallback)(
2028
+ const removeDocumentContext = (0, import_react16.useCallback)(
1743
2029
  (documentId) => {
1744
2030
  removeDocument(documentId);
1745
2031
  },
1746
2032
  [removeDocument]
1747
2033
  );
1748
- const copilotApiConfig = (0, import_react15.useMemo)(() => {
2034
+ const copilotApiConfig = (0, import_react16.useMemo)(() => {
1749
2035
  var _a2, _b2;
1750
2036
  let cloud = void 0;
1751
2037
  if (publicApiKey) {
@@ -1781,7 +2067,7 @@ ${nonDocumentStrings}`;
1781
2067
  props.cloudRestrictToTopic,
1782
2068
  props.guardrails_c
1783
2069
  ]);
1784
- const headers = (0, import_react15.useMemo)(() => {
2070
+ const headers = (0, import_react16.useMemo)(() => {
1785
2071
  const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {
1786
2072
  if (state.status === "authenticated" && state.authHeaders) {
1787
2073
  return __spreadValues(__spreadValues({}, acc), Object.entries(state.authHeaders).reduce(
@@ -1793,27 +2079,27 @@ ${nonDocumentStrings}`;
1793
2079
  }
1794
2080
  return acc;
1795
2081
  }, {});
1796
- return __spreadValues(__spreadValues(__spreadValues({}, copilotApiConfig.headers || {}), copilotApiConfig.publicApiKey ? { [import_shared12.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey } : {}), authHeaders);
2082
+ return __spreadValues(__spreadValues(__spreadValues({}, copilotApiConfig.headers || {}), copilotApiConfig.publicApiKey ? { [import_shared13.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey } : {}), authHeaders);
1797
2083
  }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);
1798
- const [internalErrorHandlers, _setInternalErrorHandler] = (0, import_react15.useState)({});
1799
- const setInternalErrorHandler = (0, import_react15.useCallback)((handler) => {
2084
+ const [internalErrorHandlers, _setInternalErrorHandler] = (0, import_react16.useState)({});
2085
+ const setInternalErrorHandler = (0, import_react16.useCallback)((handler) => {
1800
2086
  _setInternalErrorHandler((prev) => __spreadValues(__spreadValues({}, prev), handler));
1801
2087
  }, []);
1802
- const removeInternalErrorHandler = (0, import_react15.useCallback)((key) => {
2088
+ const removeInternalErrorHandler = (0, import_react16.useCallback)((key) => {
1803
2089
  _setInternalErrorHandler((prev) => {
1804
2090
  const _a2 = prev, { [key]: _removed } = _a2, rest = __objRest(_a2, [__restKey(key)]);
1805
2091
  return rest;
1806
2092
  });
1807
2093
  }, []);
1808
- const onErrorRef = (0, import_react15.useRef)(props.onError);
1809
- (0, import_react15.useEffect)(() => {
2094
+ const onErrorRef = (0, import_react16.useRef)(props.onError);
2095
+ (0, import_react16.useEffect)(() => {
1810
2096
  onErrorRef.current = props.onError;
1811
2097
  }, [props.onError]);
1812
- const internalHandlersRef = (0, import_react15.useRef)({});
1813
- (0, import_react15.useEffect)(() => {
2098
+ const internalHandlersRef = (0, import_react16.useRef)({});
2099
+ (0, import_react16.useEffect)(() => {
1814
2100
  internalHandlersRef.current = internalErrorHandlers;
1815
2101
  }, [internalErrorHandlers]);
1816
- const handleErrors = (0, import_react15.useCallback)(
2102
+ const handleErrors = (0, import_react16.useCallback)(
1817
2103
  (error) => __async(this, null, function* () {
1818
2104
  if (copilotApiConfig.publicApiKey && onErrorRef.current) {
1819
2105
  try {
@@ -1833,14 +2119,14 @@ ${nonDocumentStrings}`;
1833
2119
  }),
1834
2120
  [copilotApiConfig.publicApiKey]
1835
2121
  );
1836
- const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = (0, import_react15.useState)({});
1837
- const addChatSuggestionConfiguration = (0, import_react15.useCallback)(
2122
+ const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = (0, import_react16.useState)({});
2123
+ const addChatSuggestionConfiguration = (0, import_react16.useCallback)(
1838
2124
  (id, suggestion) => {
1839
2125
  setChatSuggestionConfiguration((prev) => __spreadProps(__spreadValues({}, prev), { [id]: suggestion }));
1840
2126
  },
1841
2127
  [setChatSuggestionConfiguration]
1842
2128
  );
1843
- const removeChatSuggestionConfiguration = (0, import_react15.useCallback)(
2129
+ const removeChatSuggestionConfiguration = (0, import_react16.useCallback)(
1844
2130
  (id) => {
1845
2131
  setChatSuggestionConfiguration((prev) => {
1846
2132
  const _a2 = prev, { [id]: _ } = _a2, rest = __objRest(_a2, [__restKey(id)]);
@@ -1849,10 +2135,10 @@ ${nonDocumentStrings}`;
1849
2135
  },
1850
2136
  [setChatSuggestionConfiguration]
1851
2137
  );
1852
- const [availableAgents, setAvailableAgents] = (0, import_react15.useState)([]);
1853
- const [coagentStates, setCoagentStates] = (0, import_react15.useState)({});
1854
- const coagentStatesRef = (0, import_react15.useRef)({});
1855
- const setCoagentStatesWithRef = (0, import_react15.useCallback)(
2138
+ const [availableAgents, setAvailableAgents] = (0, import_react16.useState)([]);
2139
+ const [coagentStates, setCoagentStates] = (0, import_react16.useState)({});
2140
+ const coagentStatesRef = (0, import_react16.useRef)({});
2141
+ const setCoagentStatesWithRef = (0, import_react16.useCallback)(
1856
2142
  (value) => {
1857
2143
  const newValue = typeof value === "function" ? value(coagentStatesRef.current) : value;
1858
2144
  coagentStatesRef.current = newValue;
@@ -1868,8 +2154,8 @@ ${nonDocumentStrings}`;
1868
2154
  agentName: props.agent
1869
2155
  };
1870
2156
  }
1871
- const [agentSession, setAgentSession] = (0, import_react15.useState)(initialAgentSession);
1872
- (0, import_react15.useEffect)(() => {
2157
+ const [agentSession, setAgentSession] = (0, import_react16.useState)(initialAgentSession);
2158
+ (0, import_react16.useEffect)(() => {
1873
2159
  if (props.agent) {
1874
2160
  setAgentSession({
1875
2161
  agentName: props.agent
@@ -1879,7 +2165,7 @@ ${nonDocumentStrings}`;
1879
2165
  }
1880
2166
  }, [props.agent]);
1881
2167
  const { threadId, setThreadId: setInternalThreadId } = useThreads();
1882
- const setThreadId = (0, import_react15.useCallback)(
2168
+ const setThreadId = (0, import_react16.useCallback)(
1883
2169
  (value) => {
1884
2170
  if (props.threadId) {
1885
2171
  throw new Error("Cannot call setThreadId() when threadId is provided via props.");
@@ -1888,11 +2174,11 @@ ${nonDocumentStrings}`;
1888
2174
  },
1889
2175
  [props.threadId]
1890
2176
  );
1891
- const [runId, setRunId] = (0, import_react15.useState)(null);
1892
- const chatAbortControllerRef = (0, import_react15.useRef)(null);
2177
+ const [runId, setRunId] = (0, import_react16.useState)(null);
2178
+ const chatAbortControllerRef = (0, import_react16.useRef)(null);
1893
2179
  const showDevConsole = shouldShowDevConsole(props.showDevConsole);
1894
- const [interruptActions, _setInterruptActions] = (0, import_react15.useState)({});
1895
- const setInterruptAction = (0, import_react15.useCallback)((action) => {
2180
+ const [interruptActions, _setInterruptActions] = (0, import_react16.useState)({});
2181
+ const setInterruptAction = (0, import_react16.useCallback)((action) => {
1896
2182
  _setInterruptActions((prev) => {
1897
2183
  var _a2;
1898
2184
  if (action == null || !action.id) {
@@ -1903,14 +2189,14 @@ ${nonDocumentStrings}`;
1903
2189
  });
1904
2190
  });
1905
2191
  }, []);
1906
- const removeInterruptAction = (0, import_react15.useCallback)((actionId) => {
2192
+ const removeInterruptAction = (0, import_react16.useCallback)((actionId) => {
1907
2193
  _setInterruptActions((prev) => {
1908
2194
  const _a2 = prev, { [actionId]: _ } = _a2, rest = __objRest(_a2, [__restKey(actionId)]);
1909
2195
  return rest;
1910
2196
  });
1911
2197
  }, []);
1912
- const [interruptEventQueue, setInterruptEventQueue] = (0, import_react15.useState)({});
1913
- const addInterruptEvent = (0, import_react15.useCallback)((queuedEvent) => {
2198
+ const [interruptEventQueue, setInterruptEventQueue] = (0, import_react16.useState)({});
2199
+ const addInterruptEvent = (0, import_react16.useCallback)((queuedEvent) => {
1914
2200
  setInterruptEventQueue((prev) => {
1915
2201
  const threadQueue = prev[queuedEvent.threadId] || [];
1916
2202
  return __spreadProps(__spreadValues({}, prev), {
@@ -1918,7 +2204,7 @@ ${nonDocumentStrings}`;
1918
2204
  });
1919
2205
  });
1920
2206
  }, []);
1921
- const resolveInterruptEvent = (0, import_react15.useCallback)(
2207
+ const resolveInterruptEvent = (0, import_react16.useCallback)(
1922
2208
  (threadId2, eventId, response) => {
1923
2209
  setInterruptEventQueue((prev) => {
1924
2210
  const threadQueue = prev[threadId2] || [];
@@ -1931,20 +2217,20 @@ ${nonDocumentStrings}`;
1931
2217
  },
1932
2218
  []
1933
2219
  );
1934
- const memoizedChildren = (0, import_react15.useMemo)(() => children, [children]);
1935
- const [bannerError, setBannerError] = (0, import_react15.useState)(null);
1936
- const agentLock = (0, import_react15.useMemo)(() => {
2220
+ const memoizedChildren = (0, import_react16.useMemo)(() => children, [children]);
2221
+ const [bannerError, setBannerError] = (0, import_react16.useState)(null);
2222
+ const agentLock = (0, import_react16.useMemo)(() => {
1937
2223
  var _a2;
1938
2224
  return (_a2 = props.agent) != null ? _a2 : null;
1939
2225
  }, [props.agent]);
1940
- const forwardedParameters = (0, import_react15.useMemo)(
2226
+ const forwardedParameters = (0, import_react16.useMemo)(
1941
2227
  () => {
1942
2228
  var _a2;
1943
2229
  return (_a2 = props.forwardedParameters) != null ? _a2 : {};
1944
2230
  },
1945
2231
  [props.forwardedParameters]
1946
2232
  );
1947
- const updateExtensions = (0, import_react15.useCallback)(
2233
+ const updateExtensions = (0, import_react16.useCallback)(
1948
2234
  (newExtensions) => {
1949
2235
  setExtensions((prev) => {
1950
2236
  const resolved = typeof newExtensions === "function" ? newExtensions(prev) : newExtensions;
@@ -1956,7 +2242,7 @@ ${nonDocumentStrings}`;
1956
2242
  },
1957
2243
  [setExtensions]
1958
2244
  );
1959
- const updateAuthStates = (0, import_react15.useCallback)(
2245
+ const updateAuthStates = (0, import_react16.useCallback)(
1960
2246
  (newAuthStates) => {
1961
2247
  setAuthStates((prev) => {
1962
2248
  const resolved = typeof newAuthStates === "function" ? newAuthStates(prev) : newAuthStates;
@@ -1968,8 +2254,8 @@ ${nonDocumentStrings}`;
1968
2254
  },
1969
2255
  [setAuthStates]
1970
2256
  );
1971
- const handleSetRegisteredActions = (0, import_react15.useCallback)((actionConfig) => {
1972
- const key = actionConfig.action.name || (0, import_shared12.randomUUID)();
2257
+ const handleSetRegisteredActions = (0, import_react16.useCallback)((actionConfig) => {
2258
+ const key = actionConfig.action.name || (0, import_shared13.randomUUID)();
1973
2259
  setRegisteredActionConfigs((prev) => {
1974
2260
  const newMap = new Map(prev);
1975
2261
  newMap.set(key, actionConfig);
@@ -1977,21 +2263,21 @@ ${nonDocumentStrings}`;
1977
2263
  });
1978
2264
  return key;
1979
2265
  }, []);
1980
- const handleRemoveRegisteredAction = (0, import_react15.useCallback)((actionKey) => {
2266
+ const handleRemoveRegisteredAction = (0, import_react16.useCallback)((actionKey) => {
1981
2267
  setRegisteredActionConfigs((prev) => {
1982
2268
  const newMap = new Map(prev);
1983
2269
  newMap.delete(actionKey);
1984
2270
  return newMap;
1985
2271
  });
1986
2272
  }, []);
1987
- const RegisteredActionsRenderer = (0, import_react15.useMemo)(() => {
2273
+ const RegisteredActionsRenderer = (0, import_react16.useMemo)(() => {
1988
2274
  return () => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_jsx_runtime9.Fragment, { children: Array.from(registeredActionConfigs.entries()).map(([key, config]) => {
1989
2275
  const Component = config.component;
1990
2276
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Component, { action: config.action }, key);
1991
2277
  }) });
1992
2278
  }, [registeredActionConfigs]);
1993
2279
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
1994
- import_react16.CopilotChatConfigurationProvider,
2280
+ import_react17.CopilotChatConfigurationProvider,
1995
2281
  {
1996
2282
  agentId: (_b = props.agent) != null ? _b : "default",
1997
2283
  threadId,
@@ -2058,6 +2344,7 @@ ${nonDocumentStrings}`;
2058
2344
  },
2059
2345
  children: [
2060
2346
  /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(CopilotListeners, {}),
2347
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(CopilotKitErrorBridge, {}),
2061
2348
  /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(CoAgentStateRendersProvider, { children: [
2062
2349
  /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(MessagesTapProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(CopilotMessages, { children: [
2063
2350
  memoizedChildren,
@@ -2112,33 +2399,33 @@ function validateProps(props) {
2112
2399
  const cloudFeatures = Object.keys(props).filter((key) => key.endsWith("_c"));
2113
2400
  const hasApiKey = props.publicApiKey || props.publicLicenseKey;
2114
2401
  if (!props.runtimeUrl && !hasApiKey) {
2115
- throw new import_shared12.ConfigurationError(
2402
+ throw new import_shared13.ConfigurationError(
2116
2403
  "Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'"
2117
2404
  );
2118
2405
  }
2119
2406
  if (cloudFeatures.length > 0 && !hasApiKey) {
2120
- throw new import_shared12.MissingPublicApiKeyError(
2407
+ throw new import_shared13.MissingPublicApiKeyError(
2121
2408
  `Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures.map(formatFeatureName).join(", ")}`
2122
2409
  );
2123
2410
  }
2124
2411
  }
2125
2412
 
2126
2413
  // src/hooks/use-copilot-chat_internal.ts
2127
- var import_react23 = require("react");
2414
+ var import_react24 = require("react");
2128
2415
  var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
2129
2416
 
2130
2417
  // src/hooks/use-langgraph-interrupt-render.ts
2131
- var import_react19 = __toESM(require("react"));
2418
+ var import_react20 = __toESM(require("react"));
2132
2419
  var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
2133
- var import_shared13 = require("@copilotkit/shared");
2420
+ var import_shared14 = require("@copilotkit/shared");
2134
2421
 
2135
2422
  // src/hooks/use-agent-nodename.ts
2136
- var import_react17 = require("react");
2137
- var import_react18 = require("@copilotkitnext/react");
2423
+ var import_react18 = require("react");
2424
+ var import_react19 = require("@copilotkitnext/react");
2138
2425
  function useAgentNodeName(agentName) {
2139
- const { agent } = (0, import_react18.useAgent)({ agentId: agentName });
2140
- const nodeNameRef = (0, import_react17.useRef)("start");
2141
- (0, import_react17.useEffect)(() => {
2426
+ const { agent } = (0, import_react19.useAgent)({ agentId: agentName });
2427
+ const nodeNameRef = (0, import_react18.useRef)("start");
2428
+ (0, import_react18.useEffect)(() => {
2142
2429
  if (!agent)
2143
2430
  return;
2144
2431
  const subscriber = {
@@ -2161,7 +2448,7 @@ function useAgentNodeName(agentName) {
2161
2448
  }
2162
2449
 
2163
2450
  // src/hooks/use-langgraph-interrupt-render.ts
2164
- var import_react20 = require("@copilotkitnext/react");
2451
+ var import_react21 = require("@copilotkitnext/react");
2165
2452
  var InterruptRenderer = ({ event, result, render, resolve }) => {
2166
2453
  return render({ event, result, resolve });
2167
2454
  };
@@ -2175,10 +2462,10 @@ function useLangGraphInterruptRender(agent) {
2175
2462
  addInterruptEvent,
2176
2463
  resolveInterruptEvent
2177
2464
  } = useCopilotContext();
2178
- const existingConfig = (0, import_react20.useCopilotChatConfiguration)();
2465
+ const existingConfig = (0, import_react21.useCopilotChatConfiguration)();
2179
2466
  const resolvedAgentId = (_a = existingConfig == null ? void 0 : existingConfig.agentId) != null ? _a : "default";
2180
2467
  const nodeName = useAgentNodeName(resolvedAgentId);
2181
- (0, import_react19.useEffect)(() => {
2468
+ (0, import_react20.useEffect)(() => {
2182
2469
  if (!agent)
2183
2470
  return;
2184
2471
  let localInterrupt = null;
@@ -2188,9 +2475,9 @@ function useLangGraphInterruptRender(agent) {
2188
2475
  const eventData = {
2189
2476
  name: import_runtime_client_gql.MetaEventName.LangGraphInterruptEvent,
2190
2477
  type: event.type,
2191
- value: (0, import_shared13.parseJson)(event.value, event.value)
2478
+ value: (0, import_shared14.parseJson)(event.value, event.value)
2192
2479
  };
2193
- const eventId = (0, import_shared13.dataToUUID)(eventData, "interruptEvents");
2480
+ const eventId = (0, import_shared14.dataToUUID)(eventData, "interruptEvents");
2194
2481
  localInterrupt = {
2195
2482
  eventId,
2196
2483
  threadId,
@@ -2213,7 +2500,7 @@ function useLangGraphInterruptRender(agent) {
2213
2500
  unsubscribe();
2214
2501
  };
2215
2502
  }, [agent, threadId]);
2216
- const handleResolve = (0, import_react19.useCallback)(
2503
+ const handleResolve = (0, import_react20.useCallback)(
2217
2504
  (eventId, response) => {
2218
2505
  agent == null ? void 0 : agent.runAgent({
2219
2506
  forwardedProps: {
@@ -2227,7 +2514,7 @@ function useLangGraphInterruptRender(agent) {
2227
2514
  // eslint-disable-next-line react-hooks/exhaustive-deps
2228
2515
  [agent, threadId]
2229
2516
  );
2230
- return (0, import_react19.useMemo)(() => {
2517
+ return (0, import_react20.useMemo)(() => {
2231
2518
  const eventQueue = interruptEventQueue[threadId] || [];
2232
2519
  const currentQueuedEvent = eventQueue.find((qe) => !qe.event.response);
2233
2520
  if (!currentQueuedEvent || !agentSession)
@@ -2258,7 +2545,7 @@ function useLangGraphInterruptRender(agent) {
2258
2545
  }
2259
2546
  if (!render)
2260
2547
  return null;
2261
- return import_react19.default.createElement(InterruptRenderer, {
2548
+ return import_react20.default.createElement(InterruptRenderer, {
2262
2549
  event: currentQueuedEvent.event,
2263
2550
  result,
2264
2551
  render,
@@ -2268,14 +2555,14 @@ function useLangGraphInterruptRender(agent) {
2268
2555
  }
2269
2556
 
2270
2557
  // src/hooks/use-copilot-chat_internal.ts
2271
- var import_react24 = require("@copilotkitnext/react");
2558
+ var import_react25 = require("@copilotkitnext/react");
2272
2559
 
2273
2560
  // src/hooks/use-lazy-tool-renderer.tsx
2274
- var import_react21 = require("@copilotkitnext/react");
2275
- var import_react22 = require("react");
2561
+ var import_react22 = require("@copilotkitnext/react");
2562
+ var import_react23 = require("react");
2276
2563
  function useLazyToolRenderer() {
2277
- const renderToolCall = (0, import_react21.useRenderToolCall)();
2278
- return (0, import_react22.useCallback)(
2564
+ const renderToolCall = (0, import_react22.useRenderToolCall)();
2565
+ return (0, import_react23.useCallback)(
2279
2566
  (message, messages) => {
2280
2567
  var _a;
2281
2568
  if (!((_a = message == null ? void 0 : message.toolCalls) == null ? void 0 : _a.length))
@@ -2305,13 +2592,13 @@ function useCopilotChatInternal({
2305
2592
  onReloadMessages
2306
2593
  } = {}) {
2307
2594
  var _a, _b, _c;
2308
- const { copilotkit } = (0, import_react24.useCopilotKit)();
2595
+ const { copilotkit } = (0, import_react25.useCopilotKit)();
2309
2596
  const { threadId, agentSession } = useCopilotContext();
2310
- const existingConfig = (0, import_react24.useCopilotChatConfiguration)();
2311
- const [agentAvailable, setAgentAvailable] = (0, import_react23.useState)(false);
2597
+ const existingConfig = (0, import_react25.useCopilotChatConfiguration)();
2598
+ const [agentAvailable, setAgentAvailable] = (0, import_react24.useState)(false);
2312
2599
  const resolvedAgentId = (_a = existingConfig == null ? void 0 : existingConfig.agentId) != null ? _a : "default";
2313
- const { agent } = (0, import_react24.useAgent)({ agentId: resolvedAgentId });
2314
- (0, import_react23.useEffect)(() => {
2600
+ const { agent } = (0, import_react25.useAgent)({ agentId: resolvedAgentId });
2601
+ (0, import_react24.useEffect)(() => {
2315
2602
  const connect = (agent2) => __async(this, null, function* () {
2316
2603
  setAgentAvailable(false);
2317
2604
  try {
@@ -2320,7 +2607,7 @@ function useCopilotChatInternal({
2320
2607
  } catch (error) {
2321
2608
  if (error instanceof import_client.AGUIConnectNotImplementedError) {
2322
2609
  } else {
2323
- throw error;
2610
+ console.error("CopilotChat: connectAgent failed", error);
2324
2611
  }
2325
2612
  }
2326
2613
  });
@@ -2331,7 +2618,7 @@ function useCopilotChatInternal({
2331
2618
  return () => {
2332
2619
  };
2333
2620
  }, [existingConfig == null ? void 0 : existingConfig.threadId, agent, copilotkit, resolvedAgentId]);
2334
- (0, import_react23.useEffect)(() => {
2621
+ (0, import_react24.useEffect)(() => {
2335
2622
  onInProgress == null ? void 0 : onInProgress(Boolean(agent == null ? void 0 : agent.isRunning));
2336
2623
  }, [agent == null ? void 0 : agent.isRunning, onInProgress]);
2337
2624
  const interrupt = useLangGraphInterruptRender(agent);
@@ -2339,7 +2626,7 @@ function useCopilotChatInternal({
2339
2626
  agent == null ? void 0 : agent.setMessages([]);
2340
2627
  agent == null ? void 0 : agent.setState(null);
2341
2628
  };
2342
- const deleteMessage = (0, import_react23.useCallback)(
2629
+ const deleteMessage = (0, import_react24.useCallback)(
2343
2630
  (messageId) => {
2344
2631
  var _a2;
2345
2632
  const filteredMessages = ((_a2 = agent == null ? void 0 : agent.messages) != null ? _a2 : []).filter(
@@ -2350,13 +2637,13 @@ function useCopilotChatInternal({
2350
2637
  [agent == null ? void 0 : agent.setMessages, agent == null ? void 0 : agent.messages]
2351
2638
  );
2352
2639
  const latestDelete = useUpdatedRef(deleteMessage);
2353
- const latestDeleteFunc = (0, import_react23.useCallback)(
2640
+ const latestDeleteFunc = (0, import_react24.useCallback)(
2354
2641
  (messageId) => {
2355
2642
  return latestDelete.current(messageId);
2356
2643
  },
2357
2644
  [latestDelete]
2358
2645
  );
2359
- const currentSuggestions = (0, import_react24.useSuggestions)({ agentId: resolvedAgentId });
2646
+ const currentSuggestions = (0, import_react25.useSuggestions)({ agentId: resolvedAgentId });
2360
2647
  const reload = useAsyncCallback(
2361
2648
  (reloadMessageId) => __async(this, null, function* () {
2362
2649
  var _a2;
@@ -2391,7 +2678,11 @@ function useCopilotChatInternal({
2391
2678
  }
2392
2679
  agent == null ? void 0 : agent.setMessages(historyCutoff);
2393
2680
  if (agent) {
2394
- copilotkit.runAgent({ agent });
2681
+ try {
2682
+ yield copilotkit.runAgent({ agent });
2683
+ } catch (error) {
2684
+ console.error("CopilotChat: runAgent failed during reload", error);
2685
+ }
2395
2686
  }
2396
2687
  return;
2397
2688
  }),
@@ -2431,7 +2722,7 @@ function useCopilotChatInternal({
2431
2722
  }),
2432
2723
  [latestSendMessageFunc]
2433
2724
  );
2434
- const latestSetMessagesFunc = (0, import_react23.useCallback)(
2725
+ const latestSetMessagesFunc = (0, import_react24.useCallback)(
2435
2726
  (messages) => {
2436
2727
  var _a2, _b2;
2437
2728
  if (messages.every((message) => message instanceof import_runtime_client_gql2.Message)) {
@@ -2454,7 +2745,7 @@ function useCopilotChatInternal({
2454
2745
  }),
2455
2746
  [latestReload, agent, onReloadMessages]
2456
2747
  );
2457
- const latestStopFunc = (0, import_react23.useCallback)(() => {
2748
+ const latestStopFunc = (0, import_react24.useCallback)(() => {
2458
2749
  var _a2, _b2;
2459
2750
  onStopGeneration == null ? void 0 : onStopGeneration({
2460
2751
  currentAgentName: agent == null ? void 0 : agent.agentId,
@@ -2463,11 +2754,11 @@ function useCopilotChatInternal({
2463
2754
  return (_b2 = agent == null ? void 0 : agent.abortRun) == null ? void 0 : _b2.call(agent);
2464
2755
  }, [onStopGeneration, agent]);
2465
2756
  const latestReset = useUpdatedRef(reset);
2466
- const latestResetFunc = (0, import_react23.useCallback)(() => {
2757
+ const latestResetFunc = (0, import_react24.useCallback)(() => {
2467
2758
  return latestReset.current();
2468
2759
  }, [latestReset]);
2469
2760
  const lazyToolRendered = useLazyToolRenderer();
2470
- const renderCustomMessage = (0, import_react24.useRenderCustomMessages)();
2761
+ const renderCustomMessage = (0, import_react25.useRenderCustomMessages)();
2471
2762
  const legacyCustomMessageRenderer = useLegacyCoagentRenderer({
2472
2763
  copilotkit,
2473
2764
  agent,
@@ -2475,7 +2766,8 @@ function useCopilotChatInternal({
2475
2766
  threadId: (_b = existingConfig == null ? void 0 : existingConfig.threadId) != null ? _b : threadId
2476
2767
  });
2477
2768
  const allMessages = (_c = agent == null ? void 0 : agent.messages) != null ? _c : [];
2478
- const resolvedMessages = (0, import_react23.useMemo)(() => {
2769
+ const resolvedMessages = (0, import_react24.useMemo)(() => {
2770
+ var _a2, _b2;
2479
2771
  let processedMessages = allMessages.map((message) => {
2480
2772
  if (message.role !== "assistant") {
2481
2773
  return message;
@@ -2488,31 +2780,78 @@ function useCopilotChatInternal({
2488
2780
  }
2489
2781
  }
2490
2782
  const bridgeRenderer = legacyCustomMessageRenderer || renderCustomMessage ? () => {
2491
- const customRender = renderCustomMessage == null ? void 0 : renderCustomMessage({
2492
- message,
2493
- position: "before"
2494
- });
2495
- if (customRender) {
2496
- return customRender;
2783
+ var _a3;
2784
+ if (legacyCustomMessageRenderer) {
2785
+ return legacyCustomMessageRenderer({ message, position: "before" });
2786
+ }
2787
+ try {
2788
+ return (_a3 = renderCustomMessage == null ? void 0 : renderCustomMessage({ message, position: "before" })) != null ? _a3 : null;
2789
+ } catch (error) {
2790
+ console.warn(
2791
+ "[CopilotKit] renderCustomMessages failed, falling back to legacy renderer",
2792
+ error
2793
+ );
2794
+ return null;
2497
2795
  }
2498
- return legacyCustomMessageRenderer == null ? void 0 : legacyCustomMessageRenderer({ message, position: "before" });
2499
2796
  } : null;
2500
2797
  if (bridgeRenderer) {
2501
- return __spreadProps(__spreadValues({}, message), { generativeUI: bridgeRenderer });
2798
+ return __spreadProps(__spreadValues({}, message), {
2799
+ generativeUI: bridgeRenderer,
2800
+ generativeUIPosition: "before"
2801
+ });
2502
2802
  }
2503
2803
  return message;
2504
2804
  });
2505
2805
  const hasAssistantMessages = processedMessages.some((msg) => msg.role === "assistant");
2806
+ const canUseCustomRenderer = Boolean(
2807
+ renderCustomMessage && ((_a2 = copilotkit == null ? void 0 : copilotkit.getAgent) == null ? void 0 : _a2.call(copilotkit, resolvedAgentId))
2808
+ );
2809
+ const placeholderRenderer = legacyCustomMessageRenderer ? legacyCustomMessageRenderer : canUseCustomRenderer ? renderCustomMessage : null;
2810
+ const shouldRenderPlaceholder = Boolean(agent == null ? void 0 : agent.isRunning) || Boolean((agent == null ? void 0 : agent.state) && Object.keys(agent.state).length);
2811
+ const effectiveThreadId = (_b2 = threadId != null ? threadId : agent == null ? void 0 : agent.threadId) != null ? _b2 : "default";
2812
+ let latestUserIndex = -1;
2813
+ for (let i = processedMessages.length - 1; i >= 0; i -= 1) {
2814
+ if (processedMessages[i].role === "user") {
2815
+ latestUserIndex = i;
2816
+ break;
2817
+ }
2818
+ }
2819
+ const latestUserMessageId = latestUserIndex >= 0 ? processedMessages[latestUserIndex].id : void 0;
2820
+ const currentRunId = latestUserMessageId ? copilotkit.getRunIdForMessage(resolvedAgentId, effectiveThreadId, latestUserMessageId) || `pending:${latestUserMessageId}` : void 0;
2821
+ const hasAssistantForCurrentRun = latestUserIndex >= 0 ? processedMessages.slice(latestUserIndex + 1).some((msg) => msg.role === "assistant") : hasAssistantMessages;
2822
+ if (placeholderRenderer && shouldRenderPlaceholder && !hasAssistantForCurrentRun) {
2823
+ const placeholderId = currentRunId ? `coagent-state-render-${resolvedAgentId}-${currentRunId}` : `coagent-state-render-${resolvedAgentId}`;
2824
+ const placeholderMessage = {
2825
+ id: placeholderId,
2826
+ role: "assistant",
2827
+ content: "",
2828
+ name: "coagent-state-render",
2829
+ runId: currentRunId
2830
+ };
2831
+ processedMessages = [
2832
+ ...processedMessages,
2833
+ __spreadProps(__spreadValues({}, placeholderMessage), {
2834
+ generativeUIPosition: "before",
2835
+ generativeUI: () => placeholderRenderer({
2836
+ message: placeholderMessage,
2837
+ position: "before"
2838
+ })
2839
+ })
2840
+ ];
2841
+ }
2506
2842
  return processedMessages;
2507
2843
  }, [
2508
2844
  agent == null ? void 0 : agent.messages,
2509
2845
  lazyToolRendered,
2510
2846
  allMessages,
2511
2847
  renderCustomMessage,
2512
- // legacyCustomMessageRenderer,
2513
- resolvedAgentId
2848
+ legacyCustomMessageRenderer,
2849
+ resolvedAgentId,
2850
+ copilotkit,
2851
+ agent == null ? void 0 : agent.isRunning,
2852
+ agent == null ? void 0 : agent.state
2514
2853
  ]);
2515
- const renderedSuggestions = (0, import_react23.useMemo)(() => {
2854
+ const renderedSuggestions = (0, import_react24.useMemo)(() => {
2516
2855
  if (Array.isArray(suggestions)) {
2517
2856
  return {
2518
2857
  suggestions: suggestions.map((s) => __spreadProps(__spreadValues({}, s), { isLoading: false })),
@@ -2547,8 +2886,8 @@ function useCopilotChatInternal({
2547
2886
  };
2548
2887
  }
2549
2888
  function useUpdatedRef(value) {
2550
- const ref = (0, import_react23.useRef)(value);
2551
- (0, import_react23.useEffect)(() => {
2889
+ const ref = (0, import_react24.useRef)(value);
2890
+ (0, import_react24.useEffect)(() => {
2552
2891
  ref.current = value;
2553
2892
  }, [value]);
2554
2893
  return ref;
@@ -2559,14 +2898,15 @@ function useLegacyCoagentRenderer({
2559
2898
  agentId,
2560
2899
  threadId
2561
2900
  }) {
2562
- return (0, import_react23.useMemo)(() => {
2901
+ return (0, import_react24.useMemo)(() => {
2563
2902
  if (!copilotkit || !agent) {
2564
2903
  return null;
2565
2904
  }
2566
2905
  return ({ message, position }) => {
2567
2906
  var _a;
2568
2907
  const effectiveThreadId = (_a = threadId != null ? threadId : agent.threadId) != null ? _a : "default";
2569
- const existingRunId = copilotkit.getRunIdForMessage(agentId, effectiveThreadId, message.id);
2908
+ const providedRunId = message.runId;
2909
+ const existingRunId = providedRunId ? providedRunId : copilotkit.getRunIdForMessage(agentId, effectiveThreadId, message.id);
2570
2910
  const runId = existingRunId || `pending:${message.id}`;
2571
2911
  const messageIndex = Math.max(
2572
2912
  agent.messages.findIndex((msg) => msg.id === message.id),
@@ -2582,7 +2922,7 @@ function useLegacyCoagentRenderer({
2582
2922
  agentId,
2583
2923
  stateSnapshot: message.state
2584
2924
  };
2585
- return (0, import_react23.createElement)(CoAgentStateRenderBridge, bridgeProps);
2925
+ return (0, import_react24.createElement)(CoAgentStateRenderBridge, bridgeProps);
2586
2926
  };
2587
2927
  }, [agent, agentId, copilotkit, threadId]);
2588
2928
  }
@@ -2616,8 +2956,8 @@ function useCopilotChat(options = {}) {
2616
2956
  }
2617
2957
 
2618
2958
  // src/hooks/use-copilot-chat-headless_c.ts
2619
- var import_react25 = require("react");
2620
- var import_shared14 = require("@copilotkit/shared");
2959
+ var import_react26 = require("react");
2960
+ var import_shared15 = require("@copilotkit/shared");
2621
2961
  var createNonFunctionalReturn = () => ({
2622
2962
  visibleMessages: [],
2623
2963
  messages: [],
@@ -2657,20 +2997,20 @@ function useCopilotChatHeadless_c(options = {}) {
2657
2997
  const { copilotApiConfig, setBannerError } = useCopilotContext();
2658
2998
  const hasPublicApiKey = Boolean(copilotApiConfig.publicApiKey);
2659
2999
  const internalResult = useCopilotChatInternal(options);
2660
- (0, import_react25.useEffect)(() => {
3000
+ (0, import_react26.useEffect)(() => {
2661
3001
  if (!hasPublicApiKey) {
2662
3002
  setBannerError(
2663
- new import_shared14.CopilotKitError({
3003
+ new import_shared15.CopilotKitError({
2664
3004
  message: (
2665
3005
  // add link to documentation here
2666
3006
  "You're using useCopilotChatHeadless_c, a premium-only feature, which offers extensive headless chat capabilities. To continue, you'll need to provide a free public license key."
2667
3007
  ),
2668
- code: import_shared14.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
2669
- severity: import_shared14.Severity.WARNING,
2670
- visibility: import_shared14.ErrorVisibility.BANNER
3008
+ code: import_shared15.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
3009
+ severity: import_shared15.Severity.WARNING,
3010
+ visibility: import_shared15.ErrorVisibility.BANNER
2671
3011
  })
2672
3012
  );
2673
- import_shared14.styledConsole.logCopilotKitPlatformMessage();
3013
+ import_shared15.styledConsole.logCopilotKitPlatformMessage();
2674
3014
  } else {
2675
3015
  setBannerError(null);
2676
3016
  }
@@ -2682,48 +3022,48 @@ function useCopilotChatHeadless_c(options = {}) {
2682
3022
  }
2683
3023
 
2684
3024
  // src/hooks/use-copilot-action.ts
2685
- var import_react32 = require("react");
3025
+ var import_react33 = require("react");
2686
3026
 
2687
3027
  // src/hooks/use-frontend-tool.ts
2688
- var import_react26 = __toESM(require("react"));
2689
- var import_shared15 = require("@copilotkit/shared");
3028
+ var import_react27 = __toESM(require("react"));
2690
3029
  var import_shared16 = require("@copilotkit/shared");
2691
- var import_react27 = require("@copilotkitnext/react");
3030
+ var import_shared17 = require("@copilotkit/shared");
3031
+ var import_react28 = require("@copilotkitnext/react");
2692
3032
  function useFrontendTool(tool, dependencies) {
2693
3033
  const { name, description, parameters, render, followUp } = tool;
2694
- const zodParameters = (0, import_shared15.getZodParameters)(parameters);
3034
+ const zodParameters = (0, import_shared16.getZodParameters)(parameters);
2695
3035
  const normalizedRender = (() => {
2696
3036
  if (typeof render === "undefined") {
2697
3037
  return void 0;
2698
3038
  }
2699
3039
  if (typeof render === "string") {
2700
3040
  const staticRender = render;
2701
- return () => import_react26.default.createElement(
2702
- import_react26.default.Fragment,
3041
+ return () => import_react27.default.createElement(
3042
+ import_react27.default.Fragment,
2703
3043
  null,
2704
3044
  staticRender
2705
3045
  );
2706
3046
  }
2707
3047
  return (args) => {
2708
3048
  const renderArgs = __spreadProps(__spreadValues({}, args), {
2709
- result: typeof args.result === "string" ? (0, import_shared16.parseJson)(args.result, args.result) : args.result
3049
+ result: typeof args.result === "string" ? (0, import_shared17.parseJson)(args.result, args.result) : args.result
2710
3050
  });
2711
3051
  const rendered = render(renderArgs);
2712
3052
  if (typeof rendered === "string") {
2713
- return import_react26.default.createElement(import_react26.default.Fragment, null, rendered);
3053
+ return import_react27.default.createElement(import_react27.default.Fragment, null, rendered);
2714
3054
  }
2715
3055
  return rendered != null ? rendered : null;
2716
3056
  };
2717
3057
  })();
2718
- const handlerRef = (0, import_react26.useRef)(tool.handler);
2719
- (0, import_react26.useEffect)(() => {
3058
+ const handlerRef = (0, import_react27.useRef)(tool.handler);
3059
+ (0, import_react27.useEffect)(() => {
2720
3060
  handlerRef.current = tool.handler;
2721
3061
  }, [tool.handler, ...dependencies != null ? dependencies : []]);
2722
3062
  const normalizedHandler = tool.handler ? (args) => {
2723
3063
  var _a;
2724
3064
  return (_a = handlerRef.current) == null ? void 0 : _a.call(handlerRef, args);
2725
3065
  } : void 0;
2726
- (0, import_react27.useFrontendTool)({
3066
+ (0, import_react28.useFrontendTool)({
2727
3067
  name,
2728
3068
  description,
2729
3069
  parameters: zodParameters,
@@ -2734,29 +3074,29 @@ function useFrontendTool(tool, dependencies) {
2734
3074
  }
2735
3075
 
2736
3076
  // src/hooks/use-render-tool-call.ts
2737
- var import_shared17 = require("@copilotkit/shared");
2738
- var import_react28 = require("react");
2739
- var import_react29 = require("@copilotkitnext/react");
2740
3077
  var import_shared18 = require("@copilotkit/shared");
3078
+ var import_react29 = require("react");
3079
+ var import_react30 = require("@copilotkitnext/react");
3080
+ var import_shared19 = require("@copilotkit/shared");
2741
3081
  function useRenderToolCall2(tool, dependencies) {
2742
- const { copilotkit } = (0, import_react29.useCopilotKit)();
2743
- const hasAddedRef = (0, import_react28.useRef)(false);
2744
- (0, import_react28.useEffect)(() => {
3082
+ const { copilotkit } = (0, import_react30.useCopilotKit)();
3083
+ const hasAddedRef = (0, import_react29.useRef)(false);
3084
+ (0, import_react29.useEffect)(() => {
2745
3085
  const { name, parameters, render } = tool;
2746
- const zodParameters = (0, import_shared17.getZodParameters)(parameters);
2747
- const renderToolCall = name === "*" ? (0, import_react29.defineToolCallRenderer)({
3086
+ const zodParameters = (0, import_shared18.getZodParameters)(parameters);
3087
+ const renderToolCall = name === "*" ? (0, import_react30.defineToolCallRenderer)({
2748
3088
  name: "*",
2749
3089
  render: (args) => {
2750
3090
  return render(__spreadProps(__spreadValues({}, args), {
2751
- result: args.result ? (0, import_shared18.parseJson)(args.result, args.result) : args.result
3091
+ result: args.result ? (0, import_shared19.parseJson)(args.result, args.result) : args.result
2752
3092
  }));
2753
3093
  }
2754
- }) : (0, import_react29.defineToolCallRenderer)({
3094
+ }) : (0, import_react30.defineToolCallRenderer)({
2755
3095
  name,
2756
3096
  args: zodParameters,
2757
3097
  render: (args) => {
2758
3098
  return render(__spreadProps(__spreadValues({}, args), {
2759
- result: args.result ? (0, import_shared18.parseJson)(args.result, args.result) : args.result
3099
+ result: args.result ? (0, import_shared19.parseJson)(args.result, args.result) : args.result
2760
3100
  }));
2761
3101
  }
2762
3102
  });
@@ -2779,19 +3119,19 @@ function useRenderToolCall2(tool, dependencies) {
2779
3119
  }
2780
3120
 
2781
3121
  // src/hooks/use-human-in-the-loop.ts
2782
- var import_shared19 = require("@copilotkit/shared");
2783
- var import_react30 = require("@copilotkitnext/react");
3122
+ var import_shared20 = require("@copilotkit/shared");
3123
+ var import_react31 = require("@copilotkitnext/react");
2784
3124
  var import_core = require("@copilotkitnext/core");
2785
- var import_react31 = __toESM(require("react"));
3125
+ var import_react32 = __toESM(require("react"));
2786
3126
  function useHumanInTheLoop(tool, dependencies) {
2787
3127
  const _a = tool, { render } = _a, toolRest = __objRest(_a, ["render"]);
2788
3128
  const { name, description, parameters, followUp } = toolRest;
2789
- const zodParameters = (0, import_shared19.getZodParameters)(parameters);
2790
- const renderRef = (0, import_react31.useRef)(null);
2791
- (0, import_react31.useEffect)(() => {
3129
+ const zodParameters = (0, import_shared20.getZodParameters)(parameters);
3130
+ const renderRef = (0, import_react32.useRef)(null);
3131
+ (0, import_react32.useEffect)(() => {
2792
3132
  renderRef.current = (args) => {
2793
3133
  if (typeof render === "string") {
2794
- return import_react31.default.createElement(import_react31.default.Fragment, null, render);
3134
+ return import_react32.default.createElement(import_react32.default.Fragment, null, render);
2795
3135
  }
2796
3136
  if (!render) {
2797
3137
  return null;
@@ -2819,24 +3159,24 @@ function useHumanInTheLoop(tool, dependencies) {
2819
3159
  args: mappedArgs,
2820
3160
  respond: args.respond,
2821
3161
  status: args.status,
2822
- result: args.result ? (0, import_shared19.parseJson)(args.result, args.result) : args.result,
3162
+ result: args.result ? (0, import_shared20.parseJson)(args.result, args.result) : args.result,
2823
3163
  handler: void 0
2824
3164
  };
2825
3165
  default:
2826
- throw new import_shared19.CopilotKitError({
2827
- code: import_shared19.CopilotKitErrorCode.UNKNOWN,
3166
+ throw new import_shared20.CopilotKitError({
3167
+ code: import_shared20.CopilotKitErrorCode.UNKNOWN,
2828
3168
  message: `Invalid tool call status: ${args.status}`
2829
3169
  });
2830
3170
  }
2831
3171
  })();
2832
3172
  const rendered = render(renderProps);
2833
3173
  if (typeof rendered === "string") {
2834
- return import_react31.default.createElement(import_react31.default.Fragment, null, rendered);
3174
+ return import_react32.default.createElement(import_react32.default.Fragment, null, rendered);
2835
3175
  }
2836
3176
  return rendered != null ? rendered : null;
2837
3177
  };
2838
3178
  }, [render, ...dependencies != null ? dependencies : []]);
2839
- (0, import_react30.useHumanInTheLoop)({
3179
+ (0, import_react31.useHumanInTheLoop)({
2840
3180
  name,
2841
3181
  description,
2842
3182
  followUp,
@@ -2892,7 +3232,7 @@ function getActionConfig(action) {
2892
3232
  throw new Error("Invalid action configuration");
2893
3233
  }
2894
3234
  function useCopilotAction(action, dependencies) {
2895
- const [initialActionConfig] = (0, import_react32.useState)(getActionConfig(action));
3235
+ const [initialActionConfig] = (0, import_react33.useState)(getActionConfig(action));
2896
3236
  const currentActionConfig = getActionConfig(action);
2897
3237
  if (initialActionConfig.type !== currentActionConfig.type) {
2898
3238
  throw new Error("Action configuration changed between renders");
@@ -2910,17 +3250,17 @@ function useCopilotAction(action, dependencies) {
2910
3250
  }
2911
3251
 
2912
3252
  // src/hooks/use-coagent-state-render.ts
2913
- var import_react33 = require("react");
2914
- var import_shared20 = require("@copilotkit/shared");
3253
+ var import_react34 = require("react");
3254
+ var import_shared21 = require("@copilotkit/shared");
2915
3255
  function useCoAgentStateRender(action, dependencies) {
2916
- const { chatComponentsCache, availableAgents } = (0, import_react33.useContext)(CopilotContext);
3256
+ const { chatComponentsCache, availableAgents } = (0, import_react34.useContext)(CopilotContext);
2917
3257
  const { setCoAgentStateRender, removeCoAgentStateRender, coAgentStateRenders } = useCoAgentStateRenders();
2918
- const idRef = (0, import_react33.useRef)((0, import_shared20.randomId)());
3258
+ const idRef = (0, import_react34.useRef)((0, import_shared21.randomId)());
2919
3259
  const { setBannerError, addToast } = useToast();
2920
- (0, import_react33.useEffect)(() => {
3260
+ (0, import_react34.useEffect)(() => {
2921
3261
  if ((availableAgents == null ? void 0 : availableAgents.length) && !availableAgents.some((a) => a.name === action.name)) {
2922
3262
  const message = `(useCoAgentStateRender): Agent "${action.name}" not found. Make sure the agent exists and is properly configured.`;
2923
- const agentError = new import_shared20.CopilotKitAgentDiscoveryError({
3263
+ const agentError = new import_shared21.CopilotKitAgentDiscoveryError({
2924
3264
  agentName: action.name,
2925
3265
  availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id }))
2926
3266
  });
@@ -2938,7 +3278,7 @@ function useCoAgentStateRender(action, dependencies) {
2938
3278
  }
2939
3279
  }
2940
3280
  }
2941
- (0, import_react33.useEffect)(() => {
3281
+ (0, import_react34.useEffect)(() => {
2942
3282
  const currentId = idRef.current;
2943
3283
  const hasDuplicate = Object.entries(coAgentStateRenders).some(([id, otherAction]) => {
2944
3284
  if (id === currentId)
@@ -2962,7 +3302,7 @@ function useCoAgentStateRender(action, dependencies) {
2962
3302
  });
2963
3303
  }
2964
3304
  }, [coAgentStateRenders]);
2965
- (0, import_react33.useEffect)(() => {
3305
+ (0, import_react34.useEffect)(() => {
2966
3306
  setCoAgentStateRender(idRef.current, action);
2967
3307
  if (chatComponentsCache.current !== null && action.render !== void 0) {
2968
3308
  chatComponentsCache.current.coAgentStateRenders[key] = action.render;
@@ -2982,11 +3322,11 @@ function useCoAgentStateRender(action, dependencies) {
2982
3322
  }
2983
3323
 
2984
3324
  // src/hooks/use-make-copilot-document-readable.ts
2985
- var import_react34 = require("react");
3325
+ var import_react35 = require("react");
2986
3326
  function useMakeCopilotDocumentReadable(document, categories, dependencies = []) {
2987
3327
  const { addDocumentContext, removeDocumentContext } = useCopilotContext();
2988
- const idRef = (0, import_react34.useRef)(void 0);
2989
- (0, import_react34.useEffect)(() => {
3328
+ const idRef = (0, import_react35.useRef)(void 0);
3329
+ (0, import_react35.useEffect)(() => {
2990
3330
  const id = addDocumentContext(document, categories);
2991
3331
  idRef.current = id;
2992
3332
  return () => {
@@ -2997,12 +3337,12 @@ function useMakeCopilotDocumentReadable(document, categories, dependencies = [])
2997
3337
  }
2998
3338
 
2999
3339
  // src/hooks/use-copilot-readable.ts
3000
- var import_react35 = require("@copilotkitnext/react");
3001
- var import_react36 = require("react");
3340
+ var import_react36 = require("@copilotkitnext/react");
3341
+ var import_react37 = require("react");
3002
3342
  function useCopilotReadable({ description, value, convert, available }, dependencies) {
3003
- const { copilotkit } = (0, import_react35.useCopilotKit)();
3004
- const ctxIdRef = (0, import_react36.useRef)(void 0);
3005
- (0, import_react36.useEffect)(() => {
3343
+ const { copilotkit } = (0, import_react36.useCopilotKit)();
3344
+ const ctxIdRef = (0, import_react37.useRef)(void 0);
3345
+ (0, import_react37.useEffect)(() => {
3006
3346
  if (!copilotkit)
3007
3347
  return;
3008
3348
  const found = Object.entries(copilotkit.context).find(([id, ctxItem]) => {
@@ -3030,13 +3370,13 @@ function useCopilotReadable({ description, value, convert, available }, dependen
3030
3370
  }
3031
3371
 
3032
3372
  // src/hooks/use-coagent.ts
3033
- var import_react37 = require("react");
3034
- var import_react38 = require("@copilotkitnext/react");
3373
+ var import_react38 = require("react");
3374
+ var import_react39 = require("@copilotkitnext/react");
3035
3375
  function useCoAgent(options) {
3036
- const { agent } = (0, import_react38.useAgent)({ agentId: options.name });
3037
- const { copilotkit } = (0, import_react38.useCopilotKit)();
3376
+ const { agent } = (0, import_react39.useAgent)({ agentId: options.name });
3377
+ const { copilotkit } = (0, import_react39.useCopilotKit)();
3038
3378
  const nodeName = useAgentNodeName(options.name);
3039
- const handleStateUpdate = (0, import_react37.useCallback)(
3379
+ const handleStateUpdate = (0, import_react38.useCallback)(
3040
3380
  (newState) => {
3041
3381
  if (!agent)
3042
3382
  return;
@@ -3049,7 +3389,7 @@ function useCoAgent(options) {
3049
3389
  },
3050
3390
  [agent == null ? void 0 : agent.state, agent == null ? void 0 : agent.setState]
3051
3391
  );
3052
- (0, import_react37.useEffect)(() => {
3392
+ (0, import_react38.useEffect)(() => {
3053
3393
  var _a;
3054
3394
  if (!options.config && !options.configurable)
3055
3395
  return;
@@ -3061,22 +3401,22 @@ function useCoAgent(options) {
3061
3401
  }
3062
3402
  copilotkit.setProperties(config);
3063
3403
  }, [options.config, options.configurable]);
3064
- const externalStateStr = (0, import_react37.useMemo)(
3404
+ const externalStateStr = (0, import_react38.useMemo)(
3065
3405
  () => isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0,
3066
3406
  [isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0]
3067
3407
  );
3068
- (0, import_react37.useEffect)(() => {
3408
+ (0, import_react38.useEffect)(() => {
3069
3409
  if ((agent == null ? void 0 : agent.state) && isExternalStateManagement(options) && JSON.stringify(options.state) !== JSON.stringify(agent.state)) {
3070
3410
  handleStateUpdate(options.state);
3071
3411
  }
3072
3412
  }, [agent, externalStateStr, handleStateUpdate]);
3073
- const hasStateValues = (0, import_react37.useCallback)((value) => {
3413
+ const hasStateValues = (0, import_react38.useCallback)((value) => {
3074
3414
  return Boolean(value && Object.keys(value).length);
3075
3415
  }, []);
3076
- const initialStateRef = (0, import_react37.useRef)(
3416
+ const initialStateRef = (0, import_react38.useRef)(
3077
3417
  isExternalStateManagement(options) ? options.state : "initialState" in options ? options.initialState : void 0
3078
3418
  );
3079
- (0, import_react37.useEffect)(() => {
3419
+ (0, import_react38.useEffect)(() => {
3080
3420
  if (isExternalStateManagement(options)) {
3081
3421
  initialStateRef.current = options.state;
3082
3422
  } else if ("initialState" in options) {
@@ -3085,7 +3425,7 @@ function useCoAgent(options) {
3085
3425
  }, [
3086
3426
  isExternalStateManagement(options) ? JSON.stringify(options.state) : "initialState" in options ? JSON.stringify(options.initialState) : void 0
3087
3427
  ]);
3088
- (0, import_react37.useEffect)(() => {
3428
+ (0, import_react38.useEffect)(() => {
3089
3429
  if (!agent)
3090
3430
  return;
3091
3431
  const subscriber = {
@@ -3113,7 +3453,7 @@ function useCoAgent(options) {
3113
3453
  subscription.unsubscribe();
3114
3454
  };
3115
3455
  }, [agent, handleStateUpdate, hasStateValues]);
3116
- return (0, import_react37.useMemo)(() => {
3456
+ return (0, import_react38.useMemo)(() => {
3117
3457
  var _a, _b, _c;
3118
3458
  if (!agent) {
3119
3459
  const noop = () => {
@@ -3169,12 +3509,12 @@ var isExternalStateManagement = (options) => {
3169
3509
 
3170
3510
  // src/hooks/use-copilot-runtime-client.ts
3171
3511
  var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
3172
- var import_react39 = require("react");
3173
- var import_shared21 = require("@copilotkit/shared");
3512
+ var import_react40 = require("react");
3513
+ var import_shared22 = require("@copilotkit/shared");
3174
3514
  var useCopilotRuntimeClient = (options) => {
3175
3515
  const { setBannerError } = useToast();
3176
3516
  const _a = options, { showDevConsole, onError } = _a, runtimeOptions = __objRest(_a, ["showDevConsole", "onError"]);
3177
- const lastStructuredErrorRef = (0, import_react39.useRef)(null);
3517
+ const lastStructuredErrorRef = (0, import_react40.useRef)(null);
3178
3518
  const traceUIError = (error, originalError) => __async(void 0, null, function* () {
3179
3519
  try {
3180
3520
  const errorEvent = {
@@ -3200,7 +3540,7 @@ var useCopilotRuntimeClient = (options) => {
3200
3540
  console.error("Error in onError handler:", error2);
3201
3541
  }
3202
3542
  });
3203
- const runtimeClient = (0, import_react39.useMemo)(() => {
3543
+ const runtimeClient = (0, import_react40.useMemo)(() => {
3204
3544
  return new import_runtime_client_gql3.CopilotRuntimeClient(__spreadProps(__spreadValues({}, runtimeOptions), {
3205
3545
  handleGQLErrors: (error) => {
3206
3546
  var _a2;
@@ -3209,7 +3549,7 @@ var useCopilotRuntimeClient = (options) => {
3209
3549
  const routeError = (gqlError) => {
3210
3550
  const extensions = gqlError.extensions;
3211
3551
  const visibility = extensions == null ? void 0 : extensions.visibility;
3212
- if (visibility === import_shared21.ErrorVisibility.SILENT) {
3552
+ if (visibility === import_shared22.ErrorVisibility.SILENT) {
3213
3553
  console.error("CopilotKit Silent Error:", gqlError.message);
3214
3554
  return;
3215
3555
  }
@@ -3224,9 +3564,9 @@ var useCopilotRuntimeClient = (options) => {
3224
3564
  setBannerError(ckError);
3225
3565
  traceUIError(ckError, gqlError);
3226
3566
  } else {
3227
- const fallbackError = new import_shared21.CopilotKitError({
3567
+ const fallbackError = new import_shared22.CopilotKitError({
3228
3568
  message: gqlError.message,
3229
- code: import_shared21.CopilotKitErrorCode.UNKNOWN
3569
+ code: import_shared22.CopilotKitErrorCode.UNKNOWN
3230
3570
  });
3231
3571
  setBannerError(fallbackError);
3232
3572
  traceUIError(fallbackError, gqlError);
@@ -3234,9 +3574,9 @@ var useCopilotRuntimeClient = (options) => {
3234
3574
  };
3235
3575
  graphQLErrors.forEach(routeError);
3236
3576
  } else {
3237
- const fallbackError = new import_shared21.CopilotKitError({
3577
+ const fallbackError = new import_shared22.CopilotKitError({
3238
3578
  message: (error == null ? void 0 : error.message) || String(error),
3239
- code: import_shared21.CopilotKitErrorCode.UNKNOWN
3579
+ code: import_shared22.CopilotKitErrorCode.UNKNOWN
3240
3580
  });
3241
3581
  setBannerError(fallbackError);
3242
3582
  traceUIError(fallbackError, error);
@@ -3244,9 +3584,9 @@ var useCopilotRuntimeClient = (options) => {
3244
3584
  },
3245
3585
  handleGQLWarning: (message) => {
3246
3586
  console.warn(message);
3247
- const warningError = new import_shared21.CopilotKitError({
3587
+ const warningError = new import_shared22.CopilotKitError({
3248
3588
  message,
3249
- code: import_shared21.CopilotKitErrorCode.UNKNOWN
3589
+ code: import_shared22.CopilotKitErrorCode.UNKNOWN
3250
3590
  });
3251
3591
  setBannerError(warningError);
3252
3592
  }
@@ -3261,16 +3601,16 @@ function createStructuredError(gqlError) {
3261
3601
  const message = (originalError == null ? void 0 : originalError.message) || gqlError.message;
3262
3602
  const code = extensions == null ? void 0 : extensions.code;
3263
3603
  if (code) {
3264
- return new import_shared21.CopilotKitError({ message, code });
3604
+ return new import_shared22.CopilotKitError({ message, code });
3265
3605
  }
3266
3606
  if ((_a = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _a.includes("CopilotApiDiscoveryError")) {
3267
- return new import_shared21.CopilotKitApiDiscoveryError({ message });
3607
+ return new import_shared22.CopilotKitApiDiscoveryError({ message });
3268
3608
  }
3269
3609
  if ((_b = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _b.includes("CopilotKitRemoteEndpointDiscoveryError")) {
3270
- return new import_shared21.CopilotKitRemoteEndpointDiscoveryError({ message });
3610
+ return new import_shared22.CopilotKitRemoteEndpointDiscoveryError({ message });
3271
3611
  }
3272
3612
  if ((_c = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _c.includes("CopilotKitAgentDiscoveryError")) {
3273
- return new import_shared21.CopilotKitAgentDiscoveryError({
3613
+ return new import_shared22.CopilotKitAgentDiscoveryError({
3274
3614
  agentName: "",
3275
3615
  availableAgents: []
3276
3616
  });
@@ -3279,28 +3619,28 @@ function createStructuredError(gqlError) {
3279
3619
  }
3280
3620
 
3281
3621
  // src/hooks/use-copilot-authenticated-action.ts
3282
- var import_react40 = require("react");
3283
- var import_react41 = __toESM(require("react"));
3622
+ var import_react41 = require("react");
3623
+ var import_react42 = __toESM(require("react"));
3284
3624
  function useCopilotAuthenticatedAction_c(action, dependencies) {
3285
3625
  const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();
3286
- const pendingActionRef = (0, import_react40.useRef)(null);
3287
- const executeAction = (0, import_react40.useCallback)(
3626
+ const pendingActionRef = (0, import_react41.useRef)(null);
3627
+ const executeAction = (0, import_react41.useCallback)(
3288
3628
  (props) => {
3289
3629
  if (typeof action.render === "function") {
3290
3630
  return action.render(props);
3291
3631
  }
3292
- return action.render || import_react41.default.createElement(import_react40.Fragment);
3632
+ return action.render || import_react42.default.createElement(import_react41.Fragment);
3293
3633
  },
3294
3634
  [action]
3295
3635
  );
3296
- const wrappedRender = (0, import_react40.useCallback)(
3636
+ const wrappedRender = (0, import_react41.useCallback)(
3297
3637
  (props) => {
3298
3638
  const isAuthenticated = Object.values(authStates_c || {}).some(
3299
3639
  (state) => state.status === "authenticated"
3300
3640
  );
3301
3641
  if (!isAuthenticated) {
3302
3642
  pendingActionRef.current = props;
3303
- return (authConfig_c == null ? void 0 : authConfig_c.SignInComponent) ? import_react41.default.createElement(authConfig_c.SignInComponent, {
3643
+ return (authConfig_c == null ? void 0 : authConfig_c.SignInComponent) ? import_react42.default.createElement(authConfig_c.SignInComponent, {
3304
3644
  onSignInComplete: (authState) => {
3305
3645
  setAuthStates_c == null ? void 0 : setAuthStates_c((prev) => __spreadProps(__spreadValues({}, prev), { [action.name]: authState }));
3306
3646
  if (pendingActionRef.current) {
@@ -3308,7 +3648,7 @@ function useCopilotAuthenticatedAction_c(action, dependencies) {
3308
3648
  pendingActionRef.current = null;
3309
3649
  }
3310
3650
  }
3311
- }) : import_react41.default.createElement(import_react40.Fragment);
3651
+ }) : import_react42.default.createElement(import_react41.Fragment);
3312
3652
  }
3313
3653
  return executeAction(props);
3314
3654
  },
@@ -3323,13 +3663,13 @@ function useCopilotAuthenticatedAction_c(action, dependencies) {
3323
3663
  }
3324
3664
 
3325
3665
  // src/hooks/use-langgraph-interrupt.ts
3326
- var import_react42 = require("react");
3327
- var import_shared22 = require("@copilotkit/shared");
3666
+ var import_react43 = require("react");
3667
+ var import_shared23 = require("@copilotkit/shared");
3328
3668
  function useLangGraphInterrupt(action, dependencies) {
3329
- const { setInterruptAction, removeInterruptAction, interruptActions, threadId } = (0, import_react42.useContext)(CopilotContext);
3669
+ const { setInterruptAction, removeInterruptAction, interruptActions, threadId } = (0, import_react43.useContext)(CopilotContext);
3330
3670
  const { addToast } = useToast();
3331
- const actionId = (0, import_shared22.dataToUUID)(action, "lgAction");
3332
- (0, import_react42.useEffect)(() => {
3671
+ const actionId = (0, import_shared23.dataToUUID)(action, "lgAction");
3672
+ (0, import_react43.useEffect)(() => {
3333
3673
  if (!action)
3334
3674
  return;
3335
3675
  setInterruptAction(__spreadProps(__spreadValues({}, action), { id: actionId }));
@@ -3340,10 +3680,10 @@ function useLangGraphInterrupt(action, dependencies) {
3340
3680
  }
3341
3681
 
3342
3682
  // src/hooks/use-copilot-additional-instructions.ts
3343
- var import_react43 = require("react");
3683
+ var import_react44 = require("react");
3344
3684
  function useCopilotAdditionalInstructions({ instructions, available = "enabled" }, dependencies) {
3345
3685
  const { setAdditionalInstructions } = useCopilotContext();
3346
- (0, import_react43.useEffect)(() => {
3686
+ (0, import_react44.useEffect)(() => {
3347
3687
  if (available === "disabled")
3348
3688
  return;
3349
3689
  setAdditionalInstructions((prevInstructions) => [...prevInstructions || [], instructions]);
@@ -3361,10 +3701,10 @@ function useDefaultTool(tool, dependencies) {
3361
3701
  }
3362
3702
 
3363
3703
  // src/hooks/use-copilot-chat-suggestions.tsx
3364
- var import_react44 = require("@copilotkitnext/react");
3704
+ var import_react45 = require("@copilotkitnext/react");
3365
3705
  function useCopilotChatSuggestions(config, dependencies = []) {
3366
3706
  var _a, _b;
3367
- const existingConfig = (0, import_react44.useCopilotChatConfiguration)();
3707
+ const existingConfig = (0, import_react45.useCopilotChatConfiguration)();
3368
3708
  const resolvedAgentId = (_a = existingConfig == null ? void 0 : existingConfig.agentId) != null ? _a : "default";
3369
3709
  const available = (_b = config.available === "enabled" ? "always" : config.available) != null ? _b : "before-first-message";
3370
3710
  const finalSuggestionConfig = __spreadProps(__spreadValues({}, config), {
@@ -3372,7 +3712,7 @@ function useCopilotChatSuggestions(config, dependencies = []) {
3372
3712
  consumerAgentId: resolvedAgentId
3373
3713
  // Use chatConfig.agentId here
3374
3714
  });
3375
- (0, import_react44.useConfigureSuggestions)(finalSuggestionConfig, dependencies);
3715
+ (0, import_react45.useConfigureSuggestions)(finalSuggestionConfig, dependencies);
3376
3716
  }
3377
3717
 
3378
3718
  // src/lib/copilot-task.ts
@@ -3380,7 +3720,7 @@ var import_runtime_client_gql5 = require("@copilotkit/runtime-client-gql");
3380
3720
 
3381
3721
  // src/types/frontend-action.ts
3382
3722
  var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
3383
- var import_shared23 = require("@copilotkit/shared");
3723
+ var import_shared24 = require("@copilotkit/shared");
3384
3724
  function processActionsForRuntimeRequest(actions) {
3385
3725
  const filteredActions = actions.filter(
3386
3726
  (action) => action.available !== import_runtime_client_gql4.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*" && action.available != "frontend" && !action.pairedAction
@@ -3396,7 +3736,7 @@ function processActionsForRuntimeRequest(actions) {
3396
3736
  return {
3397
3737
  name: action.name,
3398
3738
  description: action.description || "",
3399
- jsonSchema: JSON.stringify((0, import_shared23.actionParametersToJsonSchema)(action.parameters || [])),
3739
+ jsonSchema: JSON.stringify((0, import_shared24.actionParametersToJsonSchema)(action.parameters || [])),
3400
3740
  available
3401
3741
  };
3402
3742
  });