@copilotkit/core 1.79.1 → 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.cjs CHANGED
@@ -855,6 +855,7 @@ function ɵrepairToolCallPairs(kept, full) {
855
855
  }
856
856
  const repaired = [];
857
857
  const emitted = /* @__PURE__ */ new Set();
858
+ const expandedMessages = /* @__PURE__ */ new Set();
858
859
  const emit = (message) => {
859
860
  if (emitted.has(message.id)) return;
860
861
  emitted.add(message.id);
@@ -863,6 +864,8 @@ function ɵrepairToolCallPairs(kept, full) {
863
864
  /** Emit an assistant turn together with every result it is owed. */
864
865
  const emitWithResults = (message) => {
865
866
  emit(message);
867
+ if (expandedMessages.has(message)) return;
868
+ expandedMessages.add(message);
866
869
  for (const callId of toolCallIdsOf(message)) {
867
870
  const result = callIdToResult.get(callId);
868
871
  if (result) emit(result);
@@ -883,6 +886,198 @@ function ɵrepairToolCallPairs(kept, full) {
883
886
  }
884
887
  return repaired;
885
888
  }
889
+ /**
890
+ * Move each detached tool result to sit behind the assistant call that issued
891
+ * it — usually back to an earlier call, and forward only when no earlier call
892
+ * has its id and exactly one call in the list does — and change nothing else.
893
+ * Used for unfiltered sends, and on a configured filter's output only when
894
+ * {@link ɵrepairToolCallPairs}, which filtered sends go through otherwise,
895
+ * throws.
896
+ *
897
+ * The client store can detach a tool result from its call on its own: when a
898
+ * backend's `MESSAGES_SNAPSHOT` carries a tool message under a different id
899
+ * than the streamed `TOOL_CALL_RESULT`, the `@ag-ui/client` merge drops the
900
+ * copy placed after its call and appends the snapshot's copy at the end,
901
+ * leaving `assistant(tool_call), assistant(text), tool(result)`. A backend that
902
+ * rebuilds its state from that payload discards every result it cannot pair.
903
+ *
904
+ * The pairing rule mirrors the `@ag-ui/client` snapshot pass
905
+ * (ag-ui-protocol/ag-ui#3114):
906
+ *
907
+ * - Everything is by list position. The same object or id appearing twice is
908
+ * two independent slots, including an assistant call the merge duplicated,
909
+ * so a duplicated call can be left unanswered. Nothing is dropped,
910
+ * deduplicated, or added, and only tool-role messages ever change position.
911
+ * - Transparent entries are `activity` and `reasoning` messages and anything
912
+ * that is not a plain object (`null`, arrays, primitives). They are never
913
+ * the anchor, never separate a call from its result, and stay in place.
914
+ * Reasoning stored between a call and its result is the next step's: in a
915
+ * multi-step turn whose calls share one assistant message, Mastra leaves
916
+ * `assistant(c1, c2), tool(c1), reasoning, tool(c2)`. Moving the result in
917
+ * front of it leaves the reasoning trailing, and Mastra drops it.
918
+ * - The anchor is the last non-transparent message so far that is not `tool`.
919
+ * Each tool call an assistant issues opens a slot for its call id, and a
920
+ * result pairs with slots for its `toolCallId` alone. `subagentRunId` is
921
+ * ignored: results CopilotKit creates itself (frontend tool results,
922
+ * interrupt responses) do not carry one, and on a result it names the run
923
+ * that executed the tool, which may differ from the run that issued the
924
+ * call. Known limitation: a parent call and a subagent call that reuse one
925
+ * id are indistinguishable, so their drifted results can be swapped.
926
+ * - Pass 1, left to right: a result with an open slot issued at the anchor is
927
+ * in place; it takes that slot and stays put. A result with an open slot
928
+ * issued earlier is detached. A result with no slot for its id issued
929
+ * earlier at all is early. Any other result — every earlier slot for its id
930
+ * already answered — stays put. Detached results take no slot in this
931
+ * pass: they could only ever take a slot issued before the current anchor,
932
+ * which no later in-place result can want.
933
+ * - Pass 2, backward, per id: the detached results, from the newest back,
934
+ * each take the newest still-open slot issued before them; one that finds
935
+ * none stays put. So when several results for a reused id (providers reuse
936
+ * `call_0` every turn) are all detached, they keep their stored order
937
+ * across the calls, and a later turn's lone result goes to the later call
938
+ * rather than to an earlier one that was abandoned.
939
+ * - Pass 3, forward, per id: an early result moves forward only when its id
940
+ * is unambiguous — exactly one call slot in the whole list has it, that
941
+ * slot is issued after the result, and it is still open after passes 1-2.
942
+ * The first early result for the id, left to right, takes it; any other
943
+ * early result for that id stays put. This repairs a result whose call
944
+ * was re-issued after it (a snapshot that re-ids the assistant message but
945
+ * keeps the result's id). With a reused id (providers reuse `call_0` every
946
+ * turn) nothing moves forward: in `[t0, t1, a1(c), user, a2(c)]` nothing
947
+ * says t1 answers a2, and a2 may be a pending call (a frontend tool, an
948
+ * interrupt, a human-in-the-loop call waiting on the user). Only early
949
+ * results move forward: an extra result for a call that is already
950
+ * answered never does.
951
+ * - A moved result goes behind its issuer, after the tool and transparent
952
+ * entries already following it, but in front of any reasoning among those
953
+ * transparent entries: reasoning belongs to the message after it, so a
954
+ * moved result never lands between a reasoning message and its owner.
955
+ * Results moved behind one issuer keep their stored order. Any other
956
+ * message between a call and its result separates them, so a
957
+ * backward-moved result moves before it and a forward-moved result moves
958
+ * past it.
959
+ * - The rule cannot tell a duplicate result from a detached one. A second
960
+ * result for an already-answered call moves back to an older still-open
961
+ * slot for its id if there is one, even across user turns; it never moves
962
+ * forward.
963
+ * - Malformed entries are ignored rather than thrown on. Non-array
964
+ * `toolCalls`, call entries without a string `id`, and results without a
965
+ * string `toolCallId` open or take no slot.
966
+ *
967
+ * Returns `messages` itself when nothing moved.
968
+ */
969
+ function ɵkeepToolResultsWithCalls(messages) {
970
+ const slots = /* @__PURE__ */ new Map();
971
+ const openCount = /* @__PURE__ */ new Map();
972
+ const close = (callId, slot) => {
973
+ slot.open = false;
974
+ openCount.set(callId, openCount.get(callId) - 1);
975
+ };
976
+ const detached = /* @__PURE__ */ new Map();
977
+ const early = /* @__PURE__ */ new Map();
978
+ let anchor = -1;
979
+ for (let index = 0; index < messages.length; index++) {
980
+ const message = messages[index];
981
+ if (isTransparent(message)) continue;
982
+ const role = roleOf(message);
983
+ if (role !== "tool") {
984
+ anchor = index;
985
+ const calls = role === "assistant" ? message.toolCalls : void 0;
986
+ if (!Array.isArray(calls)) continue;
987
+ for (const call of calls) {
988
+ if (typeof call !== "object" || call === null) continue;
989
+ const callId = call.id;
990
+ if (typeof callId !== "string") continue;
991
+ push(slots, callId, {
992
+ issuer: index,
993
+ open: true
994
+ });
995
+ openCount.set(callId, (openCount.get(callId) ?? 0) + 1);
996
+ }
997
+ continue;
998
+ }
999
+ const callId = message.toolCallId;
1000
+ if (typeof callId !== "string") continue;
1001
+ const forId = slots.get(callId);
1002
+ if (!forId) {
1003
+ push(early, callId, index);
1004
+ continue;
1005
+ }
1006
+ let atAnchor;
1007
+ for (let s = forId.length - 1; s >= 0; s--) {
1008
+ const slot = forId[s];
1009
+ if (slot.issuer !== anchor) break;
1010
+ if (slot.open) atAnchor = slot;
1011
+ }
1012
+ if (atAnchor) {
1013
+ close(callId, atAnchor);
1014
+ continue;
1015
+ }
1016
+ if (openCount.get(callId) > 0) push(detached, callId, index);
1017
+ }
1018
+ const movedBehind = /* @__PURE__ */ new Map();
1019
+ const moved = /* @__PURE__ */ new Set();
1020
+ const take = (callId, slot, index) => {
1021
+ close(callId, slot);
1022
+ moved.add(index);
1023
+ push(movedBehind, slot.issuer, index);
1024
+ };
1025
+ for (const [callId, results] of detached) {
1026
+ const forId = slots.get(callId);
1027
+ let s = forId.length - 1;
1028
+ for (let r = results.length - 1; r >= 0; r--) {
1029
+ const index = results[r];
1030
+ while (s >= 0 && (!forId[s].open || forId[s].issuer >= index)) s--;
1031
+ if (s < 0) break;
1032
+ take(callId, forId[s], index);
1033
+ }
1034
+ }
1035
+ for (const [callId, results] of early) {
1036
+ const forId = slots.get(callId);
1037
+ if (forId?.length !== 1 || !forId[0].open) continue;
1038
+ take(callId, forId[0], results[0]);
1039
+ }
1040
+ if (moved.size === 0) return messages;
1041
+ const result = [];
1042
+ let openIssuer = -1;
1043
+ const flush = () => {
1044
+ const behind = movedBehind.get(openIssuer);
1045
+ if (!behind) return;
1046
+ let at = result.length;
1047
+ for (let tail = result.length - 1; tail >= 0; tail--) {
1048
+ if (!isTransparent(result[tail])) break;
1049
+ if (roleOf(result[tail]) === "reasoning") at = tail;
1050
+ }
1051
+ result.splice(at, 0, ...[...behind].sort((a, b) => a - b).map((index) => messages[index]));
1052
+ };
1053
+ for (let index = 0; index < messages.length; index++) {
1054
+ if (moved.has(index)) continue;
1055
+ const message = messages[index];
1056
+ if (!isTransparent(message) && roleOf(message) !== "tool") {
1057
+ flush();
1058
+ openIssuer = index;
1059
+ }
1060
+ result.push(message);
1061
+ }
1062
+ flush();
1063
+ return result;
1064
+ }
1065
+ function push(map, key, value) {
1066
+ const list = map.get(key);
1067
+ if (list) list.push(value);
1068
+ else map.set(key, [value]);
1069
+ }
1070
+ /**
1071
+ * Activity and reasoning messages and anything that is not a plain object
1072
+ * (`null`, arrays, primitives) never anchor or separate.
1073
+ */
1074
+ function isTransparent(message) {
1075
+ return typeof message !== "object" || message === null || Array.isArray(message) || message.role === "activity" || message.role === "reasoning";
1076
+ }
1077
+ function roleOf(message) {
1078
+ if (typeof message !== "object" || message === null) return void 0;
1079
+ return message.role;
1080
+ }
886
1081
 
887
1082
  //#endregion
888
1083
  //#region src/agent.ts
@@ -1025,7 +1220,21 @@ var ProxiedCopilotRuntimeAgent = class ProxiedCopilotRuntimeAgent extends _ag_ui
1025
1220
  this._messageFilter = filter;
1026
1221
  }
1027
1222
  /**
1028
- * Narrow the outbound payload with the configured message filter.
1223
+ * Build the outbound payload, keeping every tool result with the call that
1224
+ * issued it.
1225
+ *
1226
+ * - **No filter** (or a filter whose output is unusable, which falls back to
1227
+ * the full thread): `ɵkeepToolResultsWithCalls` re-places tool results
1228
+ * that drifted from their call and changes nothing else. The client store
1229
+ * can detach them on its own when a `MESSAGES_SNAPSHOT` re-ids a tool
1230
+ * message, and a backend that rebuilds state from such a payload drops
1231
+ * every result it cannot pair.
1232
+ * - **Filter**: `ɵrepairToolCallPairs(kept, full)` restores the call or the
1233
+ * results a filter trimmed. Its known limitations are tracked in
1234
+ * https://github.com/CopilotKit/CopilotKit/issues/7891.
1235
+ * - **Filter repair throws**: the filter's output goes through
1236
+ * `ɵkeepToolResultsWithCalls` instead, keeping its trimming and
1237
+ * redaction; if that throws too, the output is sent as is.
1029
1238
  *
1030
1239
  * **Called from the HTTP paths only, and that placement is the Intelligence
1031
1240
  * exemption.** An earlier revision applied the filter in
@@ -1048,28 +1257,83 @@ var ProxiedCopilotRuntimeAgent = class ProxiedCopilotRuntimeAgent extends _ag_ui
1048
1257
  * cannot reach the messages the UI renders no matter what it does with the
1049
1258
  * array it is handed. The filter gets a *second* deep clone on top of that,
1050
1259
  * because `input.messages` is also the repair baseline and the untrimmed
1051
- * fallback: sharing the message objects let a filter that mutates a kept
1052
- * message's `toolCallId` corrupt the baseline, and an orphaned tool result
1053
- * then went out on the wire — a payload the provider rejects, which is
1054
- * exactly the failure this whole mechanism exists to prevent.
1055
- */
1056
- #applyMessageFilter(input) {
1057
- const filter = this._messageFilter;
1058
- if (!filter) return input;
1260
+ * fallback: sharing the message objects let a filter that rewrote the tool
1261
+ * call id of an assistant message it dropped hide that issuer from the
1262
+ * repair, and the kept tool result then went out orphaned — a payload the
1263
+ * provider rejects, which is exactly the failure this whole mechanism
1264
+ * exists to prevent.
1265
+ */
1266
+ #prepareOutboundMessages(input) {
1267
+ const full = input.messages;
1268
+ const kept = this.#applyMessageFilter(full);
1269
+ const agentId = this.agentId ?? "";
1059
1270
  try {
1060
- const kept = filter((0, _ag_ui_client.structuredClone_)(input.messages), { agentId: this.agentId ?? "" });
1061
- if (!Array.isArray(kept)) {
1062
- console.warn("ProxiedCopilotRuntimeAgent: messageFilter returned a non-array value; sending the full message history instead.");
1063
- return input;
1064
- }
1271
+ const messages = kept === void 0 ? ɵkeepToolResultsWithCalls(full) : ɵrepairToolCallPairs(kept, full);
1065
1272
  return {
1066
1273
  ...input,
1067
- messages: ɵrepairToolCallPairs(kept, input.messages)
1274
+ messages
1068
1275
  };
1276
+ } catch (error) {
1277
+ if (kept === void 0) {
1278
+ console.warn(`ProxiedCopilotRuntimeAgent: tool-call repair failed for agent "${agentId}"; sending the message history unrepaired instead.`, error);
1279
+ return input;
1280
+ }
1281
+ try {
1282
+ const messages = ɵkeepToolResultsWithCalls(kept);
1283
+ console.warn(`ProxiedCopilotRuntimeAgent: tool-call repair failed for agent "${agentId}"; sending the filtered message history with only drifted tool results moved instead.`, error);
1284
+ return {
1285
+ ...input,
1286
+ messages
1287
+ };
1288
+ } catch (moveError) {
1289
+ console.warn(`ProxiedCopilotRuntimeAgent: tool-call repair failed for agent "${agentId}"; sending the filtered message history unrepaired instead.`, error, moveError);
1290
+ return {
1291
+ ...input,
1292
+ messages: kept
1293
+ };
1294
+ }
1295
+ }
1296
+ }
1297
+ /**
1298
+ * Run the configured filter. Returns `undefined` when there is no filter,
1299
+ * copying the thread for it fails, or the filter's output cannot be used,
1300
+ * meaning "send the full thread".
1301
+ *
1302
+ * A filter that throws, returns a non-array, or returns an array with an
1303
+ * entry that is not a message object (a hole or a nested array included)
1304
+ * falls back to the untrimmed thread rather than failing the run. Trimming
1305
+ * is an optimization, and taking the user's message down with it would be
1306
+ * the worse outcome; the warning is what surfaces the bug.
1307
+ */
1308
+ #applyMessageFilter(full) {
1309
+ const filter = this._messageFilter;
1310
+ if (!filter) return void 0;
1311
+ let copy;
1312
+ try {
1313
+ copy = (0, _ag_ui_client.structuredClone_)(full);
1314
+ } catch (error) {
1315
+ console.warn("ProxiedCopilotRuntimeAgent: could not copy the message history for messageFilter; sending the full message history instead.", error);
1316
+ return;
1317
+ }
1318
+ let kept;
1319
+ try {
1320
+ kept = filter(copy, { agentId: this.agentId ?? "" });
1069
1321
  } catch (error) {
1070
1322
  console.warn("ProxiedCopilotRuntimeAgent: messageFilter failed; sending the full message history instead.", error);
1071
- return input;
1323
+ return;
1324
+ }
1325
+ if (!Array.isArray(kept)) {
1326
+ console.warn("ProxiedCopilotRuntimeAgent: messageFilter returned a non-array value; sending the full message history instead.");
1327
+ return;
1328
+ }
1329
+ for (let index = 0; index < kept.length; index++) {
1330
+ const entry = kept[index];
1331
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
1332
+ console.warn("ProxiedCopilotRuntimeAgent: messageFilter returned an entry that is not a message; sending the full message history instead.");
1333
+ return;
1334
+ }
1072
1335
  }
