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