@copilotkit/core 1.79.2-canary.1792172552 → 1.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -23,17 +23,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
23
23
 
24
24
  //#endregion
25
25
  //#region src/utils/connect-replay.ts
26
- const connectRunErrorPhases = /* @__PURE__ */ new WeakMap();
27
- /**
28
- * The phase in which a connection received `event`, as recorded when it
29
- * arrived. Events that did not come through a connection with replay
30
- * boundaries report `unknown`.
31
- */
32
- function ɵgetConnectRunErrorPhase(event) {
33
- var _connectRunErrorPhase;
34
- return (_connectRunErrorPhase = connectRunErrorPhases.get(event)) !== null && _connectRunErrorPhase !== void 0 ? _connectRunErrorPhase : "unknown";
35
- }
36
- /**
26
+ /**
37
27
  * Runs an agent's `connect()` stream through the AbstractAgent apply pipeline
38
28
  * with the `verifyEvents` step omitted.
39
29
  *
@@ -88,7 +78,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
88
78
  let result;
89
79
  const previousMessageIds = new Set(agent.messages.map((m) => m.id));
90
80
  let isReplaying = true;
91
- let reportsReplayPhase = false;
92
81
  const liveErrors = /* @__PURE__ */ new WeakSet();
93
82
  const subscribers = [
94
83
  {
@@ -136,19 +125,15 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
136
125
  };
137
126
  const lifecycle = {
138
127
  onReplayStarted: () => {
139
- reportsReplayPhase = true;
140
128
  isReplaying = true;
141
129
  agent.isRunning = true;
142
130
  },
143
131
  onReplayFinished: () => {
144
- reportsReplayPhase = true;
145
132
  isReplaying = false;
146
133
  }
147
134
  };
148
135
  const source$ = (0, rxjs.defer)(() => new _ag_ui_client.CompatibilityBoundary().run(input, { run: () => connect ? connect(input, lifecycle) : self.connect(input) })).pipe((0, rxjs_operators.tap)((event) => {
149
- if (event.type !== _ag_ui_client.EventType.RUN_ERROR) return;
150
- if (!isReplaying) liveErrors.add(event);
151
- if (reportsReplayPhase) connectRunErrorPhases.set(event, isReplaying ? "replay" : "live");
136
+ if (!isReplaying && event.type === _ag_ui_client.EventType.RUN_ERROR) liveErrors.add(event);
152
137
  }), (0, _ag_ui_client.transformChunks)(self.debugLogger), (0, rxjs_operators.takeUntil)(activeRunDetach$));
153
138
  const applied$ = self.apply(input, source$, subscribers);
154
139
  await (0, rxjs.lastValueFrom)(self.processApplyEvents(input, applied$, subscribers).pipe((0, rxjs_operators.catchError)((error) => {
@@ -357,20 +342,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
357
342
  }
358
343
  };
359
344
  /**
360
- * The gateway could not replay a live run's events, so the client cannot
361
- * verify the run it is following. The run itself may still be going on the
362
- * server; reconnecting to the thread shows its real state.
363
- */
364
- var IntelligenceReplayFailedError = class extends Error {
365
- constructor(threadId, runId) {
366
- super("The run's events could not be replayed. Reconnect to the thread to check the run's status.");
367
- this.threadId = threadId;
368
- this.runId = runId;
369
- _defineProperty(this, "code", "INTELLIGENCE_REPLAY_FAILED");
370
- this.name = "IntelligenceReplayFailedError";
371
- }
372
- };
373
- /**
374
345
  * Type guard for {@link RunCompletionAware}. Returns true when `agent` exposes
375
346
  * an `activeRunCompletionPromise` property, so callers can await an in-flight
376
347
  * run without an `as unknown as` cast. Returns false for agents that don't
@@ -701,7 +672,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
701
672
  };
702
673
  const replayFailed$ = channel$.pipe((0, rxjs_operators.switchMap)(({ channel }) => this.observeChannelEvent$(channel, REPLAY_FAILED_EVENT)), (0, rxjs_operators.tap)(() => {
703
674
  controlCursor.replayFailed = true;
704
- if (options.streamMode === "run") throw new IntelligenceReplayFailedError(credentials.threadId, credentials.runId);
705
675
  }));
706
676
  const replayComplete$ = this.observeControlEvent$(input.threadId, channel$, REPLAY_COMPLETE_EVENT, controlCursor).pipe((0, rxjs_operators.tap)(() => {
707
677
  var _options$lifecycle2, _options$lifecycle2$o;
@@ -938,6 +908,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
938
908
  }
939
909
  const repaired = [];
940
910
  const emitted = /* @__PURE__ */ new Set();
911
+ const expandedMessages = /* @__PURE__ */ new Set();
941
912
  const emit = (message) => {
942
913
  if (emitted.has(message.id)) return;
943
914
  emitted.add(message.id);
@@ -946,6 +917,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
946
917
  /** Emit an assistant turn together with every result it is owed. */
947
918
  const emitWithResults = (message) => {
948
919
  emit(message);
920
+ if (expandedMessages.has(message)) return;
921
+ expandedMessages.add(message);
949
922
  for (const callId of toolCallIdsOf(message)) {
950
923
  const result = callIdToResult.get(callId);
951
924
  if (result) emit(result);
@@ -966,6 +939,199 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
966
939
  }
967
940
  return repaired;
968
941
  }
942
+ /**
943
+ * Move each detached tool result to sit behind the assistant call that issued
944
+ * it — usually back to an earlier call, and forward only when no earlier call
945
+ * has its id and exactly one call in the list does — and change nothing else.
946
+ * Used for unfiltered sends, and on a configured filter's output only when
947
+ * {@link ɵrepairToolCallPairs}, which filtered sends go through otherwise,
948
+ * throws.
949
+ *
950
+ * The client store can detach a tool result from its call on its own: when a
951
+ * backend's `MESSAGES_SNAPSHOT` carries a tool message under a different id
952
+ * than the streamed `TOOL_CALL_RESULT`, the `@ag-ui/client` merge drops the
953
+ * copy placed after its call and appends the snapshot's copy at the end,
954
+ * leaving `assistant(tool_call), assistant(text), tool(result)`. A backend that
955
+ * rebuilds its state from that payload discards every result it cannot pair.
956
+ *
957
+ * The pairing rule mirrors the `@ag-ui/client` snapshot pass
958
+ * (ag-ui-protocol/ag-ui#3114):
959
+ *
960
+ * - Everything is by list position. The same object or id appearing twice is
961
+ * two independent slots, including an assistant call the merge duplicated,
962
+ * so a duplicated call can be left unanswered. Nothing is dropped,
963
+ * deduplicated, or added, and only tool-role messages ever change position.
964
+ * - Transparent entries are `activity` and `reasoning` messages and anything
965
+ * that is not a plain object (`null`, arrays, primitives). They are never
966
+ * the anchor, never separate a call from its result, and stay in place.
967
+ * Reasoning stored between a call and its result is the next step's: in a
968
+ * multi-step turn whose calls share one assistant message, Mastra leaves
969
+ * `assistant(c1, c2), tool(c1), reasoning, tool(c2)`. Moving the result in
970
+ * front of it leaves the reasoning trailing, and Mastra drops it.
971
+ * - The anchor is the last non-transparent message so far that is not `tool`.
972
+ * Each tool call an assistant issues opens a slot for its call id, and a
973
+ * result pairs with slots for its `toolCallId` alone. `subagentRunId` is
974
+ * ignored: results CopilotKit creates itself (frontend tool results,
975
+ * interrupt responses) do not carry one, and on a result it names the run
976
+ * that executed the tool, which may differ from the run that issued the
977
+ * call. Known limitation: a parent call and a subagent call that reuse one
978
+ * id are indistinguishable, so their drifted results can be swapped.
979
+ * - Pass 1, left to right: a result with an open slot issued at the anchor is
980
+ * in place; it takes that slot and stays put. A result with an open slot
981
+ * issued earlier is detached. A result with no slot for its id issued
982
+ * earlier at all is early. Any other result — every earlier slot for its id
983
+ * already answered — stays put. Detached results take no slot in this
984
+ * pass: they could only ever take a slot issued before the current anchor,
985
+ * which no later in-place result can want.
986
+ * - Pass 2, backward, per id: the detached results, from the newest back,
987
+ * each take the newest still-open slot issued before them; one that finds
988
+ * none stays put. So when several results for a reused id (providers reuse
989
+ * `call_0` every turn) are all detached, they keep their stored order
990
+ * across the calls, and a later turn's lone result goes to the later call
991
+ * rather than to an earlier one that was abandoned.
992
+ * - Pass 3, forward, per id: an early result moves forward only when its id
993
+ * is unambiguous — exactly one call slot in the whole list has it, that
994
+ * slot is issued after the result, and it is still open after passes 1-2.
995
+ * The first early result for the id, left to right, takes it; any other
996
+ * early result for that id stays put. This repairs a result whose call
997
+ * was re-issued after it (a snapshot that re-ids the assistant message but
998
+ * keeps the result's id). With a reused id (providers reuse `call_0` every
999
+ * turn) nothing moves forward: in `[t0, t1, a1(c), user, a2(c)]` nothing
1000
+ * says t1 answers a2, and a2 may be a pending call (a frontend tool, an
1001
+ * interrupt, a human-in-the-loop call waiting on the user). Only early
1002
+ * results move forward: an extra result for a call that is already
1003
+ * answered never does.
1004
+ * - A moved result goes behind its issuer, after the tool and transparent
1005
+ * entries already following it, but in front of any reasoning among those
1006
+ * transparent entries: reasoning belongs to the message after it, so a
1007
+ * moved result never lands between a reasoning message and its owner.
1008
+ * Results moved behind one issuer keep their stored order. Any other
1009
+ * message between a call and its result separates them, so a
1010
+ * backward-moved result moves before it and a forward-moved result moves
1011
+ * past it.
1012
+ * - The rule cannot tell a duplicate result from a detached one. A second
1013
+ * result for an already-answered call moves back to an older still-open
1014
+ * slot for its id if there is one, even across user turns; it never moves
1015
+ * forward.
1016
+ * - Malformed entries are ignored rather than thrown on. Non-array
1017
+ * `toolCalls`, call entries without a string `id`, and results without a
1018
+ * string `toolCallId` open or take no slot.
1019
+ *
1020
+ * Returns `messages` itself when nothing moved.
1021
+ */
1022
+ function ɵkeepToolResultsWithCalls(messages) {
1023
+ const slots = /* @__PURE__ */ new Map();
1024
+ const openCount = /* @__PURE__ */ new Map();
1025
+ const close = (callId, slot) => {
1026
+ slot.open = false;
1027
+ openCount.set(callId, openCount.get(callId) - 1);
1028
+ };
1029
+ const detached = /* @__PURE__ */ new Map();
1030
+ const early = /* @__PURE__ */ new Map();
1031
+ let anchor = -1;
1032
+ for (let index = 0; index < messages.length; index++) {
1033
+ const message = messages[index];
1034
+ if (isTransparent(message)) continue;
1035
+ const role = roleOf(message);
1036
+ if (role !== "tool") {
1037
+ anchor = index;
1038
+ const calls = role === "assistant" ? message.toolCalls : void 0;
1039
+ if (!Array.isArray(calls)) continue;
1040
+ for (const call of calls) {
1041
+ var _openCount$get;
1042
+ if (typeof call !== "object" || call === null) continue;
1043
+ const callId = call.id;
1044
+ if (typeof callId !== "string") continue;
1045
+ push(slots, callId, {
1046
+ issuer: index,
1047
+ open: true
1048
+ });
1049
+ openCount.set(callId, ((_openCount$get = openCount.get(callId)) !== null && _openCount$get !== void 0 ? _openCount$get : 0) + 1);
1050
+ }
1051
+ continue;
1052
+ }
1053
+ const callId = message.toolCallId;
1054
+ if (typeof callId !== "string") continue;
1055
+ const forId = slots.get(callId);
1056
+ if (!forId) {
1057
+ push(early, callId, index);
1058
+ continue;
1059
+ }
1060
+ let atAnchor;
1061
+ for (let s = forId.length - 1; s >= 0; s--) {
1062
+ const slot = forId[s];
1063
+ if (slot.issuer !== anchor) break;
1064
+ if (slot.open) atAnchor = slot;
1065
+ }
1066
+ if (atAnchor) {
1067
+ close(callId, atAnchor);
1068
+ continue;
1069
+ }
1070
+ if (openCount.get(callId) > 0) push(detached, callId, index);
1071
+ }
1072
+ const movedBehind = /* @__PURE__ */ new Map();
1073
+ const moved = /* @__PURE__ */ new Set();
1074
+ const take = (callId, slot, index) => {
1075
+ close(callId, slot);
1076
+ moved.add(index);
1077
+ push(movedBehind, slot.issuer, index);
1078
+ };
1079
+ for (const [callId, results] of detached) {
1080
+ const forId = slots.get(callId);
1081
+ let s = forId.length - 1;
1082
+ for (let r = results.length - 1; r >= 0; r--) {
1083
+ const index = results[r];
1084
+ while (s >= 0 && (!forId[s].open || forId[s].issuer >= index)) s--;
1085
+ if (s < 0) break;
1086
+ take(callId, forId[s], index);
1087
+ }
1088
+ }
1089
+ for (const [callId, results] of early) {
1090
+ const forId = slots.get(callId);
1091
+ if ((forId === null || forId === void 0 ? void 0 : forId.length) !== 1 || !forId[0].open) continue;
1092
+ take(callId, forId[0], results[0]);
1093
+ }
1094
+ if (moved.size === 0) return messages;
1095
+ const result = [];
1096
+ let openIssuer = -1;
1097
+ const flush = () => {
1098
+ const behind = movedBehind.get(openIssuer);
1099
+ if (!behind) return;
1100
+ let at = result.length;
1101
+ for (let tail = result.length - 1; tail >= 0; tail--) {
1102
+ if (!isTransparent(result[tail])) break;
1103
+ if (roleOf(result[tail]) === "reasoning") at = tail;
1104
+ }
1105
+ result.splice(at, 0, ...[...behind].sort((a, b) => a - b).map((index) => messages[index]));
1106
+ };
1107
+ for (let index = 0; index < messages.length; index++) {
1108
+ if (moved.has(index)) continue;
1109
+ const message = messages[index];
1110
+ if (!isTransparent(message) && roleOf(message) !== "tool") {
1111
+ flush();
1112
+ openIssuer = index;
1113
+ }
1114
+ result.push(message);
1115
+ }
1116
+ flush();
1117
+ return result;
1118
+ }
1119
+ function push(map, key, value) {
1120
+ const list = map.get(key);
1121
+ if (list) list.push(value);
1122
+ else map.set(key, [value]);
1123
+ }
1124
+ /**
1125
+ * Activity and reasoning messages and anything that is not a plain object
1126
+ * (`null`, arrays, primitives) never anchor or separate.
1127
+ */
1128
+ function isTransparent(message) {
1129
+ return typeof message !== "object" || message === null || Array.isArray(message) || message.role === "activity" || message.role === "reasoning";
1130
+ }
1131
+ function roleOf(message) {
1132
+ if (typeof message !== "object" || message === null) return void 0;
1133
+ return message.role;
1134
+ }
969
1135
 
970
1136
  //#endregion
971
1137
  //#region \0@oxc-project+runtime@0.112.0/helpers/checkPrivateRedeclaration.js
@@ -1500,7 +1666,21 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1500
1666
  };
1501
1667
  _ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;
1502
1668
  /**
1503
- * Narrow the outbound payload with the configured message filter.
1669
+ * Build the outbound payload, keeping every tool result with the call that
1670
+ * issued it.
1671
+ *
1672
+ * - **No filter** (or a filter whose output is unusable, which falls back to
1673
+ * the full thread): `ɵkeepToolResultsWithCalls` re-places tool results
1674
+ * that drifted from their call and changes nothing else. The client store
1675
+ * can detach them on its own when a `MESSAGES_SNAPSHOT` re-ids a tool
1676
+ * message, and a backend that rebuilds state from such a payload drops
1677
+ * every result it cannot pair.
1678
+ * - **Filter**: `ɵrepairToolCallPairs(kept, full)` restores the call or the
1679
+ * results a filter trimmed. Its known limitations are tracked in
1680
+ * https://github.com/CopilotKit/CopilotKit/issues/7891.
1681
+ * - **Filter repair throws**: the filter's output goes through
1682
+ * `ɵkeepToolResultsWithCalls` instead, keeping its trimming and
1683
+ * redaction; if that throws too, the output is sent as is.
1504
1684
  *
1505
1685
  * **Called from the HTTP paths only, and that placement is the Intelligence
1506
1686
  * exemption.** An earlier revision applied the filter in
@@ -1523,35 +1703,91 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1523
1703
  * cannot reach the messages the UI renders no matter what it does with the
1524
1704
  * array it is handed. The filter gets a *second* deep clone on top of that,
1525
1705
  * because `input.messages` is also the repair baseline and the untrimmed
1526
- * fallback: sharing the message objects let a filter that mutates a kept
1527
- * message's `toolCallId` corrupt the baseline, and an orphaned tool result
1528
- * then went out on the wire — a payload the provider rejects, which is
1529
- * exactly the failure this whole mechanism exists to prevent.
1706
+ * fallback: sharing the message objects let a filter that rewrote the tool
1707
+ * call id of an assistant message it dropped hide that issuer from the
1708
+ * repair, and the kept tool result then went out orphaned — a payload the
1709
+ * provider rejects, which is exactly the failure this whole mechanism
1710
+ * exists to prevent.
1530
1711
  */
1531
- function _applyMessageFilter(input) {
1532
- const filter = this._messageFilter;
1533
- if (!filter) return input;
1712
+ function _prepareOutboundMessages(input) {
1713
+ var _this$agentId;
1714
+ const full = input.messages;
1715
+ const kept = _assertClassBrand(_ProxiedCopilotRuntimeAgent_brand, this, _applyMessageFilter).call(this, full);
1716
+ const agentId = (_this$agentId = this.agentId) !== null && _this$agentId !== void 0 ? _this$agentId : "";
1534
1717
  try {
1535
- var _this$agentId;
1536
- const kept = filter((0, _ag_ui_client.structuredClone_)(input.messages), { agentId: (_this$agentId = this.agentId) !== null && _this$agentId !== void 0 ? _this$agentId : "" });
1537
- if (!Array.isArray(kept)) {
1538
- console.warn("ProxiedCopilotRuntimeAgent: messageFilter returned a non-array value; sending the full message history instead.");
1539
- return input;
1540
- }
1718
+ const messages = kept === void 0 ? ɵkeepToolResultsWithCalls(full) : ɵrepairToolCallPairs(kept, full);
1541
1719
  return {
1542
1720
  ...input,
1543
- messages: ɵrepairToolCallPairs(kept, input.messages)
1721
+ messages
1544
1722
  };
1723
+ } catch (error) {
1724
+ if (kept === void 0) {
1725
+ console.warn(`ProxiedCopilotRuntimeAgent: tool-call repair failed for agent "${agentId}"; sending the message history unrepaired instead.`, error);
1726
+ return input;
1727
+ }
1728
+ try {
1729
+ const messages = ɵkeepToolResultsWithCalls(kept);
1730
+ console.warn(`ProxiedCopilotRuntimeAgent: tool-call repair failed for agent "${agentId}"; sending the filtered message history with only drifted tool results moved instead.`, error);
1731
+ return {
1732
+ ...input,
1733
+ messages
1734
+ };
1735
+ } catch (moveError) {
1736
+ console.warn(`ProxiedCopilotRuntimeAgent: tool-call repair failed for agent "${agentId}"; sending the filtered message history unrepaired instead.`, error, moveError);
1737
+ return {
1738
+ ...input,
1739
+ messages: kept
1740
+ };
1741
+ }
1742
+ }
1743
+ }
1744
+ /**
1745
+ * Run the configured filter. Returns `undefined` when there is no filter,
1746
+ * copying the thread for it fails, or the filter's output cannot be used,
1747
+ * meaning "send the full thread".
1748
+ *
1749
+ * A filter that throws, returns a non-array, or returns an array with an
1750
+ * entry that is not a message object (a hole or a nested array included)
1751
+ * falls back to the untrimmed thread rather than failing the run. Trimming
1752
+ * is an optimization, and taking the user's message down with it would be
1753
+ * the worse outcome; the warning is what surfaces the bug.
1754
+ */
1755
+ function _applyMessageFilter(full) {
1756
+ const filter = this._messageFilter;
1757
+ if (!filter) return void 0;
1758
+ let copy;
1759
+ try {
1760
+ copy = (0, _ag_ui_client.structuredClone_)(full);
1761
+ } catch (error) {
1762
+ console.warn("ProxiedCopilotRuntimeAgent: could not copy the message history for messageFilter; sending the full message history instead.", error);
1763
+ return;
1764
+ }
1765
+ let kept;
1766
+ try {
1767
+ var _this$agentId2;
1768
+ kept = filter(copy, { agentId: (_this$agentId2 = this.agentId) !== null && _this$agentId2 !== void 0 ? _this$agentId2 : "" });
1545
1769
  } catch (error) {
1546
1770
  console.warn("ProxiedCopilotRuntimeAgent: messageFilter failed; sending the full message history instead.", error);
1547
- return input;
1771
+ return;
1772
+ }
1773
+ if (!Array.isArray(kept)) {
1774
+ console.warn("ProxiedCopilotRuntimeAgent: messageFilter returned a non-array value; sending the full message history instead.");
1775
+ return;
1548
1776
  }
1777
+ for (let index = 0; index < kept.length; index++) {
1778
+ const entry = kept[index];
1779
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
1780
+ console.warn("ProxiedCopilotRuntimeAgent: messageFilter returned an entry that is not a message; sending the full message history instead.");
1781
+ return;
1782
+ }
1783
+ }
1784
+ return kept;
1549
1785
  }
1550
1786
  function _connectViaDelegate(input, lifecycle) {
1551
1787
  return (0, rxjs.defer)(() => (0, rxjs.from)(this.resolveDelegate())).pipe((0, rxjs_operators.switchMap)((delegate) => withAbortErrorHandling(delegate.connect(input, lifecycle))));
1552
1788
  }
1553
1789
  function _connectViaHttp(unfiltered) {
1554
- const input = _assertClassBrand(_ProxiedCopilotRuntimeAgent_brand, this, _applyMessageFilter).call(this, unfiltered);
1790
+ const input = _assertClassBrand(_ProxiedCopilotRuntimeAgent_brand, this, _prepareOutboundMessages).call(this, unfiltered);
1555
1791
  this.activeRun = void 0;
1556
1792
  const routedId = this.routedAgentId();
1557
1793
  let httpEvents;
@@ -1584,7 +1820,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1584
1820
  return (0, rxjs.defer)(() => (0, rxjs.from)(this.resolveDelegate())).pipe((0, rxjs_operators.switchMap)((delegate) => withAbortErrorHandling(delegate.run(input))));
1585
1821
  }
1586
1822
  function _runViaHttp(unfiltered) {
1587
- const input = _assertClassBrand(_ProxiedCopilotRuntimeAgent_brand, this, _applyMessageFilter).call(this, unfiltered);
1823
+ const input = _assertClassBrand(_ProxiedCopilotRuntimeAgent_brand, this, _prepareOutboundMessages).call(this, unfiltered);
1588
1824
  const activeRun = {
1589
1825
  threadId: input.threadId,
1590
1826
  runId: input.runId
@@ -3638,15 +3874,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3638
3874
  */
3639
3875
  const liveHITLStops = /* @__PURE__ */ new WeakMap();
3640
3876
  /**
3641
- * Edits `agent.messages` by replacing the array instead of changing it in
3642
- * place. The current array may be the one the agent emitted with its last
3643
- * update, which subscribers and stored snapshots still hold. Like the in-place
3644
- * edit it replaces, this notifies no subscriber.
3877
+ * The message a failed tool call reports. An error thrown with an empty
3878
+ * message still means the call failed, so it gets a fallback rather than an
3879
+ * empty string, which everything downstream reads as success.
3645
3880
  */
3646
- function editAgentMessages(agent, edit) {
3647
- const messages = [...agent.messages];
3648
- edit(messages);
3649
- agent.messages = messages;
3881
+ function toolFailureMessage(error) {
3882
+ return error.message || "Tool call failed";
3650
3883
  }
3651
3884
  function discardAbortedResult(signal, discardOnAbort, errorMessage) {
3652
3885
  var _liveHITLStops$get;
@@ -3685,8 +3918,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3685
3918
  _defineProperty(this, "_disabledCatalogComponents", /* @__PURE__ */ new Set());
3686
3919
  _defineProperty(this, "_disabledToolKeys", /* @__PURE__ */ new Set());
3687
3920
  _defineProperty(this, "_warnedMissingToolParameters", /* @__PURE__ */ new Set());
3688
- _defineProperty(this, "_runAbortController", null);
3689
- _defineProperty(this, "_runDepth", 0);
3921
+ _defineProperty(this, "_runAbortControllers", /* @__PURE__ */ new WeakMap());
3922
+ _defineProperty(this, "_runDepths", /* @__PURE__ */ new WeakMap());
3923
+ _defineProperty(this, "_originalAbortRuns", /* @__PURE__ */ new WeakMap());
3690
3924
  _defineProperty(this, "_webmcpRegistry", new WebMCPRegistry());
3691
3925
  _defineProperty(this, "_lastConnectedThreadIdsByAgent", /* @__PURE__ */ new Map());
3692
3926
  _defineProperty(this, "_lastActiveThreadIdsByAgent", /* @__PURE__ */ new Map());
@@ -3702,8 +3936,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3702
3936
  * not start a follow-up run.
3703
3937
  */
3704
3938
  abortCurrentRun(agent) {
3705
- var _this$_runAbortContro;
3706
- (_this$_runAbortContro = this._runAbortController) === null || _this$_runAbortContro === void 0 || _this$_runAbortContro.abort();
3939
+ this.abortAgentRuns(agent);
3707
3940
  const replay = this._interactionAbortControllers.get(agent);
3708
3941
  if (replay) {
3709
3942
  for (const controller of replay.controllers) controller.abort();
@@ -3711,6 +3944,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3711
3944
  this._executingToolCalls.delete(agent);
3712
3945
  }
3713
3946
  }
3947
+ abortAgentRuns(agent) {
3948
+ var _this$_runAbortContro;
3949
+ for (const controller of (_this$_runAbortContro = this._runAbortControllers.get(agent)) !== null && _this$_runAbortContro !== void 0 ? _this$_runAbortContro : []) controller.abort();
3950
+ }
3951
+ /** Signal of the agent's most recently started in-flight run, if any. */
3952
+ latestRunSignal(agent) {
3953
+ var _this$_runAbortContro2;
3954
+ let latest;
3955
+ for (const controller of (_this$_runAbortContro2 = this._runAbortControllers.get(agent)) !== null && _this$_runAbortContro2 !== void 0 ? _this$_runAbortContro2 : []) latest = controller;
3956
+ return latest === null || latest === void 0 ? void 0 : latest.signal;
3957
+ }
3714
3958
  /**
3715
3959
  * Typed access to CopilotKitCore's internal ("friend") methods.
3716
3960
  * Centralises the single unavoidable cast so call-sites stay clean.
@@ -3914,7 +4158,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3914
4158
  forwardedProps: this._internal.properties,
3915
4159
  tools: this.buildFrontendTools(agent.agentId),
3916
4160
  context: this._internal.getContextForAgent(agent.agentId)
3917
- }, this.createAgentErrorSubscriber(agent, "connect"));
4161
+ }, this.createAgentErrorSubscriber(agent));
3918
4162
  if (this._connectionGenerations.get(agent) !== connection || ((_agent$threadId4 = agent.threadId) !== null && _agent$threadId4 !== void 0 ? _agent$threadId4 : null) !== incomingThreadId) return runAgentResult;
3919
4163
  const controller = new AbortController();
3920
4164
  const replay = (_this$_interactionAbo = this._interactionAbortControllers.get(agent)) !== null && _this$_interactionAbo !== void 0 ? _this$_interactionAbo : {
@@ -3963,7 +4207,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3963
4207
  /**
3964
4208
  * Run an agent
3965
4209
  */
3966
- async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff) {
4210
+ async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff, followUpOf) {
4211
+ var _this$_runDepths$get;
3967
4212
  if (agent.agentId) this._internal.suggestionEngine.clearSuggestions(agent.agentId);
3968
4213
  try {
3969
4214
  const headersApplied = this._internal.prepareAgentHeadersForRun(agent);
@@ -3987,28 +4232,34 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3987
4232
  forwardedProps
3988
4233
  });
3989
4234
  const logicalHandoff = continuationHandoff !== null && continuationHandoff !== void 0 ? continuationHandoff : resumedRunId ? this._internal.stateManager.markNextRunAsContinuation(agent, resumedRunId) : void 0;
3990
- const isTopLevel = this._runDepth === 0;
3991
- let originalAbortRun;
3992
- if (isTopLevel) {
3993
- this._runAbortController = new AbortController();
3994
- const controller = this._runAbortController;
3995
- originalAbortRun = agent.abortRun.bind(agent);
4235
+ const isFollowUp = followUpOf !== void 0;
4236
+ const controller = followUpOf !== null && followUpOf !== void 0 ? followUpOf : new AbortController();
4237
+ const depth = (_this$_runDepths$get = this._runDepths.get(agent)) !== null && _this$_runDepths$get !== void 0 ? _this$_runDepths$get : 0;
4238
+ this._runDepths.set(agent, depth + 1);
4239
+ if (!isFollowUp) {
4240
+ var _this$_runAbortContro3;
4241
+ const controllers = (_this$_runAbortContro3 = this._runAbortControllers.get(agent)) !== null && _this$_runAbortContro3 !== void 0 ? _this$_runAbortContro3 : /* @__PURE__ */ new Set();
4242
+ controllers.add(controller);
4243
+ this._runAbortControllers.set(agent, controllers);
4244
+ }
4245
+ if (depth === 0) {
4246
+ const originalAbortRun = agent.abortRun;
4247
+ this._originalAbortRuns.set(agent, originalAbortRun);
3996
4248
  agent.abortRun = () => {
3997
- controller.abort();
3998
- originalAbortRun();
4249
+ this.abortAgentRuns(agent);
4250
+ originalAbortRun.call(agent);
3999
4251
  };
4000
- await this._internal.notifySubscribers((subscriber) => {
4252
+ }
4253
+ try {
4254
+ if (depth === 0) await this._internal.notifySubscribers((subscriber) => {
4001
4255
  var _subscriber$onAgentRu2;
4002
4256
  return (_subscriber$onAgentRu2 = subscriber.onAgentRunStarted) === null || _subscriber$onAgentRu2 === void 0 ? void 0 : _subscriber$onAgentRu2.call(subscriber, {
4003
4257
  copilotkit: this.core,
4004
4258
  agent
4005
4259
  });
4006
4260
  }, "Subscriber onAgentRunStarted error:");
4007
- }
4008
- this._runDepth++;
4009
- try {
4010
4261
  let logicalRunId = resumedRunId !== null && resumedRunId !== void 0 ? resumedRunId : runId;
4011
- const agentSubscriber = this.createAgentErrorSubscriber(agent, "run");
4262
+ const agentSubscriber = this.createAgentErrorSubscriber(agent, controller.signal);
4012
4263
  let started = false;
4013
4264
  const onRunStartedEvent = agentSubscriber.onRunStartedEvent;
4014
4265
  const onRunInitialized = agentSubscriber.onRunInitialized;
@@ -4038,7 +4289,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4038
4289
  return await this.processAgentResult({
4039
4290
  runAgentResult,
4040
4291
  agent,
4041
- runId: logicalRunId
4292
+ runId: logicalRunId,
4293
+ runController: controller
4042
4294
  });
4043
4295
  } catch (error) {
4044
4296
  logicalHandoff === null || logicalHandoff === void 0 || logicalHandoff.cancel();
@@ -4055,17 +4307,27 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4055
4307
  newMessages: []
4056
4308
  };
4057
4309
  } finally {
4058
- this._runDepth--;
4059
- if (isTopLevel && originalAbortRun) agent.abortRun = originalAbortRun;
4310
+ var _this$_runDepths$get2;
4311
+ const remainingDepth = ((_this$_runDepths$get2 = this._runDepths.get(agent)) !== null && _this$_runDepths$get2 !== void 0 ? _this$_runDepths$get2 : 1) - 1;
4312
+ this._runDepths.set(agent, remainingDepth);
4313
+ if (!isFollowUp) {
4314
+ const controllers = this._runAbortControllers.get(agent);
4315
+ controllers === null || controllers === void 0 || controllers.delete(controller);
4316
+ if ((controllers === null || controllers === void 0 ? void 0 : controllers.size) === 0) this._runAbortControllers.delete(agent);
4317
+ }
4318
+ if (remainingDepth === 0) {
4319
+ const originalAbortRun = this._originalAbortRuns.get(agent);
4320
+ if (originalAbortRun) {
4321
+ agent.abortRun = originalAbortRun;
4322
+ this._originalAbortRuns.delete(agent);
4323
+ }
4324
+ }
4060
4325
  }
4061
4326
  }
4062
4327
  /**
4063
4328
  * Process agent result and execute tools
4064
4329
  */
4065
- async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", signal = (() => {
4066
- var _this$_runAbortContro2;
4067
- return (_this$_runAbortContro2 = this._runAbortController) === null || _this$_runAbortContro2 === void 0 ? void 0 : _this$_runAbortContro2.signal;
4068
- })() }) {
4330
+ async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", runController, signal = runController === null || runController === void 0 ? void 0 : runController.signal }) {
4069
4331
  var _this$_executingToolC;
4070
4332
  const { newMessages } = runAgentResult;
4071
4333
  const agentId = agent.agentId;
@@ -4073,11 +4335,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4073
4335
  const threadId = agent.threadId;
4074
4336
  const executing = (_this$_executingToolC = this._executingToolCalls.get(agent)) !== null && _this$_executingToolC !== void 0 ? _this$_executingToolC : /* @__PURE__ */ new Set();
4075
4337
  this._executingToolCalls.set(agent, executing);
4076
- if (toolExecutionMode === "restore" && agent.messages.some((message) => {
4338
+ const messagesToProcess = toolExecutionMode === "restore" ? agent.messages.filter((message) => message.role === "assistant" && this.isInLatestUserTurn(agent.messages, message.id)) : newMessages;
4339
+ if (toolExecutionMode === "restore" && messagesToProcess.some((message) => {
4077
4340
  var _message$toolCalls;
4078
4341
  return message.role === "assistant" && ((_message$toolCalls = message.toolCalls) === null || _message$toolCalls === void 0 ? void 0 : _message$toolCalls.some((call) => executing.has(JSON.stringify([threadId, call.id])) && !agent.messages.some((result) => result.role === "tool" && result.toolCallId === call.id && !this.isFrontendPlaceholderResult(result))));
4079
4342
  })) return runAgentResult;
4080
- const messagesToProcess = toolExecutionMode === "restore" ? [...agent.messages] : newMessages;
4081
4343
  for (const message of messagesToProcess) if (message.role === "assistant") for (const toolCall of message.toolCalls || []) {
4082
4344
  var _agent$messages$find;
4083
4345
  const tool = this.getTool({
@@ -4094,16 +4356,16 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4094
4356
  return wildcardTool;
4095
4357
  };
4096
4358
  const executableTool = tool !== null && tool !== void 0 ? tool : getWildcardTool();
4097
- if (toolExecutionMode === "restore" && (!(executableTool === null || executableTool === void 0 ? void 0 : executableTool.handler) || executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
4359
+ if (toolExecutionMode === "restore" && (!executableTool || executableTool.handler && executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
4098
4360
  const executionKey = JSON.stringify([threadId, toolCall.id]);
4099
- if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || agent.threadId !== threadId || executing.has(executionKey)) continue;
4361
+ if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || agent.threadId !== threadId || toolExecutionMode === "restore" && !this.isInLatestUserTurn(agent.messages, message.id) || executing.has(executionKey)) continue;
4100
4362
  const existingResultIndex = newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
4101
4363
  let existingResult = (_agent$messages$find = agent.messages.find((m) => m.role === "tool" && m.toolCallId === toolCall.id)) !== null && _agent$messages$find !== void 0 ? _agent$messages$find : newMessages[existingResultIndex];
4102
- if (existingResult && (executableTool === null || executableTool === void 0 ? void 0 : executableTool.handler) && this.isFrontendPlaceholderResult(existingResult)) {
4364
+ if (existingResult && this.isFrontendPlaceholderResult(existingResult) && (toolExecutionMode === "restore" || (executableTool === null || executableTool === void 0 ? void 0 : executableTool.handler))) {
4103
4365
  if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
4104
4366
  existingResult = void 0;
4105
4367
  const agentMsgIdx = agent.messages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
4106
- if (agentMsgIdx !== -1) editAgentMessages(agent, (messages) => messages.splice(agentMsgIdx, 1));
4368
+ if (agentMsgIdx !== -1) agent.messages.splice(agentMsgIdx, 1);
4107
4369
  }
4108
4370
  if (!existingResult) {
4109
4371
  var _this$_interactionAbo2, _interactionControlle;
@@ -4147,18 +4409,47 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4147
4409
  if (interactionController === null || interactionController === void 0 ? void 0 : interactionController.signal.aborted) return runAgentResult;
4148
4410
  }
4149
4411
  }
4150
- if (needsFollowUp && agent.threadId === threadId && !(signal === null || signal === void 0 ? void 0 : signal.aborted)) if (this._runDepth >= MAX_FOLLOW_UP_DEPTH) _copilotkit_shared.logger.warn(`[CopilotKit] Follow-up depth limit (${MAX_FOLLOW_UP_DEPTH}) reached for agent "${agentId}". Stopping recursive follow-up runs to prevent an infinite loop. This usually indicates a tool that keeps requesting a follow-up (e.g. the LLM repeatedly calling the same tool). Consider setting "followUp: false" on the offending tool.`);
4151
- else {
4152
- await this._internal.waitForPendingFrameworkUpdates();
4153
- const continuationHandoff = this._internal.stateManager.markNextRunAsContinuation(agent, runId);
4154
- return await this.runAgent({
4155
- agent,
4156
- ...runId !== void 0 ? { runId } : {}
4157
- }, continuationHandoff);
4412
+ if (needsFollowUp && agent.threadId === threadId && !(signal === null || signal === void 0 ? void 0 : signal.aborted)) {
4413
+ var _this$_runDepths$get3;
4414
+ if (((_this$_runDepths$get3 = this._runDepths.get(agent)) !== null && _this$_runDepths$get3 !== void 0 ? _this$_runDepths$get3 : 0) >= MAX_FOLLOW_UP_DEPTH) _copilotkit_shared.logger.warn(`[CopilotKit] Follow-up depth limit (${MAX_FOLLOW_UP_DEPTH}) reached for agent "${agentId}". Stopping recursive follow-up runs to prevent an infinite loop. This usually indicates a tool that keeps requesting a follow-up (e.g. the LLM repeatedly calling the same tool). Consider setting "followUp: false" on the offending tool.`);
4415
+ else {
4416
+ await this._internal.waitForPendingFrameworkUpdates();
4417
+ if (toolExecutionMode === "restore" && !messagesToProcess.some((message) => this.isInLatestUserTurn(agent.messages, message.id))) return runAgentResult;
4418
+ const continuationHandoff = this._internal.stateManager.markNextRunAsContinuation(agent, runId);
4419
+ return await this.runAgent({
4420
+ agent,
4421
+ ...runId !== void 0 ? { runId } : {}
4422
+ }, continuationHandoff, runController);
4423
+ }
4158
4424
  }
4159
4425
  this._internal.suggestionEngine.reloadSuggestions(agentId);
4160
4426
  return runAgentResult;
4161
4427
  }
4428
+ /** A later user message supersedes pending work from an older turn. */
4429
+ isInLatestUserTurn(messages, messageId) {
4430
+ for (let index = messages.length - 1; index >= 0; index--) {
4431
+ const message = messages[index];
4432
+ if ((message === null || message === void 0 ? void 0 : message.role) === "user") return false;
4433
+ if ((message === null || message === void 0 ? void 0 : message.id) === messageId) return true;
4434
+ }
4435
+ return false;
4436
+ }
4437
+ /** Locate a missing result before saved results for later calls in its batch. */
4438
+ toolResultInsertionIndex(messages, messageIndex, toolCallId) {
4439
+ var _parent$toolCalls;
4440
+ const parent = messages[messageIndex];
4441
+ const calls = (parent === null || parent === void 0 ? void 0 : parent.role) === "assistant" ? (_parent$toolCalls = parent.toolCalls) !== null && _parent$toolCalls !== void 0 ? _parent$toolCalls : [] : [];
4442
+ const callIndex = calls.findIndex((call) => call.id === toolCallId);
4443
+ let insertAt = messageIndex + 1;
4444
+ while (insertAt < messages.length) {
4445
+ const result = messages[insertAt];
4446
+ if ((result === null || result === void 0 ? void 0 : result.role) !== "tool") break;
4447
+ if (calls.findIndex((call) => call.id === result.toolCallId) > callIndex) break;
4448
+ insertAt++;
4449
+ }
4450
+ return insertAt;
4451
+ }
4452
+ /** Identify transport placeholders that must not count as completed answers. */
4162
4453
  isFrontendPlaceholderResult(message) {
4163
4454
  return message.role === "tool" && isForwardedToClientPlaceholder(message.content);
4164
4455
  }
@@ -4167,10 +4458,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4167
4458
  * Handles arg parsing, subscriber notifications, handler invocation, result stringification,
4168
4459
  * and error handling.
4169
4460
  */
4170
- async executeToolHandler({ tool, toolCall, agent, agentId, handlerArgs, toolType, messageId, signal = (() => {
4171
- var _this$_runAbortContro3;
4172
- return (_this$_runAbortContro3 = this._runAbortController) === null || _this$_runAbortContro3 === void 0 ? void 0 : _this$_runAbortContro3.signal;
4173
- })(), discardOnAbort = false, isReplay = false }) {
4461
+ async executeToolHandler({ tool, toolCall, agent, agentId, handlerArgs, toolType, messageId, signal = this.latestRunSignal(agent), discardOnAbort = false, isReplay = false }) {
4174
4462
  let toolCallResult = "";
4175
4463
  let toolCallText = "";
4176
4464
  let errorMessage;
@@ -4180,7 +4468,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4180
4468
  parsedArgs = parseToolArguments(handlerArgs, toolCall.function.name);
4181
4469
  } catch (error) {
4182
4470
  const parseError = error instanceof Error ? error : new Error(String(error));
4183
- errorMessage = parseError.message;
4471
+ errorMessage = toolFailureMessage(parseError);
4184
4472
  isArgumentError = true;
4185
4473
  await this._internal.emitError({
4186
4474
  error: parseError,
@@ -4215,7 +4503,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4215
4503
  ({content: toolCallResult, text: toolCallText} = toToolResultContent(result));
4216
4504
  } catch (error) {
4217
4505
  const handlerError = error instanceof Error ? error : new Error(String(error));
4218
- errorMessage = handlerError.message;
4506
+ errorMessage = toolFailureMessage(handlerError);
4219
4507
  if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) await this._internal.emitError({
4220
4508
  error: handlerError,
4221
4509
  code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,
@@ -4273,18 +4561,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4273
4561
  isReplay
4274
4562
  });
4275
4563
  {
4276
- var _agent$messages$inser;
4277
4564
  const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
4278
- if (discardAbortedResult(signal, discardOnAbort, handlerResult.error) || agent.threadId !== threadId || messageIndex === -1 || agent.messages.some((m) => m.role === "tool" && m.toolCallId === toolCall.id && !this.isFrontendPlaceholderResult(m))) return false;
4279
- let insertAt = messageIndex + 1;
4280
- while (insertAt < agent.messages.length && ((_agent$messages$inser = agent.messages[insertAt]) === null || _agent$messages$inser === void 0 ? void 0 : _agent$messages$inser.role) === "tool") insertAt++;
4565
+ if (discardAbortedResult(signal, discardOnAbort, handlerResult.error) || agent.threadId !== threadId || messageIndex === -1 || isReplay && !this.isInLatestUserTurn(agent.messages, message.id) || agent.messages.some((m) => m.role === "tool" && m.toolCallId === toolCall.id && !this.isFrontendPlaceholderResult(m))) return false;
4566
+ const insertAt = this.toolResultInsertionIndex(agent.messages, messageIndex, toolCall.id);
4281
4567
  const toolMessage = {
4282
4568
  id: (0, _copilotkit_shared.randomUUID)(),
4283
4569
  role: "tool",
4284
4570
  toolCallId: toolCall.id,
4285
- content: handlerResult.content
4571
+ content: handlerResult.content,
4572
+ ...handlerResult.error ? { error: handlerResult.error } : {}
4286
4573
  };
4287
- editAgentMessages(agent, (messages) => messages.splice(insertAt, 0, toolMessage));
4574
+ agent.messages.splice(insertAt, 0, toolMessage);
4288
4575
  if (!handlerResult.error && (tool === null || tool === void 0 ? void 0 : tool.followUp) !== false) return true;
4289
4576
  }
4290
4577
  return false;
@@ -4307,7 +4594,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4307
4594
  parsedArgs = parseToolArguments(toolCall.function.arguments, toolCall.function.name);
4308
4595
  } catch (error) {
4309
4596
  const parseError = error instanceof Error ? error : new Error(String(error));
4310
- errorMessage = parseError.message;
4597
+ errorMessage = toolFailureMessage(parseError);
4311
4598
  await this._internal.emitError({
4312
4599
  error: parseError,
4313
4600
  code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,
@@ -4345,7 +4632,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4345
4632
  ({content: toolCallResult, text: toolCallText} = toToolResultContent(result));
4346
4633
  } catch (error) {
4347
4634
  const handlerError = error instanceof Error ? error : new Error(String(error));
4348
- errorMessage = handlerError.message;
4635
+ errorMessage = toolFailureMessage(handlerError);
4349
4636
  if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) await this._internal.emitError({
4350
4637
  error: handlerError,
4351
4638
  code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,
@@ -4373,18 +4660,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4373
4660
  }, "Subscriber onToolExecutionEnd error:");
4374
4661
  }
4375
4662
  {
4376
- var _agent$messages$inser2;
4377
4663
  const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
4378
- if (discardAbortedResult(signal, discardOnAbort, errorMessage) || agent.threadId !== threadId || messageIndex === -1 || agent.messages.some((m) => m.role === "tool" && m.toolCallId === toolCall.id && !this.isFrontendPlaceholderResult(m))) return false;
4379
- let insertAt = messageIndex + 1;
4380
- while (insertAt < agent.messages.length && ((_agent$messages$inser2 = agent.messages[insertAt]) === null || _agent$messages$inser2 === void 0 ? void 0 : _agent$messages$inser2.role) === "tool") insertAt++;
4664
+ if (discardAbortedResult(signal, discardOnAbort, errorMessage) || agent.threadId !== threadId || messageIndex === -1 || isReplay && !this.isInLatestUserTurn(agent.messages, message.id) || agent.messages.some((m) => m.role === "tool" && m.toolCallId === toolCall.id && !this.isFrontendPlaceholderResult(m))) return false;
4665
+ const insertAt = this.toolResultInsertionIndex(agent.messages, messageIndex, toolCall.id);
4381
4666
  const toolMessage = {
4382
4667
  id: (0, _copilotkit_shared.randomUUID)(),
4383
4668
  role: "tool",
4384
4669
  toolCallId: toolCall.id,
4385
- content: toolCallResult
4670
+ content: toolCallResult,
4671
+ ...errorMessage ? { error: errorMessage } : {}
4386
4672
  };
4387
- editAgentMessages(agent, (messages) => messages.splice(insertAt, 0, toolMessage));
4673
+ agent.messages.splice(insertAt, 0, toolMessage);
4388
4674
  if (!errorMessage && (wildcardTool === null || wildcardTool === void 0 ? void 0 : wildcardTool.followUp) !== false) return true;
4389
4675
  }
4390
4676
  return false;
@@ -4438,7 +4724,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4438
4724
  content: "",
4439
4725
  toolCalls: [assistantToolCall]
4440
4726
  };
4441
- editAgentMessages(agent, (messages) => messages.push(assistantMessage));
4727
+ agent.messages.push(assistantMessage);
4442
4728
  let handlerResult = {
4443
4729
  content: "",
4444
4730
  result: "",
@@ -4457,11 +4743,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4457
4743
  id: (0, _copilotkit_shared.randomUUID)(),
4458
4744
  role: "tool",
4459
4745
  toolCallId,
4460
- content: handlerResult.content
4746
+ content: handlerResult.content,
4747
+ ...handlerResult.error ? { error: handlerResult.error } : {}
4461
4748
  };
4462
4749
  const assistantIndex = agent.messages.findIndex((m) => m.id === assistantMessage.id);
4463
- if (assistantIndex !== -1) editAgentMessages(agent, (messages) => messages.splice(assistantIndex + 1, 0, toolResultMessage));
4464
- else editAgentMessages(agent, (messages) => messages.push(toolResultMessage));
4750
+ if (assistantIndex !== -1) agent.messages.splice(assistantIndex + 1, 0, toolResultMessage);
4751
+ else agent.messages.push(toolResultMessage);
4465
4752
  if (!handlerResult.error && followUp !== false) {
4466
4753
  if (typeof followUp === "string" && followUp !== "generate") {
4467
4754
  const userMessage = {
@@ -4469,7 +4756,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4469
4756
  role: "user",
4470
4757
  content: followUp
4471
4758
  };
4472
- editAgentMessages(agent, (messages) => messages.push(userMessage));
4759
+ agent.messages.push(userMessage);
4473
4760
  }
4474
4761
  await this._internal.waitForPendingFrameworkUpdates();
4475
4762
  await this.runAgent({ agent });
@@ -4542,7 +4829,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4542
4829
  /**
4543
4830
  * Create an agent error subscriber
4544
4831
  */
4545
- createAgentErrorSubscriber(agent, stream) {
4832
+ createAgentErrorSubscriber(agent, runSignal) {
4546
4833
  const emitAgentError = async (error, code, extraContext = {}) => {
4547
4834
  const context = { ...extraContext };
4548
4835
  if (agent.agentId) context.agentId = agent.agentId;
@@ -4557,8 +4844,15 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4557
4844
  await emitAgentError(error, error instanceof AgentThreadLockedError ? CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED : CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT, { source: "onRunFailed" });
4558
4845
  },
4559
4846
  onRunErrorEvent: async ({ event }) => {
4560
- var _this$_runAbortContro4, _event$rawEvent, _event$rawEvent2, _event$message;
4561
- if (((_this$_runAbortContro4 = this._runAbortController) === null || _this$_runAbortContro4 === void 0 ? void 0 : _this$_runAbortContro4.signal.aborted) === true || (event === null || event === void 0 ? void 0 : event.code) === "abort") return;
4847
+ var _runSignal$aborted, _event$rawEvent, _event$rawEvent2, _event$message;
4848
+ if (((_runSignal$aborted = runSignal === null || runSignal === void 0 ? void 0 : runSignal.aborted) !== null && _runSignal$aborted !== void 0 ? _runSignal$aborted : false) || (event === null || event === void 0 ? void 0 : event.code) === "abort") return;
4849
+ if ((event === null || event === void 0 ? void 0 : event.code) === _copilotkit_shared.THREAD_ALREADY_RUNNING_ERROR_CODE) {
4850
+ await emitAgentError(new AgentThreadLockedError(agent.threadId), CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED, {
4851
+ source: "onRunErrorEvent",
4852
+ event
4853
+ });
4854
+ return;
4855
+ }
4562
4856
  const eventError = (event === null || event === void 0 ? void 0 : event.rawEvent) instanceof Error ? event.rawEvent : (event === null || event === void 0 || (_event$rawEvent = event.rawEvent) === null || _event$rawEvent === void 0 ? void 0 : _event$rawEvent.error) instanceof Error ? event.rawEvent.error : void 0;
4563
4857
  const errorMessage = typeof (event === null || event === void 0 || (_event$rawEvent2 = event.rawEvent) === null || _event$rawEvent2 === void 0 ? void 0 : _event$rawEvent2.error) === "string" ? event.rawEvent.error : (_event$message = event === null || event === void 0 ? void 0 : event.message) !== null && _event$message !== void 0 ? _event$message : "Agent run error";
4564
4858
  const rawError = eventError !== null && eventError !== void 0 ? eventError : new Error(errorMessage);
@@ -4566,8 +4860,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4566
4860
  await emitAgentError(rawError, CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT, {
4567
4861
  source: "onRunErrorEvent",
4568
4862
  event,
4569
- runtimeErrorCode: event === null || event === void 0 ? void 0 : event.code,
4570
- phase: stream === "run" ? "live" : ɵgetConnectRunErrorPhase(event)
4863
+ runtimeErrorCode: event === null || event === void 0 ? void 0 : event.code
4571
4864
  });
4572
4865
  }
4573
4866
  };
@@ -5640,6 +5933,18 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5640
5933
  get isConfigured() {
5641
5934
  return this.config !== void 0;
5642
5935
  }
5936
+ /**
5937
+ * Whether events may carry agent message text: not when the capture's config
5938
+ * sets `capture.agentText` to false. A running custom-sink capture keeps the
5939
+ * choice it started with; otherwise the current config decides.
5940
+ */
5941
+ get capturesAgentText() {
5942
+ var _this$activeConfig;
5943
+ const config = (_this$activeConfig = this.activeConfig) !== null && _this$activeConfig !== void 0 ? _this$activeConfig : this.config;
5944
+ if (config === void 0) return false;
5945
+ const capture = config.capture;
5946
+ return !(typeof capture === "object" && capture !== null && capture.agentText === false);
5947
+ }
5643
5948
  get isLegacyCaptureActive() {
5644
5949
  return this.collector !== null && this.collector.trajectoryId !== null;
5645
5950
  }
@@ -5749,13 +6054,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5749
6054
  this.toolCalls.clear();
5750
6055
  this.executingTools.clear();
5751
6056
  }
5752
- /** A developer event. Only an explicit legacy sink adds open-Thread context. */
6057
+ /**
6058
+ * A developer event. Only an explicit legacy sink adds open-Thread context;
6059
+ * an event that names its own Thread gets no ambiguity next to it.
6060
+ */
5753
6061
  emit(name, value) {
5754
6062
  this.connection.emit(name, value);
5755
6063
  if (value !== null && typeof value === "object" && !Array.isArray(value)) {
5756
6064
  var _this$collector4;
6065
+ const context = typeof value["threadId"] === "string" ? {} : this.openThreadContext();
5757
6066
  (_this$collector4 = this.collector) === null || _this$collector4 === void 0 || _this$collector4.emit(name, {
5758
- ...this.openThreadContext(),
6067
+ ...context,
5759
6068
  ...value
5760
6069
  });
5761
6070
  }
@@ -5841,9 +6150,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5841
6150
  });
5842
6151
  }
5843
6152
  emitMessage(agent, message) {
5844
- var _this$activeConfig, _this$collector7;
6153
+ var _this$collector7;
5845
6154
  const content = typeof message.content === "string" ? message.content : "";
5846
- const includeText = ((_this$activeConfig = this.activeConfig) === null || _this$activeConfig === void 0 || (_this$activeConfig = _this$activeConfig.capture) === null || _this$activeConfig === void 0 ? void 0 : _this$activeConfig.agentText) !== false && typeof message.content === "string";
6155
+ const includeText = this.capturesAgentText && typeof message.content === "string";
5847
6156
  (_this$collector7 = this.collector) === null || _this$collector7 === void 0 || _this$collector7.ɵemit("agent.message", {
5848
6157
  messageId: message.id,
5849
6158
  runId: this.runIdForMessage(agent, message.id),
@@ -7011,12 +7320,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7011
7320
  CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
7012
7321
  CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
7013
7322
  CopilotKitCoreErrorCode["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
7014
- /**
7015
- * An agent emitted RUN_ERROR. `context.phase` (`RunErrorPhase`) is
7016
- * `"replay"` when the error belongs to stored thread history replayed on
7017
- * connect, `"live"` when the run is happening now, and `"unknown"` when the
7018
- * transport cannot tell. Show a live-failure notice only for `"live"`.
7019
- */
7020
7323
  CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
7021
7324
  CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
7022
7325
  CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
@@ -7482,6 +7785,15 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7482
7785
  get ɵlearningConfigured() {
7483
7786
  return this.learningBridge.isConfigured;
7484
7787
  }
7788
+ /**
7789
+ * @internal Whether captured events may carry agent message text: false
7790
+ * without a `learning` config, or when a custom sink sets
7791
+ * `capture.agentText` to false. A running custom-sink capture keeps the
7792
+ * choice it started with.
7793
+ */
7794
+ get ɵlearningCapturesAgentText() {
7795
+ return this.learningBridge.capturesAgentText;
7796
+ }
7485
7797
  /** @internal Calls `listener` when {@link ɵlearningConfigured} changes. */
7486
7798
  ɵsubscribeToLearningConfigured(listener) {
7487
7799
  this.learningConfiguredListeners.add(listener);
@@ -9141,7 +9453,6 @@ exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionS
9141
9453
  exports.CopilotKitHeaderResolutionError = CopilotKitHeaderResolutionError;
9142
9454
  exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
9143
9455
  exports.IntelligenceAgent = IntelligenceAgent;
9144
- exports.IntelligenceReplayFailedError = IntelligenceReplayFailedError;
9145
9456
  exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
9146
9457
  exports.MemoryError = MemoryError;
9147
9458
  exports.ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;