@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.cjs +450 -130
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +48 -36
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +48 -36
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +452 -131
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +450 -139
- package/dist/index.umd.js.map +1 -1
- package/package.json +5 -5
package/dist/index.cjs
CHANGED
|
@@ -26,15 +26,6 @@ function ɵisHttpAgent(agent) {
|
|
|
26
26
|
|
|
27
27
|
//#endregion
|
|
28
28
|
//#region src/utils/connect-replay.ts
|
|
29
|
-
const connectRunErrorPhases = /* @__PURE__ */ new WeakMap();
|
|
30
|
-
/**
|
|
31
|
-
* The phase in which a connection received `event`, as recorded when it
|
|
32
|
-
* arrived. Events that did not come through a connection with replay
|
|
33
|
-
* boundaries report `unknown`.
|
|
34
|
-
*/
|
|
35
|
-
function ɵgetConnectRunErrorPhase(event) {
|
|
36
|
-
return connectRunErrorPhases.get(event) ?? "unknown";
|
|
37
|
-
}
|
|
38
29
|
/**
|
|
39
30
|
* Runs an agent's `connect()` stream through the AbstractAgent apply pipeline
|
|
40
31
|
* with the `verifyEvents` step omitted.
|
|
@@ -89,7 +80,6 @@ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber,
|
|
|
89
80
|
let result;
|
|
90
81
|
const previousMessageIds = new Set(agent.messages.map((m) => m.id));
|
|
91
82
|
let isReplaying = true;
|
|
92
|
-
let reportsReplayPhase = false;
|
|
93
83
|
const liveErrors = /* @__PURE__ */ new WeakSet();
|
|
94
84
|
const subscribers = [
|
|
95
85
|
{
|
|
@@ -137,19 +127,15 @@ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber,
|
|
|
137
127
|
};
|
|
138
128
|
const lifecycle = {
|
|
139
129
|
onReplayStarted: () => {
|
|
140
|
-
reportsReplayPhase = true;
|
|
141
130
|
isReplaying = true;
|
|
142
131
|
agent.isRunning = true;
|
|
143
132
|
},
|
|
144
133
|
onReplayFinished: () => {
|
|
145
|
-
reportsReplayPhase = true;
|
|
146
134
|
isReplaying = false;
|
|
147
135
|
}
|
|
148
136
|
};
|
|
149
137
|
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) => {
|
|
150
|
-
if (event.type
|
|
151
|
-
if (!isReplaying) liveErrors.add(event);
|
|
152
|
-
if (reportsReplayPhase) connectRunErrorPhases.set(event, isReplaying ? "replay" : "live");
|
|
138
|
+
if (!isReplaying && event.type === _ag_ui_client.EventType.RUN_ERROR) liveErrors.add(event);
|
|
153
139
|
}), (0, _ag_ui_client.transformChunks)(self.debugLogger), (0, rxjs_operators.takeUntil)(activeRunDetach$));
|
|
154
140
|
const applied$ = self.apply(input, source$, subscribers);
|
|
155
141
|
await (0, rxjs.lastValueFrom)(self.processApplyEvents(input, applied$, subscribers).pipe((0, rxjs_operators.catchError)((error) => {
|
|
@@ -316,20 +302,6 @@ var AgentThreadLockedError = class extends Error {
|
|
|
316
302
|
}
|
|
317
303
|
};
|
|
318
304
|
/**
|
|
319
|
-
* The gateway could not replay a live run's events, so the client cannot
|
|
320
|
-
* verify the run it is following. The run itself may still be going on the
|
|
321
|
-
* server; reconnecting to the thread shows its real state.
|
|
322
|
-
*/
|
|
323
|
-
var IntelligenceReplayFailedError = class extends Error {
|
|
324
|
-
code = "INTELLIGENCE_REPLAY_FAILED";
|
|
325
|
-
constructor(threadId, runId) {
|
|
326
|
-
super("The run's events could not be replayed. Reconnect to the thread to check the run's status.");
|
|
327
|
-
this.threadId = threadId;
|
|
328
|
-
this.runId = runId;
|
|
329
|
-
this.name = "IntelligenceReplayFailedError";
|
|
330
|
-
}
|
|
331
|
-
};
|
|
332
|
-
/**
|
|
333
305
|
* Type guard for {@link RunCompletionAware}. Returns true when `agent` exposes
|
|
334
306
|
* an `activeRunCompletionPromise` property, so callers can await an in-flight
|
|
335
307
|
* run without an `as unknown as` cast. Returns false for agents that don't
|
|
@@ -655,7 +627,6 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
|
|
|
655
627
|
};
|
|
656
628
|
const replayFailed$ = channel$.pipe((0, rxjs_operators.switchMap)(({ channel }) => this.observeChannelEvent$(channel, REPLAY_FAILED_EVENT)), (0, rxjs_operators.tap)(() => {
|
|
657
629
|
controlCursor.replayFailed = true;
|
|
658
|
-
if (options.streamMode === "run") throw new IntelligenceReplayFailedError(credentials.threadId, credentials.runId);
|
|
659
630
|
}));
|
|
660
631
|
const replayComplete$ = this.observeControlEvent$(input.threadId, channel$, REPLAY_COMPLETE_EVENT, controlCursor).pipe((0, rxjs_operators.tap)(() => {
|
|
661
632
|
replayFinished = true;
|
|
@@ -884,6 +855,7 @@ function ɵrepairToolCallPairs(kept, full) {
|
|
|
884
855
|
}
|
|
885
856
|
const repaired = [];
|
|
886
857
|
const emitted = /* @__PURE__ */ new Set();
|
|
858
|
+
const expandedMessages = /* @__PURE__ */ new Set();
|
|
887
859
|
const emit = (message) => {
|
|
888
860
|
if (emitted.has(message.id)) return;
|
|
889
861
|
emitted.add(message.id);
|
|
@@ -892,6 +864,8 @@ function ɵrepairToolCallPairs(kept, full) {
|
|
|
892
864
|
/** Emit an assistant turn together with every result it is owed. */
|
|
893
865
|
const emitWithResults = (message) => {
|
|
894
866
|
emit(message);
|
|
867
|
+
if (expandedMessages.has(message)) return;
|
|
868
|
+
expandedMessages.add(message);
|
|
895
869
|
for (const callId of toolCallIdsOf(message)) {
|
|
896
870
|
const result = callIdToResult.get(callId);
|
|
897
871
|
if (result) emit(result);
|
|
@@ -912,6 +886,198 @@ function ɵrepairToolCallPairs(kept, full) {
|
|
|
912
886
|
}
|
|
913
887
|
return repaired;
|
|
914
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
|
+
}
|
|
915
1081
|
|
|
916
1082
|
//#endregion
|
|
917
1083
|
//#region src/agent.ts
|
|
@@ -1054,7 +1220,21 @@ var ProxiedCopilotRuntimeAgent = class ProxiedCopilotRuntimeAgent extends _ag_ui
|
|
|
1054
1220
|
this._messageFilter = filter;
|
|
1055
1221
|
}
|
|
1056
1222
|
/**
|
|
1057
|
-
*
|
|
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.
|
|
1058
1238
|
*
|
|
1059
1239
|
* **Called from the HTTP paths only, and that placement is the Intelligence
|
|
1060
1240
|
* exemption.** An earlier revision applied the filter in
|
|
@@ -1077,28 +1257,83 @@ var ProxiedCopilotRuntimeAgent = class ProxiedCopilotRuntimeAgent extends _ag_ui
|
|
|
1077
1257
|
* cannot reach the messages the UI renders no matter what it does with the
|
|
1078
1258
|
* array it is handed. The filter gets a *second* deep clone on top of that,
|
|
1079
1259
|
* because `input.messages` is also the repair baseline and the untrimmed
|
|
1080
|
-
* fallback: sharing the message objects let a filter that
|
|
1081
|
-
*
|
|
1082
|
-
* then went out
|
|
1083
|
-
* exactly the failure this whole mechanism
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
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 ?? "";
|
|
1088
1270
|
try {
|
|
1089
|
-
const
|
|
1090
|
-
if (!Array.isArray(kept)) {
|
|
1091
|
-
console.warn("ProxiedCopilotRuntimeAgent: messageFilter returned a non-array value; sending the full message history instead.");
|
|
1092
|
-
return input;
|
|
1093
|
-
}
|
|
1271
|
+
const messages = kept === void 0 ? ɵkeepToolResultsWithCalls(full) : ɵrepairToolCallPairs(kept, full);
|
|
1094
1272
|
return {
|
|
1095
1273
|
...input,
|
|
1096
|
-
messages
|
|
1274
|
+
messages
|
|
1097
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 ?? "" });
|
|
1098
1321
|
} catch (error) {
|
|
1099
1322
|
console.warn("ProxiedCopilotRuntimeAgent: messageFilter failed; sending the full message history instead.", error);
|
|
1100
|
-
return
|
|
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
|
+
}
|
|
1101
1335
|
}
|
|
1336
|
+
return kept;
|
|
1102
1337
|
}
|
|
1103
1338
|
requestInit(input) {
|
|
1104
1339
|
return {
|
|
@@ -1256,7 +1491,7 @@ var ProxiedCopilotRuntimeAgent = class ProxiedCopilotRuntimeAgent extends _ag_ui
|
|
|
1256
1491
|
return (0, rxjs.defer)(() => (0, rxjs.from)(this.resolveDelegate())).pipe((0, rxjs_operators.switchMap)((delegate) => withAbortErrorHandling(delegate.connect(input, lifecycle))));
|
|
1257
1492
|
}
|
|
1258
1493
|
#connectViaHttp(unfiltered) {
|
|
1259
|
-
const input = this.#
|
|
1494
|
+
const input = this.#prepareOutboundMessages(unfiltered);
|
|
1260
1495
|
this.activeRun = void 0;
|
|
1261
1496
|
const routedId = this.routedAgentId();
|
|
1262
1497
|
let httpEvents;
|
|
@@ -1289,7 +1524,7 @@ var ProxiedCopilotRuntimeAgent = class ProxiedCopilotRuntimeAgent extends _ag_ui
|
|
|
1289
1524
|
return (0, rxjs.defer)(() => (0, rxjs.from)(this.resolveDelegate())).pipe((0, rxjs_operators.switchMap)((delegate) => withAbortErrorHandling(delegate.run(input))));
|
|
1290
1525
|
}
|
|
1291
1526
|
#runViaHttp(unfiltered) {
|
|
1292
|
-
const input = this.#
|
|
1527
|
+
const input = this.#prepareOutboundMessages(unfiltered);
|
|
1293
1528
|
const activeRun = {
|
|
1294
1529
|
threadId: input.threadId,
|
|
1295
1530
|
runId: input.runId
|
|
@@ -3481,15 +3716,12 @@ var WebMCPRegistry = class {
|
|
|
3481
3716
|
*/
|
|
3482
3717
|
const liveHITLStops = /* @__PURE__ */ new WeakMap();
|
|
3483
3718
|
/**
|
|
3484
|
-
*
|
|
3485
|
-
*
|
|
3486
|
-
*
|
|
3487
|
-
* edit it replaces, this notifies no subscriber.
|
|
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.
|
|
3488
3722
|
*/
|
|
3489
|
-
function
|
|
3490
|
-
|
|
3491
|
-
edit(messages);
|
|
3492
|
-
agent.messages = messages;
|
|
3723
|
+
function toolFailureMessage(error) {
|
|
3724
|
+
return error.message || "Tool call failed";
|
|
3493
3725
|
}
|
|
3494
3726
|
function discardAbortedResult(signal, discardOnAbort, errorMessage) {
|
|
3495
3727
|
return !!(discardOnAbort && signal?.aborted && !(liveHITLStops.get(signal)?.() && errorMessage));
|
|
@@ -3570,18 +3802,28 @@ var RunHandler = class {
|
|
|
3570
3802
|
*/
|
|
3571
3803
|
_warnedMissingToolParameters = /* @__PURE__ */ new Set();
|
|
3572
3804
|
/**
|
|
3573
|
-
*
|
|
3574
|
-
*
|
|
3575
|
-
*
|
|
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.
|
|
3576
3812
|
*/
|
|
3577
|
-
|
|
3813
|
+
_runAbortControllers = /* @__PURE__ */ new WeakMap();
|
|
3578
3814
|
/**
|
|
3579
|
-
*
|
|
3580
|
-
* `agent.abortRun()` intercept
|
|
3581
|
-
*
|
|
3582
|
-
* `
|
|
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`.
|
|
3583
3819
|
*/
|
|
3584
|
-
|
|
3820
|
+
_runDepths = /* @__PURE__ */ new WeakMap();
|
|
3821
|
+
/**
|
|
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.
|
|
3825
|
+
*/
|
|
3826
|
+
_originalAbortRuns = /* @__PURE__ */ new WeakMap();
|
|
3585
3827
|
/**
|
|
3586
3828
|
* Keeps tools that opt in via `webmcp` registered on the page's WebMCP model
|
|
3587
3829
|
* context (`document.modelContext`), in addition to the normal agent
|
|
@@ -3621,7 +3863,7 @@ var RunHandler = class {
|
|
|
3621
3863
|
* not start a follow-up run.
|
|
3622
3864
|
*/
|
|
3623
3865
|
abortCurrentRun(agent) {
|
|
3624
|
-
this.
|
|
3866
|
+
this.abortAgentRuns(agent);
|
|
3625
3867
|
const replay = this._interactionAbortControllers.get(agent);
|
|
3626
3868
|
if (replay) {
|
|
3627
3869
|
for (const controller of replay.controllers) controller.abort();
|
|
@@ -3629,6 +3871,15 @@ var RunHandler = class {
|
|
|
3629
3871
|
this._executingToolCalls.delete(agent);
|
|
3630
3872
|
}
|
|
3631
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
|
+
}
|
|
3632
3883
|
/**
|
|
3633
3884
|
* Typed access to CopilotKitCore's internal ("friend") methods.
|
|
3634
3885
|
* Centralises the single unavoidable cast so call-sites stay clean.
|
|
@@ -3827,7 +4078,7 @@ var RunHandler = class {
|
|
|
3827
4078
|
forwardedProps: this._internal.properties,
|
|
3828
4079
|
tools: this.buildFrontendTools(agent.agentId),
|
|
3829
4080
|
context: this._internal.getContextForAgent(agent.agentId)
|
|
3830
|
-
}, this.createAgentErrorSubscriber(agent
|
|
4081
|
+
}, this.createAgentErrorSubscriber(agent));
|
|
3831
4082
|
if (this._connectionGenerations.get(agent) !== connection || (agent.threadId ?? null) !== incomingThreadId) return runAgentResult;
|
|
3832
4083
|
const controller = new AbortController();
|
|
3833
4084
|
const replay = this._interactionAbortControllers.get(agent) ?? {
|
|
@@ -3876,7 +4127,7 @@ var RunHandler = class {
|
|
|
3876
4127
|
/**
|
|
3877
4128
|
* Run an agent
|
|
3878
4129
|
*/
|
|
3879
|
-
async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff) {
|
|
4130
|
+
async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff, followUpOf) {
|
|
3880
4131
|
if (agent.agentId) this._internal.suggestionEngine.clearSuggestions(agent.agentId);
|
|
3881
4132
|
try {
|
|
3882
4133
|
const headersApplied = this._internal.prepareAgentHeadersForRun(agent);
|
|
@@ -3900,25 +4151,30 @@ var RunHandler = class {
|
|
|
3900
4151
|
forwardedProps
|
|
3901
4152
|
});
|
|
3902
4153
|
const logicalHandoff = continuationHandoff ?? (resumedRunId ? this._internal.stateManager.markNextRunAsContinuation(agent, resumedRunId) : void 0);
|
|
3903
|
-
const
|
|
3904
|
-
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
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);
|
|
3909
4166
|
agent.abortRun = () => {
|
|
3910
|
-
|
|
3911
|
-
originalAbortRun();
|
|
4167
|
+
this.abortAgentRuns(agent);
|
|
4168
|
+
originalAbortRun.call(agent);
|
|
3912
4169
|
};
|
|
3913
|
-
|
|
4170
|
+
}
|
|
4171
|
+
try {
|
|
4172
|
+
if (depth === 0) await this._internal.notifySubscribers((subscriber) => subscriber.onAgentRunStarted?.({
|
|
3914
4173
|
copilotkit: this.core,
|
|
3915
4174
|
agent
|
|
3916
4175
|
}), "Subscriber onAgentRunStarted error:");
|
|
3917
|
-
}
|
|
3918
|
-
this._runDepth++;
|
|
3919
|
-
try {
|
|
3920
4176
|
let logicalRunId = resumedRunId ?? runId;
|
|
3921
|
-
const agentSubscriber = this.createAgentErrorSubscriber(agent,
|
|
4177
|
+
const agentSubscriber = this.createAgentErrorSubscriber(agent, controller.signal);
|
|
3922
4178
|
let started = false;
|
|
3923
4179
|
const onRunStartedEvent = agentSubscriber.onRunStartedEvent;
|
|
3924
4180
|
const onRunInitialized = agentSubscriber.onRunInitialized;
|
|
@@ -3948,7 +4204,8 @@ var RunHandler = class {
|
|
|
3948
4204
|
return await this.processAgentResult({
|
|
3949
4205
|
runAgentResult,
|
|
3950
4206
|
agent,
|
|
3951
|
-
runId: logicalRunId
|
|
4207
|
+
runId: logicalRunId,
|
|
4208
|
+
runController: controller
|
|
3952
4209
|
});
|
|
3953
4210
|
} catch (error) {
|
|
3954
4211
|
logicalHandoff?.cancel();
|
|
@@ -3965,22 +4222,34 @@ var RunHandler = class {
|
|
|
3965
4222
|
newMessages: []
|
|
3966
4223
|
};
|
|
3967
4224
|
} finally {
|
|
3968
|
-
this.
|
|
3969
|
-
|
|
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
|
+
}
|
|
3970
4239
|
}
|
|
3971
4240
|
}
|
|
3972
4241
|
/**
|
|
3973
4242
|
* Process agent result and execute tools
|
|
3974
4243
|
*/
|
|
3975
|
-
async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", signal =
|
|
4244
|
+
async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", runController, signal = runController?.signal }) {
|
|
3976
4245
|
const { newMessages } = runAgentResult;
|
|
3977
4246
|
const agentId = agent.agentId;
|
|
3978
4247
|
let needsFollowUp = false;
|
|
3979
4248
|
const threadId = agent.threadId;
|
|
3980
4249
|
const executing = this._executingToolCalls.get(agent) ?? /* @__PURE__ */ new Set();
|
|
3981
4250
|
this._executingToolCalls.set(agent, executing);
|
|
3982
|
-
|
|
3983
|
-
|
|
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;
|
|
3984
4253
|
for (const message of messagesToProcess) if (message.role === "assistant") for (const toolCall of message.toolCalls || []) {
|
|
3985
4254
|
const tool = this.getTool({
|
|
3986
4255
|
toolName: toolCall.function.name,
|
|
@@ -3996,16 +4265,16 @@ var RunHandler = class {
|
|
|
3996
4265
|
return wildcardTool;
|
|
3997
4266
|
};
|
|
3998
4267
|
const executableTool = tool ?? getWildcardTool();
|
|
3999
|
-
if (toolExecutionMode === "restore" && (!executableTool
|
|
4268
|
+
if (toolExecutionMode === "restore" && (!executableTool || executableTool.handler && executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
|
|
4000
4269
|
const executionKey = JSON.stringify([threadId, toolCall.id]);
|
|
4001
|
-
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;
|
|
4002
4271
|
const existingResultIndex = newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
|
|
4003
4272
|
let existingResult = agent.messages.find((m) => m.role === "tool" && m.toolCallId === toolCall.id) ?? newMessages[existingResultIndex];
|
|
4004
|
-
if (existingResult &&
|
|
4273
|
+
if (existingResult && this.isFrontendPlaceholderResult(existingResult) && (toolExecutionMode === "restore" || executableTool?.handler)) {
|
|
4005
4274
|
if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
|
|
4006
4275
|
existingResult = void 0;
|
|
4007
4276
|
const agentMsgIdx = agent.messages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
|
|
4008
|
-
if (agentMsgIdx !== -1)
|
|
4277
|
+
if (agentMsgIdx !== -1) agent.messages.splice(agentMsgIdx, 1);
|
|
4009
4278
|
}
|
|
4010
4279
|
if (!existingResult) {
|
|
4011
4280
|
executing.add(executionKey);
|
|
@@ -4048,18 +4317,43 @@ var RunHandler = class {
|
|
|
4048
4317
|
if (interactionController?.signal.aborted) return runAgentResult;
|
|
4049
4318
|
}
|
|
4050
4319
|
}
|
|
4051
|
-
if (needsFollowUp && agent.threadId === threadId && !signal?.aborted) if (this.
|
|
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.`);
|
|
4052
4321
|
else {
|
|
4053
4322
|
await this._internal.waitForPendingFrameworkUpdates();
|
|
4323
|
+
if (toolExecutionMode === "restore" && !messagesToProcess.some((message) => this.isInLatestUserTurn(agent.messages, message.id))) return runAgentResult;
|
|
4054
4324
|
const continuationHandoff = this._internal.stateManager.markNextRunAsContinuation(agent, runId);
|
|
4055
4325
|
return await this.runAgent({
|
|
4056
4326
|
agent,
|
|
4057
4327
|
...runId !== void 0 ? { runId } : {}
|
|
4058
|
-
}, continuationHandoff);
|
|
4328
|
+
}, continuationHandoff, runController);
|
|
4059
4329
|
}
|
|
4060
4330
|
this._internal.suggestionEngine.reloadSuggestions(agentId);
|
|
4061
4331
|
return runAgentResult;
|
|
4062
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. */
|
|
4063
4357
|
isFrontendPlaceholderResult(message) {
|
|
4064
4358
|
return message.role === "tool" && isForwardedToClientPlaceholder(message.content);
|
|
4065
4359
|
}
|
|
@@ -4068,7 +4362,7 @@ var RunHandler = class {
|
|
|
4068
4362
|
* Handles arg parsing, subscriber notifications, handler invocation, result stringification,
|
|
4069
4363
|
* and error handling.
|
|
4070
4364
|
*/
|
|
4071
|
-
async executeToolHandler({ tool, toolCall, agent, agentId, handlerArgs, toolType, messageId, signal = this.
|
|
4365
|
+
async executeToolHandler({ tool, toolCall, agent, agentId, handlerArgs, toolType, messageId, signal = this.latestRunSignal(agent), discardOnAbort = false, isReplay = false }) {
|
|
4072
4366
|
let toolCallResult = "";
|
|
4073
4367
|
let toolCallText = "";
|
|
4074
4368
|
let errorMessage;
|
|
@@ -4078,7 +4372,7 @@ var RunHandler = class {
|
|
|
4078
4372
|
parsedArgs = parseToolArguments(handlerArgs, toolCall.function.name);
|
|
4079
4373
|
} catch (error) {
|
|
4080
4374
|
const parseError = error instanceof Error ? error : new Error(String(error));
|
|
4081
|
-
errorMessage = parseError
|
|
4375
|
+
errorMessage = toolFailureMessage(parseError);
|
|
4082
4376
|
isArgumentError = true;
|
|
4083
4377
|
await this._internal.emitError({
|
|
4084
4378
|
error: parseError,
|
|
@@ -4110,7 +4404,7 @@ var RunHandler = class {
|
|
|
4110
4404
|
({content: toolCallResult, text: toolCallText} = toToolResultContent(result));
|
|
4111
4405
|
} catch (error) {
|
|
4112
4406
|
const handlerError = error instanceof Error ? error : new Error(String(error));
|
|
4113
|
-
errorMessage = handlerError
|
|
4407
|
+
errorMessage = toolFailureMessage(handlerError);
|
|
4114
4408
|
if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) await this._internal.emitError({
|
|
4115
4409
|
error: handlerError,
|
|
4116
4410
|
code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,
|
|
@@ -4166,16 +4460,16 @@ var RunHandler = class {
|
|
|
4166
4460
|
});
|
|
4167
4461
|
{
|
|
4168
4462
|
const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
|
|
4169
|
-
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;
|
|
4170
|
-
|
|
4171
|
-
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);
|
|
4172
4465
|
const toolMessage = {
|
|
4173
4466
|
id: (0, _copilotkit_shared.randomUUID)(),
|
|
4174
4467
|
role: "tool",
|
|
4175
4468
|
toolCallId: toolCall.id,
|
|
4176
|
-
content: handlerResult.content
|
|
4469
|
+
content: handlerResult.content,
|
|
4470
|
+
...handlerResult.error ? { error: handlerResult.error } : {}
|
|
4177
4471
|
};
|
|
4178
|
-
|
|
4472
|
+
agent.messages.splice(insertAt, 0, toolMessage);
|
|
4179
4473
|
if (!handlerResult.error && tool?.followUp !== false) return true;
|
|
4180
4474
|
}
|
|
4181
4475
|
return false;
|
|
@@ -4198,7 +4492,7 @@ var RunHandler = class {
|
|
|
4198
4492
|
parsedArgs = parseToolArguments(toolCall.function.arguments, toolCall.function.name);
|
|
4199
4493
|
} catch (error) {
|
|
4200
4494
|
const parseError = error instanceof Error ? error : new Error(String(error));
|
|
4201
|
-
errorMessage = parseError
|
|
4495
|
+
errorMessage = toolFailureMessage(parseError);
|
|
4202
4496
|
await this._internal.emitError({
|
|
4203
4497
|
error: parseError,
|
|
4204
4498
|
code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,
|
|
@@ -4233,7 +4527,7 @@ var RunHandler = class {
|
|
|
4233
4527
|
({content: toolCallResult, text: toolCallText} = toToolResultContent(result));
|
|
4234
4528
|
} catch (error) {
|
|
4235
4529
|
const handlerError = error instanceof Error ? error : new Error(String(error));
|
|
4236
|
-
errorMessage = handlerError
|
|
4530
|
+
errorMessage = toolFailureMessage(handlerError);
|
|
4237
4531
|
if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) await this._internal.emitError({
|
|
4238
4532
|
error: handlerError,
|
|
4239
4533
|
code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,
|
|
@@ -4259,16 +4553,16 @@ var RunHandler = class {
|
|
|
4259
4553
|
}
|
|
4260
4554
|
{
|
|
4261
4555
|
const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
|
|
4262
|
-
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;
|
|
4263
|
-
|
|
4264
|
-
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);
|
|
4265
4558
|
const toolMessage = {
|
|
4266
4559
|
id: (0, _copilotkit_shared.randomUUID)(),
|
|
4267
4560
|
role: "tool",
|
|
4268
4561
|
toolCallId: toolCall.id,
|
|
4269
|
-
content: toolCallResult
|
|
4562
|
+
content: toolCallResult,
|
|
4563
|
+
...errorMessage ? { error: errorMessage } : {}
|
|
4270
4564
|
};
|
|
4271
|
-
|
|
4565
|
+
agent.messages.splice(insertAt, 0, toolMessage);
|
|
4272
4566
|
if (!errorMessage && wildcardTool?.followUp !== false) return true;
|
|
4273
4567
|
}
|
|
4274
4568
|
return false;
|
|
@@ -4322,7 +4616,7 @@ var RunHandler = class {
|
|
|
4322
4616
|
content: "",
|
|
4323
4617
|
toolCalls: [assistantToolCall]
|
|
4324
4618
|
};
|
|
4325
|
-
|
|
4619
|
+
agent.messages.push(assistantMessage);
|
|
4326
4620
|
let handlerResult = {
|
|
4327
4621
|
content: "",
|
|
4328
4622
|
result: "",
|
|
@@ -4341,11 +4635,12 @@ var RunHandler = class {
|
|
|
4341
4635
|
id: (0, _copilotkit_shared.randomUUID)(),
|
|
4342
4636
|
role: "tool",
|
|
4343
4637
|
toolCallId,
|
|
4344
|
-
content: handlerResult.content
|
|
4638
|
+
content: handlerResult.content,
|
|
4639
|
+
...handlerResult.error ? { error: handlerResult.error } : {}
|
|
4345
4640
|
};
|
|
4346
4641
|
const assistantIndex = agent.messages.findIndex((m) => m.id === assistantMessage.id);
|
|
4347
|
-
if (assistantIndex !== -1)
|
|
4348
|
-
else
|
|
4642
|
+
if (assistantIndex !== -1) agent.messages.splice(assistantIndex + 1, 0, toolResultMessage);
|
|
4643
|
+
else agent.messages.push(toolResultMessage);
|
|
4349
4644
|
if (!handlerResult.error && followUp !== false) {
|
|
4350
4645
|
if (typeof followUp === "string" && followUp !== "generate") {
|
|
4351
4646
|
const userMessage = {
|
|
@@ -4353,7 +4648,7 @@ var RunHandler = class {
|
|
|
4353
4648
|
role: "user",
|
|
4354
4649
|
content: followUp
|
|
4355
4650
|
};
|
|
4356
|
-
|
|
4651
|
+
agent.messages.push(userMessage);
|
|
4357
4652
|
}
|
|
4358
4653
|
await this._internal.waitForPendingFrameworkUpdates();
|
|
4359
4654
|
await this.runAgent({ agent });
|
|
@@ -4423,7 +4718,7 @@ var RunHandler = class {
|
|
|
4423
4718
|
/**
|
|
4424
4719
|
* Create an agent error subscriber
|
|
4425
4720
|
*/
|
|
4426
|
-
createAgentErrorSubscriber(agent,
|
|
4721
|
+
createAgentErrorSubscriber(agent, runSignal) {
|
|
4427
4722
|
const emitAgentError = async (error, code, extraContext = {}) => {
|
|
4428
4723
|
const context = { ...extraContext };
|
|
4429
4724
|
if (agent.agentId) context.agentId = agent.agentId;
|
|
@@ -4438,7 +4733,14 @@ var RunHandler = class {
|
|
|
4438
4733
|
await emitAgentError(error, error instanceof AgentThreadLockedError ? CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED : CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT, { source: "onRunFailed" });
|
|
4439
4734
|
},
|
|
4440
4735
|
onRunErrorEvent: async ({ event }) => {
|
|
4441
|
-
if (
|
|
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
|
+
}
|
|
4442
4744
|
const eventError = event?.rawEvent instanceof Error ? event.rawEvent : event?.rawEvent?.error instanceof Error ? event.rawEvent.error : void 0;
|
|
4443
4745
|
const errorMessage = typeof event?.rawEvent?.error === "string" ? event.rawEvent.error : event?.message ?? "Agent run error";
|
|
4444
4746
|
const rawError = eventError ?? new Error(errorMessage);
|
|
@@ -4446,8 +4748,7 @@ var RunHandler = class {
|
|
|
4446
4748
|
await emitAgentError(rawError, CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT, {
|
|
4447
4749
|
source: "onRunErrorEvent",
|
|
4448
4750
|
event,
|
|
4449
|
-
runtimeErrorCode: event?.code
|
|
4450
|
-
phase: stream === "run" ? "live" : ɵgetConnectRunErrorPhase(event)
|
|
4751
|
+
runtimeErrorCode: event?.code
|
|
4451
4752
|
});
|
|
4452
4753
|
}
|
|
4453
4754
|
};
|
|
@@ -5462,6 +5763,17 @@ var LearningBridge = class {
|
|
|
5462
5763
|
get isConfigured() {
|
|
5463
5764
|
return this.config !== void 0;
|
|
5464
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
|
+
}
|
|
5465
5777
|
get isLegacyCaptureActive() {
|
|
5466
5778
|
return this.collector !== null && this.collector.trajectoryId !== null;
|
|
5467
5779
|
}
|
|
@@ -5567,13 +5879,19 @@ var LearningBridge = class {
|
|
|
5567
5879
|
this.toolCalls.clear();
|
|
5568
5880
|
this.executingTools.clear();
|
|
5569
5881
|
}
|
|
5570
|
-
/**
|
|
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
|
+
*/
|
|
5571
5886
|
emit(name, value) {
|
|
5572
5887
|
this.connection.emit(name, value);
|
|
5573
|
-
if (value !== null && typeof value === "object" && !Array.isArray(value))
|
|
5574
|
-
|
|
5575
|
-
|
|
5576
|
-
|
|
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
|
+
}
|
|
5577
5895
|
}
|
|
5578
5896
|
registerOpenThread(params) {
|
|
5579
5897
|
const entry = { ...params };
|
|
@@ -5654,7 +5972,7 @@ var LearningBridge = class {
|
|
|
5654
5972
|
}
|
|
5655
5973
|
emitMessage(agent, message) {
|
|
5656
5974
|
const content = typeof message.content === "string" ? message.content : "";
|
|
5657
|
-
const includeText = this.
|
|
5975
|
+
const includeText = this.capturesAgentText && typeof message.content === "string";
|
|
5658
5976
|
this.collector?.ɵemit("agent.message", {
|
|
5659
5977
|
messageId: message.id,
|
|
5660
5978
|
runId: this.runIdForMessage(agent, message.id),
|
|
@@ -6812,12 +7130,6 @@ let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode)
|
|
|
6812
7130
|
CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
|
|
6813
7131
|
CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
|
|
6814
7132
|
CopilotKitCoreErrorCode["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
|
|
6815
|
-
/**
|
|
6816
|
-
* An agent emitted RUN_ERROR. `context.phase` (`RunErrorPhase`) is
|
|
6817
|
-
* `"replay"` when the error belongs to stored thread history replayed on
|
|
6818
|
-
* connect, `"live"` when the run is happening now, and `"unknown"` when the
|
|
6819
|
-
* transport cannot tell. Show a live-failure notice only for `"live"`.
|
|
6820
|
-
*/
|
|
6821
7133
|
CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
|
|
6822
7134
|
CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
|
|
6823
7135
|
CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
|
|
@@ -7286,6 +7598,15 @@ var CopilotKitCore = class {
|
|
|
7286
7598
|
get ɵlearningConfigured() {
|
|
7287
7599
|
return this.learningBridge.isConfigured;
|
|
7288
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
|
+
}
|
|
7289
7610
|
/** @internal Calls `listener` when {@link ɵlearningConfigured} changes. */
|
|
7290
7611
|
ɵsubscribeToLearningConfigured(listener) {
|
|
7291
7612
|
this.learningConfiguredListeners.add(listener);
|
|
@@ -8888,7 +9209,6 @@ exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionS
|
|
|
8888
9209
|
exports.CopilotKitHeaderResolutionError = CopilotKitHeaderResolutionError;
|
|
8889
9210
|
exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
|
|
8890
9211
|
exports.IntelligenceAgent = IntelligenceAgent;
|
|
8891
|
-
exports.IntelligenceReplayFailedError = IntelligenceReplayFailedError;
|
|
8892
9212
|
exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
|
|
8893
9213
|
exports.MemoryError = MemoryError;
|
|
8894
9214
|
exports.ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;
|