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