1336
+ return kept;
1073
1337
  }
1074
1338
  requestInit(input) {
1075
1339
  return {
@@ -1227,7 +1491,7 @@ var ProxiedCopilotRuntimeAgent = class ProxiedCopilotRuntimeAgent extends _ag_ui
1227
1491
  return (0, rxjs.defer)(() => (0, rxjs.from)(this.resolveDelegate())).pipe((0, rxjs_operators.switchMap)((delegate) => withAbortErrorHandling(delegate.connect(input, lifecycle))));
1228
1492
  }
1229
1493
  #connectViaHttp(unfiltered) {
1230
- const input = this.#applyMessageFilter(unfiltered);
1494
+ const input = this.#prepareOutboundMessages(unfiltered);
1231
1495
  this.activeRun = void 0;
1232
1496
  const routedId = this.routedAgentId();
1233
1497
  let httpEvents;
@@ -1260,7 +1524,7 @@ var ProxiedCopilotRuntimeAgent = class ProxiedCopilotRuntimeAgent extends _ag_ui
1260
1524
  return (0, rxjs.defer)(() => (0, rxjs.from)(this.resolveDelegate())).pipe((0, rxjs_operators.switchMap)((delegate) => withAbortErrorHandling(delegate.run(input))));
1261
1525
  }
