@copilotkit/core 1.79.2-canary.1792172552 → 1.81.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 +1828 -134
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +458 -37
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +458 -37
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1820 -135
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +1839 -143
- 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;
|
|
1101
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
|
+
}
|
|
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
|
|
@@ -2841,6 +3076,17 @@ var AgentRegistry = class {
|
|
|
2841
3076
|
}
|
|
2842
3077
|
};
|
|
2843
3078
|
|
|
3079
|
+
//#endregion
|
|
3080
|
+
//#region src/core/agent-scope.ts
|
|
3081
|
+
/**
|
|
3082
|
+
* True when an entry scoped to `agentIds` goes to a run of `agentId`. An
|
|
3083
|
+
* entry without `agentIds` goes to every agent; an entry with them does not
|
|
3084
|
+
* go to a run without an agent id. Internal, not exported.
|
|
3085
|
+
*/
|
|
3086
|
+
function isForAgent(agentIds, agentId) {
|
|
3087
|
+
return agentIds === void 0 || agentId !== void 0 && agentIds.includes(agentId);
|
|
3088
|
+
}
|
|
3089
|
+
|
|
2844
3090
|
//#endregion
|
|
2845
3091
|
//#region src/core/context-store.ts
|
|
2846
3092
|
/**
|
|
@@ -2879,7 +3125,7 @@ var ContextStore = class {
|
|
|
2879
3125
|
* protocol-shaped `{ description, value }` entries go over the wire.
|
|
2880
3126
|
*/
|
|
2881
3127
|
getContextForAgent(agentId) {
|
|
2882
|
-
return Object.values(this._context).filter((entry) =>
|
|
3128
|
+
return Object.values(this._context).filter((entry) => isForAgent(entry.agentIds, agentId)).map(({ description, value }) => ({
|
|
2883
3129
|
description,
|
|
2884
3130
|
value
|
|
2885
3131
|
}));
|
|
@@ -3064,7 +3310,7 @@ var SuggestionEngine = class {
|
|
|
3064
3310
|
await suggestionAgent.runAgent({
|
|
3065
3311
|
context: friends.getContextForAgent(consumerAgentId),
|
|
3066
3312
|
forwardedProps: {
|
|
3067
|
-
...friends.
|
|
3313
|
+
...friends.getPropertiesForAgent(consumerAgentId),
|
|
3068
3314
|
toolChoice: {
|
|
3069
3315
|
type: "function",
|
|
3070
3316
|
function: { name: "copilotkitSuggest" }
|
|
@@ -3481,15 +3727,12 @@ var WebMCPRegistry = class {
|
|
|
3481
3727
|
*/
|
|
3482
3728
|
const liveHITLStops = /* @__PURE__ */ new WeakMap();
|
|
3483
3729
|
/**
|
|
3484
|
-
*
|
|
3485
|
-
*
|
|
3486
|
-
*
|
|
3487
|
-
* edit it replaces, this notifies no subscriber.
|
|
3730
|
+
* The message a failed tool call reports. An error thrown with an empty
|
|
3731
|
+
* message still means the call failed, so it gets a fallback rather than an
|
|
3732
|
+
* empty string, which everything downstream reads as success.
|
|
3488
3733
|
*/
|
|
3489
|
-
function
|
|
3490
|
-
|
|
3491
|
-
edit(messages);
|
|
3492
|
-
agent.messages = messages;
|
|
3734
|
+
function toolFailureMessage(error) {
|
|
3735
|
+
return error.message || "Tool call failed";
|
|
3493
3736
|
}
|
|
3494
3737
|
function discardAbortedResult(signal, discardOnAbort, errorMessage) {
|
|
3495
3738
|
return !!(discardOnAbort && signal?.aborted && !(liveHITLStops.get(signal)?.() && errorMessage));
|
|
@@ -3570,18 +3813,28 @@ var RunHandler = class {
|
|
|
3570
3813
|
*/
|
|
3571
3814
|
_warnedMissingToolParameters = /* @__PURE__ */ new Set();
|
|
3572
3815
|
/**
|
|
3573
|
-
*
|
|
3574
|
-
*
|
|
3575
|
-
*
|
|
3816
|
+
* Abort controllers of each agent's in-flight run chains (a run plus its
|
|
3817
|
+
* recursive follow-ups), recording whether a chain, including its tool
|
|
3818
|
+
* execution, was aborted via `stopAgent()` or `agent.abortRun()`. Every run
|
|
3819
|
+
* that is not a follow-up gets a fresh controller, so a run started after
|
|
3820
|
+
* Stop is not born aborted while the stopped chain is still settling. Keyed
|
|
3821
|
+
* by agent so that stopping one agent never cancels another agent's run on
|
|
3822
|
+
* the same core.
|
|
3823
|
+
*/
|
|
3824
|
+
_runAbortControllers = /* @__PURE__ */ new WeakMap();
|
|
3825
|
+
/**
|
|
3826
|
+
* Per-agent `runAgent` depth (in-flight runs plus their recursive
|
|
3827
|
+
* follow-ups), so that the `agent.abortRun()` intercept is installed while
|
|
3828
|
+
* any of the agent's runs is in flight and removed once none is, and so
|
|
3829
|
+
* that runaway follow-up chains trip `MAX_FOLLOW_UP_DEPTH`.
|
|
3576
3830
|
*/
|
|
3577
|
-
|
|
3831
|
+
_runDepths = /* @__PURE__ */ new WeakMap();
|
|
3578
3832
|
/**
|
|
3579
|
-
*
|
|
3580
|
-
*
|
|
3581
|
-
*
|
|
3582
|
-
* `processAgentResult`.
|
|
3833
|
+
* Each agent's own `abortRun`, saved while RunHandler's intercept is
|
|
3834
|
+
* installed. Restored only once none of the agent's runs is in flight, so an
|
|
3835
|
+
* overlapping run keeps the intercept after an earlier run finishes.
|
|
3583
3836
|
*/
|
|
3584
|
-
|
|
3837
|
+
_originalAbortRuns = /* @__PURE__ */ new WeakMap();
|
|
3585
3838
|
/**
|
|
3586
3839
|
* Keeps tools that opt in via `webmcp` registered on the page's WebMCP model
|
|
3587
3840
|
* context (`document.modelContext`), in addition to the normal agent
|
|
@@ -3621,7 +3874,7 @@ var RunHandler = class {
|
|
|
3621
3874
|
* not start a follow-up run.
|
|
3622
3875
|
*/
|
|
3623
3876
|
abortCurrentRun(agent) {
|
|
3624
|
-
this.
|
|
3877
|
+
this.abortAgentRuns(agent);
|
|
3625
3878
|
const replay = this._interactionAbortControllers.get(agent);
|
|
3626
3879
|
if (replay) {
|
|
3627
3880
|
for (const controller of replay.controllers) controller.abort();
|
|
@@ -3629,6 +3882,15 @@ var RunHandler = class {
|
|
|
3629
3882
|
this._executingToolCalls.delete(agent);
|
|
3630
3883
|
}
|
|
3631
3884
|
}
|
|
3885
|
+
abortAgentRuns(agent) {
|
|
3886
|
+
for (const controller of this._runAbortControllers.get(agent) ?? []) controller.abort();
|
|
3887
|
+
}
|
|
3888
|
+
/** Signal of the agent's most recently started in-flight run, if any. */
|
|
3889
|
+
latestRunSignal(agent) {
|
|
3890
|
+
let latest;
|
|
3891
|
+
for (const controller of this._runAbortControllers.get(agent) ?? []) latest = controller;
|
|
3892
|
+
return latest?.signal;
|
|
3893
|
+
}
|
|
3632
3894
|
/**
|
|
3633
3895
|
* Typed access to CopilotKitCore's internal ("friend") methods.
|
|
3634
3896
|
* Centralises the single unavoidable cast so call-sites stay clean.
|
|
@@ -3824,10 +4086,10 @@ var RunHandler = class {
|
|
|
3824
4086
|
newMessages: []
|
|
3825
4087
|
};
|
|
3826
4088
|
const runAgentResult = await agent.connectAgent({
|
|
3827
|
-
forwardedProps: this._internal.
|
|
4089
|
+
forwardedProps: this._internal.getPropertiesForAgent(agent.agentId),
|
|
3828
4090
|
tools: this.buildFrontendTools(agent.agentId),
|
|
3829
4091
|
context: this._internal.getContextForAgent(agent.agentId)
|
|
3830
|
-
}, this.createAgentErrorSubscriber(agent
|
|
4092
|
+
}, this.createAgentErrorSubscriber(agent));
|
|
3831
4093
|
if (this._connectionGenerations.get(agent) !== connection || (agent.threadId ?? null) !== incomingThreadId) return runAgentResult;
|
|
3832
4094
|
const controller = new AbortController();
|
|
3833
4095
|
const replay = this._interactionAbortControllers.get(agent) ?? {
|
|
@@ -3876,7 +4138,7 @@ var RunHandler = class {
|
|
|
3876
4138
|
/**
|
|
3877
4139
|
* Run an agent
|
|
3878
4140
|
*/
|
|
3879
|
-
async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff) {
|
|
4141
|
+
async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff, followUpOf) {
|
|
3880
4142
|
if (agent.agentId) this._internal.suggestionEngine.clearSuggestions(agent.agentId);
|
|
3881
4143
|
try {
|
|
3882
4144
|
const headersApplied = this._internal.prepareAgentHeadersForRun(agent);
|
|
@@ -3900,25 +4162,30 @@ var RunHandler = class {
|
|
|
3900
4162
|
forwardedProps
|
|
3901
4163
|
});
|
|
3902
4164
|
const logicalHandoff = continuationHandoff ?? (resumedRunId ? this._internal.stateManager.markNextRunAsContinuation(agent, resumedRunId) : void 0);
|
|
3903
|
-
const
|
|
3904
|
-
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
4165
|
+
const isFollowUp = followUpOf !== void 0;
|
|
4166
|
+
const controller = followUpOf ?? new AbortController();
|
|
4167
|
+
const depth = this._runDepths.get(agent) ?? 0;
|
|
4168
|
+
this._runDepths.set(agent, depth + 1);
|
|
4169
|
+
if (!isFollowUp) {
|
|
4170
|
+
const controllers = this._runAbortControllers.get(agent) ?? /* @__PURE__ */ new Set();
|
|
4171
|
+
controllers.add(controller);
|
|
4172
|
+
this._runAbortControllers.set(agent, controllers);
|
|
4173
|
+
}
|
|
4174
|
+
if (depth === 0) {
|
|
4175
|
+
const originalAbortRun = agent.abortRun;
|
|
4176
|
+
this._originalAbortRuns.set(agent, originalAbortRun);
|
|
3909
4177
|
agent.abortRun = () => {
|
|
3910
|
-
|
|
3911
|
-
originalAbortRun();
|
|
4178
|
+
this.abortAgentRuns(agent);
|
|
4179
|
+
originalAbortRun.call(agent);
|
|
3912
4180
|
};
|
|
3913
|
-
|
|
4181
|
+
}
|
|
4182
|
+
try {
|
|
4183
|
+
if (depth === 0) await this._internal.notifySubscribers((subscriber) => subscriber.onAgentRunStarted?.({
|
|
3914
4184
|
copilotkit: this.core,
|
|
3915
4185
|
agent
|
|
3916
4186
|
}), "Subscriber onAgentRunStarted error:");
|
|
3917
|
-
}
|
|
3918
|
-
this._runDepth++;
|
|
3919
|
-
try {
|
|
3920
4187
|
let logicalRunId = resumedRunId ?? runId;
|
|
3921
|
-
const agentSubscriber = this.createAgentErrorSubscriber(agent,
|
|
4188
|
+
const agentSubscriber = this.createAgentErrorSubscriber(agent, controller.signal);
|
|
3922
4189
|
let started = false;
|
|
3923
4190
|
const onRunStartedEvent = agentSubscriber.onRunStartedEvent;
|
|
3924
4191
|
const onRunInitialized = agentSubscriber.onRunInitialized;
|
|
@@ -3935,7 +4202,7 @@ var RunHandler = class {
|
|
|
3935
4202
|
const pinRunIdOnWire = runId !== void 0 && !continuationHandoff;
|
|
3936
4203
|
const agentRunInput = {
|
|
3937
4204
|
forwardedProps: {
|
|
3938
|
-
...this._internal.
|
|
4205
|
+
...this._internal.getPropertiesForAgent(agent.agentId),
|
|
3939
4206
|
...forwardedProps
|
|
3940
4207
|
},
|
|
3941
4208
|
...resume !== void 0 ? { resume } : {},
|
|
@@ -3948,7 +4215,8 @@ var RunHandler = class {
|
|
|
3948
4215
|
return await this.processAgentResult({
|
|
3949
4216
|
runAgentResult,
|
|
3950
4217
|
agent,
|
|
3951
|
-
runId: logicalRunId
|
|
4218
|
+
runId: logicalRunId,
|
|
4219
|
+
runController: controller
|
|
3952
4220
|
});
|
|
3953
4221
|
} catch (error) {
|
|
3954
4222
|
logicalHandoff?.cancel();
|
|
@@ -3965,22 +4233,34 @@ var RunHandler = class {
|
|
|
3965
4233
|
newMessages: []
|
|
3966
4234
|
};
|
|
3967
4235
|
} finally {
|
|
3968
|
-
this.
|
|
3969
|
-
|
|
4236
|
+
const remainingDepth = (this._runDepths.get(agent) ?? 1) - 1;
|
|
4237
|
+
this._runDepths.set(agent, remainingDepth);
|
|
4238
|
+
if (!isFollowUp) {
|
|
4239
|
+
const controllers = this._runAbortControllers.get(agent);
|
|
4240
|
+
controllers?.delete(controller);
|
|
4241
|
+
if (controllers?.size === 0) this._runAbortControllers.delete(agent);
|
|
4242
|
+
}
|
|
4243
|
+
if (remainingDepth === 0) {
|
|
4244
|
+
const originalAbortRun = this._originalAbortRuns.get(agent);
|
|
4245
|
+
if (originalAbortRun) {
|
|
4246
|
+
agent.abortRun = originalAbortRun;
|
|
4247
|
+
this._originalAbortRuns.delete(agent);
|
|
4248
|
+
}
|
|
4249
|
+
}
|
|
3970
4250
|
}
|
|
3971
4251
|
}
|
|
3972
4252
|
/**
|
|
3973
4253
|
* Process agent result and execute tools
|
|
3974
4254
|
*/
|
|
3975
|
-
async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", signal =
|
|
4255
|
+
async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", runController, signal = runController?.signal }) {
|
|
3976
4256
|
const { newMessages } = runAgentResult;
|
|
3977
4257
|
const agentId = agent.agentId;
|
|
3978
4258
|
let needsFollowUp = false;
|
|
3979
4259
|
const threadId = agent.threadId;
|
|
3980
4260
|
const executing = this._executingToolCalls.get(agent) ?? /* @__PURE__ */ new Set();
|
|
3981
4261
|
this._executingToolCalls.set(agent, executing);
|
|
3982
|
-
|
|
3983
|
-
|
|
4262
|
+
const messagesToProcess = toolExecutionMode === "restore" ? agent.messages.filter((message) => message.role === "assistant" && this.isInLatestUserTurn(agent.messages, message.id)) : newMessages;
|
|
4263
|
+
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
4264
|
for (const message of messagesToProcess) if (message.role === "assistant") for (const toolCall of message.toolCalls || []) {
|
|
3985
4265
|
const tool = this.getTool({
|
|
3986
4266
|
toolName: toolCall.function.name,
|
|
@@ -3996,16 +4276,16 @@ var RunHandler = class {
|
|
|
3996
4276
|
return wildcardTool;
|
|
3997
4277
|
};
|
|
3998
4278
|
const executableTool = tool ?? getWildcardTool();
|
|
3999
|
-
if (toolExecutionMode === "restore" && (!executableTool
|
|
4279
|
+
if (toolExecutionMode === "restore" && (!executableTool || executableTool.handler && executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
|
|
4000
4280
|
const executionKey = JSON.stringify([threadId, toolCall.id]);
|
|
4001
|
-
if (signal?.aborted || agent.threadId !== threadId || executing.has(executionKey)) continue;
|
|
4281
|
+
if (signal?.aborted || agent.threadId !== threadId || toolExecutionMode === "restore" && !this.isInLatestUserTurn(agent.messages, message.id) || executing.has(executionKey)) continue;
|
|
4002
4282
|
const existingResultIndex = newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
|
|
4003
4283
|
let existingResult = agent.messages.find((m) => m.role === "tool" && m.toolCallId === toolCall.id) ?? newMessages[existingResultIndex];
|
|
4004
|
-
if (existingResult &&
|
|
4284
|
+
if (existingResult && this.isFrontendPlaceholderResult(existingResult) && (toolExecutionMode === "restore" || executableTool?.handler)) {
|
|
4005
4285
|
if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
|
|
4006
4286
|
existingResult = void 0;
|
|
4007
4287
|
const agentMsgIdx = agent.messages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
|
|
4008
|
-
if (agentMsgIdx !== -1)
|
|
4288
|
+
if (agentMsgIdx !== -1) agent.messages.splice(agentMsgIdx, 1);
|
|
4009
4289
|
}
|
|
4010
4290
|
if (!existingResult) {
|
|
4011
4291
|
executing.add(executionKey);
|
|
@@ -4048,18 +4328,43 @@ var RunHandler = class {
|
|
|
4048
4328
|
if (interactionController?.signal.aborted) return runAgentResult;
|
|
4049
4329
|
}
|
|
4050
4330
|
}
|
|
4051
|
-
if (needsFollowUp && agent.threadId === threadId && !signal?.aborted) if (this.
|
|
4331
|
+
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
4332
|
else {
|
|
4053
4333
|
await this._internal.waitForPendingFrameworkUpdates();
|
|
4334
|
+
if (toolExecutionMode === "restore" && !messagesToProcess.some((message) => this.isInLatestUserTurn(agent.messages, message.id))) return runAgentResult;
|
|
4054
4335
|
const continuationHandoff = this._internal.stateManager.markNextRunAsContinuation(agent, runId);
|
|
4055
4336
|
return await this.runAgent({
|
|
4056
4337
|
agent,
|
|
4057
4338
|
...runId !== void 0 ? { runId } : {}
|
|
4058
|
-
}, continuationHandoff);
|
|
4339
|
+
}, continuationHandoff, runController);
|
|
4059
4340
|
}
|
|
4060
4341
|
this._internal.suggestionEngine.reloadSuggestions(agentId);
|
|
4061
4342
|
return runAgentResult;
|
|
4062
4343
|
}
|
|
4344
|
+
/** A later user message supersedes pending work from an older turn. */
|
|
4345
|
+
isInLatestUserTurn(messages, messageId) {
|
|
4346
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
4347
|
+
const message = messages[index];
|
|
4348
|
+
if (message?.role === "user") return false;
|
|
4349
|
+
if (message?.id === messageId) return true;
|
|
4350
|
+
}
|
|
4351
|
+
return false;
|
|
4352
|
+
}
|
|
4353
|
+
/** Locate a missing result before saved results for later calls in its batch. */
|
|
4354
|
+
toolResultInsertionIndex(messages, messageIndex, toolCallId) {
|
|
4355
|
+
const parent = messages[messageIndex];
|
|
4356
|
+
const calls = parent?.role === "assistant" ? parent.toolCalls ?? [] : [];
|
|
4357
|
+
const callIndex = calls.findIndex((call) => call.id === toolCallId);
|
|
4358
|
+
let insertAt = messageIndex + 1;
|
|
4359
|
+
while (insertAt < messages.length) {
|
|
4360
|
+
const result = messages[insertAt];
|
|
4361
|
+
if (result?.role !== "tool") break;
|
|
4362
|
+
if (calls.findIndex((call) => call.id === result.toolCallId) > callIndex) break;
|
|
4363
|
+
insertAt++;
|
|
4364
|
+
}
|
|
4365
|
+
return insertAt;
|
|
4366
|
+
}
|
|
4367
|
+
/** Identify transport placeholders that must not count as completed answers. */
|
|
4063
4368
|
isFrontendPlaceholderResult(message) {
|
|
4064
4369
|
return message.role === "tool" && isForwardedToClientPlaceholder(message.content);
|
|
4065
4370
|
}
|
|
@@ -4068,7 +4373,7 @@ var RunHandler = class {
|
|
|
4068
4373
|
* Handles arg parsing, subscriber notifications, handler invocation, result stringification,
|
|
4069
4374
|
* and error handling.
|
|
4070
4375
|
*/
|
|
4071
|
-
async executeToolHandler({ tool, toolCall, agent, agentId, handlerArgs, toolType, messageId, signal = this.
|
|
4376
|
+
async executeToolHandler({ tool, toolCall, agent, agentId, handlerArgs, toolType, messageId, signal = this.latestRunSignal(agent), discardOnAbort = false, isReplay = false }) {
|
|
4072
4377
|
let toolCallResult = "";
|
|
4073
4378
|
let toolCallText = "";
|
|
4074
4379
|
let errorMessage;
|
|
@@ -4078,7 +4383,7 @@ var RunHandler = class {
|
|
|
4078
4383
|
parsedArgs = parseToolArguments(handlerArgs, toolCall.function.name);
|
|
4079
4384
|
} catch (error) {
|
|
4080
4385
|
const parseError = error instanceof Error ? error : new Error(String(error));
|
|
4081
|
-
errorMessage = parseError
|
|
4386
|
+
errorMessage = toolFailureMessage(parseError);
|
|
4082
4387
|
isArgumentError = true;
|
|
4083
4388
|
await this._internal.emitError({
|
|
4084
4389
|
error: parseError,
|
|
@@ -4110,7 +4415,7 @@ var RunHandler = class {
|
|
|
4110
4415
|
({content: toolCallResult, text: toolCallText} = toToolResultContent(result));
|
|
4111
4416
|
} catch (error) {
|
|
4112
4417
|
const handlerError = error instanceof Error ? error : new Error(String(error));
|
|
4113
|
-
errorMessage = handlerError
|
|
4418
|
+
errorMessage = toolFailureMessage(handlerError);
|
|
4114
4419
|
if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) await this._internal.emitError({
|
|
4115
4420
|
error: handlerError,
|
|
4116
4421
|
code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,
|
|
@@ -4166,16 +4471,16 @@ var RunHandler = class {
|
|
|
4166
4471
|
});
|
|
4167
4472
|
{
|
|
4168
4473
|
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++;
|
|
4474
|
+
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;
|
|
4475
|
+
const insertAt = this.toolResultInsertionIndex(agent.messages, messageIndex, toolCall.id);
|
|
4172
4476
|
const toolMessage = {
|
|
4173
4477
|
id: (0, _copilotkit_shared.randomUUID)(),
|
|
4174
4478
|
role: "tool",
|
|
4175
4479
|
toolCallId: toolCall.id,
|
|
4176
|
-
content: handlerResult.content
|
|
4480
|
+
content: handlerResult.content,
|
|
4481
|
+
...handlerResult.error ? { error: handlerResult.error } : {}
|
|
4177
4482
|
};
|
|
4178
|
-
|
|
4483
|
+
agent.messages.splice(insertAt, 0, toolMessage);
|
|
4179
4484
|
if (!handlerResult.error && tool?.followUp !== false) return true;
|
|
4180
4485
|
}
|
|
4181
4486
|
return false;
|
|
@@ -4198,7 +4503,7 @@ var RunHandler = class {
|
|
|
4198
4503
|
parsedArgs = parseToolArguments(toolCall.function.arguments, toolCall.function.name);
|
|
4199
4504
|
} catch (error) {
|
|
4200
4505
|
const parseError = error instanceof Error ? error : new Error(String(error));
|
|
4201
|
-
errorMessage = parseError
|
|
4506
|
+
errorMessage = toolFailureMessage(parseError);
|
|
4202
4507
|
await this._internal.emitError({
|
|
4203
4508
|
error: parseError,
|
|
4204
4509
|
code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,
|
|
@@ -4233,7 +4538,7 @@ var RunHandler = class {
|
|
|
4233
4538
|
({content: toolCallResult, text: toolCallText} = toToolResultContent(result));
|
|
4234
4539
|
} catch (error) {
|
|
4235
4540
|
const handlerError = error instanceof Error ? error : new Error(String(error));
|
|
4236
|
-
errorMessage = handlerError
|
|
4541
|
+
errorMessage = toolFailureMessage(handlerError);
|
|
4237
4542
|
if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) await this._internal.emitError({
|
|
4238
4543
|
error: handlerError,
|
|
4239
4544
|
code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,
|
|
@@ -4259,16 +4564,16 @@ var RunHandler = class {
|
|
|
4259
4564
|
}
|
|
4260
4565
|
{
|
|
4261
4566
|
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++;
|
|
4567
|
+
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;
|
|
4568
|
+
const insertAt = this.toolResultInsertionIndex(agent.messages, messageIndex, toolCall.id);
|
|
4265
4569
|
const toolMessage = {
|
|
4266
4570
|
id: (0, _copilotkit_shared.randomUUID)(),
|
|
4267
4571
|
role: "tool",
|
|
4268
4572
|
toolCallId: toolCall.id,
|
|
4269
|
-
content: toolCallResult
|
|
4573
|
+
content: toolCallResult,
|
|
4574
|
+
...errorMessage ? { error: errorMessage } : {}
|
|
4270
4575
|
};
|
|
4271
|
-
|
|
4576
|
+
agent.messages.splice(insertAt, 0, toolMessage);
|
|
4272
4577
|
if (!errorMessage && wildcardTool?.followUp !== false) return true;
|
|
4273
4578
|
}
|
|
4274
4579
|
return false;
|
|
@@ -4322,7 +4627,7 @@ var RunHandler = class {
|
|
|
4322
4627
|
content: "",
|
|
4323
4628
|
toolCalls: [assistantToolCall]
|
|
4324
4629
|
};
|
|
4325
|
-
|
|
4630
|
+
agent.messages.push(assistantMessage);
|
|
4326
4631
|
let handlerResult = {
|
|
4327
4632
|
content: "",
|
|
4328
4633
|
result: "",
|
|
@@ -4341,11 +4646,12 @@ var RunHandler = class {
|
|
|
4341
4646
|
id: (0, _copilotkit_shared.randomUUID)(),
|
|
4342
4647
|
role: "tool",
|
|
4343
4648
|
toolCallId,
|
|
4344
|
-
content: handlerResult.content
|
|
4649
|
+
content: handlerResult.content,
|
|
4650
|
+
...handlerResult.error ? { error: handlerResult.error } : {}
|
|
4345
4651
|
};
|
|
4346
4652
|
const assistantIndex = agent.messages.findIndex((m) => m.id === assistantMessage.id);
|
|
4347
|
-
if (assistantIndex !== -1)
|
|
4348
|
-
else
|
|
4653
|
+
if (assistantIndex !== -1) agent.messages.splice(assistantIndex + 1, 0, toolResultMessage);
|
|
4654
|
+
else agent.messages.push(toolResultMessage);
|
|
4349
4655
|
if (!handlerResult.error && followUp !== false) {
|
|
4350
4656
|
if (typeof followUp === "string" && followUp !== "generate") {
|
|
4351
4657
|
const userMessage = {
|
|
@@ -4353,7 +4659,7 @@ var RunHandler = class {
|
|
|
4353
4659
|
role: "user",
|
|
4354
4660
|
content: followUp
|
|
4355
4661
|
};
|
|
4356
|
-
|
|
4662
|
+
agent.messages.push(userMessage);
|
|
4357
4663
|
}
|
|
4358
4664
|
await this._internal.waitForPendingFrameworkUpdates();
|
|
4359
4665
|
await this.runAgent({ agent });
|
|
@@ -4423,7 +4729,7 @@ var RunHandler = class {
|
|
|
4423
4729
|
/**
|
|
4424
4730
|
* Create an agent error subscriber
|
|
4425
4731
|
*/
|
|
4426
|
-
createAgentErrorSubscriber(agent,
|
|
4732
|
+
createAgentErrorSubscriber(agent, runSignal) {
|
|
4427
4733
|
const emitAgentError = async (error, code, extraContext = {}) => {
|
|
4428
4734
|
const context = { ...extraContext };
|
|
4429
4735
|
if (agent.agentId) context.agentId = agent.agentId;
|
|
@@ -4438,7 +4744,14 @@ var RunHandler = class {
|
|
|
4438
4744
|
await emitAgentError(error, error instanceof AgentThreadLockedError ? CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED : CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT, { source: "onRunFailed" });
|
|
4439
4745
|
},
|
|
4440
4746
|
onRunErrorEvent: async ({ event }) => {
|
|
4441
|
-
if (
|
|
4747
|
+
if ((runSignal?.aborted ?? false) || event?.code === "abort") return;
|
|
4748
|
+
if (event?.code === _copilotkit_shared.THREAD_ALREADY_RUNNING_ERROR_CODE) {
|
|
4749
|
+
await emitAgentError(new AgentThreadLockedError(agent.threadId), CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED, {
|
|
4750
|
+
source: "onRunErrorEvent",
|
|
4751
|
+
event
|
|
4752
|
+
});
|
|
4753
|
+
return;
|
|
4754
|
+
}
|
|
4442
4755
|
const eventError = event?.rawEvent instanceof Error ? event.rawEvent : event?.rawEvent?.error instanceof Error ? event.rawEvent.error : void 0;
|
|
4443
4756
|
const errorMessage = typeof event?.rawEvent?.error === "string" ? event.rawEvent.error : event?.message ?? "Agent run error";
|
|
4444
4757
|
const rawError = eventError ?? new Error(errorMessage);
|
|
@@ -4446,8 +4759,7 @@ var RunHandler = class {
|
|
|
4446
4759
|
await emitAgentError(rawError, CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT, {
|
|
4447
4760
|
source: "onRunErrorEvent",
|
|
4448
4761
|
event,
|
|
4449
|
-
runtimeErrorCode: event?.code
|
|
4450
|
-
phase: stream === "run" ? "live" : ɵgetConnectRunErrorPhase(event)
|
|
4762
|
+
runtimeErrorCode: event?.code
|
|
4451
4763
|
});
|
|
4452
4764
|
}
|
|
4453
4765
|
};
|
|
@@ -5462,6 +5774,17 @@ var LearningBridge = class {
|
|
|
5462
5774
|
get isConfigured() {
|
|
5463
5775
|
return this.config !== void 0;
|
|
5464
5776
|
}
|
|
5777
|
+
/**
|
|
5778
|
+
* Whether events may carry agent message text: not when the capture's config
|
|
5779
|
+
* sets `capture.agentText` to false. A running custom-sink capture keeps the
|
|
5780
|
+
* choice it started with; otherwise the current config decides.
|
|
5781
|
+
*/
|
|
5782
|
+
get capturesAgentText() {
|
|
5783
|
+
const config = this.activeConfig ?? this.config;
|
|
5784
|
+
if (config === void 0) return false;
|
|
5785
|
+
const capture = config.capture;
|
|
5786
|
+
return !(typeof capture === "object" && capture !== null && capture.agentText === false);
|
|
5787
|
+
}
|
|
5465
5788
|
get isLegacyCaptureActive() {
|
|
5466
5789
|
return this.collector !== null && this.collector.trajectoryId !== null;
|
|
5467
5790
|
}
|
|
@@ -5567,13 +5890,19 @@ var LearningBridge = class {
|
|
|
5567
5890
|
this.toolCalls.clear();
|
|
5568
5891
|
this.executingTools.clear();
|
|
5569
5892
|
}
|
|
5570
|
-
/**
|
|
5893
|
+
/**
|
|
5894
|
+
* A developer event. Only an explicit legacy sink adds open-Thread context;
|
|
5895
|
+
* an event that names its own Thread gets no ambiguity next to it.
|
|
5896
|
+
*/
|
|
5571
5897
|
emit(name, value) {
|
|
5572
5898
|
this.connection.emit(name, value);
|
|
5573
|
-
if (value !== null && typeof value === "object" && !Array.isArray(value))
|
|
5574
|
-
|
|
5575
|
-
|
|
5576
|
-
|
|
5899
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
|
|
5900
|
+
const context = typeof value["threadId"] === "string" ? {} : this.openThreadContext();
|
|
5901
|
+
this.collector?.emit(name, {
|
|
5902
|
+
...context,
|
|
5903
|
+
...value
|
|
5904
|
+
});
|
|
5905
|
+
}
|
|
5577
5906
|
}
|
|
5578
5907
|
registerOpenThread(params) {
|
|
5579
5908
|
const entry = { ...params };
|
|
@@ -5654,7 +5983,7 @@ var LearningBridge = class {
|
|
|
5654
5983
|
}
|
|
5655
5984
|
emitMessage(agent, message) {
|
|
5656
5985
|
const content = typeof message.content === "string" ? message.content : "";
|
|
5657
|
-
const includeText = this.
|
|
5986
|
+
const includeText = this.capturesAgentText && typeof message.content === "string";
|
|
5658
5987
|
this.collector?.ɵemit("agent.message", {
|
|
5659
5988
|
messageId: message.id,
|
|
5660
5989
|
runId: this.runIdForMessage(agent, message.id),
|
|
@@ -6807,17 +7136,15 @@ const ɵselectMemoriesRealtimeStatus = selectMemoriesRealtimeStatus;
|
|
|
6807
7136
|
|
|
6808
7137
|
//#endregion
|
|
6809
7138
|
//#region src/core/core.ts
|
|
7139
|
+
/** True for an object literal. Arrays, `null`, and class instances are not plain objects. */
|
|
7140
|
+
function isPlainObject(value) {
|
|
7141
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
|
|
7142
|
+
}
|
|
6810
7143
|
let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode) {
|
|
6811
7144
|
CopilotKitCoreErrorCode["RUNTIME_INFO_FETCH_FAILED"] = "runtime_info_fetch_failed";
|
|
6812
7145
|
CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
|
|
6813
7146
|
CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
|
|
6814
7147
|
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
7148
|
CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
|
|
6822
7149
|
CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
|
|
6823
7150
|
CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
|
|
@@ -6878,6 +7205,7 @@ var CopilotKitCore = class {
|
|
|
6878
7205
|
_credentials;
|
|
6879
7206
|
_messageFilter;
|
|
6880
7207
|
_properties;
|
|
7208
|
+
_scopedProperties = /* @__PURE__ */ new Map();
|
|
6881
7209
|
_defaultThrottleMs;
|
|
6882
7210
|
_debug;
|
|
6883
7211
|
subscribers = /* @__PURE__ */ new Set();
|
|
@@ -6890,6 +7218,8 @@ var CopilotKitCore = class {
|
|
|
6890
7218
|
learningBridge;
|
|
6891
7219
|
notifiedTrajectoryId = null;
|
|
6892
7220
|
learningConfiguredListeners = /* @__PURE__ */ new Set();
|
|
7221
|
+
_generativeUIDebugSource;
|
|
7222
|
+
generativeUIDebugListeners = /* @__PURE__ */ new Set();
|
|
6893
7223
|
/**
|
|
6894
7224
|
* The single core-owned memory store, created lazily on first
|
|
6895
7225
|
* `getMemoryStore()` and kept user-scoped for the lifetime of the core.
|
|
@@ -7223,6 +7553,59 @@ var CopilotKitCore = class {
|
|
|
7223
7553
|
this._messageFilter = messageFilter;
|
|
7224
7554
|
this.agentRegistry.applyMessageFilterToAgents(this.agentRegistry.agents);
|
|
7225
7555
|
}
|
|
7556
|
+
/**
|
|
7557
|
+
* Add run properties that go only to the runs of `agentIds`. When
|
|
7558
|
+
* `agentIds` is omitted, every agent gets them. They merge on top of the
|
|
7559
|
+
* base `properties`.
|
|
7560
|
+
*
|
|
7561
|
+
* When an entry value and the existing value under the same key are both
|
|
7562
|
+
* plain objects, their keys merge one level deep. So several entries can
|
|
7563
|
+
* add keys under one namespace (for example `copilotkit`).
|
|
7564
|
+
*
|
|
7565
|
+
* @param entry - The properties and the optional agent ids.
|
|
7566
|
+
* @returns The id to pass to `removeScopedProperties`.
|
|
7567
|
+
*
|
|
7568
|
+
* @example
|
|
7569
|
+
* const id = copilotkit.addScopedProperties({
|
|
7570
|
+
* properties: { copilotkit: { theme: "dark" } },
|
|
7571
|
+
* agentIds: ["research"],
|
|
7572
|
+
* });
|
|
7573
|
+
* copilotkit.removeScopedProperties(id);
|
|
7574
|
+
*/
|
|
7575
|
+
addScopedProperties({ properties, agentIds }) {
|
|
7576
|
+
let id = (0, _copilotkit_shared.randomUUID)();
|
|
7577
|
+
for (let n = 1; this._scopedProperties.has(id); n++) id = `${id}-${n}`;
|
|
7578
|
+
this._scopedProperties.set(id, {
|
|
7579
|
+
properties,
|
|
7580
|
+
...agentIds ? { agentIds } : {}
|
|
7581
|
+
});
|
|
7582
|
+
return id;
|
|
7583
|
+
}
|
|
7584
|
+
/** Remove an entry that `addScopedProperties` added. An unknown id does nothing. */
|
|
7585
|
+
removeScopedProperties(id) {
|
|
7586
|
+
this._scopedProperties.delete(id);
|
|
7587
|
+
}
|
|
7588
|
+
/**
|
|
7589
|
+
* Build the forwarded properties for a run of the given agent: the base
|
|
7590
|
+
* properties plus every scoped entry that matches the agent. An entry with
|
|
7591
|
+
* `agentIds` does not match when `agentId` is omitted.
|
|
7592
|
+
*/
|
|
7593
|
+
getPropertiesForAgent(agentId) {
|
|
7594
|
+
const merged = { ...this._properties };
|
|
7595
|
+
const entries = this._scopedProperties.values();
|
|
7596
|
+
for (const entry of entries) {
|
|
7597
|
+
if (!isForAgent(entry.agentIds, agentId)) continue;
|
|
7598
|
+
const properties = Object.entries(entry.properties);
|
|
7599
|
+
for (const [key, value] of properties) {
|
|
7600
|
+
const base = merged[key];
|
|
7601
|
+
merged[key] = isPlainObject(base) && isPlainObject(value) ? {
|
|
7602
|
+
...base,
|
|
7603
|
+
...value
|
|
7604
|
+
} : value;
|
|
7605
|
+
}
|
|
7606
|
+
}
|
|
7607
|
+
return merged;
|
|
7608
|
+
}
|
|
7226
7609
|
setProperties(properties) {
|
|
7227
7610
|
this._properties = properties;
|
|
7228
7611
|
this.notifySubscribers((subscriber) => subscriber.onPropertiesChanged?.({
|
|
@@ -7286,6 +7669,15 @@ var CopilotKitCore = class {
|
|
|
7286
7669
|
get ɵlearningConfigured() {
|
|
7287
7670
|
return this.learningBridge.isConfigured;
|
|
7288
7671
|
}
|
|
7672
|
+
/**
|
|
7673
|
+
* @internal Whether captured events may carry agent message text: false
|
|
7674
|
+
* without a `learning` config, or when a custom sink sets
|
|
7675
|
+
* `capture.agentText` to false. A running custom-sink capture keeps the
|
|
7676
|
+
* choice it started with.
|
|
7677
|
+
*/
|
|
7678
|
+
get ɵlearningCapturesAgentText() {
|
|
7679
|
+
return this.learningBridge.capturesAgentText;
|
|
7680
|
+
}
|
|
7289
7681
|
/** @internal Calls `listener` when {@link ɵlearningConfigured} changes. */
|
|
7290
7682
|
ɵsubscribeToLearningConfigured(listener) {
|
|
7291
7683
|
this.learningConfiguredListeners.add(listener);
|
|
@@ -7293,6 +7685,30 @@ var CopilotKitCore = class {
|
|
|
7293
7685
|
this.learningConfiguredListeners.delete(listener);
|
|
7294
7686
|
};
|
|
7295
7687
|
}
|
|
7688
|
+
/**
|
|
7689
|
+
* @internal The generative UI of the framework package, for the inspector.
|
|
7690
|
+
* `undefined` when no provider has a `generativeUI` config.
|
|
7691
|
+
*/
|
|
7692
|
+
get ɵgenerativeUIDebugSource() {
|
|
7693
|
+
return this._generativeUIDebugSource;
|
|
7694
|
+
}
|
|
7695
|
+
/** @internal Set by the framework package. `undefined` removes it. */
|
|
7696
|
+
ɵsetGenerativeUIDebugSource(source) {
|
|
7697
|
+
if (source === this._generativeUIDebugSource) return;
|
|
7698
|
+
this._generativeUIDebugSource = source;
|
|
7699
|
+
for (const listener of [...this.generativeUIDebugListeners]) try {
|
|
7700
|
+
listener();
|
|
7701
|
+
} catch (error) {
|
|
7702
|
+
console.error("Generative UI debug listener error:", error);
|
|
7703
|
+
}
|
|
7704
|
+
}
|
|
7705
|
+
/** @internal Calls `listener` when {@link ɵgenerativeUIDebugSource} is set or removed. */
|
|
7706
|
+
ɵsubscribeToGenerativeUIDebugSource(listener) {
|
|
7707
|
+
this.generativeUIDebugListeners.add(listener);
|
|
7708
|
+
return () => {
|
|
7709
|
+
this.generativeUIDebugListeners.delete(listener);
|
|
7710
|
+
};
|
|
7711
|
+
}
|
|
7296
7712
|
/** The active capture's Trajectory ID, or null while capture is stopped. */
|
|
7297
7713
|
get trajectoryId() {
|
|
7298
7714
|
return this.learningBridge.trajectoryId;
|
|
@@ -8879,6 +9295,1276 @@ function onInspectorViewThreadResult(handler) {
|
|
|
8879
9295
|
}
|
|
8880
9296
|
|
|
8881
9297
|
//#endregion
|
|
9298
|
+
//#region src/a2ui-markdown/fence-parser.ts
|
|
9299
|
+
/** Language of a fenced code block that carries A2UI operations. */
|
|
9300
|
+
const A2UI_FENCE_LANGUAGE = "a2ui";
|
|
9301
|
+
/** Column-0 fence opener: a run of 3+ backticks or tildes, then the info string. */
|
|
9302
|
+
const FENCE_OPEN = /^(`{3,}|~{3,})(.*)$/;
|
|
9303
|
+
/** Info-string token that names the placement target of an a2ui fence. */
|
|
9304
|
+
const TARGET_TOKEN = /^target=(.+)$/;
|
|
9305
|
+
function isCloser(line, fence) {
|
|
9306
|
+
const trimmed = line.trim();
|
|
9307
|
+
if (trimmed.length < fence.length) return false;
|
|
9308
|
+
for (const ch of trimmed) if (ch !== fence.char) return false;
|
|
9309
|
+
return true;
|
|
9310
|
+
}
|
|
9311
|
+
/** The id of the first `target=<id>` token. Other tokens are ignored. */
|
|
9312
|
+
function readTarget(tokens) {
|
|
9313
|
+
for (const token of tokens) {
|
|
9314
|
+
const match = TARGET_TOKEN.exec(token);
|
|
9315
|
+
if (match) return match[1];
|
|
9316
|
+
}
|
|
9317
|
+
}
|
|
9318
|
+
function a2uiSegment(fence, text, closed) {
|
|
9319
|
+
const segment = {
|
|
9320
|
+
type: "a2ui",
|
|
9321
|
+
index: fence.index,
|
|
9322
|
+
text,
|
|
9323
|
+
closed
|
|
9324
|
+
};
|
|
9325
|
+
if (fence.target !== void 0) segment.target = fence.target;
|
|
9326
|
+
return segment;
|
|
9327
|
+
}
|
|
9328
|
+
/**
|
|
9329
|
+
* Split a (possibly still streaming) markdown string into prose segments and
|
|
9330
|
+
* top-level ```a2ui fences. Fences of other languages stay inside prose
|
|
9331
|
+
* segments byte-for-byte, and a2ui markers inside them are ignored. Only
|
|
9332
|
+
* column-0 fences are recognised, so a fence indented inside a list item is
|
|
9333
|
+
* left to the markdown renderer.
|
|
9334
|
+
*
|
|
9335
|
+
* The first info-string token must be exactly `a2ui`. A later
|
|
9336
|
+
* `target=<id>` token sets `target` on the segment (for example
|
|
9337
|
+
* ```` ```a2ui target=recommendations ````). Other tokens are ignored.
|
|
9338
|
+
*
|
|
9339
|
+
* An a2ui segment's `text` is the fence body. For a closed fence it ends with
|
|
9340
|
+
* "\n" when non-empty. For an open (still streaming or aborted) fence it is
|
|
9341
|
+
* everything after the opener line, minus a half-streamed closing marker.
|
|
9342
|
+
*
|
|
9343
|
+
* @param markdown - The assistant message text, complete or still streaming.
|
|
9344
|
+
* @returns The segments in source order.
|
|
9345
|
+
*
|
|
9346
|
+
* @example
|
|
9347
|
+
* ```ts
|
|
9348
|
+
* for (const segment of splitA2UIMarkdown(message.content)) {
|
|
9349
|
+
* if (segment.type === "a2ui") renderSurface(segment.text, segment.target);
|
|
9350
|
+
* else renderMarkdown(segment.text);
|
|
9351
|
+
* }
|
|
9352
|
+
* ```
|
|
9353
|
+
*/
|
|
9354
|
+
function splitA2UIMarkdown(markdown) {
|
|
9355
|
+
const segments = [];
|
|
9356
|
+
let proseStart = 0;
|
|
9357
|
+
let fence = null;
|
|
9358
|
+
let a2uiIndex = 0;
|
|
9359
|
+
const pushProse = (end) => {
|
|
9360
|
+
if (end > proseStart) segments.push({
|
|
9361
|
+
type: "markdown",
|
|
9362
|
+
text: markdown.slice(proseStart, end)
|
|
9363
|
+
});
|
|
9364
|
+
};
|
|
9365
|
+
let lineStart = 0;
|
|
9366
|
+
while (lineStart <= markdown.length) {
|
|
9367
|
+
const newline = markdown.indexOf("\n", lineStart);
|
|
9368
|
+
const lineEnd = newline < 0 ? markdown.length : newline;
|
|
9369
|
+
const hasCR = lineEnd > lineStart && markdown[lineEnd - 1] === "\r";
|
|
9370
|
+
const line = markdown.slice(lineStart, hasCR ? lineEnd - 1 : lineEnd);
|
|
9371
|
+
if (fence) {
|
|
9372
|
+
if (isCloser(line, fence)) {
|
|
9373
|
+
if (fence.index >= 0) {
|
|
9374
|
+
const body = markdown.slice(fence.bodyStart, Math.max(fence.bodyStart, lineStart));
|
|
9375
|
+
segments.push(a2uiSegment(fence, body, true));
|
|
9376
|
+
proseStart = hasCR ? lineEnd - 1 : lineEnd;
|
|
9377
|
+
}
|
|
9378
|
+
fence = null;
|
|
9379
|
+
}
|
|
9380
|
+
} else {
|
|
9381
|
+
const open = FENCE_OPEN.exec(line);
|
|
9382
|
+
if (open) {
|
|
9383
|
+
const marker = open[1] ?? "";
|
|
9384
|
+
const info = open[2] ?? "";
|
|
9385
|
+
const char = marker.charAt(0);
|
|
9386
|
+
if (!(char === "`" && info.includes("`"))) {
|
|
9387
|
+
const [lang = "", ...tokens] = info.trim().split(/\s+/);
|
|
9388
|
+
const isA2UI = lang === A2UI_FENCE_LANGUAGE;
|
|
9389
|
+
if (isA2UI) pushProse(lineStart);
|
|
9390
|
+
fence = {
|
|
9391
|
+
char,
|
|
9392
|
+
length: marker.length,
|
|
9393
|
+
bodyStart: newline < 0 ? markdown.length : lineEnd + 1,
|
|
9394
|
+
index: isA2UI ? a2uiIndex++ : -1,
|
|
9395
|
+
target: isA2UI ? readTarget(tokens) : void 0
|
|
9396
|
+
};
|
|
9397
|
+
}
|
|
9398
|
+
}
|
|
9399
|
+
}
|
|
9400
|
+
if (newline < 0) break;
|
|
9401
|
+
lineStart = newline + 1;
|
|
9402
|
+
}
|
|
9403
|
+
if (fence && fence.index >= 0) {
|
|
9404
|
+
const { char } = fence;
|
|
9405
|
+
let body = markdown.slice(fence.bodyStart);
|
|
9406
|
+
const lastNewline = body.lastIndexOf("\n");
|
|
9407
|
+
const lastLine = body.slice(lastNewline + 1).replace(/\r$/, "");
|
|
9408
|
+
if (lastLine.length > 0 && [...lastLine].every((ch) => ch === char)) body = body.slice(0, lastNewline + 1);
|
|
9409
|
+
segments.push(a2uiSegment(fence, body, false));
|
|
9410
|
+
} else pushProse(markdown.length);
|
|
9411
|
+
return segments;
|
|
9412
|
+
}
|
|
9413
|
+
|
|
9414
|
+
//#endregion
|
|
9415
|
+
//#region src/a2ui-markdown/operations.ts
|
|
9416
|
+
/** The operation keys that change a surface. */
|
|
9417
|
+
const SURFACE_OP_KEYS = [
|
|
9418
|
+
"createSurface",
|
|
9419
|
+
"updateComponents",
|
|
9420
|
+
"updateDataModel",
|
|
9421
|
+
"deleteSurface"
|
|
9422
|
+
];
|
|
9423
|
+
/** The operation key of an agent-called function. It has no surface. */
|
|
9424
|
+
const FUNCTION_CALL_KEY = "callRendererFunction";
|
|
9425
|
+
const OP_KEYS = [...SURFACE_OP_KEYS, FUNCTION_CALL_KEY];
|
|
9426
|
+
function isRecord(value) {
|
|
9427
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9428
|
+
}
|
|
9429
|
+
function isWhitespace(ch) {
|
|
9430
|
+
return ch === " " || ch === "\n" || ch === "\r" || ch === " ";
|
|
9431
|
+
}
|
|
9432
|
+
function skipWhitespace(s, i) {
|
|
9433
|
+
while (i < s.length && isWhitespace(s[i])) i++;
|
|
9434
|
+
return i;
|
|
9435
|
+
}
|
|
9436
|
+
/** Index of the closing quote of the JSON string opening at `start`, or -1. */
|
|
9437
|
+
function findStringEnd(s, start) {
|
|
9438
|
+
for (let i = start + 1; i < s.length; i++) {
|
|
9439
|
+
if (s[i] === "\\") {
|
|
9440
|
+
i++;
|
|
9441
|
+
continue;
|
|
9442
|
+
}
|
|
9443
|
+
if (s[i] === "\"") return i;
|
|
9444
|
+
}
|
|
9445
|
+
return -1;
|
|
9446
|
+
}
|
|
9447
|
+
/**
|
|
9448
|
+
* Find the first `"key":` whose value starts with `opener` and return the index
|
|
9449
|
+
* of that opener, or -1.
|
|
9450
|
+
*/
|
|
9451
|
+
function findKeyValue(s, key, opener) {
|
|
9452
|
+
const needle = `"${key}"`;
|
|
9453
|
+
let from = 0;
|
|
9454
|
+
while (true) {
|
|
9455
|
+
const k = s.indexOf(needle, from);
|
|
9456
|
+
if (k < 0) return -1;
|
|
9457
|
+
let i = skipWhitespace(s, k + needle.length);
|
|
9458
|
+
if (s[i] === ":") {
|
|
9459
|
+
i = skipWhitespace(s, i + 1);
|
|
9460
|
+
if (s[i] === opener) return i;
|
|
9461
|
+
}
|
|
9462
|
+
from = k + 1;
|
|
9463
|
+
}
|
|
9464
|
+
}
|
|
9465
|
+
/**
|
|
9466
|
+
* Read `"key":"value"` from partial JSON. The first match anywhere in the
|
|
9467
|
+
* text wins, at any depth.
|
|
9468
|
+
*
|
|
9469
|
+
* @param partialJson - JSON text that can still be streaming.
|
|
9470
|
+
* @param key - The field name.
|
|
9471
|
+
* @returns The string value, or null until its closing quote has arrived.
|
|
9472
|
+
*
|
|
9473
|
+
* @example
|
|
9474
|
+
* ```ts
|
|
9475
|
+
* extractStringField('{"createSurface":{"surfaceId":"plan","cat', "surfaceId"); // "plan"
|
|
9476
|
+
* ```
|
|
9477
|
+
*/
|
|
9478
|
+
function extractStringField(partialJson, key) {
|
|
9479
|
+
const start = findKeyValue(partialJson, key, "\"");
|
|
9480
|
+
if (start < 0) return null;
|
|
9481
|
+
const end = findStringEnd(partialJson, start);
|
|
9482
|
+
if (end < 0) return null;
|
|
9483
|
+
try {
|
|
9484
|
+
const value = JSON.parse(partialJson.slice(start, end + 1));
|
|
9485
|
+
return typeof value === "string" ? value : null;
|
|
9486
|
+
} catch {
|
|
9487
|
+
return null;
|
|
9488
|
+
}
|
|
9489
|
+
}
|
|
9490
|
+
function pushItem(raw, items) {
|
|
9491
|
+
const trimmed = raw.trim();
|
|
9492
|
+
if (!trimmed) return;
|
|
9493
|
+
try {
|
|
9494
|
+
items.push(JSON.parse(trimmed));
|
|
9495
|
+
} catch {}
|
|
9496
|
+
}
|
|
9497
|
+
/**
|
|
9498
|
+
* Find `"key":[` in partial JSON and return every complete item of that array
|
|
9499
|
+
* so far, plus whether the array has closed. Items of a `components` array get
|
|
9500
|
+
* structural-key depth repair: a component that lost closing braces is fixed
|
|
9501
|
+
* when its `id`, `component`, `child` or `children` key shows where it ends.
|
|
9502
|
+
*
|
|
9503
|
+
* @param partialJson - JSON text that can still be streaming.
|
|
9504
|
+
* @param key - The name of the array field.
|
|
9505
|
+
* @returns `{ items, closed }`, or null when the key (with an array value)
|
|
9506
|
+
* has not appeared yet.
|
|
9507
|
+
*
|
|
9508
|
+
* @example
|
|
9509
|
+
* ```ts
|
|
9510
|
+
* const result = extractCompleteArrayItems(streamedText, "components");
|
|
9511
|
+
* if (result) render(result.items);
|
|
9512
|
+
* ```
|
|
9513
|
+
*/
|
|
9514
|
+
function extractCompleteArrayItems(partialJson, key) {
|
|
9515
|
+
const open = findKeyValue(partialJson, key, "[");
|
|
9516
|
+
if (open < 0) return null;
|
|
9517
|
+
return completeArrayItemsAt(partialJson, open, { repairComponents: key === "components" });
|
|
9518
|
+
}
|
|
9519
|
+
/** Index of the last non-whitespace character before `i`, or -1. */
|
|
9520
|
+
function prevNonWhitespace(s, i) {
|
|
9521
|
+
let j = i - 1;
|
|
9522
|
+
while (j >= 0 && isWhitespace(s[j])) j--;
|
|
9523
|
+
return j;
|
|
9524
|
+
}
|
|
9525
|
+
/**
|
|
9526
|
+
* Keys that only ever belong at a component's top level. Seen nested inside
|
|
9527
|
+
* the component's objects, they mean the model forgot closing braces.
|
|
9528
|
+
*/
|
|
9529
|
+
const STRUCTURAL_KEYS = new Set([
|
|
9530
|
+
"id",
|
|
9531
|
+
"component",
|
|
9532
|
+
"child",
|
|
9533
|
+
"children"
|
|
9534
|
+
]);
|
|
9535
|
+
/** Whether a value starting with `ch` has the shape `key` takes on a component. */
|
|
9536
|
+
function structuralValueFits(key, ch) {
|
|
9537
|
+
if (key === "children") return ch === "[" || ch === "{";
|
|
9538
|
+
return ch === "\"";
|
|
9539
|
+
}
|
|
9540
|
+
/** `{"id":` — a new component object starting at `i`. */
|
|
9541
|
+
const COMPONENT_START = /^\{\s*"id"\s*:/;
|
|
9542
|
+
/**
|
|
9543
|
+
* Structural-key depth repair for one component item. While scanning, a
|
|
9544
|
+
* structural key (`id`, `component`, `child`, `children`) found as an object
|
|
9545
|
+
* key below the item's top level, with only objects (no arrays) between it
|
|
9546
|
+
* and the item root, a value of the expected shape, and not already present
|
|
9547
|
+
* at the top level, means closing braces were dropped: the missing `}` are
|
|
9548
|
+
* synthesized right before it so it lands at the top level. Containers still
|
|
9549
|
+
* open at the end are closed. Returns null when a string never terminates.
|
|
9550
|
+
*/
|
|
9551
|
+
function repairComponentItem(item) {
|
|
9552
|
+
const stack = [];
|
|
9553
|
+
const topKeys = /* @__PURE__ */ new Set();
|
|
9554
|
+
let out = "";
|
|
9555
|
+
let copied = 0;
|
|
9556
|
+
for (let i = 0; i < item.length; i++) {
|
|
9557
|
+
const c = item[i];
|
|
9558
|
+
if (c === "\"") {
|
|
9559
|
+
const end = findStringEnd(item, i);
|
|
9560
|
+
if (end < 0) return null;
|
|
9561
|
+
const prev = prevNonWhitespace(item, i);
|
|
9562
|
+
const prevCh = item[prev];
|
|
9563
|
+
const colon = skipWhitespace(item, end + 1);
|
|
9564
|
+
if (stack[stack.length - 1] === "{" && (prevCh === "," || prevCh === "{") && item[colon] === ":") {
|
|
9565
|
+
let key;
|
|
9566
|
+
try {
|
|
9567
|
+
key = JSON.parse(item.slice(i, end + 1));
|
|
9568
|
+
} catch {
|
|
9569
|
+
return null;
|
|
9570
|
+
}
|
|
9571
|
+
if (typeof key === "string") {
|
|
9572
|
+
if (stack.length === 1) topKeys.add(key);
|
|
9573
|
+
else if (STRUCTURAL_KEYS.has(key) && !topKeys.has(key) && stack.every((x) => x === "{") && structuralValueFits(key, item[skipWhitespace(item, colon + 1)])) {
|
|
9574
|
+
const closers = "}".repeat(stack.length - 1);
|
|
9575
|
+
if (prevCh === ",") {
|
|
9576
|
+
out += item.slice(copied, prev) + closers;
|
|
9577
|
+
copied = prev;
|
|
9578
|
+
} else {
|
|
9579
|
+
out += item.slice(copied, i) + closers + ",";
|
|
9580
|
+
copied = i;
|
|
9581
|
+
}
|
|
9582
|
+
stack.length = 1;
|
|
9583
|
+
topKeys.add(key);
|
|
9584
|
+
}
|
|
9585
|
+
}
|
|
9586
|
+
}
|
|
9587
|
+
i = end;
|
|
9588
|
+
continue;
|
|
9589
|
+
}
|
|
9590
|
+
if (c === "{" || c === "[") stack.push(c);
|
|
9591
|
+
else if (c === "}" || c === "]") {
|
|
9592
|
+
stack.pop();
|
|
9593
|
+
if (stack.length === 0) return out + item.slice(copied, i + 1);
|
|
9594
|
+
}
|
|
9595
|
+
}
|
|
9596
|
+
const closers = stack.reduceRight((text, opener) => text + (opener === "{" ? "}" : "]"), "");
|
|
9597
|
+
return out + item.slice(copied) + closers;
|
|
9598
|
+
}
|
|
9599
|
+
function parseRecord(text) {
|
|
9600
|
+
if (text === null) return void 0;
|
|
9601
|
+
try {
|
|
9602
|
+
const value = JSON.parse(text);
|
|
9603
|
+
return isRecord(value) ? value : void 0;
|
|
9604
|
+
} catch {
|
|
9605
|
+
return;
|
|
9606
|
+
}
|
|
9607
|
+
}
|
|
9608
|
+
/**
|
|
9609
|
+
* Complete items of the (possibly unterminated) array whose "[" is at `open`.
|
|
9610
|
+
* With `repairComponents`, an item that balanced but does not parse is retried
|
|
9611
|
+
* with structural-key repair, and a `,{"id":` where an item expects a key
|
|
9612
|
+
* ends that (unbalanced) item there, so one malformed component cannot
|
|
9613
|
+
* swallow the rest of the array; the cut item is kept only if repair makes
|
|
9614
|
+
* it parse.
|
|
9615
|
+
*/
|
|
9616
|
+
function completeArrayItemsAt(partialJson, open, options) {
|
|
9617
|
+
const { repairComponents } = options;
|
|
9618
|
+
const s = partialJson;
|
|
9619
|
+
const items = [];
|
|
9620
|
+
const stack = [];
|
|
9621
|
+
let inString = false;
|
|
9622
|
+
let itemStart = -1;
|
|
9623
|
+
const finishItem = (end, balanced) => {
|
|
9624
|
+
const raw = s.slice(itemStart, end);
|
|
9625
|
+
if (!repairComponents) {
|
|
9626
|
+
pushItem(raw, items);
|
|
9627
|
+
return;
|
|
9628
|
+
}
|
|
9629
|
+
if (balanced) try {
|
|
9630
|
+
items.push(JSON.parse(raw));
|
|
9631
|
+
return;
|
|
9632
|
+
} catch {}
|
|
9633
|
+
const repaired = parseRecord(repairComponentItem(raw.trim()));
|
|
9634
|
+
if (repaired !== void 0) items.push(repaired);
|
|
9635
|
+
};
|
|
9636
|
+
for (let i = open + 1; i < s.length; i++) {
|
|
9637
|
+
const c = s[i];
|
|
9638
|
+
if (inString) {
|
|
9639
|
+
if (c === "\\") i++;
|
|
9640
|
+
else if (c === "\"") inString = false;
|
|
9641
|
+
continue;
|
|
9642
|
+
}
|
|
9643
|
+
if (c === "\"") {
|
|
9644
|
+
inString = true;
|
|
9645
|
+
if (stack.length === 0 && itemStart < 0) itemStart = i;
|
|
9646
|
+
continue;
|
|
9647
|
+
}
|
|
9648
|
+
if (c === "{" || c === "[") {
|
|
9649
|
+
if (repairComponents && c === "{" && stack[stack.length - 1] === "{" && COMPONENT_START.test(s.slice(i, i + 24))) {
|
|
9650
|
+
const prev = prevNonWhitespace(s, i);
|
|
9651
|
+
if (s[prev] === ",") {
|
|
9652
|
+
finishItem(prev, false);
|
|
9653
|
+
stack.length = 0;
|
|
9654
|
+
itemStart = i;
|
|
9655
|
+
stack.push(c);
|
|
9656
|
+
continue;
|
|
9657
|
+
}
|
|
9658
|
+
}
|
|
9659
|
+
if (stack.length === 0) itemStart = i;
|
|
9660
|
+
stack.push(c);
|
|
9661
|
+
continue;
|
|
9662
|
+
}
|
|
9663
|
+
if (c === "}" || c === "]") {
|
|
9664
|
+
if (stack.length === 0) {
|
|
9665
|
+
if (c === "]") {
|
|
9666
|
+
if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
|
|
9667
|
+
return {
|
|
9668
|
+
items,
|
|
9669
|
+
closed: true
|
|
9670
|
+
};
|
|
9671
|
+
}
|
|
9672
|
+
return {
|
|
9673
|
+
items,
|
|
9674
|
+
closed: false
|
|
9675
|
+
};
|
|
9676
|
+
}
|
|
9677
|
+
stack.pop();
|
|
9678
|
+
if (stack.length === 0) {
|
|
9679
|
+
finishItem(i + 1, true);
|
|
9680
|
+
itemStart = -1;
|
|
9681
|
+
}
|
|
9682
|
+
continue;
|
|
9683
|
+
}
|
|
9684
|
+
if (stack.length === 0) {
|
|
9685
|
+
if (c === ",") {
|
|
9686
|
+
if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
|
|
9687
|
+
itemStart = -1;
|
|
9688
|
+
} else if (itemStart < 0 && !isWhitespace(c)) itemStart = i;
|
|
9689
|
+
}
|
|
9690
|
+
}
|
|
9691
|
+
return {
|
|
9692
|
+
items,
|
|
9693
|
+
closed: false
|
|
9694
|
+
};
|
|
9695
|
+
}
|
|
9696
|
+
/** The first operation key whose value is an object, with that value. */
|
|
9697
|
+
function getOperationEntry(op) {
|
|
9698
|
+
for (const key of OP_KEYS) {
|
|
9699
|
+
const inner = op[key];
|
|
9700
|
+
if (isRecord(inner)) return {
|
|
9701
|
+
key,
|
|
9702
|
+
inner
|
|
9703
|
+
};
|
|
9704
|
+
}
|
|
9705
|
+
return null;
|
|
9706
|
+
}
|
|
9707
|
+
/**
|
|
9708
|
+
* The surfaceId an operation targets: the one nested under its operation key,
|
|
9709
|
+
* else a top-level `surfaceId`. A `callRendererFunction` operation targets no
|
|
9710
|
+
* surface, so it gets undefined.
|
|
9711
|
+
*
|
|
9712
|
+
* It is named `getMarkdownOperationSurfaceId` because `@copilotkit/shared`
|
|
9713
|
+
* already exports a strict `getOperationSurfaceId`. This one also reads a
|
|
9714
|
+
* top-level `surfaceId`, which models sometimes write.
|
|
9715
|
+
*
|
|
9716
|
+
* @param op - An operation from an a2ui fence.
|
|
9717
|
+
* @returns The surfaceId, or undefined when the operation names none or is a
|
|
9718
|
+
* function call.
|
|
9719
|
+
*
|
|
9720
|
+
* @example
|
|
9721
|
+
* ```ts
|
|
9722
|
+
* getMarkdownOperationSurfaceId({ updateDataModel: { surfaceId: "plan" } }); // "plan"
|
|
9723
|
+
* ```
|
|
9724
|
+
*/
|
|
9725
|
+
function getMarkdownOperationSurfaceId(op) {
|
|
9726
|
+
if (getOperationEntry(op)?.key === FUNCTION_CALL_KEY) return void 0;
|
|
9727
|
+
for (const key of SURFACE_OP_KEYS) {
|
|
9728
|
+
const inner = op[key];
|
|
9729
|
+
if (isRecord(inner) && typeof inner.surfaceId === "string") return inner.surfaceId;
|
|
9730
|
+
}
|
|
9731
|
+
return typeof op.surfaceId === "string" ? op.surfaceId : void 0;
|
|
9732
|
+
}
|
|
9733
|
+
/**
|
|
9734
|
+
* Index just past the JSON value starting at `start`, or -1 when the value is
|
|
9735
|
+
* still incomplete. A primitive at the very end of the input counts as
|
|
9736
|
+
* incomplete, since more digits or letters may still stream in.
|
|
9737
|
+
*/
|
|
9738
|
+
function findValueEnd(s, start) {
|
|
9739
|
+
const c = s[start];
|
|
9740
|
+
if (c === "\"") {
|
|
9741
|
+
const end = findStringEnd(s, start);
|
|
9742
|
+
return end < 0 ? -1 : end + 1;
|
|
9743
|
+
}
|
|
9744
|
+
if (c === "{" || c === "[") {
|
|
9745
|
+
let depth = 0;
|
|
9746
|
+
for (let i = start; i < s.length; i++) {
|
|
9747
|
+
const ch = s[i];
|
|
9748
|
+
if (ch === "\"") {
|
|
9749
|
+
const end = findStringEnd(s, i);
|
|
9750
|
+
if (end < 0) return -1;
|
|
9751
|
+
i = end;
|
|
9752
|
+
} else if (ch === "{" || ch === "[") depth++;
|
|
9753
|
+
else if (ch === "}" || ch === "]") {
|
|
9754
|
+
depth--;
|
|
9755
|
+
if (depth === 0) return i + 1;
|
|
9756
|
+
}
|
|
9757
|
+
}
|
|
9758
|
+
return -1;
|
|
9759
|
+
}
|
|
9760
|
+
let i = start;
|
|
9761
|
+
while (i < s.length && !isWhitespace(s[i]) && !",}]".includes(s[i])) i++;
|
|
9762
|
+
return i >= s.length ? -1 : i;
|
|
9763
|
+
}
|
|
9764
|
+
/**
|
|
9765
|
+
* Walk the direct entries of the (possibly unterminated) JSON object whose "{"
|
|
9766
|
+
* is at `objStart`, calling `visit` with each key and the index where its value
|
|
9767
|
+
* starts. Nested objects and arrays are skipped whole, so keys inside them are
|
|
9768
|
+
* never visited. Stops when `visit` returns true, at the object's end, or where
|
|
9769
|
+
* the input runs out.
|
|
9770
|
+
*/
|
|
9771
|
+
function visitDirectEntries(s, objStart, visit) {
|
|
9772
|
+
let i = objStart + 1;
|
|
9773
|
+
while (i < s.length) {
|
|
9774
|
+
i = skipWhitespace(s, i);
|
|
9775
|
+
const c = s[i];
|
|
9776
|
+
if (c === ",") {
|
|
9777
|
+
i++;
|
|
9778
|
+
continue;
|
|
9779
|
+
}
|
|
9780
|
+
if (c !== "\"") return;
|
|
9781
|
+
const keyEnd = findStringEnd(s, i);
|
|
9782
|
+
if (keyEnd < 0) return;
|
|
9783
|
+
let key;
|
|
9784
|
+
try {
|
|
9785
|
+
key = JSON.parse(s.slice(i, keyEnd + 1));
|
|
9786
|
+
} catch {
|
|
9787
|
+
return;
|
|
9788
|
+
}
|
|
9789
|
+
i = skipWhitespace(s, keyEnd + 1);
|
|
9790
|
+
if (s[i] !== ":") return;
|
|
9791
|
+
i = skipWhitespace(s, i + 1);
|
|
9792
|
+
if (i >= s.length) return;
|
|
9793
|
+
if (typeof key === "string" && visit(key, i)) return;
|
|
9794
|
+
const valueEnd = findValueEnd(s, i);
|
|
9795
|
+
if (valueEnd < 0) return;
|
|
9796
|
+
i = valueEnd;
|
|
9797
|
+
}
|
|
9798
|
+
}
|
|
9799
|
+
/**
|
|
9800
|
+
* Value start of a direct `key` of the object at `objStart` whose value begins
|
|
9801
|
+
* with `opener` (any value when omitted), or -1.
|
|
9802
|
+
*/
|
|
9803
|
+
function findDirectKeyValue(s, objStart, key, opener) {
|
|
9804
|
+
let found = -1;
|
|
9805
|
+
visitDirectEntries(s, objStart, (k, valueStart) => {
|
|
9806
|
+
if (k !== key) return false;
|
|
9807
|
+
if (opener === void 0 || s[valueStart] === opener) found = valueStart;
|
|
9808
|
+
return true;
|
|
9809
|
+
});
|
|
9810
|
+
return found;
|
|
9811
|
+
}
|
|
9812
|
+
/** A direct string field of the object at `objStart`, once its closing quote has arrived. */
|
|
9813
|
+
function readDirectString(s, objStart, key) {
|
|
9814
|
+
if (objStart < 0) return null;
|
|
9815
|
+
const start = findDirectKeyValue(s, objStart, key, "\"");
|
|
9816
|
+
if (start < 0) return null;
|
|
9817
|
+
const end = findValueEnd(s, start);
|
|
9818
|
+
if (end < 0) return null;
|
|
9819
|
+
try {
|
|
9820
|
+
const value = JSON.parse(s.slice(start, end));
|
|
9821
|
+
return typeof value === "string" ? value : null;
|
|
9822
|
+
} catch {
|
|
9823
|
+
return null;
|
|
9824
|
+
}
|
|
9825
|
+
}
|
|
9826
|
+
/** A direct object field of the object at `objStart`, once the whole object has arrived. */
|
|
9827
|
+
function readDirectRecord(s, objStart, key) {
|
|
9828
|
+
const start = findDirectKeyValue(s, objStart, key, "{");
|
|
9829
|
+
if (start < 0) return void 0;
|
|
9830
|
+
const end = findValueEnd(s, start);
|
|
9831
|
+
if (end < 0) return void 0;
|
|
9832
|
+
return parseRecord(s.slice(start, end));
|
|
9833
|
+
}
|
|
9834
|
+
/**
|
|
9835
|
+
* The complete part of a (possibly unterminated) JSON value: the parsed value
|
|
9836
|
+
* when it is complete; for an open object, its complete entries plus the
|
|
9837
|
+
* complete items of any streaming array entry; otherwise undefined.
|
|
9838
|
+
*/
|
|
9839
|
+
function completePartOfValue(s, start) {
|
|
9840
|
+
const end = findValueEnd(s, start);
|
|
9841
|
+
if (end >= 0) try {
|
|
9842
|
+
return JSON.parse(s.slice(start, end));
|
|
9843
|
+
} catch {
|
|
9844
|
+
return;
|
|
9845
|
+
}
|
|
9846
|
+
if (s[start] !== "{") return void 0;
|
|
9847
|
+
const out = {};
|
|
9848
|
+
visitDirectEntries(s, start, (key, valueStart) => {
|
|
9849
|
+
const valueEnd = findValueEnd(s, valueStart);
|
|
9850
|
+
if (valueEnd >= 0) try {
|
|
9851
|
+
out[key] = JSON.parse(s.slice(valueStart, valueEnd));
|
|
9852
|
+
} catch {}
|
|
9853
|
+
else if (s[valueStart] === "[") {
|
|
9854
|
+
const { items } = completeArrayItemsAt(s, valueStart, { repairComponents: false });
|
|
9855
|
+
if (items.length > 0) out[key] = items;
|
|
9856
|
+
}
|
|
9857
|
+
return false;
|
|
9858
|
+
});
|
|
9859
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
9860
|
+
}
|
|
9861
|
+
/**
|
|
9862
|
+
* Best-effort operation from an unfinished or malformed top-level object.
|
|
9863
|
+
* Fields are read only from the operation's own keys (`version` at the top
|
|
9864
|
+
* level, `surfaceId`, `catalogId`, `path`, `dataModel` and `components` inside
|
|
9865
|
+
* the operation object), never from component props or data-model values that
|
|
9866
|
+
* happen to share a name.
|
|
9867
|
+
*
|
|
9868
|
+
* A `createSurface` keeps its complete components and a `dataModel` that has
|
|
9869
|
+
* fully arrived, so a surface created in one line renders while it streams.
|
|
9870
|
+
* A `callRendererFunction` gives nothing: a function must not run with half
|
|
9871
|
+
* of its args.
|
|
9872
|
+
*/
|
|
9873
|
+
function partialOperation(line) {
|
|
9874
|
+
const root = skipWhitespace(line, 0);
|
|
9875
|
+
if (line[root] !== "{") return null;
|
|
9876
|
+
const version = readDirectString(line, root, "version") ?? _copilotkit_shared.A2UI_VERSION;
|
|
9877
|
+
const components = findDirectKeyValue(line, root, "updateComponents", "{");
|
|
9878
|
+
if (components >= 0) {
|
|
9879
|
+
const arrayStart = findDirectKeyValue(line, components, "components", "[");
|
|
9880
|
+
if (arrayStart < 0) return null;
|
|
9881
|
+
const { items } = completeArrayItemsAt(line, arrayStart, { repairComponents: true });
|
|
9882
|
+
if (items.length === 0) return null;
|
|
9883
|
+
const surfaceId = readDirectString(line, components, "surfaceId");
|
|
9884
|
+
return {
|
|
9885
|
+
version,
|
|
9886
|
+
updateComponents: {
|
|
9887
|
+
...surfaceId ? { surfaceId } : {},
|
|
9888
|
+
components: items
|
|
9889
|
+
}
|
|
9890
|
+
};
|
|
9891
|
+
}
|
|
9892
|
+
const data = findDirectKeyValue(line, root, "updateDataModel", "{");
|
|
9893
|
+
if (data >= 0) {
|
|
9894
|
+
const valueStart = findDirectKeyValue(line, data, "value");
|
|
9895
|
+
if (valueStart < 0) return null;
|
|
9896
|
+
const value = completePartOfValue(line, valueStart);
|
|
9897
|
+
if (value === void 0) return null;
|
|
9898
|
+
const surfaceId = readDirectString(line, data, "surfaceId");
|
|
9899
|
+
const path = readDirectString(line, data, "path");
|
|
9900
|
+
return {
|
|
9901
|
+
version,
|
|
9902
|
+
updateDataModel: {
|
|
9903
|
+
...surfaceId ? { surfaceId } : {},
|
|
9904
|
+
...path ? { path } : {},
|
|
9905
|
+
value
|
|
9906
|
+
}
|
|
9907
|
+
};
|
|
9908
|
+
}
|
|
9909
|
+
const create = findDirectKeyValue(line, root, "createSurface", "{");
|
|
9910
|
+
if (create >= 0) {
|
|
9911
|
+
const surfaceId = readDirectString(line, create, "surfaceId");
|
|
9912
|
+
if (!surfaceId) return null;
|
|
9913
|
+
const catalogId = readDirectString(line, create, "catalogId");
|
|
9914
|
+
const dataModel = readDirectRecord(line, create, "dataModel");
|
|
9915
|
+
const componentsStart = findDirectKeyValue(line, create, "components", "[");
|
|
9916
|
+
const components = componentsStart < 0 ? [] : completeArrayItemsAt(line, componentsStart, { repairComponents: true }).items;
|
|
9917
|
+
return {
|
|
9918
|
+
version,
|
|
9919
|
+
createSurface: {
|
|
9920
|
+
surfaceId,
|
|
9921
|
+
...catalogId ? { catalogId } : {},
|
|
9922
|
+
...dataModel ? { dataModel } : {},
|
|
9923
|
+
...components.length > 0 ? { components } : {}
|
|
9924
|
+
}
|
|
9925
|
+
};
|
|
9926
|
+
}
|
|
9927
|
+
return null;
|
|
9928
|
+
}
|
|
9929
|
+
/**
|
|
9930
|
+
* A line that opens a new top-level operation: `{"version":"v…` or
|
|
9931
|
+
* `{"<operation>":{`. Seen at the start of a line while an earlier object is
|
|
9932
|
+
* still unbalanced, it means that object is malformed and has ended.
|
|
9933
|
+
*/
|
|
9934
|
+
const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"v\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
|
|
9935
|
+
/**
|
|
9936
|
+
* Scan the top-level object whose "{" is at `start`. Returns the index just
|
|
9937
|
+
* past it and whether it balanced. An unbalanced object ends early (at the
|
|
9938
|
+
* start of the line) when a line opens a new operation; otherwise it runs to
|
|
9939
|
+
* the end of the input. JSON strings cannot contain raw newlines, so a newline
|
|
9940
|
+
* inside a string ends it: a stray quote then breaks one line, not the rest of
|
|
9941
|
+
* the fence.
|
|
9942
|
+
*/
|
|
9943
|
+
function scanTopLevelObject(s, start) {
|
|
9944
|
+
let depth = 0;
|
|
9945
|
+
let inString = false;
|
|
9946
|
+
for (let i = start; i < s.length; i++) {
|
|
9947
|
+
const c = s[i];
|
|
9948
|
+
if (inString) {
|
|
9949
|
+
if (c === "\\" && s[i + 1] !== "\n") i++;
|
|
9950
|
+
else if (c === "\"" || c === "\n") inString = false;
|
|
9951
|
+
if (c !== "\n") continue;
|
|
9952
|
+
}
|
|
9953
|
+
if (c === "\n") {
|
|
9954
|
+
const next = skipWhitespace(s, i + 1);
|
|
9955
|
+
if (OPERATION_START.test(s.slice(next, next + 40))) return {
|
|
9956
|
+
end: i + 1,
|
|
9957
|
+
balanced: false
|
|
9958
|
+
};
|
|
9959
|
+
continue;
|
|
9960
|
+
}
|
|
9961
|
+
if (c === "\"") inString = true;
|
|
9962
|
+
else if (c === "{" || c === "[") depth++;
|
|
9963
|
+
else if (c === "}" || c === "]") {
|
|
9964
|
+
depth--;
|
|
9965
|
+
if (depth === 0) return {
|
|
9966
|
+
end: i + 1,
|
|
9967
|
+
balanced: true
|
|
9968
|
+
};
|
|
9969
|
+
}
|
|
9970
|
+
}
|
|
9971
|
+
return {
|
|
9972
|
+
end: s.length,
|
|
9973
|
+
balanced: false
|
|
9974
|
+
};
|
|
9975
|
+
}
|
|
9976
|
+
/**
|
|
9977
|
+
* Parse the body of an a2ui fence as a stream of top-level JSON values, so
|
|
9978
|
+
* operations may be one per line (the documented format), several per line,
|
|
9979
|
+
* pretty-printed over many lines, or wrapped in a top-level array (which is
|
|
9980
|
+
* flattened). Whitespace and commas between objects are ignored.
|
|
9981
|
+
*
|
|
9982
|
+
* - A balanced object is `JSON.parse`d. When that fails (e.g. a stray quote),
|
|
9983
|
+
* its raw text goes to `invalidLines` and whatever `partialOperation` can
|
|
9984
|
+
* salvage (complete components, data-model entries, createSurface fields)
|
|
9985
|
+
* is kept.
|
|
9986
|
+
* - An unbalanced object followed by a line that opens a new operation is
|
|
9987
|
+
* treated the same way.
|
|
9988
|
+
* - The trailing unbalanced object (still streaming, or never closed) is
|
|
9989
|
+
* `partialObject` and yields a partial operation when it has usable data.
|
|
9990
|
+
* - Other text between objects is skipped and reported in `recovered` (and in
|
|
9991
|
+
* `invalidLines`, which predates it).
|
|
9992
|
+
*
|
|
9993
|
+
* `partialLine` is a deprecated alias of `partialObject`.
|
|
9994
|
+
*
|
|
9995
|
+
* @param fenceText - The body of an a2ui fence (`text` of an a2ui
|
|
9996
|
+
* `MarkdownSegment`), complete or still streaming.
|
|
9997
|
+
* @returns `{ operations, partialObject, partialLine, invalidLines, recovered }`.
|
|
9998
|
+
*
|
|
9999
|
+
* @example
|
|
10000
|
+
* ```ts
|
|
10001
|
+
* const { operations } = extractFenceOperations(segment.text);
|
|
10002
|
+
* ```
|
|
10003
|
+
*/
|
|
10004
|
+
function extractFenceOperations(fenceText) {
|
|
10005
|
+
const s = fenceText;
|
|
10006
|
+
const operations = [];
|
|
10007
|
+
const invalidLines = [];
|
|
10008
|
+
const recovered = [];
|
|
10009
|
+
let partialObject = null;
|
|
10010
|
+
const salvage = (raw) => {
|
|
10011
|
+
invalidLines.push(raw.trim());
|
|
10012
|
+
const partial = partialOperation(raw);
|
|
10013
|
+
if (partial) operations.push(partial);
|
|
10014
|
+
};
|
|
10015
|
+
let junkStart = -1;
|
|
10016
|
+
const flushJunk = (end) => {
|
|
10017
|
+
if (junkStart < 0) return;
|
|
10018
|
+
const junk = s.slice(junkStart, end).trim();
|
|
10019
|
+
junkStart = -1;
|
|
10020
|
+
if (!junk) return;
|
|
10021
|
+
recovered.push(junk);
|
|
10022
|
+
invalidLines.push(junk);
|
|
10023
|
+
};
|
|
10024
|
+
let i = 0;
|
|
10025
|
+
while (i < s.length) {
|
|
10026
|
+
const c = s[i];
|
|
10027
|
+
if (c === "{") {
|
|
10028
|
+
flushJunk(i);
|
|
10029
|
+
const { end, balanced } = scanTopLevelObject(s, i);
|
|
10030
|
+
const raw = s.slice(i, end);
|
|
10031
|
+
if (balanced) {
|
|
10032
|
+
let parsed;
|
|
10033
|
+
try {
|
|
10034
|
+
parsed = JSON.parse(raw);
|
|
10035
|
+
} catch {
|
|
10036
|
+
parsed = void 0;
|
|
10037
|
+
}
|
|
10038
|
+
if (isRecord(parsed)) operations.push(parsed);
|
|
10039
|
+
else salvage(raw);
|
|
10040
|
+
} else if (end < s.length) salvage(raw);
|
|
10041
|
+
else {
|
|
10042
|
+
partialObject = raw;
|
|
10043
|
+
const partial = partialOperation(raw);
|
|
10044
|
+
if (partial) operations.push(partial);
|
|
10045
|
+
}
|
|
10046
|
+
i = end;
|
|
10047
|
+
continue;
|
|
10048
|
+
}
|
|
10049
|
+
if (c === "\n" || c === "[" || c === "]") flushJunk(i);
|
|
10050
|
+
else if (junkStart < 0 && !isWhitespace(c) && c !== ",") junkStart = i;
|
|
10051
|
+
i++;
|
|
10052
|
+
}
|
|
10053
|
+
flushJunk(s.length);
|
|
10054
|
+
return {
|
|
10055
|
+
operations,
|
|
10056
|
+
partialObject,
|
|
10057
|
+
partialLine: partialObject,
|
|
10058
|
+
invalidLines,
|
|
10059
|
+
recovered
|
|
10060
|
+
};
|
|
10061
|
+
}
|
|
10062
|
+
/**
|
|
10063
|
+
* Normalise a fence's operations for the renderer: drop unknown messages, fill
|
|
10064
|
+
* in `version` and missing `surfaceId`s, keep only the first `createSurface`,
|
|
10065
|
+
* keep its `catalogId` when `catalogIds` lists it (else use `catalogId`), synthesize
|
|
10066
|
+
* `createSurface` when the model omitted it, and report the
|
|
10067
|
+
* surfaceId (the first one found, else `fallbackSurfaceId`).
|
|
10068
|
+
*
|
|
10069
|
+
* `callRendererFunction` operations target no surface. They get no surfaceId,
|
|
10070
|
+
* do not cause a synthesized `createSurface`, and come back in
|
|
10071
|
+
* `functionCalls` (in fence order), never in `operations`.
|
|
10072
|
+
*
|
|
10073
|
+
* @param input.operations - Operations from `extractFenceOperations`.
|
|
10074
|
+
* @param input.fallbackSurfaceId - The surfaceId to use when no operation
|
|
10075
|
+
* names one.
|
|
10076
|
+
* @param input.catalogId - The client catalog. It replaces a catalogId of the
|
|
10077
|
+
* model that `catalogIds` does not list.
|
|
10078
|
+
* @param input.catalogIds - The catalogs that the model can name. Left out,
|
|
10079
|
+
* only `catalogId`.
|
|
10080
|
+
* @returns `{ surfaceId, operations, functionCalls }`.
|
|
10081
|
+
*
|
|
10082
|
+
* @example
|
|
10083
|
+
* ```ts
|
|
10084
|
+
* const { surfaceId, operations, functionCalls } = prepareSurfaceOperations({
|
|
10085
|
+
* operations: extractFenceOperations(segment.text).operations,
|
|
10086
|
+
* fallbackSurfaceId: `${messageId}-${segment.index}`,
|
|
10087
|
+
* catalogId,
|
|
10088
|
+
* });
|
|
10089
|
+
* ```
|
|
10090
|
+
*/
|
|
10091
|
+
function prepareSurfaceOperations(input) {
|
|
10092
|
+
const { operations, fallbackSurfaceId, catalogId } = input;
|
|
10093
|
+
const catalogIds = input.catalogIds ?? [catalogId];
|
|
10094
|
+
const surfaceId = operations.map(getMarkdownOperationSurfaceId).find((id) => !!id) ?? fallbackSurfaceId;
|
|
10095
|
+
const out = [];
|
|
10096
|
+
const functionCalls = [];
|
|
10097
|
+
let hasCreate = false;
|
|
10098
|
+
for (const op of operations) {
|
|
10099
|
+
const entry = getOperationEntry(op);
|
|
10100
|
+
if (!entry) continue;
|
|
10101
|
+
const { key } = entry;
|
|
10102
|
+
const inner = { ...entry.inner };
|
|
10103
|
+
const version = typeof op.version === "string" ? op.version : _copilotkit_shared.A2UI_VERSION;
|
|
10104
|
+
if (key === FUNCTION_CALL_KEY) {
|
|
10105
|
+
functionCalls.push({
|
|
10106
|
+
version,
|
|
10107
|
+
[key]: inner
|
|
10108
|
+
});
|
|
10109
|
+
continue;
|
|
10110
|
+
}
|
|
10111
|
+
if (typeof inner.surfaceId !== "string") inner.surfaceId = surfaceId;
|
|
10112
|
+
if (key === "createSurface") {
|
|
10113
|
+
if (hasCreate) {
|
|
10114
|
+
const { surfaceId: id, dataModel, components } = inner;
|
|
10115
|
+
if (dataModel !== void 0) out.push({
|
|
10116
|
+
version,
|
|
10117
|
+
updateDataModel: {
|
|
10118
|
+
surfaceId: id,
|
|
10119
|
+
path: "/",
|
|
10120
|
+
value: dataModel
|
|
10121
|
+
}
|
|
10122
|
+
});
|
|
10123
|
+
if (Array.isArray(components) && components.length > 0) out.push({
|
|
10124
|
+
version,
|
|
10125
|
+
updateComponents: {
|
|
10126
|
+
surfaceId: id,
|
|
10127
|
+
components
|
|
10128
|
+
}
|
|
10129
|
+
});
|
|
10130
|
+
continue;
|
|
10131
|
+
}
|
|
10132
|
+
hasCreate = true;
|
|
10133
|
+
if (!catalogIds.includes(inner.catalogId)) inner.catalogId = catalogId;
|
|
10134
|
+
}
|
|
10135
|
+
out.push({
|
|
10136
|
+
version,
|
|
10137
|
+
[key]: inner
|
|
10138
|
+
});
|
|
10139
|
+
}
|
|
10140
|
+
if (!hasCreate && out.length > 0) out.unshift({
|
|
10141
|
+
version: _copilotkit_shared.A2UI_VERSION,
|
|
10142
|
+
createSurface: {
|
|
10143
|
+
surfaceId,
|
|
10144
|
+
catalogId
|
|
10145
|
+
}
|
|
10146
|
+
});
|
|
10147
|
+
return {
|
|
10148
|
+
surfaceId,
|
|
10149
|
+
operations: out,
|
|
10150
|
+
functionCalls
|
|
10151
|
+
};
|
|
10152
|
+
}
|
|
10153
|
+
/**
|
|
10154
|
+
* Components a user operates. A Card containing one of these is an
|
|
10155
|
+
* interactive panel and keeps its box; every other Card is informational.
|
|
10156
|
+
*/
|
|
10157
|
+
const INTERACTIVE_COMPONENTS = new Set([
|
|
10158
|
+
"Button",
|
|
10159
|
+
"Pressable",
|
|
10160
|
+
"Form",
|
|
10161
|
+
"TextField",
|
|
10162
|
+
"TextArea",
|
|
10163
|
+
"Select",
|
|
10164
|
+
"CheckBox",
|
|
10165
|
+
"Radio",
|
|
10166
|
+
"RadioGroup",
|
|
10167
|
+
"Slider",
|
|
10168
|
+
"SegmentedControl",
|
|
10169
|
+
"ChoicePicker",
|
|
10170
|
+
"DateTimeInput"
|
|
10171
|
+
]);
|
|
10172
|
+
/** A component id referenced by a `child`/`children` entry or a table cell. */
|
|
10173
|
+
function referencedId(value) {
|
|
10174
|
+
if (typeof value === "string") return value;
|
|
10175
|
+
if (isRecord(value)) {
|
|
10176
|
+
if (typeof value.componentId === "string") return value.componentId;
|
|
10177
|
+
if (typeof value.id === "string") return value.id;
|
|
10178
|
+
}
|
|
10179
|
+
}
|
|
10180
|
+
/** Ids of a table cell / column that renders a component (`{componentId}` or `{id}`). */
|
|
10181
|
+
function cellComponentId(value) {
|
|
10182
|
+
return isRecord(value) ? referencedId(value) : void 0;
|
|
10183
|
+
}
|
|
10184
|
+
/**
|
|
10185
|
+
* Ids a component renders directly: `child`, `children` (string ids, an
|
|
10186
|
+
* array, or a `{componentId}` template), component cells of a Table's
|
|
10187
|
+
* `rows`/`columns`, and the ids that `extra` finds in its typed references.
|
|
10188
|
+
*/
|
|
10189
|
+
function directChildIds(component, extra) {
|
|
10190
|
+
const ids = [];
|
|
10191
|
+
const add = (id) => {
|
|
10192
|
+
if (id) ids.push(id);
|
|
10193
|
+
};
|
|
10194
|
+
const extraIds = extra?.(component);
|
|
10195
|
+
if (Array.isArray(extraIds)) extraIds.forEach(add);
|
|
10196
|
+
add(referencedId(component.child));
|
|
10197
|
+
const children = component.children;
|
|
10198
|
+
if (Array.isArray(children)) children.forEach((c) => add(referencedId(c)));
|
|
10199
|
+
else add(referencedId(children));
|
|
10200
|
+
if (Array.isArray(component.columns)) component.columns.forEach((c) => add(cellComponentId(c)));
|
|
10201
|
+
if (Array.isArray(component.rows)) {
|
|
10202
|
+
for (const row of component.rows) if (Array.isArray(row)) row.forEach((c) => add(cellComponentId(c)));
|
|
10203
|
+
}
|
|
10204
|
+
return ids;
|
|
10205
|
+
}
|
|
10206
|
+
/** Components of every updateComponents operation, by id (last definition wins). */
|
|
10207
|
+
function componentsById(operations) {
|
|
10208
|
+
const byId = /* @__PURE__ */ new Map();
|
|
10209
|
+
for (const op of operations) {
|
|
10210
|
+
const update = op.updateComponents;
|
|
10211
|
+
const list = isRecord(update) ? update.components : void 0;
|
|
10212
|
+
if (!Array.isArray(list)) continue;
|
|
10213
|
+
for (const c of list) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
|
|
10214
|
+
}
|
|
10215
|
+
return byId;
|
|
10216
|
+
}
|
|
10217
|
+
function descendantIds(rootId, byId, extra) {
|
|
10218
|
+
const seen = /* @__PURE__ */ new Set();
|
|
10219
|
+
const stack = [...directChildIds(byId.get(rootId) ?? {}, extra)];
|
|
10220
|
+
while (stack.length > 0) {
|
|
10221
|
+
const id = stack.pop();
|
|
10222
|
+
if (seen.has(id) || id === rootId) continue;
|
|
10223
|
+
seen.add(id);
|
|
10224
|
+
const c = byId.get(id);
|
|
10225
|
+
if (c) stack.push(...directChildIds(c, extra));
|
|
10226
|
+
}
|
|
10227
|
+
return seen;
|
|
10228
|
+
}
|
|
10229
|
+
/**
|
|
10230
|
+
* Ids of the `Card` components that are interactive panels: at least one
|
|
10231
|
+
* descendant (via `child`, `children` or table component cells) is a control
|
|
10232
|
+
* (Button, Pressable, Form, TextField, TextArea, Select, CheckBox, Radio,
|
|
10233
|
+
* RadioGroup, Slider, SegmentedControl, DateTimeInput).
|
|
10234
|
+
*
|
|
10235
|
+
* @param components - The components of one surface.
|
|
10236
|
+
* @returns The ids of the interactive cards.
|
|
10237
|
+
*
|
|
10238
|
+
* @example
|
|
10239
|
+
* ```ts
|
|
10240
|
+
* const interactive = classifySurfaceCards(components);
|
|
10241
|
+
* const keepsBox = interactive.has("quote-form");
|
|
10242
|
+
* ```
|
|
10243
|
+
*/
|
|
10244
|
+
function classifySurfaceCards(components, options = {}) {
|
|
10245
|
+
const byId = /* @__PURE__ */ new Map();
|
|
10246
|
+
for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
|
|
10247
|
+
const interactive = /* @__PURE__ */ new Set();
|
|
10248
|
+
for (const [id, c] of byId) {
|
|
10249
|
+
if (c.component !== "Card") continue;
|
|
10250
|
+
for (const d of descendantIds(id, byId, options.childIds)) {
|
|
10251
|
+
const type = byId.get(d)?.component;
|
|
10252
|
+
if (typeof type === "string" && INTERACTIVE_COMPONENTS.has(type)) {
|
|
10253
|
+
interactive.add(id);
|
|
10254
|
+
break;
|
|
10255
|
+
}
|
|
10256
|
+
}
|
|
10257
|
+
}
|
|
10258
|
+
return interactive;
|
|
10259
|
+
}
|
|
10260
|
+
/**
|
|
10261
|
+
* Markdown mode: only interactive panels keep a box. Every `Card` that is not
|
|
10262
|
+
* an interactive panel (see `classifySurfaceCards`), sets no `variant` or
|
|
10263
|
+
* `border` of its own and is not nested inside an interactive panel becomes
|
|
10264
|
+
* `variant: "section"` (a heading plus content without a box). Operations
|
|
10265
|
+
* other than updateComponents pass through unchanged.
|
|
10266
|
+
*
|
|
10267
|
+
* @param operations - The operations of one surface.
|
|
10268
|
+
* @returns The operations with informational cards set to `variant: "section"`.
|
|
10269
|
+
* When no card changes, it returns the same array.
|
|
10270
|
+
*
|
|
10271
|
+
* @example
|
|
10272
|
+
* ```ts
|
|
10273
|
+
* const operations = flattenInformationalCards(prepared.operations);
|
|
10274
|
+
* ```
|
|
10275
|
+
*/
|
|
10276
|
+
function flattenInformationalCards(operations, options = {}) {
|
|
10277
|
+
const byId = componentsById(operations);
|
|
10278
|
+
if (![...byId.values()].some((c) => c.component === "Card")) return operations;
|
|
10279
|
+
const interactive = classifySurfaceCards([...byId.values()], options);
|
|
10280
|
+
const insideInteractive = /* @__PURE__ */ new Set();
|
|
10281
|
+
for (const id of interactive) for (const d of descendantIds(id, byId, options.childIds)) insideInteractive.add(d);
|
|
10282
|
+
const flatten = (c) => c.component === "Card" && typeof c.id === "string" && !interactive.has(c.id) && !insideInteractive.has(c.id) && c.variant == null && c.border == null;
|
|
10283
|
+
return operations.map((op) => {
|
|
10284
|
+
const update = op.updateComponents;
|
|
10285
|
+
if (!isRecord(update) || !Array.isArray(update.components)) return op;
|
|
10286
|
+
if (!update.components.some((c) => isRecord(c) && flatten(c))) return op;
|
|
10287
|
+
return {
|
|
10288
|
+
...op,
|
|
10289
|
+
updateComponents: {
|
|
10290
|
+
...update,
|
|
10291
|
+
components: update.components.map((c) => isRecord(c) && flatten(c) ? {
|
|
10292
|
+
...c,
|
|
10293
|
+
variant: "section"
|
|
10294
|
+
} : c)
|
|
10295
|
+
}
|
|
10296
|
+
};
|
|
10297
|
+
});
|
|
10298
|
+
}
|
|
10299
|
+
/** Text-bearing components that belong in the chat's markdown, not a surface. */
|
|
10300
|
+
const PROSE_TEXT_COMPONENTS = new Set([
|
|
10301
|
+
"Title",
|
|
10302
|
+
"Text",
|
|
10303
|
+
"Caption",
|
|
10304
|
+
"Markdown"
|
|
10305
|
+
]);
|
|
10306
|
+
/** One line of text: list items and headings cannot span lines in markdown. */
|
|
10307
|
+
function oneLine(text) {
|
|
10308
|
+
return text.trim().replace(/\s*\n\s*/g, " ");
|
|
10309
|
+
}
|
|
10310
|
+
/**
|
|
10311
|
+
* A literal List entry as list-item markdown: a non-empty string, or
|
|
10312
|
+
* `{ label, description? }` with literal strings only. Anything carrying
|
|
10313
|
+
* behaviour or decoration (`icon`, `action`, other keys, bound values) is null.
|
|
10314
|
+
*/
|
|
10315
|
+
function listEntryMarkdown(entry) {
|
|
10316
|
+
if (typeof entry === "string") return entry.trim() ? oneLine(entry) : null;
|
|
10317
|
+
if (!isRecord(entry)) return null;
|
|
10318
|
+
for (const key of Object.keys(entry)) if (key !== "label" && key !== "description") return null;
|
|
10319
|
+
if (typeof entry.label !== "string" || !entry.label.trim()) return null;
|
|
10320
|
+
const label = oneLine(entry.label);
|
|
10321
|
+
if (entry.description === void 0) return label;
|
|
10322
|
+
if (typeof entry.description !== "string") return null;
|
|
10323
|
+
return entry.description.trim() ? `**${label}** — ${oneLine(entry.description)}` : label;
|
|
10324
|
+
}
|
|
10325
|
+
/**
|
|
10326
|
+
* A List of literal text items as a markdown list (`marker: "number"` →
|
|
10327
|
+
* `1. …`, otherwise `- …`), or null when it binds its items, renders
|
|
10328
|
+
* `children`, or any item is not plain text.
|
|
10329
|
+
*/
|
|
10330
|
+
function listToMarkdown(c) {
|
|
10331
|
+
const children = c.children;
|
|
10332
|
+
if (children != null && !(Array.isArray(children) && children.length === 0)) return null;
|
|
10333
|
+
if (!Array.isArray(c.items) || c.items.length === 0) return null;
|
|
10334
|
+
const lines = [];
|
|
10335
|
+
for (const entry of c.items) {
|
|
10336
|
+
const line = listEntryMarkdown(entry);
|
|
10337
|
+
if (line === null) return null;
|
|
10338
|
+
lines.push(line);
|
|
10339
|
+
}
|
|
10340
|
+
if (c.marker === "number") {
|
|
10341
|
+
const start = typeof c.start === "number" && Number.isInteger(c.start) ? c.start : 1;
|
|
10342
|
+
return lines.map((line, i) => `${start + i}. ${line}`).join("\n");
|
|
10343
|
+
}
|
|
10344
|
+
return lines.map((line) => `- ${line}`).join("\n");
|
|
10345
|
+
}
|
|
10346
|
+
/** The prose item a component converts to, or null when it is not prose. */
|
|
10347
|
+
function toProseItem(c) {
|
|
10348
|
+
if (!c) return null;
|
|
10349
|
+
if (c.accessibility !== void 0) return null;
|
|
10350
|
+
if (c.component === "Divider") return { kind: "divider" };
|
|
10351
|
+
if (c.component === "Spacer") return { kind: "spacer" };
|
|
10352
|
+
if (c.component === "List") {
|
|
10353
|
+
if (c.direction !== void 0 && c.direction !== "vertical") return null;
|
|
10354
|
+
const markdown = listToMarkdown(c);
|
|
10355
|
+
return markdown === null ? null : {
|
|
10356
|
+
kind: "text",
|
|
10357
|
+
markdown
|
|
10358
|
+
};
|
|
10359
|
+
}
|
|
10360
|
+
if (typeof c.component !== "string") return null;
|
|
10361
|
+
if (!PROSE_TEXT_COMPONENTS.has(c.component)) return null;
|
|
10362
|
+
if (typeof c.text !== "string" || c.text.trim() === "") return null;
|
|
10363
|
+
const text = c.text.trim();
|
|
10364
|
+
switch (c.component) {
|
|
10365
|
+
case "Title": {
|
|
10366
|
+
const size = typeof c.size === "string" ? c.size : "md";
|
|
10367
|
+
return {
|
|
10368
|
+
kind: "text",
|
|
10369
|
+
markdown: `${size === "sm" ? "####" : size === "md" || size === "lg" ? "###" : "##"} ${text}`
|
|
10370
|
+
};
|
|
10371
|
+
}
|
|
10372
|
+
case "Text":
|
|
10373
|
+
if (directChildIds(c).length > 0) return null;
|
|
10374
|
+
return {
|
|
10375
|
+
kind: "text",
|
|
10376
|
+
markdown: c.strong === true ? `**${text}**` : text
|
|
10377
|
+
};
|
|
10378
|
+
default: return {
|
|
10379
|
+
kind: "text",
|
|
10380
|
+
markdown: text
|
|
10381
|
+
};
|
|
10382
|
+
}
|
|
10383
|
+
}
|
|
10384
|
+
/** Prose items as markdown: separators only survive between two text items. */
|
|
10385
|
+
function proseItemsToMarkdown(items) {
|
|
10386
|
+
const blocks = [];
|
|
10387
|
+
let pendingDivider = false;
|
|
10388
|
+
for (const item of items) if (item?.kind === "text") {
|
|
10389
|
+
if (pendingDivider && blocks.length > 0) blocks.push("---");
|
|
10390
|
+
pendingDivider = false;
|
|
10391
|
+
blocks.push(item.markdown);
|
|
10392
|
+
} else if (item?.kind === "divider") pendingDivider = true;
|
|
10393
|
+
return blocks.join("\n\n");
|
|
10394
|
+
}
|
|
10395
|
+
/** Column, column-direction Box, or an informational Card (section/unset variant). */
|
|
10396
|
+
function isVerticalStack(c, interactiveCards) {
|
|
10397
|
+
if (c.accessibility !== void 0) return false;
|
|
10398
|
+
if (c.component === "Column") return true;
|
|
10399
|
+
if (c.component === "Box") return c.direction == null || c.direction === "col";
|
|
10400
|
+
if (c.component === "Card") return (c.variant == null || c.variant === "section") && typeof c.id === "string" && !interactiveCards.has(c.id);
|
|
10401
|
+
return false;
|
|
10402
|
+
}
|
|
10403
|
+
/** The child-id list of a stack (`children`, or a lone `child`), else null. */
|
|
10404
|
+
/**
|
|
10405
|
+
* The children of a stack in render order: `child` first (a Card renders
|
|
10406
|
+
* its `child` before its `children`), then `children`.
|
|
10407
|
+
*/
|
|
10408
|
+
function stackChildren(c) {
|
|
10409
|
+
const first = typeof c.child === "string" ? [c.child] : [];
|
|
10410
|
+
if (Array.isArray(c.children)) return [...first, ...c.children];
|
|
10411
|
+
if (first.length > 0 && c.children === void 0) return first;
|
|
10412
|
+
return null;
|
|
10413
|
+
}
|
|
10414
|
+
/**
|
|
10415
|
+
* Partitions the stack's children into alternating prose and surface runs.
|
|
10416
|
+
* A run of consecutive prose items is prose only when it holds text: a run of
|
|
10417
|
+
* separators alone (Divider/Spacer between two UI components, or at the very
|
|
10418
|
+
* start/end of the stack) stays with the surface it sits in.
|
|
10419
|
+
*/
|
|
10420
|
+
function partitionChildren(items) {
|
|
10421
|
+
const runs = [];
|
|
10422
|
+
let i = 0;
|
|
10423
|
+
while (i < items.length) {
|
|
10424
|
+
const candidate = items[i] !== null;
|
|
10425
|
+
let hasText = false;
|
|
10426
|
+
let j = i;
|
|
10427
|
+
while (j < items.length && items[j] !== null === candidate) {
|
|
10428
|
+
if (items[j]?.kind === "text") hasText = true;
|
|
10429
|
+
j++;
|
|
10430
|
+
}
|
|
10431
|
+
const prose = candidate && hasText;
|
|
10432
|
+
const last = runs[runs.length - 1];
|
|
10433
|
+
if (!prose && last && !last.prose) last.end = j;
|
|
10434
|
+
else runs.push({
|
|
10435
|
+
prose,
|
|
10436
|
+
start: i,
|
|
10437
|
+
end: j
|
|
10438
|
+
});
|
|
10439
|
+
i = j;
|
|
10440
|
+
}
|
|
10441
|
+
return runs;
|
|
10442
|
+
}
|
|
10443
|
+
/**
|
|
10444
|
+
* Markdown mode: split a surface into markdown and surface segments so that
|
|
10445
|
+
* only real UI renders as A2UI and everything else is the chat's markdown.
|
|
10446
|
+
*
|
|
10447
|
+
* From `root`, descend through single-child vertical containers (Column,
|
|
10448
|
+
* column Box, informational Card) to the first one with several children:
|
|
10449
|
+
* the stack. Its children are partitioned, in order, into runs of prose and
|
|
10450
|
+
* runs of UI. Prose is `Title`, `Text`, `Caption`, `Markdown` with literal
|
|
10451
|
+
* text, a `List` of literal text items, plus `Divider`/`Spacer` next to them:
|
|
10452
|
+
* `Title` → heading by size (sm `####`, md/lg `###`, larger `##`), `Text` →
|
|
10453
|
+
* paragraph (`strong` → `**…**`), `Caption`/`Markdown` → paragraph, `List` →
|
|
10454
|
+
* `- …` (or `1. …` for `marker: "number"`, `**label** — description` for
|
|
10455
|
+
* described items), and a `Divider` between two prose blocks → `---`.
|
|
10456
|
+
*
|
|
10457
|
+
* Not prose: `{path}`-bound text or items, a Text with inline children, a
|
|
10458
|
+
* List with `children`/icons/actions, a template entry, a component with an
|
|
10459
|
+
* `accessibility` envelope, and a child whose component has not streamed
|
|
10460
|
+
* yet. Separators with no text beside them stay in
|
|
10461
|
+
* the surface. An interactive Card (see `classifySurfaceCards`) is never
|
|
10462
|
+
* entered.
|
|
10463
|
+
*
|
|
10464
|
+
* Each prose run becomes a markdown segment; each UI run becomes a surface
|
|
10465
|
+
* segment whose `root` is a copy of the stack (its other props kept, `child`
|
|
10466
|
+
* dropped) with only that run's `children`, followed by every component
|
|
10467
|
+
* reachable from them. When nothing is prose the input comes back as the one
|
|
10468
|
+
* surface segment (same array); when everything is (or `root` itself is),
|
|
10469
|
+
* there are only markdown segments.
|
|
10470
|
+
*
|
|
10471
|
+
* Pure and linear in the number of components, so it runs on every stream
|
|
10472
|
+
* update.
|
|
10473
|
+
*
|
|
10474
|
+
* @param components - The components of one surface, root included.
|
|
10475
|
+
* @returns The segments in render order.
|
|
10476
|
+
*
|
|
10477
|
+
* @example
|
|
10478
|
+
* ```ts
|
|
10479
|
+
* for (const segment of segmentSurfaceProse(components)) {
|
|
10480
|
+
* if (segment.kind === "markdown") renderMarkdown(segment.markdown);
|
|
10481
|
+
* else renderSurface(segment.components);
|
|
10482
|
+
* }
|
|
10483
|
+
* ```
|
|
10484
|
+
*/
|
|
10485
|
+
function segmentSurfaceProse(components, options = {}) {
|
|
10486
|
+
const unchanged = [{
|
|
10487
|
+
kind: "surface",
|
|
10488
|
+
components
|
|
10489
|
+
}];
|
|
10490
|
+
const byId = /* @__PURE__ */ new Map();
|
|
10491
|
+
for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
|
|
10492
|
+
const root = byId.get(_copilotkit_shared.GENERATIVE_UI_ROOT_ID);
|
|
10493
|
+
if (!root) return unchanged;
|
|
10494
|
+
if (components.some((c) => isRecord(c) && options.childIds?.(c) === "unknown")) return unchanged;
|
|
10495
|
+
const rootItem = toProseItem(root);
|
|
10496
|
+
if (rootItem?.kind === "text") return [{
|
|
10497
|
+
kind: "markdown",
|
|
10498
|
+
markdown: rootItem.markdown
|
|
10499
|
+
}];
|
|
10500
|
+
const interactiveCards = classifySurfaceCards(components, options);
|
|
10501
|
+
let stack = root;
|
|
10502
|
+
let stackId = _copilotkit_shared.GENERATIVE_UI_ROOT_ID;
|
|
10503
|
+
let children;
|
|
10504
|
+
const visited = /* @__PURE__ */ new Set();
|
|
10505
|
+
while (true) {
|
|
10506
|
+
if (!isVerticalStack(stack, interactiveCards)) return unchanged;
|
|
10507
|
+
visited.add(stackId);
|
|
10508
|
+
const list = stackChildren(stack);
|
|
10509
|
+
if (!list) return unchanged;
|
|
10510
|
+
children = list;
|
|
10511
|
+
const nextId = list.length === 1 ? list[0] : void 0;
|
|
10512
|
+
if (typeof nextId !== "string") break;
|
|
10513
|
+
const next = byId.get(nextId);
|
|
10514
|
+
if (!next || visited.has(nextId) || toProseItem(next)) break;
|
|
10515
|
+
stack = next;
|
|
10516
|
+
stackId = nextId;
|
|
10517
|
+
}
|
|
10518
|
+
const stackChildIds = children;
|
|
10519
|
+
const items = stackChildIds.map((id) => typeof id === "string" ? toProseItem(byId.get(id)) : null);
|
|
10520
|
+
const runs = partitionChildren(items);
|
|
10521
|
+
if (!runs.some((run) => run.prose)) return unchanged;
|
|
10522
|
+
const surfaceRuns = runs.filter((run) => !run.prose);
|
|
10523
|
+
const owners = /* @__PURE__ */ new Map();
|
|
10524
|
+
surfaceRuns.forEach((run, index) => {
|
|
10525
|
+
const pending = stackChildIds.slice(run.start, run.end).map(referencedId).filter((id) => id !== void 0);
|
|
10526
|
+
const seen = /* @__PURE__ */ new Set();
|
|
10527
|
+
while (pending.length > 0) {
|
|
10528
|
+
const id = pending.pop();
|
|
10529
|
+
if (id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID || id === stackId || seen.has(id)) continue;
|
|
10530
|
+
seen.add(id);
|
|
10531
|
+
const list = owners.get(id);
|
|
10532
|
+
if (list) list.push(index);
|
|
10533
|
+
else owners.set(id, [index]);
|
|
10534
|
+
const c = byId.get(id);
|
|
10535
|
+
if (c) pending.push(...directChildIds(c, options.childIds));
|
|
10536
|
+
}
|
|
10537
|
+
});
|
|
10538
|
+
const surfaceComponents = surfaceRuns.map((run) => {
|
|
10539
|
+
const { child: _child, ...stackRest } = stack;
|
|
10540
|
+
const nextRoot = {
|
|
10541
|
+
...stackRest,
|
|
10542
|
+
id: _copilotkit_shared.GENERATIVE_UI_ROOT_ID,
|
|
10543
|
+
children: stackChildIds.slice(run.start, run.end)
|
|
10544
|
+
};
|
|
10545
|
+
delete nextRoot.child;
|
|
10546
|
+
return [nextRoot];
|
|
10547
|
+
});
|
|
10548
|
+
for (const c of components) {
|
|
10549
|
+
if (!isRecord(c) || typeof c.id !== "string" || byId.get(c.id) !== c) continue;
|
|
10550
|
+
const ownerIndexes = owners.get(c.id) ?? [];
|
|
10551
|
+
for (const index of ownerIndexes) surfaceComponents[index].push(c);
|
|
10552
|
+
}
|
|
10553
|
+
let surfaceIndex = 0;
|
|
10554
|
+
return runs.map((run) => {
|
|
10555
|
+
if (run.prose) return {
|
|
10556
|
+
kind: "markdown",
|
|
10557
|
+
markdown: proseItemsToMarkdown(items.slice(run.start, run.end))
|
|
10558
|
+
};
|
|
10559
|
+
return {
|
|
10560
|
+
kind: "surface",
|
|
10561
|
+
components: surfaceComponents[surfaceIndex++]
|
|
10562
|
+
};
|
|
10563
|
+
});
|
|
10564
|
+
}
|
|
10565
|
+
|
|
10566
|
+
//#endregion
|
|
10567
|
+
exports.A2UI_FENCE_LANGUAGE = A2UI_FENCE_LANGUAGE;
|
|
8882
10568
|
exports.AgentRegistry = AgentRegistry;
|
|
8883
10569
|
exports.AgentThreadLockedError = AgentThreadLockedError;
|
|
8884
10570
|
exports.ContextStore = ContextStore;
|
|
@@ -8888,7 +10574,6 @@ exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionS
|
|
|
8888
10574
|
exports.CopilotKitHeaderResolutionError = CopilotKitHeaderResolutionError;
|
|
8889
10575
|
exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
|
|
8890
10576
|
exports.IntelligenceAgent = IntelligenceAgent;
|
|
8891
|
-
exports.IntelligenceReplayFailedError = IntelligenceReplayFailedError;
|
|
8892
10577
|
exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
|
|
8893
10578
|
exports.MemoryError = MemoryError;
|
|
8894
10579
|
exports.ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;
|
|
@@ -8897,6 +10582,7 @@ exports.StateManager = StateManager;
|
|
|
8897
10582
|
exports.SuggestionEngine = SuggestionEngine;
|
|
8898
10583
|
exports.ToolCallStatus = ToolCallStatus;
|
|
8899
10584
|
exports.WebMCPRegistry = WebMCPRegistry;
|
|
10585
|
+
exports.classifySurfaceCards = classifySurfaceCards;
|
|
8900
10586
|
exports.completePartialMarkdown = completePartialMarkdown;
|
|
8901
10587
|
exports.createActionGroup = createActionGroup;
|
|
8902
10588
|
exports.createEffect = createEffect;
|
|
@@ -8910,6 +10596,11 @@ exports.emitInspectorViewThread = emitInspectorViewThread;
|
|
|
8910
10596
|
exports.emitInspectorViewThreadResult = emitInspectorViewThreadResult;
|
|
8911
10597
|
exports.empty = empty;
|
|
8912
10598
|
exports.ensureObjectArgs = ensureObjectArgs;
|
|
10599
|
+
exports.extractCompleteArrayItems = extractCompleteArrayItems;
|
|
10600
|
+
exports.extractFenceOperations = extractFenceOperations;
|
|
10601
|
+
exports.extractStringField = extractStringField;
|
|
10602
|
+
exports.flattenInformationalCards = flattenInformationalCards;
|
|
10603
|
+
exports.getMarkdownOperationSurfaceId = getMarkdownOperationSurfaceId;
|
|
8913
10604
|
exports.getWebMCPModelContext = getWebMCPModelContext;
|
|
8914
10605
|
exports.isAbortError = isAbortError;
|
|
8915
10606
|
exports.isInspectorThreadBridgeEnabled = isInspectorThreadBridgeEnabled;
|
|
@@ -8921,8 +10612,11 @@ exports.onInspectorStopViewing = onInspectorStopViewing;
|
|
|
8921
10612
|
exports.onInspectorViewThread = onInspectorViewThread;
|
|
8922
10613
|
exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
|
|
8923
10614
|
exports.parseToolArguments = parseToolArguments;
|
|
10615
|
+
exports.prepareSurfaceOperations = prepareSurfaceOperations;
|
|
8924
10616
|
exports.props = props;
|
|
10617
|
+
exports.segmentSurfaceProse = segmentSurfaceProse;
|
|
8925
10618
|
exports.select = select;
|
|
10619
|
+
exports.splitA2UIMarkdown = splitA2UIMarkdown;
|
|
8926
10620
|
exports.ɵCOPILOTKIT_FEATURES = ɵCOPILOTKIT_FEATURES;
|
|
8927
10621
|
exports.ɵInterruptState = ɵInterruptState;
|
|
8928
10622
|
exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;
|