1262
1526
  #runViaHttp(unfiltered) {
1263
- const input = this.#applyMessageFilter(unfiltered);
1527
+ const input = this.#prepareOutboundMessages(unfiltered);
1264
1528
  const activeRun = {
1265
1529
  threadId: input.threadId,
1266
1530
  runId: input.runId
@@ -3451,6 +3715,14 @@ var WebMCPRegistry = class {
3451
3715
  * takes no reason and whose signals never expose one.
3452
3716
  */
3453
3717
  const liveHITLStops = /* @__PURE__ */ new WeakMap();
3718
+ /**
3719
+ * The message a failed tool call reports. An error thrown with an empty
3720
+ * message still means the call failed, so it gets a fallback rather than an
3721
+ * empty string, which everything downstream reads as success.
3722
+ */
3723
+ function toolFailureMessage(error) {
3724
+ return error.message || "Tool call failed";
3725
+ }
3454
3726
  function discardAbortedResult(signal, discardOnAbort, errorMessage) {
3455
3727
  return !!(discardOnAbort && signal?.aborted && !(liveHITLStops.get(signal)?.() && errorMessage));
3456
3728
  }
@@ -3530,18 +3802,28 @@ var RunHandler = class {
3530
3802
  */
3531
3803
  _warnedMissingToolParameters = /* @__PURE__ */ new Set();
3532
3804
  /**
3533
- * Tracks whether the current run (including in-flight tool execution)
3534
- * has been aborted via `stopAgent()` or `agent.abortRun()`. Created
3535
- * fresh in `runAgent()`, aborted by `abortCurrentRun()`.
3805
+ * Abort controllers of each agent's in-flight run chains (a run plus its
3806
+ * recursive follow-ups), recording whether a chain, including its tool
3807
+ * execution, was aborted via `stopAgent()` or `agent.abortRun()`. Every run
3808
+ * that is not a follow-up gets a fresh controller, so a run started after
3809
+ * Stop is not born aborted while the stopped chain is still settling. Keyed
3810
+ * by agent so that stopping one agent never cancels another agent's run on
3811
+ * the same core.
3812
+ */
3813
+ _runAbortControllers = /* @__PURE__ */ new WeakMap();
3814
+ /**
3815
+ * Per-agent `runAgent` depth (in-flight runs plus their recursive
3816
+ * follow-ups), so that the `agent.abortRun()` intercept is installed while
3817
+ * any of the agent's runs is in flight and removed once none is, and so
3818
+ * that runaway follow-up chains trip `MAX_FOLLOW_UP_DEPTH`.
3536
3819
  */
3537
- _runAbortController = null;
3820
+ _runDepths = /* @__PURE__ */ new WeakMap();
3538
3821
  /**
3539
- * Tracks recursive `runAgent` depth so that the abort controller and
3540
- * `agent.abortRun()` intercept are only set up / torn down at the
3541
- * top-level call, not on follow-up recursive calls from
3542
- * `processAgentResult`.
3822
+ * Each agent's own `abortRun`, saved while RunHandler's intercept is
3823
+ * installed. Restored only once none of the agent's runs is in flight, so an
3824
+ * overlapping run keeps the intercept after an earlier run finishes.
3543
3825
  */
3544
- _runDepth = 0;
3826
+ _originalAbortRuns = /* @__PURE__ */ new WeakMap();
3545
3827
  /**
3546
3828
  * Keeps tools that opt in via `webmcp` registered on the page's WebMCP model
3547
3829
  * context (`document.modelContext`), in addition to the normal agent
@@ -3581,7 +3863,7 @@ var RunHandler = class {
3581
3863
  * not start a follow-up run.
3582
3864
  */
3583
3865
  abortCurrentRun(agent) {
3584
- this._runAbortController?.abort();
3866
+ this.abortAgentRuns(agent);
3585
3867
  const replay = this._interactionAbortControllers.get(agent);
3586
3868
  if (replay) {
3587
3869
  for (const controller of replay.controllers) controller.abort();
@@ -3589,6 +3871,15 @@ var RunHandler = class {
3589
3871
  this._executingToolCalls.delete(agent);
3590
3872
  }
3591
3873
  }
3874
+ abortAgentRuns(agent) {
3875
+ for (const controller of this._runAbortControllers.get(agent) ?? []) controller.abort();
3876
+ }
3877
+ /** Signal of the agent's most recently started in-flight run, if any. */
3878
+ latestRunSignal(agent) {
3879
+ let latest;
3880
+ for (const controller of this._runAbortControllers.get(agent) ?? []) latest = controller;
3881
+ return latest?.signal;
3882
+ }
3592
3883
  /**
3593
3884
  * Typed access to CopilotKitCore's internal ("friend") methods.
3594
3885
  * Centralises the single unavoidable cast so call-sites stay clean.
@@ -3836,7 +4127,7 @@ var RunHandler = class {
3836
4127
  /**
3837
4128
  * Run an agent
3838
4129
  */
3839
- async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff) {
4130
+ async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff, followUpOf) {
3840
4131
  if (agent.agentId) this._internal.suggestionEngine.clearSuggestions(agent.agentId);
3841
4132
  try {
3842
4133
  const headersApplied = this._internal.prepareAgentHeadersForRun(agent);
@@ -3860,25 +4151,30 @@ var RunHandler = class {
3860
4151
  forwardedProps
3861
4152
  });
3862
4153
  const logicalHandoff = continuationHandoff ?? (resumedRunId ? this._internal.stateManager.markNextRunAsContinuation(agent, resumedRunId) : void 0);
3863
- const isTopLevel = this._runDepth === 0;
3864
- let originalAbortRun;
3865
- if (isTopLevel) {
3866
- this._runAbortController = new AbortController();
3867
- const controller = this._runAbortController;
3868
- originalAbortRun = agent.abortRun.bind(agent);
4154
+ const isFollowUp = followUpOf !== void 0;
4155
+ const controller = followUpOf ?? new AbortController();
4156
+ const depth = this._runDepths.get(agent) ?? 0;
4157
+ this._runDepths.set(agent, depth + 1);
4158
+ if (!isFollowUp) {
4159
+ const controllers = this._runAbortControllers.get(agent) ?? /* @__PURE__ */ new Set();
4160
+ controllers.add(controller);
4161
+ this._runAbortControllers.set(agent, controllers);
4162
+ }
4163
+ if (depth === 0) {
4164
+ const originalAbortRun = agent.abortRun;
4165
+ this._originalAbortRuns.set(agent, originalAbortRun);
3869
4166
  agent.abortRun = () => {
3870
- controller.abort();
3871
- originalAbortRun();
4167
+ this.abortAgentRuns(agent);
4168
+ originalAbortRun.call(agent);
3872
4169
  };
3873
- await this._internal.notifySubscribers((subscriber) => subscriber.onAgentRunStarted?.({
4170
+ }
4171
+ try {
4172
+ if (depth === 0) await this._internal.notifySubscribers((subscriber) => subscriber.onAgentRunStarted?.({
3874
4173
  copilotkit: this.core,
3875
4174
  agent
3876
4175
  }), "Subscriber onAgentRunStarted error:");
3877
- }
3878
- this._runDepth++;
3879
- try {
3880
4176
  let logicalRunId = resumedRunId ?? runId;
3881
- const agentSubscriber = this.createAgentErrorSubscriber(agent);
4177
+ const agentSubscriber = this.createAgentErrorSubscriber(agent, controller.signal);
3882
4178
  let started = false;
3883
4179
  const onRunStartedEvent = agentSubscriber.onRunStartedEvent;
3884
4180
  const onRunInitialized = agentSubscriber.onRunInitialized;
@@ -3908,7 +4204,8 @@ var RunHandler = class {
3908
4204
  return await this.processAgentResult({
3909
4205
  runAgentResult,
3910
4206
  agent,
3911
- runId: logicalRunId
4207
+ runId: logicalRunId,
4208
+ runController: controller
3912
4209
  });
3913
4210
  } catch (error) {
3914
4211
  logicalHandoff?.cancel();
@@ -3925,22 +4222,34 @@ var RunHandler = class {
3925
4222
  newMessages: []
3926
4223
  };
3927
4224
  } finally {
3928
- this._runDepth--;
3929
- if (isTopLevel && originalAbortRun) agent.abortRun = originalAbortRun;
4225
+ const remainingDepth = (this._runDepths.get(agent) ?? 1) - 1;
4226
+ this._runDepths.set(agent, remainingDepth);
4227
+ if (!isFollowUp) {
4228
+ const controllers = this._runAbortControllers.get(agent);
4229
+ controllers?.delete(controller);
4230
+ if (controllers?.size === 0) this._runAbortControllers.delete(agent);
4231
+ }
4232
+ if (remainingDepth === 0) {
4233
+ const originalAbortRun = this._originalAbortRuns.get(agent);
4234
+ if (originalAbortRun) {
4235
+ agent.abortRun = originalAbortRun;
4236
+ this._originalAbortRuns.delete(agent);
4237
+ }
4238
+ }
3930
4239
  }
3931
4240
  }
3932
4241
  /**
3933
4242
  * Process agent result and execute tools
3934
4243
  */
3935
- async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", signal = this._runAbortController?.signal }) {
4244
+ async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", runController, signal = runController?.signal }) {
3936
4245
  const { newMessages } = runAgentResult;
3937
4246
  const agentId = agent.agentId;
3938
4247
  let needsFollowUp = false;
3939
4248
  const threadId = agent.threadId;
3940
4249
  const executing = this._executingToolCalls.get(agent) ?? /* @__PURE__ */ new Set();
3941
4250
  this._executingToolCalls.set(agent, executing);
3942
- if (toolExecutionMode === "restore" && agent.messages.some((message) => message.role === "assistant" && 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))))) return runAgentResult;
3943
- const messagesToProcess = toolExecutionMode === "restore" ? [...agent.messages] : newMessages;
4251
+ const messagesToProcess = toolExecutionMode === "restore" ? agent.messages.filter((message) => message.role === "assistant" && this.isInLatestUserTurn(agent.messages, message.id)) : newMessages;
4252
+ if (toolExecutionMode === "restore" && messagesToProcess.some((message) => message.role === "assistant" && 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))))) return runAgentResult;
3944
4253
  for (const message of messagesToProcess) if (message.role === "assistant") for (const toolCall of message.toolCalls || []) {
3945
4254
  const tool = this.getTool({
3946
4255
  toolName: toolCall.function.name,
@@ -3956,12 +4265,12 @@ var RunHandler = class {
3956
4265
  return wildcardTool;
3957
4266
  };
3958
4267
  const executableTool = tool ?? getWildcardTool();
3959
- if (toolExecutionMode === "restore" && (!executableTool?.handler || executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
4268
+ if (toolExecutionMode === "restore" && (!executableTool || executableTool.handler && executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
3960
4269
  const executionKey = JSON.stringify([threadId, toolCall.id]);
3961
- if (signal?.aborted || agent.threadId !== threadId || executing.has(executionKey)) continue;
4270
+ if (signal?.aborted || agent.threadId !== threadId || toolExecutionMode === "restore" && !this.isInLatestUserTurn(agent.messages, message.id) || executing.has(executionKey)) continue;
3962
4271
  const existingResultIndex = newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
3963
4272
  let existingResult = agent.messages.find((m) => m.role === "tool" && m.toolCallId === toolCall.id) ?? newMessages[existingResultIndex];
3964
- if (existingResult && executableTool?.handler && this.isFrontendPlaceholderResult(existingResult)) {
4273
+ if (existingResult && this.isFrontendPlaceholderResult(existingResult) && (toolExecutionMode === "restore" || executableTool?.handler)) {
3965
4274
  if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
3966
4275
  existingResult = void 0;
3967
4276
  const agentMsgIdx = agent.messages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
@@ -4008,18 +4317,43 @@ var RunHandler = class {
4008
4317
  if (interactionController?.signal.aborted) return runAgentResult;
4009
4318
  }
4010
4319
  }
4011
- if (needsFollowUp && agent.threadId === threadId && !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.`);
4320
+ if (needsFollowUp && agent.threadId === threadId && !signal?.aborted) if ((this._runDepths.get(agent) ?? 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.`);
4012
4321
  else {
4013
4322
  await this._internal.waitForPendingFrameworkUpdates();
4323
+ if (toolExecutionMode === "restore" && !messagesToProcess.some((message) => this.isInLatestUserTurn(agent.messages, message.id))) return runAgentResult;
4014
4324
  const continuationHandoff = this._internal.stateManager.markNextRunAsContinuation(agent, runId);
4015
4325
  return await this.runAgent({
4016
4326
  agent,
4017
4327
  ...runId !== void 0 ? { runId } : {}
4018
- }, continuationHandoff);
4328
+ }, continuationHandoff, runController);
4019
4329
  }
4020
4330
  this._internal.suggestionEngine.reloadSuggestions(agentId);
4021
4331
  return runAgentResult;
4022
4332
  }
4333
+ /** A later user message supersedes pending work from an older turn. */
4334
+ isInLatestUserTurn(messages, messageId) {
4335
+ for (let index = messages.length - 1; index >= 0; index--) {
4336
+ const message = messages[index];
4337
+ if (message?.role === "user") return false;
4338
+ if (message?.id === messageId) return true;
4339
+ }
4340
+ return false;
4341
+ }
4342
+ /** Locate a missing result before saved results for later calls in its batch. */
4343
+ toolResultInsertionIndex(messages, messageIndex, toolCallId) {
4344
+ const parent = messages[messageIndex];
4345
+ const calls = parent?.role === "assistant" ? parent.toolCalls ?? [] : [];
4346
+ const callIndex = calls.findIndex((call) => call.id === toolCallId);
4347
+ let insertAt = messageIndex + 1;
4348
+ while (insertAt < messages.length) {
4349
+ const result = messages[insertAt];
4350
+ if (result?.role !== "tool") break;
4351
+ if (calls.findIndex((call) => call.id === result.toolCallId) > callIndex) break;
4352
+ insertAt++;
4353
+ }
4354
+ return insertAt;
4355
+ }
4356
+ /** Identify transport placeholders that must not count as completed answers. */
4023
4357
  isFrontendPlaceholderResult(message) {
4024
4358
  return message.role === "tool" && isForwardedToClientPlaceholder(message.content);
4025
4359
  }
@@ -4028,7 +4362,7 @@ var RunHandler = class {
4028
4362
  * Handles arg parsing, subscriber notifications, handler invocation, result stringification,
4029
4363
  * and error handling.
4030
4364
  */
4031
- async executeToolHandler({ tool, toolCall, agent, agentId, handlerArgs, toolType, messageId, signal = this._runAbortController?.signal, discardOnAbort = false, isReplay = false }) {
4365
+ async executeToolHandler({ tool, toolCall, agent, agentId, handlerArgs, toolType, messageId, signal = this.latestRunSignal(agent), discardOnAbort = false, isReplay = false }) {
4032
4366
  let toolCallResult = "";
4033
4367
  let toolCallText = "";
4034
4368
  let errorMessage;
@@ -4038,7 +4372,7 @@ var RunHandler = class {
4038
4372
  parsedArgs = parseToolArguments(handlerArgs, toolCall.function.name);
4039
4373
  } catch (error) {
4040
4374
  const parseError = error instanceof Error ? error : new Error(String(error));
4041
- errorMessage = parseError.message;
4375
+ errorMessage = toolFailureMessage(parseError);
4042
4376
  isArgumentError = true;
4043
4377
  await this._internal.emitError({
4044
4378
  error: parseError,
@@ -4070,7 +4404,7 @@ var RunHandler = class {
4070
4404
  ({content: toolCallResult, text: toolCallText} = toToolResultContent(result));
4071
4405
  } catch (error) {
4072
4406
  const handlerError = error instanceof Error ? error : new Error(String(error));
4073
- errorMessage = handlerError.message;
4407
+ errorMessage = toolFailureMessage(handlerError);
4074
4408
  if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) await this._internal.emitError({
4075
4409
  error: handlerError,
4076
4410
  code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,
@@ -4126,14 +4460,14 @@ var RunHandler = class {
4126
4460
  });
4127
4461
  {
4128
4462
  const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
4129
- 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;
4130
- let insertAt = messageIndex + 1;
4131
- while (insertAt < agent.messages.length && agent.messages[insertAt]?.role === "tool") insertAt++;
4463
+ 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;
4464
+ const insertAt = this.toolResultInsertionIndex(agent.messages, messageIndex, toolCall.id);
4132
4465
  const toolMessage = {
4133
4466
  id: (0, _copilotkit_shared.randomUUID)(),
4134
4467
  role: "tool",
4135
4468
  toolCallId: toolCall.id,
4136
- content: handlerResult.content
4469
+ content: handlerResult.content,
4470
+ ...handlerResult.error ? { error: handlerResult.error } : {}
4137
4471
  };
4138
4472
  agent.messages.splice(insertAt, 0, toolMessage);
4139
4473
  if (!handlerResult.error && tool?.followUp !== false) return true;
@@ -4158,7 +4492,7 @@ var RunHandler = class {
4158
4492
  parsedArgs = parseToolArguments(toolCall.function.arguments, toolCall.function.name);
4159
4493
  } catch (error) {
4160
4494
  const parseError = error instanceof Error ? error : new Error(String(error));
4161
- errorMessage = parseError.message;
4495
+ errorMessage = toolFailureMessage(parseError);
4162
4496
  await this._internal.emitError({
4163
4497
  error: parseError,
4164
4498
  code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,
@@ -4193,7 +4527,7 @@ var RunHandler = class {
4193
4527
  ({content: toolCallResult, text: toolCallText} = toToolResultContent(result));
4194
4528
  } catch (error) {
4195
4529
  const handlerError = error instanceof Error ? error : new Error(String(error));
4196
- errorMessage = handlerError.message;
4530
+ errorMessage = toolFailureMessage(handlerError);
4197
4531
  if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) await this._internal.emitError({
4198
4532
  error: handlerError,
4199
4533
  code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,
@@ -4219,14 +4553,14 @@ var RunHandler = class {
4219
4553
  }
4220
4554
  {
4221
4555
  const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
4222
- 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;
4223
- let insertAt = messageIndex + 1;
4224
- while (insertAt < agent.messages.length && agent.messages[insertAt]?.role === "tool") insertAt++;
4556
+ 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;
4557
+ const insertAt = this.toolResultInsertionIndex(agent.messages, messageIndex, toolCall.id);
4225
4558
  const toolMessage = {
4226
4559
  id: (0, _copilotkit_shared.randomUUID)(),
4227
4560
  role: "tool",
4228
4561
  toolCallId: toolCall.id,
4229
- content: toolCallResult
4562
+ content: toolCallResult,
4563
+ ...errorMessage ? { error: errorMessage } : {}
4230
4564
  };
4231
4565
  agent.messages.splice(insertAt, 0, toolMessage);
4232
4566
  if (!errorMessage && wildcardTool?.followUp !== false) return true;
@@ -4301,7 +4635,8 @@ var RunHandler = class {
4301
4635
  id: (0, _copilotkit_shared.randomUUID)(),
4302
4636
  role: "tool",
4303
4637
  toolCallId,
4304
- content: handlerResult.content
4638
+ content: handlerResult.content,
4639
+ ...handlerResult.error ? { error: handlerResult.error } : {}
4305
4640
  };
4306
4641
  const assistantIndex = agent.messages.findIndex((m) => m.id === assistantMessage.id);
4307
4642
  if (assistantIndex !== -1) agent.messages.splice(assistantIndex + 1, 0, toolResultMessage);
@@ -4383,7 +4718,7 @@ var RunHandler = class {
4383
4718
  /**
4384
4719
  * Create an agent error subscriber
4385
4720
  */
4386
- createAgentErrorSubscriber(agent) {
4721
+ createAgentErrorSubscriber(agent, runSignal) {
4387
4722
  const emitAgentError = async (error, code, extraContext = {}) => {
4388
4723
  const context = { ...extraContext };
4389
4724
  if (agent.agentId) context.agentId = agent.agentId;
@@ -4398,7 +4733,14 @@ var RunHandler = class {
4398
4733
  await emitAgentError(error, error instanceof AgentThreadLockedError ? CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED : CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT, { source: "onRunFailed" });
4399
4734
  },
4400
4735
  onRunErrorEvent: async ({ event }) => {
4401
- if (this._runAbortController?.signal.aborted === true || event?.code === "abort") return;
4736
+ if ((runSignal?.aborted ?? false) || event?.code === "abort") return;
4737
+ if (event?.code === _copilotkit_shared.THREAD_ALREADY_RUNNING_ERROR_CODE) {
4738
+ await emitAgentError(new AgentThreadLockedError(agent.threadId), CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED, {
4739
+ source: "onRunErrorEvent",
4740
+ event
4741
+ });
4742
+ return;
4743
+ }
4402
4744
  const eventError = event?.rawEvent instanceof Error ? event.rawEvent : event?.rawEvent?.error instanceof Error ? event.rawEvent.error : void 0;
4403
4745
  const errorMessage = typeof event?.rawEvent?.error === "string" ? event.rawEvent.error : event?.message ?? "Agent run error";
4404
4746
  const rawError = eventError ?? new Error(errorMessage);
@@ -5421,6 +5763,17 @@ var LearningBridge = class {
5421
5763
  get isConfigured() {
5422
5764
  return this.config !== void 0;
5423
5765
  }
5766
+ /**
5767
+ * Whether events may carry agent message text: not when the capture's config
5768
+ * sets `capture.agentText` to false. A running custom-sink capture keeps the
5769
+ * choice it started with; otherwise the current config decides.
5770
+ */
5771
+ get capturesAgentText() {
5772
+ const config = this.activeConfig ?? this.config;
5773
+ if (config === void 0) return false;
5774
+ const capture = config.capture;
5775
+ return !(typeof capture === "object" && capture !== null && capture.agentText === false);
5776
+ }
5424
5777
  get isLegacyCaptureActive() {
5425
5778
  return this.collector !== null && this.collector.trajectoryId !== null;
5426
5779
  }
@@ -5526,13 +5879,19 @@ var LearningBridge = class {
5526
5879
  this.toolCalls.clear();
5527
5880
  this.executingTools.clear();
5528
5881
  }
5529
- /** A developer event. Only an explicit legacy sink adds open-Thread context. */
5882
+ /**
5883
+ * A developer event. Only an explicit legacy sink adds open-Thread context;
5884
+ * an event that names its own Thread gets no ambiguity next to it.
5885
+ */
5530
5886
  emit(name, value) {
5531
5887
  this.connection.emit(name, value);
5532
- if (value !== null && typeof value === "object" && !Array.isArray(value)) this.collector?.emit(name, {
5533
- ...this.openThreadContext(),
5534
- ...value
5535
- });
5888
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
5889
+ const context = typeof value["threadId"] === "string" ? {} : this.openThreadContext();
5890
+ this.collector?.emit(name, {
5891
+ ...context,
5892
+ ...value
5893
+ });
5894
+ }
5536
5895
  }
5537
5896
  registerOpenThread(params) {
5538
5897
  const entry = { ...params };
@@ -5613,7 +5972,7 @@ var LearningBridge = class {
5613
5972
  }
5614
5973
  emitMessage(agent, message) {
5615
5974
  const content = typeof message.content === "string" ? message.content : "";
5616
- const includeText = this.activeConfig?.capture?.agentText !== false && typeof message.content === "string";
5975
+ const includeText = this.capturesAgentText && typeof message.content === "string";
5617
5976
  this.collector?.ɵemit("agent.message", {
5618
5977
  messageId: message.id,
5619
5978
  runId: this.runIdForMessage(agent, message.id),
@@ -7239,6 +7598,15 @@ var CopilotKitCore = class {
7239
7598
  get ɵlearningConfigured() {
7240
7599
  return this.learningBridge.isConfigured;
7241
7600
  }
7601
+ /**
7602
+ * @internal Whether captured events may carry agent message text: false
7603
+ * without a `learning` config, or when a custom sink sets
7604
+ * `capture.agentText` to false. A running custom-sink capture keeps the
7605
+ * choice it started with.
7606
+ */
7607
+ get ɵlearningCapturesAgentText() {
7608
+ return this.learningBridge.capturesAgentText;
7609
+ }
7242
7610
  /** @internal Calls `listener` when {@link ɵlearningConfigured} changes. */
7243
7611
  ɵsubscribeToLearningConfigured(listener) {
7244
7612
  this.learningConfiguredListeners.add(listener);