@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.umd.js
CHANGED
|
@@ -23,17 +23,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
23
23
|
|
|
24
24
|
//#endregion
|
|
25
25
|
//#region src/utils/connect-replay.ts
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* The phase in which a connection received `event`, as recorded when it
|
|
29
|
-
* arrived. Events that did not come through a connection with replay
|
|
30
|
-
* boundaries report `unknown`.
|
|
31
|
-
*/
|
|
32
|
-
function ɵgetConnectRunErrorPhase(event) {
|
|
33
|
-
var _connectRunErrorPhase;
|
|
34
|
-
return (_connectRunErrorPhase = connectRunErrorPhases.get(event)) !== null && _connectRunErrorPhase !== void 0 ? _connectRunErrorPhase : "unknown";
|
|
35
|
-
}
|
|
36
|
-
/**
|
|
26
|
+
/**
|
|
37
27
|
* Runs an agent's `connect()` stream through the AbstractAgent apply pipeline
|
|
38
28
|
* with the `verifyEvents` step omitted.
|
|
39
29
|
*
|
|
@@ -88,7 +78,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
88
78
|
let result;
|
|
89
79
|
const previousMessageIds = new Set(agent.messages.map((m) => m.id));
|
|
90
80
|
let isReplaying = true;
|
|
91
|
-
let reportsReplayPhase = false;
|
|
92
81
|
const liveErrors = /* @__PURE__ */ new WeakSet();
|
|
93
82
|
const subscribers = [
|
|
94
83
|
{
|
|
@@ -136,19 +125,15 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
136
125
|
};
|
|
137
126
|
const lifecycle = {
|
|
138
127
|
onReplayStarted: () => {
|
|
139
|
-
reportsReplayPhase = true;
|
|
140
128
|
isReplaying = true;
|
|
141
129
|
agent.isRunning = true;
|
|
142
130
|
},
|
|
143
131
|
onReplayFinished: () => {
|
|
144
|
-
reportsReplayPhase = true;
|
|
145
132
|
isReplaying = false;
|
|
146
133
|
}
|
|
147
134
|
};
|
|
148
135
|
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) => {
|
|
149
|
-
if (event.type
|
|
150
|
-
if (!isReplaying) liveErrors.add(event);
|
|
151
|
-
if (reportsReplayPhase) connectRunErrorPhases.set(event, isReplaying ? "replay" : "live");
|
|
136
|
+
if (!isReplaying && event.type === _ag_ui_client.EventType.RUN_ERROR) liveErrors.add(event);
|
|
152
137
|
}), (0, _ag_ui_client.transformChunks)(self.debugLogger), (0, rxjs_operators.takeUntil)(activeRunDetach$));
|
|
153
138
|
const applied$ = self.apply(input, source$, subscribers);
|
|
154
139
|
await (0, rxjs.lastValueFrom)(self.processApplyEvents(input, applied$, subscribers).pipe((0, rxjs_operators.catchError)((error) => {
|
|
@@ -357,20 +342,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
357
342
|
}
|
|
358
343
|
};
|
|
359
344
|
/**
|
|
360
|
-
* The gateway could not replay a live run's events, so the client cannot
|
|
361
|
-
* verify the run it is following. The run itself may still be going on the
|
|
362
|
-
* server; reconnecting to the thread shows its real state.
|
|
363
|
-
*/
|
|
364
|
-
var IntelligenceReplayFailedError = class extends Error {
|
|
365
|
-
constructor(threadId, runId) {
|
|
366
|
-
super("The run's events could not be replayed. Reconnect to the thread to check the run's status.");
|
|
367
|
-
this.threadId = threadId;
|
|
368
|
-
this.runId = runId;
|
|
369
|
-
_defineProperty(this, "code", "INTELLIGENCE_REPLAY_FAILED");
|
|
370
|
-
this.name = "IntelligenceReplayFailedError";
|
|
371
|
-
}
|
|
372
|
-
};
|
|
373
|
-
/**
|
|
374
345
|
* Type guard for {@link RunCompletionAware}. Returns true when `agent` exposes
|
|
375
346
|
* an `activeRunCompletionPromise` property, so callers can await an in-flight
|
|
376
347
|
* run without an `as unknown as` cast. Returns false for agents that don't
|
|
@@ -701,7 +672,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
701
672
|
};
|
|
702
673
|
const replayFailed$ = channel$.pipe((0, rxjs_operators.switchMap)(({ channel }) => this.observeChannelEvent$(channel, REPLAY_FAILED_EVENT)), (0, rxjs_operators.tap)(() => {
|
|
703
674
|
controlCursor.replayFailed = true;
|
|
704
|
-
if (options.streamMode === "run") throw new IntelligenceReplayFailedError(credentials.threadId, credentials.runId);
|
|
705
675
|
}));
|
|
706
676
|
const replayComplete$ = this.observeControlEvent$(input.threadId, channel$, REPLAY_COMPLETE_EVENT, controlCursor).pipe((0, rxjs_operators.tap)(() => {
|
|
707
677
|
var _options$lifecycle2, _options$lifecycle2$o;
|
|
@@ -938,6 +908,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
938
908
|
}
|
|
939
909
|
const repaired = [];
|
|
940
910
|
const emitted = /* @__PURE__ */ new Set();
|
|
911
|
+
const expandedMessages = /* @__PURE__ */ new Set();
|
|
941
912
|
const emit = (message) => {
|
|
942
913
|
if (emitted.has(message.id)) return;
|
|
943
914
|
emitted.add(message.id);
|
|
@@ -946,6 +917,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
946
917
|
/** Emit an assistant turn together with every result it is owed. */
|
|
947
918
|
const emitWithResults = (message) => {
|
|
948
919
|
emit(message);
|
|
920
|
+
if (expandedMessages.has(message)) return;
|
|
921
|
+
expandedMessages.add(message);
|
|
949
922
|
for (const callId of toolCallIdsOf(message)) {
|
|
950
923
|
const result = callIdToResult.get(callId);
|
|
951
924
|
if (result) emit(result);
|
|
@@ -966,6 +939,199 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
966
939
|
}
|
|
967
940
|
return repaired;
|
|
968
941
|
}
|
|
942
|
+
/**
|
|
943
|
+
* Move each detached tool result to sit behind the assistant call that issued
|
|
944
|
+
* it — usually back to an earlier call, and forward only when no earlier call
|
|
945
|
+
* has its id and exactly one call in the list does — and change nothing else.
|
|
946
|
+
* Used for unfiltered sends, and on a configured filter's output only when
|
|
947
|
+
* {@link ɵrepairToolCallPairs}, which filtered sends go through otherwise,
|
|
948
|
+
* throws.
|
|
949
|
+
*
|
|
950
|
+
* The client store can detach a tool result from its call on its own: when a
|
|
951
|
+
* backend's `MESSAGES_SNAPSHOT` carries a tool message under a different id
|
|
952
|
+
* than the streamed `TOOL_CALL_RESULT`, the `@ag-ui/client` merge drops the
|
|
953
|
+
* copy placed after its call and appends the snapshot's copy at the end,
|
|
954
|
+
* leaving `assistant(tool_call), assistant(text), tool(result)`. A backend that
|
|
955
|
+
* rebuilds its state from that payload discards every result it cannot pair.
|
|
956
|
+
*
|
|
957
|
+
* The pairing rule mirrors the `@ag-ui/client` snapshot pass
|
|
958
|
+
* (ag-ui-protocol/ag-ui#3114):
|
|
959
|
+
*
|
|
960
|
+
* - Everything is by list position. The same object or id appearing twice is
|
|
961
|
+
* two independent slots, including an assistant call the merge duplicated,
|
|
962
|
+
* so a duplicated call can be left unanswered. Nothing is dropped,
|
|
963
|
+
* deduplicated, or added, and only tool-role messages ever change position.
|
|
964
|
+
* - Transparent entries are `activity` and `reasoning` messages and anything
|
|
965
|
+
* that is not a plain object (`null`, arrays, primitives). They are never
|
|
966
|
+
* the anchor, never separate a call from its result, and stay in place.
|
|
967
|
+
* Reasoning stored between a call and its result is the next step's: in a
|
|
968
|
+
* multi-step turn whose calls share one assistant message, Mastra leaves
|
|
969
|
+
* `assistant(c1, c2), tool(c1), reasoning, tool(c2)`. Moving the result in
|
|
970
|
+
* front of it leaves the reasoning trailing, and Mastra drops it.
|
|
971
|
+
* - The anchor is the last non-transparent message so far that is not `tool`.
|
|
972
|
+
* Each tool call an assistant issues opens a slot for its call id, and a
|
|
973
|
+
* result pairs with slots for its `toolCallId` alone. `subagentRunId` is
|
|
974
|
+
* ignored: results CopilotKit creates itself (frontend tool results,
|
|
975
|
+
* interrupt responses) do not carry one, and on a result it names the run
|
|
976
|
+
* that executed the tool, which may differ from the run that issued the
|
|
977
|
+
* call. Known limitation: a parent call and a subagent call that reuse one
|
|
978
|
+
* id are indistinguishable, so their drifted results can be swapped.
|
|
979
|
+
* - Pass 1, left to right: a result with an open slot issued at the anchor is
|
|
980
|
+
* in place; it takes that slot and stays put. A result with an open slot
|
|
981
|
+
* issued earlier is detached. A result with no slot for its id issued
|
|
982
|
+
* earlier at all is early. Any other result — every earlier slot for its id
|
|
983
|
+
* already answered — stays put. Detached results take no slot in this
|
|
984
|
+
* pass: they could only ever take a slot issued before the current anchor,
|
|
985
|
+
* which no later in-place result can want.
|
|
986
|
+
* - Pass 2, backward, per id: the detached results, from the newest back,
|
|
987
|
+
* each take the newest still-open slot issued before them; one that finds
|
|
988
|
+
* none stays put. So when several results for a reused id (providers reuse
|
|
989
|
+
* `call_0` every turn) are all detached, they keep their stored order
|
|
990
|
+
* across the calls, and a later turn's lone result goes to the later call
|
|
991
|
+
* rather than to an earlier one that was abandoned.
|
|
992
|
+
* - Pass 3, forward, per id: an early result moves forward only when its id
|
|
993
|
+
* is unambiguous — exactly one call slot in the whole list has it, that
|
|
994
|
+
* slot is issued after the result, and it is still open after passes 1-2.
|
|
995
|
+
* The first early result for the id, left to right, takes it; any other
|
|
996
|
+
* early result for that id stays put. This repairs a result whose call
|
|
997
|
+
* was re-issued after it (a snapshot that re-ids the assistant message but
|
|
998
|
+
* keeps the result's id). With a reused id (providers reuse `call_0` every
|
|
999
|
+
* turn) nothing moves forward: in `[t0, t1, a1(c), user, a2(c)]` nothing
|
|
1000
|
+
* says t1 answers a2, and a2 may be a pending call (a frontend tool, an
|
|
1001
|
+
* interrupt, a human-in-the-loop call waiting on the user). Only early
|
|
1002
|
+
* results move forward: an extra result for a call that is already
|
|
1003
|
+
* answered never does.
|
|
1004
|
+
* - A moved result goes behind its issuer, after the tool and transparent
|
|
1005
|
+
* entries already following it, but in front of any reasoning among those
|
|
1006
|
+
* transparent entries: reasoning belongs to the message after it, so a
|
|
1007
|
+
* moved result never lands between a reasoning message and its owner.
|
|
1008
|
+
* Results moved behind one issuer keep their stored order. Any other
|
|
1009
|
+
* message between a call and its result separates them, so a
|
|
1010
|
+
* backward-moved result moves before it and a forward-moved result moves
|
|
1011
|
+
* past it.
|
|
1012
|
+
* - The rule cannot tell a duplicate result from a detached one. A second
|
|
1013
|
+
* result for an already-answered call moves back to an older still-open
|
|
1014
|
+
* slot for its id if there is one, even across user turns; it never moves
|
|
1015
|
+
* forward.
|
|
1016
|
+
* - Malformed entries are ignored rather than thrown on. Non-array
|
|
1017
|
+
* `toolCalls`, call entries without a string `id`, and results without a
|
|
1018
|
+
* string `toolCallId` open or take no slot.
|
|
1019
|
+
*
|
|
1020
|
+
* Returns `messages` itself when nothing moved.
|
|
1021
|
+
*/
|
|
1022
|
+
function ɵkeepToolResultsWithCalls(messages) {
|
|
1023
|
+
const slots = /* @__PURE__ */ new Map();
|
|
1024
|
+
const openCount = /* @__PURE__ */ new Map();
|
|
1025
|
+
const close = (callId, slot) => {
|
|
1026
|
+
slot.open = false;
|
|
1027
|
+
openCount.set(callId, openCount.get(callId) - 1);
|
|
1028
|
+
};
|
|
1029
|
+
const detached = /* @__PURE__ */ new Map();
|
|
1030
|
+
const early = /* @__PURE__ */ new Map();
|
|
1031
|
+
let anchor = -1;
|
|
1032
|
+
for (let index = 0; index < messages.length; index++) {
|
|
1033
|
+
const message = messages[index];
|
|
1034
|
+
if (isTransparent(message)) continue;
|
|
1035
|
+
const role = roleOf(message);
|
|
1036
|
+
if (role !== "tool") {
|
|
1037
|
+
anchor = index;
|
|
1038
|
+
const calls = role === "assistant" ? message.toolCalls : void 0;
|
|
1039
|
+
if (!Array.isArray(calls)) continue;
|
|
1040
|
+
for (const call of calls) {
|
|
1041
|
+
var _openCount$get;
|
|
1042
|
+
if (typeof call !== "object" || call === null) continue;
|
|
1043
|
+
const callId = call.id;
|
|
1044
|
+
if (typeof callId !== "string") continue;
|
|
1045
|
+
push(slots, callId, {
|
|
1046
|
+
issuer: index,
|
|
1047
|
+
open: true
|
|
1048
|
+
});
|
|
1049
|
+
openCount.set(callId, ((_openCount$get = openCount.get(callId)) !== null && _openCount$get !== void 0 ? _openCount$get : 0) + 1);
|
|
1050
|
+
}
|
|
1051
|
+
continue;
|
|
1052
|
+
}
|
|
1053
|
+
const callId = message.toolCallId;
|
|
1054
|
+
if (typeof callId !== "string") continue;
|
|
1055
|
+
const forId = slots.get(callId);
|
|
1056
|
+
if (!forId) {
|
|
1057
|
+
push(early, callId, index);
|
|
1058
|
+
continue;
|
|
1059
|
+
}
|
|
1060
|
+
let atAnchor;
|
|
1061
|
+
for (let s = forId.length - 1; s >= 0; s--) {
|
|
1062
|
+
const slot = forId[s];
|
|
1063
|
+
if (slot.issuer !== anchor) break;
|
|
1064
|
+
if (slot.open) atAnchor = slot;
|
|
1065
|
+
}
|
|
1066
|
+
if (atAnchor) {
|
|
1067
|
+
close(callId, atAnchor);
|
|
1068
|
+
continue;
|
|
1069
|
+
}
|
|
1070
|
+
if (openCount.get(callId) > 0) push(detached, callId, index);
|
|
1071
|
+
}
|
|
1072
|
+
const movedBehind = /* @__PURE__ */ new Map();
|
|
1073
|
+
const moved = /* @__PURE__ */ new Set();
|
|
1074
|
+
const take = (callId, slot, index) => {
|
|
1075
|
+
close(callId, slot);
|
|
1076
|
+
moved.add(index);
|
|
1077
|
+
push(movedBehind, slot.issuer, index);
|
|
1078
|
+
};
|
|
1079
|
+
for (const [callId, results] of detached) {
|
|
1080
|
+
const forId = slots.get(callId);
|
|
1081
|
+
let s = forId.length - 1;
|
|
1082
|
+
for (let r = results.length - 1; r >= 0; r--) {
|
|
1083
|
+
const index = results[r];
|
|
1084
|
+
while (s >= 0 && (!forId[s].open || forId[s].issuer >= index)) s--;
|
|
1085
|
+
if (s < 0) break;
|
|
1086
|
+
take(callId, forId[s], index);
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
for (const [callId, results] of early) {
|
|
1090
|
+
const forId = slots.get(callId);
|
|
1091
|
+
if ((forId === null || forId === void 0 ? void 0 : forId.length) !== 1 || !forId[0].open) continue;
|
|
1092
|
+
take(callId, forId[0], results[0]);
|
|
1093
|
+
}
|
|
1094
|
+
if (moved.size === 0) return messages;
|
|
1095
|
+
const result = [];
|
|
1096
|
+
let openIssuer = -1;
|
|
1097
|
+
const flush = () => {
|
|
1098
|
+
const behind = movedBehind.get(openIssuer);
|
|
1099
|
+
if (!behind) return;
|
|
1100
|
+
let at = result.length;
|
|
1101
|
+
for (let tail = result.length - 1; tail >= 0; tail--) {
|
|
1102
|
+
if (!isTransparent(result[tail])) break;
|
|
1103
|
+
if (roleOf(result[tail]) === "reasoning") at = tail;
|
|
1104
|
+
}
|
|
1105
|
+
result.splice(at, 0, ...[...behind].sort((a, b) => a - b).map((index) => messages[index]));
|
|
1106
|
+
};
|
|
1107
|
+
for (let index = 0; index < messages.length; index++) {
|
|
1108
|
+
if (moved.has(index)) continue;
|
|
1109
|
+
const message = messages[index];
|
|
1110
|
+
if (!isTransparent(message) && roleOf(message) !== "tool") {
|
|
1111
|
+
flush();
|
|
1112
|
+
openIssuer = index;
|
|
1113
|
+
}
|
|
1114
|
+
result.push(message);
|
|
1115
|
+
}
|
|
1116
|
+
flush();
|
|
1117
|
+
return result;
|
|
1118
|
+
}
|
|
1119
|
+
function push(map, key, value) {
|
|
1120
|
+
const list = map.get(key);
|
|
1121
|
+
if (list) list.push(value);
|
|
1122
|
+
else map.set(key, [value]);
|
|
1123
|
+
}
|
|
1124
|
+
/**
|
|
1125
|
+
* Activity and reasoning messages and anything that is not a plain object
|
|
1126
|
+
* (`null`, arrays, primitives) never anchor or separate.
|
|
1127
|
+
*/
|
|
1128
|
+
function isTransparent(message) {
|
|
1129
|
+
return typeof message !== "object" || message === null || Array.isArray(message) || message.role === "activity" || message.role === "reasoning";
|
|
1130
|
+
}
|
|
1131
|
+
function roleOf(message) {
|
|
1132
|
+
if (typeof message !== "object" || message === null) return void 0;
|
|
1133
|
+
return message.role;
|
|
1134
|
+
}
|
|
969
1135
|
|
|
970
1136
|
//#endregion
|
|
971
1137
|
//#region \0@oxc-project+runtime@0.112.0/helpers/checkPrivateRedeclaration.js
|
|
@@ -1500,7 +1666,21 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
1500
1666
|
};
|
|
1501
1667
|
_ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;
|
|
1502
1668
|
/**
|
|
1503
|
-
*
|
|
1669
|
+
* Build the outbound payload, keeping every tool result with the call that
|
|
1670
|
+
* issued it.
|
|
1671
|
+
*
|
|
1672
|
+
* - **No filter** (or a filter whose output is unusable, which falls back to
|
|
1673
|
+
* the full thread): `ɵkeepToolResultsWithCalls` re-places tool results
|
|
1674
|
+
* that drifted from their call and changes nothing else. The client store
|
|
1675
|
+
* can detach them on its own when a `MESSAGES_SNAPSHOT` re-ids a tool
|
|
1676
|
+
* message, and a backend that rebuilds state from such a payload drops
|
|
1677
|
+
* every result it cannot pair.
|
|
1678
|
+
* - **Filter**: `ɵrepairToolCallPairs(kept, full)` restores the call or the
|
|
1679
|
+
* results a filter trimmed. Its known limitations are tracked in
|
|
1680
|
+
* https://github.com/CopilotKit/CopilotKit/issues/7891.
|
|
1681
|
+
* - **Filter repair throws**: the filter's output goes through
|
|
1682
|
+
* `ɵkeepToolResultsWithCalls` instead, keeping its trimming and
|
|
1683
|
+
* redaction; if that throws too, the output is sent as is.
|
|
1504
1684
|
*
|
|
1505
1685
|
* **Called from the HTTP paths only, and that placement is the Intelligence
|
|
1506
1686
|
* exemption.** An earlier revision applied the filter in
|
|
@@ -1523,35 +1703,91 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
1523
1703
|
* cannot reach the messages the UI renders no matter what it does with the
|
|
1524
1704
|
* array it is handed. The filter gets a *second* deep clone on top of that,
|
|
1525
1705
|
* because `input.messages` is also the repair baseline and the untrimmed
|
|
1526
|
-
* fallback: sharing the message objects let a filter that
|
|
1527
|
-
*
|
|
1528
|
-
* then went out
|
|
1529
|
-
* exactly the failure this whole mechanism
|
|
1706
|
+
* fallback: sharing the message objects let a filter that rewrote the tool
|
|
1707
|
+
* call id of an assistant message it dropped hide that issuer from the
|
|
1708
|
+
* repair, and the kept tool result then went out orphaned — a payload the
|
|
1709
|
+
* provider rejects, which is exactly the failure this whole mechanism
|
|
1710
|
+
* exists to prevent.
|
|
1530
1711
|
*/
|
|
1531
|
-
function
|
|
1532
|
-
|
|
1533
|
-
|
|
1712
|
+
function _prepareOutboundMessages(input) {
|
|
1713
|
+
var _this$agentId;
|
|
1714
|
+
const full = input.messages;
|
|
1715
|
+
const kept = _assertClassBrand(_ProxiedCopilotRuntimeAgent_brand, this, _applyMessageFilter).call(this, full);
|
|
1716
|
+
const agentId = (_this$agentId = this.agentId) !== null && _this$agentId !== void 0 ? _this$agentId : "";
|
|
1534
1717
|
try {
|
|
1535
|
-
|
|
1536
|
-
const kept = filter((0, _ag_ui_client.structuredClone_)(input.messages), { agentId: (_this$agentId = this.agentId) !== null && _this$agentId !== void 0 ? _this$agentId : "" });
|
|
1537
|
-
if (!Array.isArray(kept)) {
|
|
1538
|
-
console.warn("ProxiedCopilotRuntimeAgent: messageFilter returned a non-array value; sending the full message history instead.");
|
|
1539
|
-
return input;
|
|
1540
|
-
}
|
|
1718
|
+
const messages = kept === void 0 ? ɵkeepToolResultsWithCalls(full) : ɵrepairToolCallPairs(kept, full);
|
|
1541
1719
|
return {
|
|
1542
1720
|
...input,
|
|
1543
|
-
messages
|
|
1721
|
+
messages
|
|
1544
1722
|
};
|
|
1723
|
+
} catch (error) {
|
|
1724
|
+
if (kept === void 0) {
|
|
1725
|
+
console.warn(`ProxiedCopilotRuntimeAgent: tool-call repair failed for agent "${agentId}"; sending the message history unrepaired instead.`, error);
|
|
1726
|
+
return input;
|
|
1727
|
+
}
|
|
1728
|
+
try {
|
|
1729
|
+
const messages = ɵkeepToolResultsWithCalls(kept);
|
|
1730
|
+
console.warn(`ProxiedCopilotRuntimeAgent: tool-call repair failed for agent "${agentId}"; sending the filtered message history with only drifted tool results moved instead.`, error);
|
|
1731
|
+
return {
|
|
1732
|
+
...input,
|
|
1733
|
+
messages
|
|
1734
|
+
};
|
|
1735
|
+
} catch (moveError) {
|
|
1736
|
+
console.warn(`ProxiedCopilotRuntimeAgent: tool-call repair failed for agent "${agentId}"; sending the filtered message history unrepaired instead.`, error, moveError);
|
|
1737
|
+
return {
|
|
1738
|
+
...input,
|
|
1739
|
+
messages: kept
|
|
1740
|
+
};
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
/**
|
|
1745
|
+
* Run the configured filter. Returns `undefined` when there is no filter,
|
|
1746
|
+
* copying the thread for it fails, or the filter's output cannot be used,
|
|
1747
|
+
* meaning "send the full thread".
|
|
1748
|
+
*
|
|
1749
|
+
* A filter that throws, returns a non-array, or returns an array with an
|
|
1750
|
+
* entry that is not a message object (a hole or a nested array included)
|
|
1751
|
+
* falls back to the untrimmed thread rather than failing the run. Trimming
|
|
1752
|
+
* is an optimization, and taking the user's message down with it would be
|
|
1753
|
+
* the worse outcome; the warning is what surfaces the bug.
|
|
1754
|
+
*/
|
|
1755
|
+
function _applyMessageFilter(full) {
|
|
1756
|
+
const filter = this._messageFilter;
|
|
1757
|
+
if (!filter) return void 0;
|
|
1758
|
+
let copy;
|
|
1759
|
+
try {
|
|
1760
|
+
copy = (0, _ag_ui_client.structuredClone_)(full);
|
|
1761
|
+
} catch (error) {
|
|
1762
|
+
console.warn("ProxiedCopilotRuntimeAgent: could not copy the message history for messageFilter; sending the full message history instead.", error);
|
|
1763
|
+
return;
|
|
1764
|
+
}
|
|
1765
|
+
let kept;
|
|
1766
|
+
try {
|
|
1767
|
+
var _this$agentId2;
|
|
1768
|
+
kept = filter(copy, { agentId: (_this$agentId2 = this.agentId) !== null && _this$agentId2 !== void 0 ? _this$agentId2 : "" });
|
|
1545
1769
|
} catch (error) {
|
|
1546
1770
|
console.warn("ProxiedCopilotRuntimeAgent: messageFilter failed; sending the full message history instead.", error);
|
|
1547
|
-
return
|
|
1771
|
+
return;
|
|
1548
1772
|
}
|
|
1773
|
+
if (!Array.isArray(kept)) {
|
|
1774
|
+
console.warn("ProxiedCopilotRuntimeAgent: messageFilter returned a non-array value; sending the full message history instead.");
|
|
1775
|
+
return;
|
|
1776
|
+
}
|
|
1777
|
+
for (let index = 0; index < kept.length; index++) {
|
|
1778
|
+
const entry = kept[index];
|
|
1779
|
+
if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
|
|
1780
|
+
console.warn("ProxiedCopilotRuntimeAgent: messageFilter returned an entry that is not a message; sending the full message history instead.");
|
|
1781
|
+
return;
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
return kept;
|
|
1549
1785
|
}
|
|
1550
1786
|
function _connectViaDelegate(input, lifecycle) {
|
|
1551
1787
|
return (0, rxjs.defer)(() => (0, rxjs.from)(this.resolveDelegate())).pipe((0, rxjs_operators.switchMap)((delegate) => withAbortErrorHandling(delegate.connect(input, lifecycle))));
|
|
1552
1788
|
}
|
|
1553
1789
|
function _connectViaHttp(unfiltered) {
|
|
1554
|
-
const input = _assertClassBrand(_ProxiedCopilotRuntimeAgent_brand, this,
|
|
1790
|
+
const input = _assertClassBrand(_ProxiedCopilotRuntimeAgent_brand, this, _prepareOutboundMessages).call(this, unfiltered);
|
|
1555
1791
|
this.activeRun = void 0;
|
|
1556
1792
|
const routedId = this.routedAgentId();
|
|
1557
1793
|
let httpEvents;
|
|
@@ -1584,7 +1820,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
1584
1820
|
return (0, rxjs.defer)(() => (0, rxjs.from)(this.resolveDelegate())).pipe((0, rxjs_operators.switchMap)((delegate) => withAbortErrorHandling(delegate.run(input))));
|
|
1585
1821
|
}
|
|
1586
1822
|
function _runViaHttp(unfiltered) {
|
|
1587
|
-
const input = _assertClassBrand(_ProxiedCopilotRuntimeAgent_brand, this,
|
|
1823
|
+
const input = _assertClassBrand(_ProxiedCopilotRuntimeAgent_brand, this, _prepareOutboundMessages).call(this, unfiltered);
|
|
1588
1824
|
const activeRun = {
|
|
1589
1825
|
threadId: input.threadId,
|
|
1590
1826
|
runId: input.runId
|
|
@@ -2970,6 +3206,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
2970
3206
|
}
|
|
2971
3207
|
};
|
|
2972
3208
|
|
|
3209
|
+
//#endregion
|
|
3210
|
+
//#region src/core/agent-scope.ts
|
|
3211
|
+
/**
|
|
3212
|
+
* True when an entry scoped to `agentIds` goes to a run of `agentId`. An
|
|
3213
|
+
* entry without `agentIds` goes to every agent; an entry with them does not
|
|
3214
|
+
* go to a run without an agent id. Internal, not exported.
|
|
3215
|
+
*/
|
|
3216
|
+
function isForAgent(agentIds, agentId) {
|
|
3217
|
+
return agentIds === void 0 || agentId !== void 0 && agentIds.includes(agentId);
|
|
3218
|
+
}
|
|
3219
|
+
|
|
2973
3220
|
//#endregion
|
|
2974
3221
|
//#region src/core/context-store.ts
|
|
2975
3222
|
/**
|
|
@@ -3008,7 +3255,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
3008
3255
|
* protocol-shaped `{ description, value }` entries go over the wire.
|
|
3009
3256
|
*/
|
|
3010
3257
|
getContextForAgent(agentId) {
|
|
3011
|
-
return Object.values(this._context).filter((entry) =>
|
|
3258
|
+
return Object.values(this._context).filter((entry) => isForAgent(entry.agentIds, agentId)).map(({ description, value }) => ({
|
|
3012
3259
|
description,
|
|
3013
3260
|
value
|
|
3014
3261
|
}));
|
|
@@ -3199,7 +3446,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
3199
3446
|
await suggestionAgent.runAgent({
|
|
3200
3447
|
context: friends.getContextForAgent(consumerAgentId),
|
|
3201
3448
|
forwardedProps: {
|
|
3202
|
-
...friends.
|
|
3449
|
+
...friends.getPropertiesForAgent(consumerAgentId),
|
|
3203
3450
|
toolChoice: {
|
|
3204
3451
|
type: "function",
|
|
3205
3452
|
function: { name: "copilotkitSuggest" }
|
|
@@ -3638,15 +3885,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
3638
3885
|
*/
|
|
3639
3886
|
const liveHITLStops = /* @__PURE__ */ new WeakMap();
|
|
3640
3887
|
/**
|
|
3641
|
-
*
|
|
3642
|
-
*
|
|
3643
|
-
*
|
|
3644
|
-
* edit it replaces, this notifies no subscriber.
|
|
3888
|
+
* The message a failed tool call reports. An error thrown with an empty
|
|
3889
|
+
* message still means the call failed, so it gets a fallback rather than an
|
|
3890
|
+
* empty string, which everything downstream reads as success.
|
|
3645
3891
|
*/
|
|
3646
|
-
function
|
|
3647
|
-
|
|
3648
|
-
edit(messages);
|
|
3649
|
-
agent.messages = messages;
|
|
3892
|
+
function toolFailureMessage(error) {
|
|
3893
|
+
return error.message || "Tool call failed";
|
|
3650
3894
|
}
|
|
3651
3895
|
function discardAbortedResult(signal, discardOnAbort, errorMessage) {
|
|
3652
3896
|
var _liveHITLStops$get;
|
|
@@ -3685,8 +3929,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
3685
3929
|
_defineProperty(this, "_disabledCatalogComponents", /* @__PURE__ */ new Set());
|
|
3686
3930
|
_defineProperty(this, "_disabledToolKeys", /* @__PURE__ */ new Set());
|
|
3687
3931
|
_defineProperty(this, "_warnedMissingToolParameters", /* @__PURE__ */ new Set());
|
|
3688
|
-
_defineProperty(this, "
|
|
3689
|
-
_defineProperty(this, "
|
|
3932
|
+
_defineProperty(this, "_runAbortControllers", /* @__PURE__ */ new WeakMap());
|
|
3933
|
+
_defineProperty(this, "_runDepths", /* @__PURE__ */ new WeakMap());
|
|
3934
|
+
_defineProperty(this, "_originalAbortRuns", /* @__PURE__ */ new WeakMap());
|
|
3690
3935
|
_defineProperty(this, "_webmcpRegistry", new WebMCPRegistry());
|
|
3691
3936
|
_defineProperty(this, "_lastConnectedThreadIdsByAgent", /* @__PURE__ */ new Map());
|
|
3692
3937
|
_defineProperty(this, "_lastActiveThreadIdsByAgent", /* @__PURE__ */ new Map());
|
|
@@ -3702,8 +3947,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
3702
3947
|
* not start a follow-up run.
|
|
3703
3948
|
*/
|
|
3704
3949
|
abortCurrentRun(agent) {
|
|
3705
|
-
|
|
3706
|
-
(_this$_runAbortContro = this._runAbortController) === null || _this$_runAbortContro === void 0 || _this$_runAbortContro.abort();
|
|
3950
|
+
this.abortAgentRuns(agent);
|
|
3707
3951
|
const replay = this._interactionAbortControllers.get(agent);
|
|
3708
3952
|
if (replay) {
|
|
3709
3953
|
for (const controller of replay.controllers) controller.abort();
|
|
@@ -3711,6 +3955,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
3711
3955
|
this._executingToolCalls.delete(agent);
|
|
3712
3956
|
}
|
|
3713
3957
|
}
|
|
3958
|
+
abortAgentRuns(agent) {
|
|
3959
|
+
var _this$_runAbortContro;
|
|
3960
|
+
for (const controller of (_this$_runAbortContro = this._runAbortControllers.get(agent)) !== null && _this$_runAbortContro !== void 0 ? _this$_runAbortContro : []) controller.abort();
|
|
3961
|
+
}
|
|
3962
|
+
/** Signal of the agent's most recently started in-flight run, if any. */
|
|
3963
|
+
latestRunSignal(agent) {
|
|
3964
|
+
var _this$_runAbortContro2;
|
|
3965
|
+
let latest;
|
|
3966
|
+
for (const controller of (_this$_runAbortContro2 = this._runAbortControllers.get(agent)) !== null && _this$_runAbortContro2 !== void 0 ? _this$_runAbortContro2 : []) latest = controller;
|
|
3967
|
+
return latest === null || latest === void 0 ? void 0 : latest.signal;
|
|
3968
|
+
}
|
|
3714
3969
|
/**
|
|
3715
3970
|
* Typed access to CopilotKitCore's internal ("friend") methods.
|
|
3716
3971
|
* Centralises the single unavoidable cast so call-sites stay clean.
|
|
@@ -3911,10 +4166,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
3911
4166
|
newMessages: []
|
|
3912
4167
|
};
|
|
3913
4168
|
const runAgentResult = await agent.connectAgent({
|
|
3914
|
-
forwardedProps: this._internal.
|
|
4169
|
+
forwardedProps: this._internal.getPropertiesForAgent(agent.agentId),
|
|
3915
4170
|
tools: this.buildFrontendTools(agent.agentId),
|
|
3916
4171
|
context: this._internal.getContextForAgent(agent.agentId)
|
|
3917
|
-
}, this.createAgentErrorSubscriber(agent
|
|
4172
|
+
}, this.createAgentErrorSubscriber(agent));
|
|
3918
4173
|
if (this._connectionGenerations.get(agent) !== connection || ((_agent$threadId4 = agent.threadId) !== null && _agent$threadId4 !== void 0 ? _agent$threadId4 : null) !== incomingThreadId) return runAgentResult;
|
|
3919
4174
|
const controller = new AbortController();
|
|
3920
4175
|
const replay = (_this$_interactionAbo = this._interactionAbortControllers.get(agent)) !== null && _this$_interactionAbo !== void 0 ? _this$_interactionAbo : {
|
|
@@ -3963,7 +4218,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
3963
4218
|
/**
|
|
3964
4219
|
* Run an agent
|
|
3965
4220
|
*/
|
|
3966
|
-
async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff) {
|
|
4221
|
+
async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff, followUpOf) {
|
|
4222
|
+
var _this$_runDepths$get;
|
|
3967
4223
|
if (agent.agentId) this._internal.suggestionEngine.clearSuggestions(agent.agentId);
|
|
3968
4224
|
try {
|
|
3969
4225
|
const headersApplied = this._internal.prepareAgentHeadersForRun(agent);
|
|
@@ -3987,28 +4243,34 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
3987
4243
|
forwardedProps
|
|
3988
4244
|
});
|
|
3989
4245
|
const logicalHandoff = continuationHandoff !== null && continuationHandoff !== void 0 ? continuationHandoff : resumedRunId ? this._internal.stateManager.markNextRunAsContinuation(agent, resumedRunId) : void 0;
|
|
3990
|
-
const
|
|
3991
|
-
|
|
3992
|
-
|
|
3993
|
-
|
|
3994
|
-
|
|
3995
|
-
|
|
4246
|
+
const isFollowUp = followUpOf !== void 0;
|
|
4247
|
+
const controller = followUpOf !== null && followUpOf !== void 0 ? followUpOf : new AbortController();
|
|
4248
|
+
const depth = (_this$_runDepths$get = this._runDepths.get(agent)) !== null && _this$_runDepths$get !== void 0 ? _this$_runDepths$get : 0;
|
|
4249
|
+
this._runDepths.set(agent, depth + 1);
|
|
4250
|
+
if (!isFollowUp) {
|
|
4251
|
+
var _this$_runAbortContro3;
|
|
4252
|
+
const controllers = (_this$_runAbortContro3 = this._runAbortControllers.get(agent)) !== null && _this$_runAbortContro3 !== void 0 ? _this$_runAbortContro3 : /* @__PURE__ */ new Set();
|
|
4253
|
+
controllers.add(controller);
|
|
4254
|
+
this._runAbortControllers.set(agent, controllers);
|
|
4255
|
+
}
|
|
4256
|
+
if (depth === 0) {
|
|
4257
|
+
const originalAbortRun = agent.abortRun;
|
|
4258
|
+
this._originalAbortRuns.set(agent, originalAbortRun);
|
|
3996
4259
|
agent.abortRun = () => {
|
|
3997
|
-
|
|
3998
|
-
originalAbortRun();
|
|
4260
|
+
this.abortAgentRuns(agent);
|
|
4261
|
+
originalAbortRun.call(agent);
|
|
3999
4262
|
};
|
|
4000
|
-
|
|
4263
|
+
}
|
|
4264
|
+
try {
|
|
4265
|
+
if (depth === 0) await this._internal.notifySubscribers((subscriber) => {
|
|
4001
4266
|
var _subscriber$onAgentRu2;
|
|
4002
4267
|
return (_subscriber$onAgentRu2 = subscriber.onAgentRunStarted) === null || _subscriber$onAgentRu2 === void 0 ? void 0 : _subscriber$onAgentRu2.call(subscriber, {
|
|
4003
4268
|
copilotkit: this.core,
|
|
4004
4269
|
agent
|
|
4005
4270
|
});
|
|
4006
4271
|
}, "Subscriber onAgentRunStarted error:");
|
|
4007
|
-
}
|
|
4008
|
-
this._runDepth++;
|
|
4009
|
-
try {
|
|
4010
4272
|
let logicalRunId = resumedRunId !== null && resumedRunId !== void 0 ? resumedRunId : runId;
|
|
4011
|
-
const agentSubscriber = this.createAgentErrorSubscriber(agent,
|
|
4273
|
+
const agentSubscriber = this.createAgentErrorSubscriber(agent, controller.signal);
|
|
4012
4274
|
let started = false;
|
|
4013
4275
|
const onRunStartedEvent = agentSubscriber.onRunStartedEvent;
|
|
4014
4276
|
const onRunInitialized = agentSubscriber.onRunInitialized;
|
|
@@ -4025,7 +4287,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4025
4287
|
const pinRunIdOnWire = runId !== void 0 && !continuationHandoff;
|
|
4026
4288
|
const agentRunInput = {
|
|
4027
4289
|
forwardedProps: {
|
|
4028
|
-
...this._internal.
|
|
4290
|
+
...this._internal.getPropertiesForAgent(agent.agentId),
|
|
4029
4291
|
...forwardedProps
|
|
4030
4292
|
},
|
|
4031
4293
|
...resume !== void 0 ? { resume } : {},
|
|
@@ -4038,7 +4300,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4038
4300
|
return await this.processAgentResult({
|
|
4039
4301
|
runAgentResult,
|
|
4040
4302
|
agent,
|
|
4041
|
-
runId: logicalRunId
|
|
4303
|
+
runId: logicalRunId,
|
|
4304
|
+
runController: controller
|
|
4042
4305
|
});
|
|
4043
4306
|
} catch (error) {
|
|
4044
4307
|
logicalHandoff === null || logicalHandoff === void 0 || logicalHandoff.cancel();
|
|
@@ -4055,17 +4318,27 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4055
4318
|
newMessages: []
|
|
4056
4319
|
};
|
|
4057
4320
|
} finally {
|
|
4058
|
-
|
|
4059
|
-
|
|
4321
|
+
var _this$_runDepths$get2;
|
|
4322
|
+
const remainingDepth = ((_this$_runDepths$get2 = this._runDepths.get(agent)) !== null && _this$_runDepths$get2 !== void 0 ? _this$_runDepths$get2 : 1) - 1;
|
|
4323
|
+
this._runDepths.set(agent, remainingDepth);
|
|
4324
|
+
if (!isFollowUp) {
|
|
4325
|
+
const controllers = this._runAbortControllers.get(agent);
|
|
4326
|
+
controllers === null || controllers === void 0 || controllers.delete(controller);
|
|
4327
|
+
if ((controllers === null || controllers === void 0 ? void 0 : controllers.size) === 0) this._runAbortControllers.delete(agent);
|
|
4328
|
+
}
|
|
4329
|
+
if (remainingDepth === 0) {
|
|
4330
|
+
const originalAbortRun = this._originalAbortRuns.get(agent);
|
|
4331
|
+
if (originalAbortRun) {
|
|
4332
|
+
agent.abortRun = originalAbortRun;
|
|
4333
|
+
this._originalAbortRuns.delete(agent);
|
|
4334
|
+
}
|
|
4335
|
+
}
|
|
4060
4336
|
}
|
|
4061
4337
|
}
|
|
4062
4338
|
/**
|
|
4063
4339
|
* Process agent result and execute tools
|
|
4064
4340
|
*/
|
|
4065
|
-
async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", signal =
|
|
4066
|
-
var _this$_runAbortContro2;
|
|
4067
|
-
return (_this$_runAbortContro2 = this._runAbortController) === null || _this$_runAbortContro2 === void 0 ? void 0 : _this$_runAbortContro2.signal;
|
|
4068
|
-
})() }) {
|
|
4341
|
+
async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", runController, signal = runController === null || runController === void 0 ? void 0 : runController.signal }) {
|
|
4069
4342
|
var _this$_executingToolC;
|
|
4070
4343
|
const { newMessages } = runAgentResult;
|
|
4071
4344
|
const agentId = agent.agentId;
|
|
@@ -4073,11 +4346,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4073
4346
|
const threadId = agent.threadId;
|
|
4074
4347
|
const executing = (_this$_executingToolC = this._executingToolCalls.get(agent)) !== null && _this$_executingToolC !== void 0 ? _this$_executingToolC : /* @__PURE__ */ new Set();
|
|
4075
4348
|
this._executingToolCalls.set(agent, executing);
|
|
4076
|
-
|
|
4349
|
+
const messagesToProcess = toolExecutionMode === "restore" ? agent.messages.filter((message) => message.role === "assistant" && this.isInLatestUserTurn(agent.messages, message.id)) : newMessages;
|
|
4350
|
+
if (toolExecutionMode === "restore" && messagesToProcess.some((message) => {
|
|
4077
4351
|
var _message$toolCalls;
|
|
4078
4352
|
return message.role === "assistant" && ((_message$toolCalls = message.toolCalls) === null || _message$toolCalls === void 0 ? void 0 : _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))));
|
|
4079
4353
|
})) return runAgentResult;
|
|
4080
|
-
const messagesToProcess = toolExecutionMode === "restore" ? [...agent.messages] : newMessages;
|
|
4081
4354
|
for (const message of messagesToProcess) if (message.role === "assistant") for (const toolCall of message.toolCalls || []) {
|
|
4082
4355
|
var _agent$messages$find;
|
|
4083
4356
|
const tool = this.getTool({
|
|
@@ -4094,16 +4367,16 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4094
4367
|
return wildcardTool;
|
|
4095
4368
|
};
|
|
4096
4369
|
const executableTool = tool !== null && tool !== void 0 ? tool : getWildcardTool();
|
|
4097
|
-
if (toolExecutionMode === "restore" && (!
|
|
4370
|
+
if (toolExecutionMode === "restore" && (!executableTool || executableTool.handler && executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
|
|
4098
4371
|
const executionKey = JSON.stringify([threadId, toolCall.id]);
|
|
4099
|
-
if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || agent.threadId !== threadId || executing.has(executionKey)) continue;
|
|
4372
|
+
if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || agent.threadId !== threadId || toolExecutionMode === "restore" && !this.isInLatestUserTurn(agent.messages, message.id) || executing.has(executionKey)) continue;
|
|
4100
4373
|
const existingResultIndex = newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
|
|
4101
4374
|
let existingResult = (_agent$messages$find = agent.messages.find((m) => m.role === "tool" && m.toolCallId === toolCall.id)) !== null && _agent$messages$find !== void 0 ? _agent$messages$find : newMessages[existingResultIndex];
|
|
4102
|
-
if (existingResult && (executableTool === null || executableTool === void 0 ? void 0 : executableTool.handler)
|
|
4375
|
+
if (existingResult && this.isFrontendPlaceholderResult(existingResult) && (toolExecutionMode === "restore" || (executableTool === null || executableTool === void 0 ? void 0 : executableTool.handler))) {
|
|
4103
4376
|
if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
|
|
4104
4377
|
existingResult = void 0;
|
|
4105
4378
|
const agentMsgIdx = agent.messages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
|
|
4106
|
-
if (agentMsgIdx !== -1)
|
|
4379
|
+
if (agentMsgIdx !== -1) agent.messages.splice(agentMsgIdx, 1);
|
|
4107
4380
|
}
|
|
4108
4381
|
if (!existingResult) {
|
|
4109
4382
|
var _this$_interactionAbo2, _interactionControlle;
|
|
@@ -4147,18 +4420,47 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4147
4420
|
if (interactionController === null || interactionController === void 0 ? void 0 : interactionController.signal.aborted) return runAgentResult;
|
|
4148
4421
|
}
|
|
4149
4422
|
}
|
|
4150
|
-
if (needsFollowUp && agent.threadId === threadId && !(signal === null || signal === void 0 ? void 0 : signal.aborted))
|
|
4151
|
-
|
|
4152
|
-
|
|
4153
|
-
|
|
4154
|
-
|
|
4155
|
-
agent,
|
|
4156
|
-
|
|
4157
|
-
|
|
4423
|
+
if (needsFollowUp && agent.threadId === threadId && !(signal === null || signal === void 0 ? void 0 : signal.aborted)) {
|
|
4424
|
+
var _this$_runDepths$get3;
|
|
4425
|
+
if (((_this$_runDepths$get3 = this._runDepths.get(agent)) !== null && _this$_runDepths$get3 !== void 0 ? _this$_runDepths$get3 : 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.`);
|
|
4426
|
+
else {
|
|
4427
|
+
await this._internal.waitForPendingFrameworkUpdates();
|
|
4428
|
+
if (toolExecutionMode === "restore" && !messagesToProcess.some((message) => this.isInLatestUserTurn(agent.messages, message.id))) return runAgentResult;
|
|
4429
|
+
const continuationHandoff = this._internal.stateManager.markNextRunAsContinuation(agent, runId);
|
|
4430
|
+
return await this.runAgent({
|
|
4431
|
+
agent,
|
|
4432
|
+
...runId !== void 0 ? { runId } : {}
|
|
4433
|
+
}, continuationHandoff, runController);
|
|
4434
|
+
}
|
|
4158
4435
|
}
|
|
4159
4436
|
this._internal.suggestionEngine.reloadSuggestions(agentId);
|
|
4160
4437
|
return runAgentResult;
|
|
4161
4438
|
}
|
|
4439
|
+
/** A later user message supersedes pending work from an older turn. */
|
|
4440
|
+
isInLatestUserTurn(messages, messageId) {
|
|
4441
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
4442
|
+
const message = messages[index];
|
|
4443
|
+
if ((message === null || message === void 0 ? void 0 : message.role) === "user") return false;
|
|
4444
|
+
if ((message === null || message === void 0 ? void 0 : message.id) === messageId) return true;
|
|
4445
|
+
}
|
|
4446
|
+
return false;
|
|
4447
|
+
}
|
|
4448
|
+
/** Locate a missing result before saved results for later calls in its batch. */
|
|
4449
|
+
toolResultInsertionIndex(messages, messageIndex, toolCallId) {
|
|
4450
|
+
var _parent$toolCalls;
|
|
4451
|
+
const parent = messages[messageIndex];
|
|
4452
|
+
const calls = (parent === null || parent === void 0 ? void 0 : parent.role) === "assistant" ? (_parent$toolCalls = parent.toolCalls) !== null && _parent$toolCalls !== void 0 ? _parent$toolCalls : [] : [];
|
|
4453
|
+
const callIndex = calls.findIndex((call) => call.id === toolCallId);
|
|
4454
|
+
let insertAt = messageIndex + 1;
|
|
4455
|
+
while (insertAt < messages.length) {
|
|
4456
|
+
const result = messages[insertAt];
|
|
4457
|
+
if ((result === null || result === void 0 ? void 0 : result.role) !== "tool") break;
|
|
4458
|
+
if (calls.findIndex((call) => call.id === result.toolCallId) > callIndex) break;
|
|
4459
|
+
insertAt++;
|
|
4460
|
+
}
|
|
4461
|
+
return insertAt;
|
|
4462
|
+
}
|
|
4463
|
+
/** Identify transport placeholders that must not count as completed answers. */
|
|
4162
4464
|
isFrontendPlaceholderResult(message) {
|
|
4163
4465
|
return message.role === "tool" && isForwardedToClientPlaceholder(message.content);
|
|
4164
4466
|
}
|
|
@@ -4167,10 +4469,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4167
4469
|
* Handles arg parsing, subscriber notifications, handler invocation, result stringification,
|
|
4168
4470
|
* and error handling.
|
|
4169
4471
|
*/
|
|
4170
|
-
async executeToolHandler({ tool, toolCall, agent, agentId, handlerArgs, toolType, messageId, signal = (
|
|
4171
|
-
var _this$_runAbortContro3;
|
|
4172
|
-
return (_this$_runAbortContro3 = this._runAbortController) === null || _this$_runAbortContro3 === void 0 ? void 0 : _this$_runAbortContro3.signal;
|
|
4173
|
-
})(), discardOnAbort = false, isReplay = false }) {
|
|
4472
|
+
async executeToolHandler({ tool, toolCall, agent, agentId, handlerArgs, toolType, messageId, signal = this.latestRunSignal(agent), discardOnAbort = false, isReplay = false }) {
|
|
4174
4473
|
let toolCallResult = "";
|
|
4175
4474
|
let toolCallText = "";
|
|
4176
4475
|
let errorMessage;
|
|
@@ -4180,7 +4479,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4180
4479
|
parsedArgs = parseToolArguments(handlerArgs, toolCall.function.name);
|
|
4181
4480
|
} catch (error) {
|
|
4182
4481
|
const parseError = error instanceof Error ? error : new Error(String(error));
|
|
4183
|
-
errorMessage = parseError
|
|
4482
|
+
errorMessage = toolFailureMessage(parseError);
|
|
4184
4483
|
isArgumentError = true;
|
|
4185
4484
|
await this._internal.emitError({
|
|
4186
4485
|
error: parseError,
|
|
@@ -4215,7 +4514,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4215
4514
|
({content: toolCallResult, text: toolCallText} = toToolResultContent(result));
|
|
4216
4515
|
} catch (error) {
|
|
4217
4516
|
const handlerError = error instanceof Error ? error : new Error(String(error));
|
|
4218
|
-
errorMessage = handlerError
|
|
4517
|
+
errorMessage = toolFailureMessage(handlerError);
|
|
4219
4518
|
if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) await this._internal.emitError({
|
|
4220
4519
|
error: handlerError,
|
|
4221
4520
|
code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,
|
|
@@ -4273,18 +4572,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4273
4572
|
isReplay
|
|
4274
4573
|
});
|
|
4275
4574
|
{
|
|
4276
|
-
var _agent$messages$inser;
|
|
4277
4575
|
const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
|
|
4278
|
-
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;
|
|
4279
|
-
|
|
4280
|
-
while (insertAt < agent.messages.length && ((_agent$messages$inser = agent.messages[insertAt]) === null || _agent$messages$inser === void 0 ? void 0 : _agent$messages$inser.role) === "tool") insertAt++;
|
|
4576
|
+
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;
|
|
4577
|
+
const insertAt = this.toolResultInsertionIndex(agent.messages, messageIndex, toolCall.id);
|
|
4281
4578
|
const toolMessage = {
|
|
4282
4579
|
id: (0, _copilotkit_shared.randomUUID)(),
|
|
4283
4580
|
role: "tool",
|
|
4284
4581
|
toolCallId: toolCall.id,
|
|
4285
|
-
content: handlerResult.content
|
|
4582
|
+
content: handlerResult.content,
|
|
4583
|
+
...handlerResult.error ? { error: handlerResult.error } : {}
|
|
4286
4584
|
};
|
|
4287
|
-
|
|
4585
|
+
agent.messages.splice(insertAt, 0, toolMessage);
|
|
4288
4586
|
if (!handlerResult.error && (tool === null || tool === void 0 ? void 0 : tool.followUp) !== false) return true;
|
|
4289
4587
|
}
|
|
4290
4588
|
return false;
|
|
@@ -4307,7 +4605,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4307
4605
|
parsedArgs = parseToolArguments(toolCall.function.arguments, toolCall.function.name);
|
|
4308
4606
|
} catch (error) {
|
|
4309
4607
|
const parseError = error instanceof Error ? error : new Error(String(error));
|
|
4310
|
-
errorMessage = parseError
|
|
4608
|
+
errorMessage = toolFailureMessage(parseError);
|
|
4311
4609
|
await this._internal.emitError({
|
|
4312
4610
|
error: parseError,
|
|
4313
4611
|
code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,
|
|
@@ -4345,7 +4643,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4345
4643
|
({content: toolCallResult, text: toolCallText} = toToolResultContent(result));
|
|
4346
4644
|
} catch (error) {
|
|
4347
4645
|
const handlerError = error instanceof Error ? error : new Error(String(error));
|
|
4348
|
-
errorMessage = handlerError
|
|
4646
|
+
errorMessage = toolFailureMessage(handlerError);
|
|
4349
4647
|
if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) await this._internal.emitError({
|
|
4350
4648
|
error: handlerError,
|
|
4351
4649
|
code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,
|
|
@@ -4373,18 +4671,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4373
4671
|
}, "Subscriber onToolExecutionEnd error:");
|
|
4374
4672
|
}
|
|
4375
4673
|
{
|
|
4376
|
-
var _agent$messages$inser2;
|
|
4377
4674
|
const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
|
|
4378
|
-
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;
|
|
4379
|
-
|
|
4380
|
-
while (insertAt < agent.messages.length && ((_agent$messages$inser2 = agent.messages[insertAt]) === null || _agent$messages$inser2 === void 0 ? void 0 : _agent$messages$inser2.role) === "tool") insertAt++;
|
|
4675
|
+
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;
|
|
4676
|
+
const insertAt = this.toolResultInsertionIndex(agent.messages, messageIndex, toolCall.id);
|
|
4381
4677
|
const toolMessage = {
|
|
4382
4678
|
id: (0, _copilotkit_shared.randomUUID)(),
|
|
4383
4679
|
role: "tool",
|
|
4384
4680
|
toolCallId: toolCall.id,
|
|
4385
|
-
content: toolCallResult
|
|
4681
|
+
content: toolCallResult,
|
|
4682
|
+
...errorMessage ? { error: errorMessage } : {}
|
|
4386
4683
|
};
|
|
4387
|
-
|
|
4684
|
+
agent.messages.splice(insertAt, 0, toolMessage);
|
|
4388
4685
|
if (!errorMessage && (wildcardTool === null || wildcardTool === void 0 ? void 0 : wildcardTool.followUp) !== false) return true;
|
|
4389
4686
|
}
|
|
4390
4687
|
return false;
|
|
@@ -4438,7 +4735,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4438
4735
|
content: "",
|
|
4439
4736
|
toolCalls: [assistantToolCall]
|
|
4440
4737
|
};
|
|
4441
|
-
|
|
4738
|
+
agent.messages.push(assistantMessage);
|
|
4442
4739
|
let handlerResult = {
|
|
4443
4740
|
content: "",
|
|
4444
4741
|
result: "",
|
|
@@ -4457,11 +4754,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4457
4754
|
id: (0, _copilotkit_shared.randomUUID)(),
|
|
4458
4755
|
role: "tool",
|
|
4459
4756
|
toolCallId,
|
|
4460
|
-
content: handlerResult.content
|
|
4757
|
+
content: handlerResult.content,
|
|
4758
|
+
...handlerResult.error ? { error: handlerResult.error } : {}
|
|
4461
4759
|
};
|
|
4462
4760
|
const assistantIndex = agent.messages.findIndex((m) => m.id === assistantMessage.id);
|
|
4463
|
-
if (assistantIndex !== -1)
|
|
4464
|
-
else
|
|
4761
|
+
if (assistantIndex !== -1) agent.messages.splice(assistantIndex + 1, 0, toolResultMessage);
|
|
4762
|
+
else agent.messages.push(toolResultMessage);
|
|
4465
4763
|
if (!handlerResult.error && followUp !== false) {
|
|
4466
4764
|
if (typeof followUp === "string" && followUp !== "generate") {
|
|
4467
4765
|
const userMessage = {
|
|
@@ -4469,7 +4767,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4469
4767
|
role: "user",
|
|
4470
4768
|
content: followUp
|
|
4471
4769
|
};
|
|
4472
|
-
|
|
4770
|
+
agent.messages.push(userMessage);
|
|
4473
4771
|
}
|
|
4474
4772
|
await this._internal.waitForPendingFrameworkUpdates();
|
|
4475
4773
|
await this.runAgent({ agent });
|
|
@@ -4542,7 +4840,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4542
4840
|
/**
|
|
4543
4841
|
* Create an agent error subscriber
|
|
4544
4842
|
*/
|
|
4545
|
-
createAgentErrorSubscriber(agent,
|
|
4843
|
+
createAgentErrorSubscriber(agent, runSignal) {
|
|
4546
4844
|
const emitAgentError = async (error, code, extraContext = {}) => {
|
|
4547
4845
|
const context = { ...extraContext };
|
|
4548
4846
|
if (agent.agentId) context.agentId = agent.agentId;
|
|
@@ -4557,8 +4855,15 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4557
4855
|
await emitAgentError(error, error instanceof AgentThreadLockedError ? CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED : CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT, { source: "onRunFailed" });
|
|
4558
4856
|
},
|
|
4559
4857
|
onRunErrorEvent: async ({ event }) => {
|
|
4560
|
-
var
|
|
4561
|
-
if (((
|
|
4858
|
+
var _runSignal$aborted, _event$rawEvent, _event$rawEvent2, _event$message;
|
|
4859
|
+
if (((_runSignal$aborted = runSignal === null || runSignal === void 0 ? void 0 : runSignal.aborted) !== null && _runSignal$aborted !== void 0 ? _runSignal$aborted : false) || (event === null || event === void 0 ? void 0 : event.code) === "abort") return;
|
|
4860
|
+
if ((event === null || event === void 0 ? void 0 : event.code) === _copilotkit_shared.THREAD_ALREADY_RUNNING_ERROR_CODE) {
|
|
4861
|
+
await emitAgentError(new AgentThreadLockedError(agent.threadId), CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED, {
|
|
4862
|
+
source: "onRunErrorEvent",
|
|
4863
|
+
event
|
|
4864
|
+
});
|
|
4865
|
+
return;
|
|
4866
|
+
}
|
|
4562
4867
|
const eventError = (event === null || event === void 0 ? void 0 : event.rawEvent) instanceof Error ? event.rawEvent : (event === null || event === void 0 || (_event$rawEvent = event.rawEvent) === null || _event$rawEvent === void 0 ? void 0 : _event$rawEvent.error) instanceof Error ? event.rawEvent.error : void 0;
|
|
4563
4868
|
const errorMessage = typeof (event === null || event === void 0 || (_event$rawEvent2 = event.rawEvent) === null || _event$rawEvent2 === void 0 ? void 0 : _event$rawEvent2.error) === "string" ? event.rawEvent.error : (_event$message = event === null || event === void 0 ? void 0 : event.message) !== null && _event$message !== void 0 ? _event$message : "Agent run error";
|
|
4564
4869
|
const rawError = eventError !== null && eventError !== void 0 ? eventError : new Error(errorMessage);
|
|
@@ -4566,8 +4871,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
4566
4871
|
await emitAgentError(rawError, CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT, {
|
|
4567
4872
|
source: "onRunErrorEvent",
|
|
4568
4873
|
event,
|
|
4569
|
-
runtimeErrorCode: event === null || event === void 0 ? void 0 : event.code
|
|
4570
|
-
phase: stream === "run" ? "live" : ɵgetConnectRunErrorPhase(event)
|
|
4874
|
+
runtimeErrorCode: event === null || event === void 0 ? void 0 : event.code
|
|
4571
4875
|
});
|
|
4572
4876
|
}
|
|
4573
4877
|
};
|
|
@@ -5640,6 +5944,18 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
5640
5944
|
get isConfigured() {
|
|
5641
5945
|
return this.config !== void 0;
|
|
5642
5946
|
}
|
|
5947
|
+
/**
|
|
5948
|
+
* Whether events may carry agent message text: not when the capture's config
|
|
5949
|
+
* sets `capture.agentText` to false. A running custom-sink capture keeps the
|
|
5950
|
+
* choice it started with; otherwise the current config decides.
|
|
5951
|
+
*/
|
|
5952
|
+
get capturesAgentText() {
|
|
5953
|
+
var _this$activeConfig;
|
|
5954
|
+
const config = (_this$activeConfig = this.activeConfig) !== null && _this$activeConfig !== void 0 ? _this$activeConfig : this.config;
|
|
5955
|
+
if (config === void 0) return false;
|
|
5956
|
+
const capture = config.capture;
|
|
5957
|
+
return !(typeof capture === "object" && capture !== null && capture.agentText === false);
|
|
5958
|
+
}
|
|
5643
5959
|
get isLegacyCaptureActive() {
|
|
5644
5960
|
return this.collector !== null && this.collector.trajectoryId !== null;
|
|
5645
5961
|
}
|
|
@@ -5749,13 +6065,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
5749
6065
|
this.toolCalls.clear();
|
|
5750
6066
|
this.executingTools.clear();
|
|
5751
6067
|
}
|
|
5752
|
-
/**
|
|
6068
|
+
/**
|
|
6069
|
+
* A developer event. Only an explicit legacy sink adds open-Thread context;
|
|
6070
|
+
* an event that names its own Thread gets no ambiguity next to it.
|
|
6071
|
+
*/
|
|
5753
6072
|
emit(name, value) {
|
|
5754
6073
|
this.connection.emit(name, value);
|
|
5755
6074
|
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
|
|
5756
6075
|
var _this$collector4;
|
|
6076
|
+
const context = typeof value["threadId"] === "string" ? {} : this.openThreadContext();
|
|
5757
6077
|
(_this$collector4 = this.collector) === null || _this$collector4 === void 0 || _this$collector4.emit(name, {
|
|
5758
|
-
...
|
|
6078
|
+
...context,
|
|
5759
6079
|
...value
|
|
5760
6080
|
});
|
|
5761
6081
|
}
|
|
@@ -5841,9 +6161,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
5841
6161
|
});
|
|
5842
6162
|
}
|
|
5843
6163
|
emitMessage(agent, message) {
|
|
5844
|
-
var _this$
|
|
6164
|
+
var _this$collector7;
|
|
5845
6165
|
const content = typeof message.content === "string" ? message.content : "";
|
|
5846
|
-
const includeText =
|
|
6166
|
+
const includeText = this.capturesAgentText && typeof message.content === "string";
|
|
5847
6167
|
(_this$collector7 = this.collector) === null || _this$collector7 === void 0 || _this$collector7.ɵemit("agent.message", {
|
|
5848
6168
|
messageId: message.id,
|
|
5849
6169
|
runId: this.runIdForMessage(agent, message.id),
|
|
@@ -7006,17 +7326,15 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
7006
7326
|
|
|
7007
7327
|
//#endregion
|
|
7008
7328
|
//#region src/core/core.ts
|
|
7329
|
+
/** True for an object literal. Arrays, `null`, and class instances are not plain objects. */
|
|
7330
|
+
function isPlainObject(value) {
|
|
7331
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
|
|
7332
|
+
}
|
|
7009
7333
|
let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode) {
|
|
7010
7334
|
CopilotKitCoreErrorCode["RUNTIME_INFO_FETCH_FAILED"] = "runtime_info_fetch_failed";
|
|
7011
7335
|
CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
|
|
7012
7336
|
CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
|
|
7013
7337
|
CopilotKitCoreErrorCode["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
|
|
7014
|
-
/**
|
|
7015
|
-
* An agent emitted RUN_ERROR. `context.phase` (`RunErrorPhase`) is
|
|
7016
|
-
* `"replay"` when the error belongs to stored thread history replayed on
|
|
7017
|
-
* connect, `"live"` when the run is happening now, and `"unknown"` when the
|
|
7018
|
-
* transport cannot tell. Show a live-failure notice only for `"live"`.
|
|
7019
|
-
*/
|
|
7020
7338
|
CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
|
|
7021
7339
|
CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
|
|
7022
7340
|
CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
|
|
@@ -7078,6 +7396,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
7078
7396
|
_defineProperty(this, "_credentials", void 0);
|
|
7079
7397
|
_defineProperty(this, "_messageFilter", void 0);
|
|
7080
7398
|
_defineProperty(this, "_properties", void 0);
|
|
7399
|
+
_defineProperty(this, "_scopedProperties", /* @__PURE__ */ new Map());
|
|
7081
7400
|
_defineProperty(this, "_defaultThrottleMs", void 0);
|
|
7082
7401
|
_defineProperty(this, "_debug", void 0);
|
|
7083
7402
|
_defineProperty(this, "subscribers", /* @__PURE__ */ new Set());
|
|
@@ -7090,6 +7409,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
7090
7409
|
_defineProperty(this, "learningBridge", void 0);
|
|
7091
7410
|
_defineProperty(this, "notifiedTrajectoryId", null);
|
|
7092
7411
|
_defineProperty(this, "learningConfiguredListeners", /* @__PURE__ */ new Set());
|
|
7412
|
+
_defineProperty(this, "_generativeUIDebugSource", void 0);
|
|
7413
|
+
_defineProperty(this, "generativeUIDebugListeners", /* @__PURE__ */ new Set());
|
|
7093
7414
|
_defineProperty(this, "_memoryStore", void 0);
|
|
7094
7415
|
_defineProperty(this, "previousAgentIds", /* @__PURE__ */ new Set());
|
|
7095
7416
|
this.headerSource = new HeaderSourceResolver((error) => {
|
|
@@ -7416,6 +7737,59 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
7416
7737
|
this._messageFilter = messageFilter;
|
|
7417
7738
|
this.agentRegistry.applyMessageFilterToAgents(this.agentRegistry.agents);
|
|
7418
7739
|
}
|
|
7740
|
+
/**
|
|
7741
|
+
* Add run properties that go only to the runs of `agentIds`. When
|
|
7742
|
+
* `agentIds` is omitted, every agent gets them. They merge on top of the
|
|
7743
|
+
* base `properties`.
|
|
7744
|
+
*
|
|
7745
|
+
* When an entry value and the existing value under the same key are both
|
|
7746
|
+
* plain objects, their keys merge one level deep. So several entries can
|
|
7747
|
+
* add keys under one namespace (for example `copilotkit`).
|
|
7748
|
+
*
|
|
7749
|
+
* @param entry - The properties and the optional agent ids.
|
|
7750
|
+
* @returns The id to pass to `removeScopedProperties`.
|
|
7751
|
+
*
|
|
7752
|
+
* @example
|
|
7753
|
+
* const id = copilotkit.addScopedProperties({
|
|
7754
|
+
* properties: { copilotkit: { theme: "dark" } },
|
|
7755
|
+
* agentIds: ["research"],
|
|
7756
|
+
* });
|
|
7757
|
+
* copilotkit.removeScopedProperties(id);
|
|
7758
|
+
*/
|
|
7759
|
+
addScopedProperties({ properties, agentIds }) {
|
|
7760
|
+
let id = (0, _copilotkit_shared.randomUUID)();
|
|
7761
|
+
for (let n = 1; this._scopedProperties.has(id); n++) id = `${id}-${n}`;
|
|
7762
|
+
this._scopedProperties.set(id, {
|
|
7763
|
+
properties,
|
|
7764
|
+
...agentIds ? { agentIds } : {}
|
|
7765
|
+
});
|
|
7766
|
+
return id;
|
|
7767
|
+
}
|
|
7768
|
+
/** Remove an entry that `addScopedProperties` added. An unknown id does nothing. */
|
|
7769
|
+
removeScopedProperties(id) {
|
|
7770
|
+
this._scopedProperties.delete(id);
|
|
7771
|
+
}
|
|
7772
|
+
/**
|
|
7773
|
+
* Build the forwarded properties for a run of the given agent: the base
|
|
7774
|
+
* properties plus every scoped entry that matches the agent. An entry with
|
|
7775
|
+
* `agentIds` does not match when `agentId` is omitted.
|
|
7776
|
+
*/
|
|
7777
|
+
getPropertiesForAgent(agentId) {
|
|
7778
|
+
const merged = { ...this._properties };
|
|
7779
|
+
const entries = this._scopedProperties.values();
|
|
7780
|
+
for (const entry of entries) {
|
|
7781
|
+
if (!isForAgent(entry.agentIds, agentId)) continue;
|
|
7782
|
+
const properties = Object.entries(entry.properties);
|
|
7783
|
+
for (const [key, value] of properties) {
|
|
7784
|
+
const base = merged[key];
|
|
7785
|
+
merged[key] = isPlainObject(base) && isPlainObject(value) ? {
|
|
7786
|
+
...base,
|
|
7787
|
+
...value
|
|
7788
|
+
} : value;
|
|
7789
|
+
}
|
|
7790
|
+
}
|
|
7791
|
+
return merged;
|
|
7792
|
+
}
|
|
7419
7793
|
setProperties(properties) {
|
|
7420
7794
|
this._properties = properties;
|
|
7421
7795
|
this.notifySubscribers((subscriber) => {
|
|
@@ -7482,6 +7856,15 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
7482
7856
|
get ɵlearningConfigured() {
|
|
7483
7857
|
return this.learningBridge.isConfigured;
|
|
7484
7858
|
}
|
|
7859
|
+
/**
|
|
7860
|
+
* @internal Whether captured events may carry agent message text: false
|
|
7861
|
+
* without a `learning` config, or when a custom sink sets
|
|
7862
|
+
* `capture.agentText` to false. A running custom-sink capture keeps the
|
|
7863
|
+
* choice it started with.
|
|
7864
|
+
*/
|
|
7865
|
+
get ɵlearningCapturesAgentText() {
|
|
7866
|
+
return this.learningBridge.capturesAgentText;
|
|
7867
|
+
}
|
|
7485
7868
|
/** @internal Calls `listener` when {@link ɵlearningConfigured} changes. */
|
|
7486
7869
|
ɵsubscribeToLearningConfigured(listener) {
|
|
7487
7870
|
this.learningConfiguredListeners.add(listener);
|
|
@@ -7489,6 +7872,30 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
7489
7872
|
this.learningConfiguredListeners.delete(listener);
|
|
7490
7873
|
};
|
|
7491
7874
|
}
|
|
7875
|
+
/**
|
|
7876
|
+
* @internal The generative UI of the framework package, for the inspector.
|
|
7877
|
+
* `undefined` when no provider has a `generativeUI` config.
|
|
7878
|
+
*/
|
|
7879
|
+
get ɵgenerativeUIDebugSource() {
|
|
7880
|
+
return this._generativeUIDebugSource;
|
|
7881
|
+
}
|
|
7882
|
+
/** @internal Set by the framework package. `undefined` removes it. */
|
|
7883
|
+
ɵsetGenerativeUIDebugSource(source) {
|
|
7884
|
+
if (source === this._generativeUIDebugSource) return;
|
|
7885
|
+
this._generativeUIDebugSource = source;
|
|
7886
|
+
for (const listener of [...this.generativeUIDebugListeners]) try {
|
|
7887
|
+
listener();
|
|
7888
|
+
} catch (error) {
|
|
7889
|
+
console.error("Generative UI debug listener error:", error);
|
|
7890
|
+
}
|
|
7891
|
+
}
|
|
7892
|
+
/** @internal Calls `listener` when {@link ɵgenerativeUIDebugSource} is set or removed. */
|
|
7893
|
+
ɵsubscribeToGenerativeUIDebugSource(listener) {
|
|
7894
|
+
this.generativeUIDebugListeners.add(listener);
|
|
7895
|
+
return () => {
|
|
7896
|
+
this.generativeUIDebugListeners.delete(listener);
|
|
7897
|
+
};
|
|
7898
|
+
}
|
|
7492
7899
|
/** The active capture's Trajectory ID, or null while capture is stopped. */
|
|
7493
7900
|
get trajectoryId() {
|
|
7494
7901
|
return this.learningBridge.trajectoryId;
|
|
@@ -9132,6 +9539,1287 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
9132
9539
|
}
|
|
9133
9540
|
|
|
9134
9541
|
//#endregion
|
|
9542
|
+
//#region src/a2ui-markdown/fence-parser.ts
|
|
9543
|
+
/** Language of a fenced code block that carries A2UI operations. */
|
|
9544
|
+
const A2UI_FENCE_LANGUAGE = "a2ui";
|
|
9545
|
+
/** Column-0 fence opener: a run of 3+ backticks or tildes, then the info string. */
|
|
9546
|
+
const FENCE_OPEN = /^(`{3,}|~{3,})(.*)$/;
|
|
9547
|
+
/** Info-string token that names the placement target of an a2ui fence. */
|
|
9548
|
+
const TARGET_TOKEN = /^target=(.+)$/;
|
|
9549
|
+
function isCloser(line, fence) {
|
|
9550
|
+
const trimmed = line.trim();
|
|
9551
|
+
if (trimmed.length < fence.length) return false;
|
|
9552
|
+
for (const ch of trimmed) if (ch !== fence.char) return false;
|
|
9553
|
+
return true;
|
|
9554
|
+
}
|
|
9555
|
+
/** The id of the first `target=<id>` token. Other tokens are ignored. */
|
|
9556
|
+
function readTarget(tokens) {
|
|
9557
|
+
for (const token of tokens) {
|
|
9558
|
+
const match = TARGET_TOKEN.exec(token);
|
|
9559
|
+
if (match) return match[1];
|
|
9560
|
+
}
|
|
9561
|
+
}
|
|
9562
|
+
function a2uiSegment(fence, text, closed) {
|
|
9563
|
+
const segment = {
|
|
9564
|
+
type: "a2ui",
|
|
9565
|
+
index: fence.index,
|
|
9566
|
+
text,
|
|
9567
|
+
closed
|
|
9568
|
+
};
|
|
9569
|
+
if (fence.target !== void 0) segment.target = fence.target;
|
|
9570
|
+
return segment;
|
|
9571
|
+
}
|
|
9572
|
+
/**
|
|
9573
|
+
* Split a (possibly still streaming) markdown string into prose segments and
|
|
9574
|
+
* top-level ```a2ui fences. Fences of other languages stay inside prose
|
|
9575
|
+
* segments byte-for-byte, and a2ui markers inside them are ignored. Only
|
|
9576
|
+
* column-0 fences are recognised, so a fence indented inside a list item is
|
|
9577
|
+
* left to the markdown renderer.
|
|
9578
|
+
*
|
|
9579
|
+
* The first info-string token must be exactly `a2ui`. A later
|
|
9580
|
+
* `target=<id>` token sets `target` on the segment (for example
|
|
9581
|
+
* ```` ```a2ui target=recommendations ````). Other tokens are ignored.
|
|
9582
|
+
*
|
|
9583
|
+
* An a2ui segment's `text` is the fence body. For a closed fence it ends with
|
|
9584
|
+
* "\n" when non-empty. For an open (still streaming or aborted) fence it is
|
|
9585
|
+
* everything after the opener line, minus a half-streamed closing marker.
|
|
9586
|
+
*
|
|
9587
|
+
* @param markdown - The assistant message text, complete or still streaming.
|
|
9588
|
+
* @returns The segments in source order.
|
|
9589
|
+
*
|
|
9590
|
+
* @example
|
|
9591
|
+
* ```ts
|
|
9592
|
+
* for (const segment of splitA2UIMarkdown(message.content)) {
|
|
9593
|
+
* if (segment.type === "a2ui") renderSurface(segment.text, segment.target);
|
|
9594
|
+
* else renderMarkdown(segment.text);
|
|
9595
|
+
* }
|
|
9596
|
+
* ```
|
|
9597
|
+
*/
|
|
9598
|
+
function splitA2UIMarkdown(markdown) {
|
|
9599
|
+
const segments = [];
|
|
9600
|
+
let proseStart = 0;
|
|
9601
|
+
let fence = null;
|
|
9602
|
+
let a2uiIndex = 0;
|
|
9603
|
+
const pushProse = (end) => {
|
|
9604
|
+
if (end > proseStart) segments.push({
|
|
9605
|
+
type: "markdown",
|
|
9606
|
+
text: markdown.slice(proseStart, end)
|
|
9607
|
+
});
|
|
9608
|
+
};
|
|
9609
|
+
let lineStart = 0;
|
|
9610
|
+
while (lineStart <= markdown.length) {
|
|
9611
|
+
const newline = markdown.indexOf("\n", lineStart);
|
|
9612
|
+
const lineEnd = newline < 0 ? markdown.length : newline;
|
|
9613
|
+
const hasCR = lineEnd > lineStart && markdown[lineEnd - 1] === "\r";
|
|
9614
|
+
const line = markdown.slice(lineStart, hasCR ? lineEnd - 1 : lineEnd);
|
|
9615
|
+
if (fence) {
|
|
9616
|
+
if (isCloser(line, fence)) {
|
|
9617
|
+
if (fence.index >= 0) {
|
|
9618
|
+
const body = markdown.slice(fence.bodyStart, Math.max(fence.bodyStart, lineStart));
|
|
9619
|
+
segments.push(a2uiSegment(fence, body, true));
|
|
9620
|
+
proseStart = hasCR ? lineEnd - 1 : lineEnd;
|
|
9621
|
+
}
|
|
9622
|
+
fence = null;
|
|
9623
|
+
}
|
|
9624
|
+
} else {
|
|
9625
|
+
const open = FENCE_OPEN.exec(line);
|
|
9626
|
+
if (open) {
|
|
9627
|
+
var _open$, _open$2;
|
|
9628
|
+
const marker = (_open$ = open[1]) !== null && _open$ !== void 0 ? _open$ : "";
|
|
9629
|
+
const info = (_open$2 = open[2]) !== null && _open$2 !== void 0 ? _open$2 : "";
|
|
9630
|
+
const char = marker.charAt(0);
|
|
9631
|
+
if (!(char === "`" && info.includes("`"))) {
|
|
9632
|
+
const [lang = "", ...tokens] = info.trim().split(/\s+/);
|
|
9633
|
+
const isA2UI = lang === A2UI_FENCE_LANGUAGE;
|
|
9634
|
+
if (isA2UI) pushProse(lineStart);
|
|
9635
|
+
fence = {
|
|
9636
|
+
char,
|
|
9637
|
+
length: marker.length,
|
|
9638
|
+
bodyStart: newline < 0 ? markdown.length : lineEnd + 1,
|
|
9639
|
+
index: isA2UI ? a2uiIndex++ : -1,
|
|
9640
|
+
target: isA2UI ? readTarget(tokens) : void 0
|
|
9641
|
+
};
|
|
9642
|
+
}
|
|
9643
|
+
}
|
|
9644
|
+
}
|
|
9645
|
+
if (newline < 0) break;
|
|
9646
|
+
lineStart = newline + 1;
|
|
9647
|
+
}
|
|
9648
|
+
if (fence && fence.index >= 0) {
|
|
9649
|
+
const { char } = fence;
|
|
9650
|
+
let body = markdown.slice(fence.bodyStart);
|
|
9651
|
+
const lastNewline = body.lastIndexOf("\n");
|
|
9652
|
+
const lastLine = body.slice(lastNewline + 1).replace(/\r$/, "");
|
|
9653
|
+
if (lastLine.length > 0 && [...lastLine].every((ch) => ch === char)) body = body.slice(0, lastNewline + 1);
|
|
9654
|
+
segments.push(a2uiSegment(fence, body, false));
|
|
9655
|
+
} else pushProse(markdown.length);
|
|
9656
|
+
return segments;
|
|
9657
|
+
}
|
|
9658
|
+
|
|
9659
|
+
//#endregion
|
|
9660
|
+
//#region src/a2ui-markdown/operations.ts
|
|
9661
|
+
/** The operation keys that change a surface. */
|
|
9662
|
+
const SURFACE_OP_KEYS = [
|
|
9663
|
+
"createSurface",
|
|
9664
|
+
"updateComponents",
|
|
9665
|
+
"updateDataModel",
|
|
9666
|
+
"deleteSurface"
|
|
9667
|
+
];
|
|
9668
|
+
/** The operation key of an agent-called function. It has no surface. */
|
|
9669
|
+
const FUNCTION_CALL_KEY = "callRendererFunction";
|
|
9670
|
+
const OP_KEYS = [...SURFACE_OP_KEYS, FUNCTION_CALL_KEY];
|
|
9671
|
+
function isRecord(value) {
|
|
9672
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9673
|
+
}
|
|
9674
|
+
function isWhitespace(ch) {
|
|
9675
|
+
return ch === " " || ch === "\n" || ch === "\r" || ch === " ";
|
|
9676
|
+
}
|
|
9677
|
+
function skipWhitespace(s, i) {
|
|
9678
|
+
while (i < s.length && isWhitespace(s[i])) i++;
|
|
9679
|
+
return i;
|
|
9680
|
+
}
|
|
9681
|
+
/** Index of the closing quote of the JSON string opening at `start`, or -1. */
|
|
9682
|
+
function findStringEnd(s, start) {
|
|
9683
|
+
for (let i = start + 1; i < s.length; i++) {
|
|
9684
|
+
if (s[i] === "\\") {
|
|
9685
|
+
i++;
|
|
9686
|
+
continue;
|
|
9687
|
+
}
|
|
9688
|
+
if (s[i] === "\"") return i;
|
|
9689
|
+
}
|
|
9690
|
+
return -1;
|
|
9691
|
+
}
|
|
9692
|
+
/**
|
|
9693
|
+
* Find the first `"key":` whose value starts with `opener` and return the index
|
|
9694
|
+
* of that opener, or -1.
|
|
9695
|
+
*/
|
|
9696
|
+
function findKeyValue(s, key, opener) {
|
|
9697
|
+
const needle = `"${key}"`;
|
|
9698
|
+
let from = 0;
|
|
9699
|
+
while (true) {
|
|
9700
|
+
const k = s.indexOf(needle, from);
|
|
9701
|
+
if (k < 0) return -1;
|
|
9702
|
+
let i = skipWhitespace(s, k + needle.length);
|
|
9703
|
+
if (s[i] === ":") {
|
|
9704
|
+
i = skipWhitespace(s, i + 1);
|
|
9705
|
+
if (s[i] === opener) return i;
|
|
9706
|
+
}
|
|
9707
|
+
from = k + 1;
|
|
9708
|
+
}
|
|
9709
|
+
}
|
|
9710
|
+
/**
|
|
9711
|
+
* Read `"key":"value"` from partial JSON. The first match anywhere in the
|
|
9712
|
+
* text wins, at any depth.
|
|
9713
|
+
*
|
|
9714
|
+
* @param partialJson - JSON text that can still be streaming.
|
|
9715
|
+
* @param key - The field name.
|
|
9716
|
+
* @returns The string value, or null until its closing quote has arrived.
|
|
9717
|
+
*
|
|
9718
|
+
* @example
|
|
9719
|
+
* ```ts
|
|
9720
|
+
* extractStringField('{"createSurface":{"surfaceId":"plan","cat', "surfaceId"); // "plan"
|
|
9721
|
+
* ```
|
|
9722
|
+
*/
|
|
9723
|
+
function extractStringField(partialJson, key) {
|
|
9724
|
+
const start = findKeyValue(partialJson, key, "\"");
|
|
9725
|
+
if (start < 0) return null;
|
|
9726
|
+
const end = findStringEnd(partialJson, start);
|
|
9727
|
+
if (end < 0) return null;
|
|
9728
|
+
try {
|
|
9729
|
+
const value = JSON.parse(partialJson.slice(start, end + 1));
|
|
9730
|
+
return typeof value === "string" ? value : null;
|
|
9731
|
+
} catch (_unused) {
|
|
9732
|
+
return null;
|
|
9733
|
+
}
|
|
9734
|
+
}
|
|
9735
|
+
function pushItem(raw, items) {
|
|
9736
|
+
const trimmed = raw.trim();
|
|
9737
|
+
if (!trimmed) return;
|
|
9738
|
+
try {
|
|
9739
|
+
items.push(JSON.parse(trimmed));
|
|
9740
|
+
} catch (_unused2) {}
|
|
9741
|
+
}
|
|
9742
|
+
/**
|
|
9743
|
+
* Find `"key":[` in partial JSON and return every complete item of that array
|
|
9744
|
+
* so far, plus whether the array has closed. Items of a `components` array get
|
|
9745
|
+
* structural-key depth repair: a component that lost closing braces is fixed
|
|
9746
|
+
* when its `id`, `component`, `child` or `children` key shows where it ends.
|
|
9747
|
+
*
|
|
9748
|
+
* @param partialJson - JSON text that can still be streaming.
|
|
9749
|
+
* @param key - The name of the array field.
|
|
9750
|
+
* @returns `{ items, closed }`, or null when the key (with an array value)
|
|
9751
|
+
* has not appeared yet.
|
|
9752
|
+
*
|
|
9753
|
+
* @example
|
|
9754
|
+
* ```ts
|
|
9755
|
+
* const result = extractCompleteArrayItems(streamedText, "components");
|
|
9756
|
+
* if (result) render(result.items);
|
|
9757
|
+
* ```
|
|
9758
|
+
*/
|
|
9759
|
+
function extractCompleteArrayItems(partialJson, key) {
|
|
9760
|
+
const open = findKeyValue(partialJson, key, "[");
|
|
9761
|
+
if (open < 0) return null;
|
|
9762
|
+
return completeArrayItemsAt(partialJson, open, { repairComponents: key === "components" });
|
|
9763
|
+
}
|
|
9764
|
+
/** Index of the last non-whitespace character before `i`, or -1. */
|
|
9765
|
+
function prevNonWhitespace(s, i) {
|
|
9766
|
+
let j = i - 1;
|
|
9767
|
+
while (j >= 0 && isWhitespace(s[j])) j--;
|
|
9768
|
+
return j;
|
|
9769
|
+
}
|
|
9770
|
+
/**
|
|
9771
|
+
* Keys that only ever belong at a component's top level. Seen nested inside
|
|
9772
|
+
* the component's objects, they mean the model forgot closing braces.
|
|
9773
|
+
*/
|
|
9774
|
+
const STRUCTURAL_KEYS = new Set([
|
|
9775
|
+
"id",
|
|
9776
|
+
"component",
|
|
9777
|
+
"child",
|
|
9778
|
+
"children"
|
|
9779
|
+
]);
|
|
9780
|
+
/** Whether a value starting with `ch` has the shape `key` takes on a component. */
|
|
9781
|
+
function structuralValueFits(key, ch) {
|
|
9782
|
+
if (key === "children") return ch === "[" || ch === "{";
|
|
9783
|
+
return ch === "\"";
|
|
9784
|
+
}
|
|
9785
|
+
/** `{"id":` — a new component object starting at `i`. */
|
|
9786
|
+
const COMPONENT_START = /^\{\s*"id"\s*:/;
|
|
9787
|
+
/**
|
|
9788
|
+
* Structural-key depth repair for one component item. While scanning, a
|
|
9789
|
+
* structural key (`id`, `component`, `child`, `children`) found as an object
|
|
9790
|
+
* key below the item's top level, with only objects (no arrays) between it
|
|
9791
|
+
* and the item root, a value of the expected shape, and not already present
|
|
9792
|
+
* at the top level, means closing braces were dropped: the missing `}` are
|
|
9793
|
+
* synthesized right before it so it lands at the top level. Containers still
|
|
9794
|
+
* open at the end are closed. Returns null when a string never terminates.
|
|
9795
|
+
*/
|
|
9796
|
+
function repairComponentItem(item) {
|
|
9797
|
+
const stack = [];
|
|
9798
|
+
const topKeys = /* @__PURE__ */ new Set();
|
|
9799
|
+
let out = "";
|
|
9800
|
+
let copied = 0;
|
|
9801
|
+
for (let i = 0; i < item.length; i++) {
|
|
9802
|
+
const c = item[i];
|
|
9803
|
+
if (c === "\"") {
|
|
9804
|
+
const end = findStringEnd(item, i);
|
|
9805
|
+
if (end < 0) return null;
|
|
9806
|
+
const prev = prevNonWhitespace(item, i);
|
|
9807
|
+
const prevCh = item[prev];
|
|
9808
|
+
const colon = skipWhitespace(item, end + 1);
|
|
9809
|
+
if (stack[stack.length - 1] === "{" && (prevCh === "," || prevCh === "{") && item[colon] === ":") {
|
|
9810
|
+
let key;
|
|
9811
|
+
try {
|
|
9812
|
+
key = JSON.parse(item.slice(i, end + 1));
|
|
9813
|
+
} catch (_unused3) {
|
|
9814
|
+
return null;
|
|
9815
|
+
}
|
|
9816
|
+
if (typeof key === "string") {
|
|
9817
|
+
if (stack.length === 1) topKeys.add(key);
|
|
9818
|
+
else if (STRUCTURAL_KEYS.has(key) && !topKeys.has(key) && stack.every((x) => x === "{") && structuralValueFits(key, item[skipWhitespace(item, colon + 1)])) {
|
|
9819
|
+
const closers = "}".repeat(stack.length - 1);
|
|
9820
|
+
if (prevCh === ",") {
|
|
9821
|
+
out += item.slice(copied, prev) + closers;
|
|
9822
|
+
copied = prev;
|
|
9823
|
+
} else {
|
|
9824
|
+
out += item.slice(copied, i) + closers + ",";
|
|
9825
|
+
copied = i;
|
|
9826
|
+
}
|
|
9827
|
+
stack.length = 1;
|
|
9828
|
+
topKeys.add(key);
|
|
9829
|
+
}
|
|
9830
|
+
}
|
|
9831
|
+
}
|
|
9832
|
+
i = end;
|
|
9833
|
+
continue;
|
|
9834
|
+
}
|
|
9835
|
+
if (c === "{" || c === "[") stack.push(c);
|
|
9836
|
+
else if (c === "}" || c === "]") {
|
|
9837
|
+
stack.pop();
|
|
9838
|
+
if (stack.length === 0) return out + item.slice(copied, i + 1);
|
|
9839
|
+
}
|
|
9840
|
+
}
|
|
9841
|
+
const closers = stack.reduceRight((text, opener) => text + (opener === "{" ? "}" : "]"), "");
|
|
9842
|
+
return out + item.slice(copied) + closers;
|
|
9843
|
+
}
|
|
9844
|
+
function parseRecord(text) {
|
|
9845
|
+
if (text === null) return void 0;
|
|
9846
|
+
try {
|
|
9847
|
+
const value = JSON.parse(text);
|
|
9848
|
+
return isRecord(value) ? value : void 0;
|
|
9849
|
+
} catch (_unused4) {
|
|
9850
|
+
return;
|
|
9851
|
+
}
|
|
9852
|
+
}
|
|
9853
|
+
/**
|
|
9854
|
+
* Complete items of the (possibly unterminated) array whose "[" is at `open`.
|
|
9855
|
+
* With `repairComponents`, an item that balanced but does not parse is retried
|
|
9856
|
+
* with structural-key repair, and a `,{"id":` where an item expects a key
|
|
9857
|
+
* ends that (unbalanced) item there, so one malformed component cannot
|
|
9858
|
+
* swallow the rest of the array; the cut item is kept only if repair makes
|
|
9859
|
+
* it parse.
|
|
9860
|
+
*/
|
|
9861
|
+
function completeArrayItemsAt(partialJson, open, options) {
|
|
9862
|
+
const { repairComponents } = options;
|
|
9863
|
+
const s = partialJson;
|
|
9864
|
+
const items = [];
|
|
9865
|
+
const stack = [];
|
|
9866
|
+
let inString = false;
|
|
9867
|
+
let itemStart = -1;
|
|
9868
|
+
const finishItem = (end, balanced) => {
|
|
9869
|
+
const raw = s.slice(itemStart, end);
|
|
9870
|
+
if (!repairComponents) {
|
|
9871
|
+
pushItem(raw, items);
|
|
9872
|
+
return;
|
|
9873
|
+
}
|
|
9874
|
+
if (balanced) try {
|
|
9875
|
+
items.push(JSON.parse(raw));
|
|
9876
|
+
return;
|
|
9877
|
+
} catch (_unused5) {}
|
|
9878
|
+
const repaired = parseRecord(repairComponentItem(raw.trim()));
|
|
9879
|
+
if (repaired !== void 0) items.push(repaired);
|
|
9880
|
+
};
|
|
9881
|
+
for (let i = open + 1; i < s.length; i++) {
|
|
9882
|
+
const c = s[i];
|
|
9883
|
+
if (inString) {
|
|
9884
|
+
if (c === "\\") i++;
|
|
9885
|
+
else if (c === "\"") inString = false;
|
|
9886
|
+
continue;
|
|
9887
|
+
}
|
|
9888
|
+
if (c === "\"") {
|
|
9889
|
+
inString = true;
|
|
9890
|
+
if (stack.length === 0 && itemStart < 0) itemStart = i;
|
|
9891
|
+
continue;
|
|
9892
|
+
}
|
|
9893
|
+
if (c === "{" || c === "[") {
|
|
9894
|
+
if (repairComponents && c === "{" && stack[stack.length - 1] === "{" && COMPONENT_START.test(s.slice(i, i + 24))) {
|
|
9895
|
+
const prev = prevNonWhitespace(s, i);
|
|
9896
|
+
if (s[prev] === ",") {
|
|
9897
|
+
finishItem(prev, false);
|
|
9898
|
+
stack.length = 0;
|
|
9899
|
+
itemStart = i;
|
|
9900
|
+
stack.push(c);
|
|
9901
|
+
continue;
|
|
9902
|
+
}
|
|
9903
|
+
}
|
|
9904
|
+
if (stack.length === 0) itemStart = i;
|
|
9905
|
+
stack.push(c);
|
|
9906
|
+
continue;
|
|
9907
|
+
}
|
|
9908
|
+
if (c === "}" || c === "]") {
|
|
9909
|
+
if (stack.length === 0) {
|
|
9910
|
+
if (c === "]") {
|
|
9911
|
+
if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
|
|
9912
|
+
return {
|
|
9913
|
+
items,
|
|
9914
|
+
closed: true
|
|
9915
|
+
};
|
|
9916
|
+
}
|
|
9917
|
+
return {
|
|
9918
|
+
items,
|
|
9919
|
+
closed: false
|
|
9920
|
+
};
|
|
9921
|
+
}
|
|
9922
|
+
stack.pop();
|
|
9923
|
+
if (stack.length === 0) {
|
|
9924
|
+
finishItem(i + 1, true);
|
|
9925
|
+
itemStart = -1;
|
|
9926
|
+
}
|
|
9927
|
+
continue;
|
|
9928
|
+
}
|
|
9929
|
+
if (stack.length === 0) {
|
|
9930
|
+
if (c === ",") {
|
|
9931
|
+
if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
|
|
9932
|
+
itemStart = -1;
|
|
9933
|
+
} else if (itemStart < 0 && !isWhitespace(c)) itemStart = i;
|
|
9934
|
+
}
|
|
9935
|
+
}
|
|
9936
|
+
return {
|
|
9937
|
+
items,
|
|
9938
|
+
closed: false
|
|
9939
|
+
};
|
|
9940
|
+
}
|
|
9941
|
+
/** The first operation key whose value is an object, with that value. */
|
|
9942
|
+
function getOperationEntry(op) {
|
|
9943
|
+
for (const key of OP_KEYS) {
|
|
9944
|
+
const inner = op[key];
|
|
9945
|
+
if (isRecord(inner)) return {
|
|
9946
|
+
key,
|
|
9947
|
+
inner
|
|
9948
|
+
};
|
|
9949
|
+
}
|
|
9950
|
+
return null;
|
|
9951
|
+
}
|
|
9952
|
+
/**
|
|
9953
|
+
* The surfaceId an operation targets: the one nested under its operation key,
|
|
9954
|
+
* else a top-level `surfaceId`. A `callRendererFunction` operation targets no
|
|
9955
|
+
* surface, so it gets undefined.
|
|
9956
|
+
*
|
|
9957
|
+
* It is named `getMarkdownOperationSurfaceId` because `@copilotkit/shared`
|
|
9958
|
+
* already exports a strict `getOperationSurfaceId`. This one also reads a
|
|
9959
|
+
* top-level `surfaceId`, which models sometimes write.
|
|
9960
|
+
*
|
|
9961
|
+
* @param op - An operation from an a2ui fence.
|
|
9962
|
+
* @returns The surfaceId, or undefined when the operation names none or is a
|
|
9963
|
+
* function call.
|
|
9964
|
+
*
|
|
9965
|
+
* @example
|
|
9966
|
+
* ```ts
|
|
9967
|
+
* getMarkdownOperationSurfaceId({ updateDataModel: { surfaceId: "plan" } }); // "plan"
|
|
9968
|
+
* ```
|
|
9969
|
+
*/
|
|
9970
|
+
function getMarkdownOperationSurfaceId(op) {
|
|
9971
|
+
var _getOperationEntry;
|
|
9972
|
+
if (((_getOperationEntry = getOperationEntry(op)) === null || _getOperationEntry === void 0 ? void 0 : _getOperationEntry.key) === FUNCTION_CALL_KEY) return void 0;
|
|
9973
|
+
for (const key of SURFACE_OP_KEYS) {
|
|
9974
|
+
const inner = op[key];
|
|
9975
|
+
if (isRecord(inner) && typeof inner.surfaceId === "string") return inner.surfaceId;
|
|
9976
|
+
}
|
|
9977
|
+
return typeof op.surfaceId === "string" ? op.surfaceId : void 0;
|
|
9978
|
+
}
|
|
9979
|
+
/**
|
|
9980
|
+
* Index just past the JSON value starting at `start`, or -1 when the value is
|
|
9981
|
+
* still incomplete. A primitive at the very end of the input counts as
|
|
9982
|
+
* incomplete, since more digits or letters may still stream in.
|
|
9983
|
+
*/
|
|
9984
|
+
function findValueEnd(s, start) {
|
|
9985
|
+
const c = s[start];
|
|
9986
|
+
if (c === "\"") {
|
|
9987
|
+
const end = findStringEnd(s, start);
|
|
9988
|
+
return end < 0 ? -1 : end + 1;
|
|
9989
|
+
}
|
|
9990
|
+
if (c === "{" || c === "[") {
|
|
9991
|
+
let depth = 0;
|
|
9992
|
+
for (let i = start; i < s.length; i++) {
|
|
9993
|
+
const ch = s[i];
|
|
9994
|
+
if (ch === "\"") {
|
|
9995
|
+
const end = findStringEnd(s, i);
|
|
9996
|
+
if (end < 0) return -1;
|
|
9997
|
+
i = end;
|
|
9998
|
+
} else if (ch === "{" || ch === "[") depth++;
|
|
9999
|
+
else if (ch === "}" || ch === "]") {
|
|
10000
|
+
depth--;
|
|
10001
|
+
if (depth === 0) return i + 1;
|
|
10002
|
+
}
|
|
10003
|
+
}
|
|
10004
|
+
return -1;
|
|
10005
|
+
}
|
|
10006
|
+
let i = start;
|
|
10007
|
+
while (i < s.length && !isWhitespace(s[i]) && !",}]".includes(s[i])) i++;
|
|
10008
|
+
return i >= s.length ? -1 : i;
|
|
10009
|
+
}
|
|
10010
|
+
/**
|
|
10011
|
+
* Walk the direct entries of the (possibly unterminated) JSON object whose "{"
|
|
10012
|
+
* is at `objStart`, calling `visit` with each key and the index where its value
|
|
10013
|
+
* starts. Nested objects and arrays are skipped whole, so keys inside them are
|
|
10014
|
+
* never visited. Stops when `visit` returns true, at the object's end, or where
|
|
10015
|
+
* the input runs out.
|
|
10016
|
+
*/
|
|
10017
|
+
function visitDirectEntries(s, objStart, visit) {
|
|
10018
|
+
let i = objStart + 1;
|
|
10019
|
+
while (i < s.length) {
|
|
10020
|
+
i = skipWhitespace(s, i);
|
|
10021
|
+
const c = s[i];
|
|
10022
|
+
if (c === ",") {
|
|
10023
|
+
i++;
|
|
10024
|
+
continue;
|
|
10025
|
+
}
|
|
10026
|
+
if (c !== "\"") return;
|
|
10027
|
+
const keyEnd = findStringEnd(s, i);
|
|
10028
|
+
if (keyEnd < 0) return;
|
|
10029
|
+
let key;
|
|
10030
|
+
try {
|
|
10031
|
+
key = JSON.parse(s.slice(i, keyEnd + 1));
|
|
10032
|
+
} catch (_unused6) {
|
|
10033
|
+
return;
|
|
10034
|
+
}
|
|
10035
|
+
i = skipWhitespace(s, keyEnd + 1);
|
|
10036
|
+
if (s[i] !== ":") return;
|
|
10037
|
+
i = skipWhitespace(s, i + 1);
|
|
10038
|
+
if (i >= s.length) return;
|
|
10039
|
+
if (typeof key === "string" && visit(key, i)) return;
|
|
10040
|
+
const valueEnd = findValueEnd(s, i);
|
|
10041
|
+
if (valueEnd < 0) return;
|
|
10042
|
+
i = valueEnd;
|
|
10043
|
+
}
|
|
10044
|
+
}
|
|
10045
|
+
/**
|
|
10046
|
+
* Value start of a direct `key` of the object at `objStart` whose value begins
|
|
10047
|
+
* with `opener` (any value when omitted), or -1.
|
|
10048
|
+
*/
|
|
10049
|
+
function findDirectKeyValue(s, objStart, key, opener) {
|
|
10050
|
+
let found = -1;
|
|
10051
|
+
visitDirectEntries(s, objStart, (k, valueStart) => {
|
|
10052
|
+
if (k !== key) return false;
|
|
10053
|
+
if (opener === void 0 || s[valueStart] === opener) found = valueStart;
|
|
10054
|
+
return true;
|
|
10055
|
+
});
|
|
10056
|
+
return found;
|
|
10057
|
+
}
|
|
10058
|
+
/** A direct string field of the object at `objStart`, once its closing quote has arrived. */
|
|
10059
|
+
function readDirectString(s, objStart, key) {
|
|
10060
|
+
if (objStart < 0) return null;
|
|
10061
|
+
const start = findDirectKeyValue(s, objStart, key, "\"");
|
|
10062
|
+
if (start < 0) return null;
|
|
10063
|
+
const end = findValueEnd(s, start);
|
|
10064
|
+
if (end < 0) return null;
|
|
10065
|
+
try {
|
|
10066
|
+
const value = JSON.parse(s.slice(start, end));
|
|
10067
|
+
return typeof value === "string" ? value : null;
|
|
10068
|
+
} catch (_unused7) {
|
|
10069
|
+
return null;
|
|
10070
|
+
}
|
|
10071
|
+
}
|
|
10072
|
+
/** A direct object field of the object at `objStart`, once the whole object has arrived. */
|
|
10073
|
+
function readDirectRecord(s, objStart, key) {
|
|
10074
|
+
const start = findDirectKeyValue(s, objStart, key, "{");
|
|
10075
|
+
if (start < 0) return void 0;
|
|
10076
|
+
const end = findValueEnd(s, start);
|
|
10077
|
+
if (end < 0) return void 0;
|
|
10078
|
+
return parseRecord(s.slice(start, end));
|
|
10079
|
+
}
|
|
10080
|
+
/**
|
|
10081
|
+
* The complete part of a (possibly unterminated) JSON value: the parsed value
|
|
10082
|
+
* when it is complete; for an open object, its complete entries plus the
|
|
10083
|
+
* complete items of any streaming array entry; otherwise undefined.
|
|
10084
|
+
*/
|
|
10085
|
+
function completePartOfValue(s, start) {
|
|
10086
|
+
const end = findValueEnd(s, start);
|
|
10087
|
+
if (end >= 0) try {
|
|
10088
|
+
return JSON.parse(s.slice(start, end));
|
|
10089
|
+
} catch (_unused8) {
|
|
10090
|
+
return;
|
|
10091
|
+
}
|
|
10092
|
+
if (s[start] !== "{") return void 0;
|
|
10093
|
+
const out = {};
|
|
10094
|
+
visitDirectEntries(s, start, (key, valueStart) => {
|
|
10095
|
+
const valueEnd = findValueEnd(s, valueStart);
|
|
10096
|
+
if (valueEnd >= 0) try {
|
|
10097
|
+
out[key] = JSON.parse(s.slice(valueStart, valueEnd));
|
|
10098
|
+
} catch (_unused9) {}
|
|
10099
|
+
else if (s[valueStart] === "[") {
|
|
10100
|
+
const { items } = completeArrayItemsAt(s, valueStart, { repairComponents: false });
|
|
10101
|
+
if (items.length > 0) out[key] = items;
|
|
10102
|
+
}
|
|
10103
|
+
return false;
|
|
10104
|
+
});
|
|
10105
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
10106
|
+
}
|
|
10107
|
+
/**
|
|
10108
|
+
* Best-effort operation from an unfinished or malformed top-level object.
|
|
10109
|
+
* Fields are read only from the operation's own keys (`version` at the top
|
|
10110
|
+
* level, `surfaceId`, `catalogId`, `path`, `dataModel` and `components` inside
|
|
10111
|
+
* the operation object), never from component props or data-model values that
|
|
10112
|
+
* happen to share a name.
|
|
10113
|
+
*
|
|
10114
|
+
* A `createSurface` keeps its complete components and a `dataModel` that has
|
|
10115
|
+
* fully arrived, so a surface created in one line renders while it streams.
|
|
10116
|
+
* A `callRendererFunction` gives nothing: a function must not run with half
|
|
10117
|
+
* of its args.
|
|
10118
|
+
*/
|
|
10119
|
+
function partialOperation(line) {
|
|
10120
|
+
var _readDirectString;
|
|
10121
|
+
const root = skipWhitespace(line, 0);
|
|
10122
|
+
if (line[root] !== "{") return null;
|
|
10123
|
+
const version = (_readDirectString = readDirectString(line, root, "version")) !== null && _readDirectString !== void 0 ? _readDirectString : _copilotkit_shared.A2UI_VERSION;
|
|
10124
|
+
const components = findDirectKeyValue(line, root, "updateComponents", "{");
|
|
10125
|
+
if (components >= 0) {
|
|
10126
|
+
const arrayStart = findDirectKeyValue(line, components, "components", "[");
|
|
10127
|
+
if (arrayStart < 0) return null;
|
|
10128
|
+
const { items } = completeArrayItemsAt(line, arrayStart, { repairComponents: true });
|
|
10129
|
+
if (items.length === 0) return null;
|
|
10130
|
+
const surfaceId = readDirectString(line, components, "surfaceId");
|
|
10131
|
+
return {
|
|
10132
|
+
version,
|
|
10133
|
+
updateComponents: {
|
|
10134
|
+
...surfaceId ? { surfaceId } : {},
|
|
10135
|
+
components: items
|
|
10136
|
+
}
|
|
10137
|
+
};
|
|
10138
|
+
}
|
|
10139
|
+
const data = findDirectKeyValue(line, root, "updateDataModel", "{");
|
|
10140
|
+
if (data >= 0) {
|
|
10141
|
+
const valueStart = findDirectKeyValue(line, data, "value");
|
|
10142
|
+
if (valueStart < 0) return null;
|
|
10143
|
+
const value = completePartOfValue(line, valueStart);
|
|
10144
|
+
if (value === void 0) return null;
|
|
10145
|
+
const surfaceId = readDirectString(line, data, "surfaceId");
|
|
10146
|
+
const path = readDirectString(line, data, "path");
|
|
10147
|
+
return {
|
|
10148
|
+
version,
|
|
10149
|
+
updateDataModel: {
|
|
10150
|
+
...surfaceId ? { surfaceId } : {},
|
|
10151
|
+
...path ? { path } : {},
|
|
10152
|
+
value
|
|
10153
|
+
}
|
|
10154
|
+
};
|
|
10155
|
+
}
|
|
10156
|
+
const create = findDirectKeyValue(line, root, "createSurface", "{");
|
|
10157
|
+
if (create >= 0) {
|
|
10158
|
+
const surfaceId = readDirectString(line, create, "surfaceId");
|
|
10159
|
+
if (!surfaceId) return null;
|
|
10160
|
+
const catalogId = readDirectString(line, create, "catalogId");
|
|
10161
|
+
const dataModel = readDirectRecord(line, create, "dataModel");
|
|
10162
|
+
const componentsStart = findDirectKeyValue(line, create, "components", "[");
|
|
10163
|
+
const components = componentsStart < 0 ? [] : completeArrayItemsAt(line, componentsStart, { repairComponents: true }).items;
|
|
10164
|
+
return {
|
|
10165
|
+
version,
|
|
10166
|
+
createSurface: {
|
|
10167
|
+
surfaceId,
|
|
10168
|
+
...catalogId ? { catalogId } : {},
|
|
10169
|
+
...dataModel ? { dataModel } : {},
|
|
10170
|
+
...components.length > 0 ? { components } : {}
|
|
10171
|
+
}
|
|
10172
|
+
};
|
|
10173
|
+
}
|
|
10174
|
+
return null;
|
|
10175
|
+
}
|
|
10176
|
+
/**
|
|
10177
|
+
* A line that opens a new top-level operation: `{"version":"v…` or
|
|
10178
|
+
* `{"<operation>":{`. Seen at the start of a line while an earlier object is
|
|
10179
|
+
* still unbalanced, it means that object is malformed and has ended.
|
|
10180
|
+
*/
|
|
10181
|
+
const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"v\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
|
|
10182
|
+
/**
|
|
10183
|
+
* Scan the top-level object whose "{" is at `start`. Returns the index just
|
|
10184
|
+
* past it and whether it balanced. An unbalanced object ends early (at the
|
|
10185
|
+
* start of the line) when a line opens a new operation; otherwise it runs to
|
|
10186
|
+
* the end of the input. JSON strings cannot contain raw newlines, so a newline
|
|
10187
|
+
* inside a string ends it: a stray quote then breaks one line, not the rest of
|
|
10188
|
+
* the fence.
|
|
10189
|
+
*/
|
|
10190
|
+
function scanTopLevelObject(s, start) {
|
|
10191
|
+
let depth = 0;
|
|
10192
|
+
let inString = false;
|
|
10193
|
+
for (let i = start; i < s.length; i++) {
|
|
10194
|
+
const c = s[i];
|
|
10195
|
+
if (inString) {
|
|
10196
|
+
if (c === "\\" && s[i + 1] !== "\n") i++;
|
|
10197
|
+
else if (c === "\"" || c === "\n") inString = false;
|
|
10198
|
+
if (c !== "\n") continue;
|
|
10199
|
+
}
|
|
10200
|
+
if (c === "\n") {
|
|
10201
|
+
const next = skipWhitespace(s, i + 1);
|
|
10202
|
+
if (OPERATION_START.test(s.slice(next, next + 40))) return {
|
|
10203
|
+
end: i + 1,
|
|
10204
|
+
balanced: false
|
|
10205
|
+
};
|
|
10206
|
+
continue;
|
|
10207
|
+
}
|
|
10208
|
+
if (c === "\"") inString = true;
|
|
10209
|
+
else if (c === "{" || c === "[") depth++;
|
|
10210
|
+
else if (c === "}" || c === "]") {
|
|
10211
|
+
depth--;
|
|
10212
|
+
if (depth === 0) return {
|
|
10213
|
+
end: i + 1,
|
|
10214
|
+
balanced: true
|
|
10215
|
+
};
|
|
10216
|
+
}
|
|
10217
|
+
}
|
|
10218
|
+
return {
|
|
10219
|
+
end: s.length,
|
|
10220
|
+
balanced: false
|
|
10221
|
+
};
|
|
10222
|
+
}
|
|
10223
|
+
/**
|
|
10224
|
+
* Parse the body of an a2ui fence as a stream of top-level JSON values, so
|
|
10225
|
+
* operations may be one per line (the documented format), several per line,
|
|
10226
|
+
* pretty-printed over many lines, or wrapped in a top-level array (which is
|
|
10227
|
+
* flattened). Whitespace and commas between objects are ignored.
|
|
10228
|
+
*
|
|
10229
|
+
* - A balanced object is `JSON.parse`d. When that fails (e.g. a stray quote),
|
|
10230
|
+
* its raw text goes to `invalidLines` and whatever `partialOperation` can
|
|
10231
|
+
* salvage (complete components, data-model entries, createSurface fields)
|
|
10232
|
+
* is kept.
|
|
10233
|
+
* - An unbalanced object followed by a line that opens a new operation is
|
|
10234
|
+
* treated the same way.
|
|
10235
|
+
* - The trailing unbalanced object (still streaming, or never closed) is
|
|
10236
|
+
* `partialObject` and yields a partial operation when it has usable data.
|
|
10237
|
+
* - Other text between objects is skipped and reported in `recovered` (and in
|
|
10238
|
+
* `invalidLines`, which predates it).
|
|
10239
|
+
*
|
|
10240
|
+
* `partialLine` is a deprecated alias of `partialObject`.
|
|
10241
|
+
*
|
|
10242
|
+
* @param fenceText - The body of an a2ui fence (`text` of an a2ui
|
|
10243
|
+
* `MarkdownSegment`), complete or still streaming.
|
|
10244
|
+
* @returns `{ operations, partialObject, partialLine, invalidLines, recovered }`.
|
|
10245
|
+
*
|
|
10246
|
+
* @example
|
|
10247
|
+
* ```ts
|
|
10248
|
+
* const { operations } = extractFenceOperations(segment.text);
|
|
10249
|
+
* ```
|
|
10250
|
+
*/
|
|
10251
|
+
function extractFenceOperations(fenceText) {
|
|
10252
|
+
const s = fenceText;
|
|
10253
|
+
const operations = [];
|
|
10254
|
+
const invalidLines = [];
|
|
10255
|
+
const recovered = [];
|
|
10256
|
+
let partialObject = null;
|
|
10257
|
+
const salvage = (raw) => {
|
|
10258
|
+
invalidLines.push(raw.trim());
|
|
10259
|
+
const partial = partialOperation(raw);
|
|
10260
|
+
if (partial) operations.push(partial);
|
|
10261
|
+
};
|
|
10262
|
+
let junkStart = -1;
|
|
10263
|
+
const flushJunk = (end) => {
|
|
10264
|
+
if (junkStart < 0) return;
|
|
10265
|
+
const junk = s.slice(junkStart, end).trim();
|
|
10266
|
+
junkStart = -1;
|
|
10267
|
+
if (!junk) return;
|
|
10268
|
+
recovered.push(junk);
|
|
10269
|
+
invalidLines.push(junk);
|
|
10270
|
+
};
|
|
10271
|
+
let i = 0;
|
|
10272
|
+
while (i < s.length) {
|
|
10273
|
+
const c = s[i];
|
|
10274
|
+
if (c === "{") {
|
|
10275
|
+
flushJunk(i);
|
|
10276
|
+
const { end, balanced } = scanTopLevelObject(s, i);
|
|
10277
|
+
const raw = s.slice(i, end);
|
|
10278
|
+
if (balanced) {
|
|
10279
|
+
let parsed;
|
|
10280
|
+
try {
|
|
10281
|
+
parsed = JSON.parse(raw);
|
|
10282
|
+
} catch (_unused10) {
|
|
10283
|
+
parsed = void 0;
|
|
10284
|
+
}
|
|
10285
|
+
if (isRecord(parsed)) operations.push(parsed);
|
|
10286
|
+
else salvage(raw);
|
|
10287
|
+
} else if (end < s.length) salvage(raw);
|
|
10288
|
+
else {
|
|
10289
|
+
partialObject = raw;
|
|
10290
|
+
const partial = partialOperation(raw);
|
|
10291
|
+
if (partial) operations.push(partial);
|
|
10292
|
+
}
|
|
10293
|
+
i = end;
|
|
10294
|
+
continue;
|
|
10295
|
+
}
|
|
10296
|
+
if (c === "\n" || c === "[" || c === "]") flushJunk(i);
|
|
10297
|
+
else if (junkStart < 0 && !isWhitespace(c) && c !== ",") junkStart = i;
|
|
10298
|
+
i++;
|
|
10299
|
+
}
|
|
10300
|
+
flushJunk(s.length);
|
|
10301
|
+
return {
|
|
10302
|
+
operations,
|
|
10303
|
+
partialObject,
|
|
10304
|
+
partialLine: partialObject,
|
|
10305
|
+
invalidLines,
|
|
10306
|
+
recovered
|
|
10307
|
+
};
|
|
10308
|
+
}
|
|
10309
|
+
/**
|
|
10310
|
+
* Normalise a fence's operations for the renderer: drop unknown messages, fill
|
|
10311
|
+
* in `version` and missing `surfaceId`s, keep only the first `createSurface`,
|
|
10312
|
+
* keep its `catalogId` when `catalogIds` lists it (else use `catalogId`), synthesize
|
|
10313
|
+
* `createSurface` when the model omitted it, and report the
|
|
10314
|
+
* surfaceId (the first one found, else `fallbackSurfaceId`).
|
|
10315
|
+
*
|
|
10316
|
+
* `callRendererFunction` operations target no surface. They get no surfaceId,
|
|
10317
|
+
* do not cause a synthesized `createSurface`, and come back in
|
|
10318
|
+
* `functionCalls` (in fence order), never in `operations`.
|
|
10319
|
+
*
|
|
10320
|
+
* @param input.operations - Operations from `extractFenceOperations`.
|
|
10321
|
+
* @param input.fallbackSurfaceId - The surfaceId to use when no operation
|
|
10322
|
+
* names one.
|
|
10323
|
+
* @param input.catalogId - The client catalog. It replaces a catalogId of the
|
|
10324
|
+
* model that `catalogIds` does not list.
|
|
10325
|
+
* @param input.catalogIds - The catalogs that the model can name. Left out,
|
|
10326
|
+
* only `catalogId`.
|
|
10327
|
+
* @returns `{ surfaceId, operations, functionCalls }`.
|
|
10328
|
+
*
|
|
10329
|
+
* @example
|
|
10330
|
+
* ```ts
|
|
10331
|
+
* const { surfaceId, operations, functionCalls } = prepareSurfaceOperations({
|
|
10332
|
+
* operations: extractFenceOperations(segment.text).operations,
|
|
10333
|
+
* fallbackSurfaceId: `${messageId}-${segment.index}`,
|
|
10334
|
+
* catalogId,
|
|
10335
|
+
* });
|
|
10336
|
+
* ```
|
|
10337
|
+
*/
|
|
10338
|
+
function prepareSurfaceOperations(input) {
|
|
10339
|
+
var _input$catalogIds, _operations$map$find;
|
|
10340
|
+
const { operations, fallbackSurfaceId, catalogId } = input;
|
|
10341
|
+
const catalogIds = (_input$catalogIds = input.catalogIds) !== null && _input$catalogIds !== void 0 ? _input$catalogIds : [catalogId];
|
|
10342
|
+
const surfaceId = (_operations$map$find = operations.map(getMarkdownOperationSurfaceId).find((id) => !!id)) !== null && _operations$map$find !== void 0 ? _operations$map$find : fallbackSurfaceId;
|
|
10343
|
+
const out = [];
|
|
10344
|
+
const functionCalls = [];
|
|
10345
|
+
let hasCreate = false;
|
|
10346
|
+
for (const op of operations) {
|
|
10347
|
+
const entry = getOperationEntry(op);
|
|
10348
|
+
if (!entry) continue;
|
|
10349
|
+
const { key } = entry;
|
|
10350
|
+
const inner = { ...entry.inner };
|
|
10351
|
+
const version = typeof op.version === "string" ? op.version : _copilotkit_shared.A2UI_VERSION;
|
|
10352
|
+
if (key === FUNCTION_CALL_KEY) {
|
|
10353
|
+
functionCalls.push({
|
|
10354
|
+
version,
|
|
10355
|
+
[key]: inner
|
|
10356
|
+
});
|
|
10357
|
+
continue;
|
|
10358
|
+
}
|
|
10359
|
+
if (typeof inner.surfaceId !== "string") inner.surfaceId = surfaceId;
|
|
10360
|
+
if (key === "createSurface") {
|
|
10361
|
+
if (hasCreate) {
|
|
10362
|
+
const { surfaceId: id, dataModel, components } = inner;
|
|
10363
|
+
if (dataModel !== void 0) out.push({
|
|
10364
|
+
version,
|
|
10365
|
+
updateDataModel: {
|
|
10366
|
+
surfaceId: id,
|
|
10367
|
+
path: "/",
|
|
10368
|
+
value: dataModel
|
|
10369
|
+
}
|
|
10370
|
+
});
|
|
10371
|
+
if (Array.isArray(components) && components.length > 0) out.push({
|
|
10372
|
+
version,
|
|
10373
|
+
updateComponents: {
|
|
10374
|
+
surfaceId: id,
|
|
10375
|
+
components
|
|
10376
|
+
}
|
|
10377
|
+
});
|
|
10378
|
+
continue;
|
|
10379
|
+
}
|
|
10380
|
+
hasCreate = true;
|
|
10381
|
+
if (!catalogIds.includes(inner.catalogId)) inner.catalogId = catalogId;
|
|
10382
|
+
}
|
|
10383
|
+
out.push({
|
|
10384
|
+
version,
|
|
10385
|
+
[key]: inner
|
|
10386
|
+
});
|
|
10387
|
+
}
|
|
10388
|
+
if (!hasCreate && out.length > 0) out.unshift({
|
|
10389
|
+
version: _copilotkit_shared.A2UI_VERSION,
|
|
10390
|
+
createSurface: {
|
|
10391
|
+
surfaceId,
|
|
10392
|
+
catalogId
|
|
10393
|
+
}
|
|
10394
|
+
});
|
|
10395
|
+
return {
|
|
10396
|
+
surfaceId,
|
|
10397
|
+
operations: out,
|
|
10398
|
+
functionCalls
|
|
10399
|
+
};
|
|
10400
|
+
}
|
|
10401
|
+
/**
|
|
10402
|
+
* Components a user operates. A Card containing one of these is an
|
|
10403
|
+
* interactive panel and keeps its box; every other Card is informational.
|
|
10404
|
+
*/
|
|
10405
|
+
const INTERACTIVE_COMPONENTS = new Set([
|
|
10406
|
+
"Button",
|
|
10407
|
+
"Pressable",
|
|
10408
|
+
"Form",
|
|
10409
|
+
"TextField",
|
|
10410
|
+
"TextArea",
|
|
10411
|
+
"Select",
|
|
10412
|
+
"CheckBox",
|
|
10413
|
+
"Radio",
|
|
10414
|
+
"RadioGroup",
|
|
10415
|
+
"Slider",
|
|
10416
|
+
"SegmentedControl",
|
|
10417
|
+
"ChoicePicker",
|
|
10418
|
+
"DateTimeInput"
|
|
10419
|
+
]);
|
|
10420
|
+
/** A component id referenced by a `child`/`children` entry or a table cell. */
|
|
10421
|
+
function referencedId(value) {
|
|
10422
|
+
if (typeof value === "string") return value;
|
|
10423
|
+
if (isRecord(value)) {
|
|
10424
|
+
if (typeof value.componentId === "string") return value.componentId;
|
|
10425
|
+
if (typeof value.id === "string") return value.id;
|
|
10426
|
+
}
|
|
10427
|
+
}
|
|
10428
|
+
/** Ids of a table cell / column that renders a component (`{componentId}` or `{id}`). */
|
|
10429
|
+
function cellComponentId(value) {
|
|
10430
|
+
return isRecord(value) ? referencedId(value) : void 0;
|
|
10431
|
+
}
|
|
10432
|
+
/**
|
|
10433
|
+
* Ids a component renders directly: `child`, `children` (string ids, an
|
|
10434
|
+
* array, or a `{componentId}` template), component cells of a Table's
|
|
10435
|
+
* `rows`/`columns`, and the ids that `extra` finds in its typed references.
|
|
10436
|
+
*/
|
|
10437
|
+
function directChildIds(component, extra) {
|
|
10438
|
+
const ids = [];
|
|
10439
|
+
const add = (id) => {
|
|
10440
|
+
if (id) ids.push(id);
|
|
10441
|
+
};
|
|
10442
|
+
const extraIds = extra === null || extra === void 0 ? void 0 : extra(component);
|
|
10443
|
+
if (Array.isArray(extraIds)) extraIds.forEach(add);
|
|
10444
|
+
add(referencedId(component.child));
|
|
10445
|
+
const children = component.children;
|
|
10446
|
+
if (Array.isArray(children)) children.forEach((c) => add(referencedId(c)));
|
|
10447
|
+
else add(referencedId(children));
|
|
10448
|
+
if (Array.isArray(component.columns)) component.columns.forEach((c) => add(cellComponentId(c)));
|
|
10449
|
+
if (Array.isArray(component.rows)) {
|
|
10450
|
+
for (const row of component.rows) if (Array.isArray(row)) row.forEach((c) => add(cellComponentId(c)));
|
|
10451
|
+
}
|
|
10452
|
+
return ids;
|
|
10453
|
+
}
|
|
10454
|
+
/** Components of every updateComponents operation, by id (last definition wins). */
|
|
10455
|
+
function componentsById(operations) {
|
|
10456
|
+
const byId = /* @__PURE__ */ new Map();
|
|
10457
|
+
for (const op of operations) {
|
|
10458
|
+
const update = op.updateComponents;
|
|
10459
|
+
const list = isRecord(update) ? update.components : void 0;
|
|
10460
|
+
if (!Array.isArray(list)) continue;
|
|
10461
|
+
for (const c of list) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
|
|
10462
|
+
}
|
|
10463
|
+
return byId;
|
|
10464
|
+
}
|
|
10465
|
+
function descendantIds(rootId, byId, extra) {
|
|
10466
|
+
var _byId$get;
|
|
10467
|
+
const seen = /* @__PURE__ */ new Set();
|
|
10468
|
+
const stack = [...directChildIds((_byId$get = byId.get(rootId)) !== null && _byId$get !== void 0 ? _byId$get : {}, extra)];
|
|
10469
|
+
while (stack.length > 0) {
|
|
10470
|
+
const id = stack.pop();
|
|
10471
|
+
if (seen.has(id) || id === rootId) continue;
|
|
10472
|
+
seen.add(id);
|
|
10473
|
+
const c = byId.get(id);
|
|
10474
|
+
if (c) stack.push(...directChildIds(c, extra));
|
|
10475
|
+
}
|
|
10476
|
+
return seen;
|
|
10477
|
+
}
|
|
10478
|
+
/**
|
|
10479
|
+
* Ids of the `Card` components that are interactive panels: at least one
|
|
10480
|
+
* descendant (via `child`, `children` or table component cells) is a control
|
|
10481
|
+
* (Button, Pressable, Form, TextField, TextArea, Select, CheckBox, Radio,
|
|
10482
|
+
* RadioGroup, Slider, SegmentedControl, DateTimeInput).
|
|
10483
|
+
*
|
|
10484
|
+
* @param components - The components of one surface.
|
|
10485
|
+
* @returns The ids of the interactive cards.
|
|
10486
|
+
*
|
|
10487
|
+
* @example
|
|
10488
|
+
* ```ts
|
|
10489
|
+
* const interactive = classifySurfaceCards(components);
|
|
10490
|
+
* const keepsBox = interactive.has("quote-form");
|
|
10491
|
+
* ```
|
|
10492
|
+
*/
|
|
10493
|
+
function classifySurfaceCards(components, options = {}) {
|
|
10494
|
+
const byId = /* @__PURE__ */ new Map();
|
|
10495
|
+
for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
|
|
10496
|
+
const interactive = /* @__PURE__ */ new Set();
|
|
10497
|
+
for (const [id, c] of byId) {
|
|
10498
|
+
if (c.component !== "Card") continue;
|
|
10499
|
+
for (const d of descendantIds(id, byId, options.childIds)) {
|
|
10500
|
+
var _byId$get2;
|
|
10501
|
+
const type = (_byId$get2 = byId.get(d)) === null || _byId$get2 === void 0 ? void 0 : _byId$get2.component;
|
|
10502
|
+
if (typeof type === "string" && INTERACTIVE_COMPONENTS.has(type)) {
|
|
10503
|
+
interactive.add(id);
|
|
10504
|
+
break;
|
|
10505
|
+
}
|
|
10506
|
+
}
|
|
10507
|
+
}
|
|
10508
|
+
return interactive;
|
|
10509
|
+
}
|
|
10510
|
+
/**
|
|
10511
|
+
* Markdown mode: only interactive panels keep a box. Every `Card` that is not
|
|
10512
|
+
* an interactive panel (see `classifySurfaceCards`), sets no `variant` or
|
|
10513
|
+
* `border` of its own and is not nested inside an interactive panel becomes
|
|
10514
|
+
* `variant: "section"` (a heading plus content without a box). Operations
|
|
10515
|
+
* other than updateComponents pass through unchanged.
|
|
10516
|
+
*
|
|
10517
|
+
* @param operations - The operations of one surface.
|
|
10518
|
+
* @returns The operations with informational cards set to `variant: "section"`.
|
|
10519
|
+
* When no card changes, it returns the same array.
|
|
10520
|
+
*
|
|
10521
|
+
* @example
|
|
10522
|
+
* ```ts
|
|
10523
|
+
* const operations = flattenInformationalCards(prepared.operations);
|
|
10524
|
+
* ```
|
|
10525
|
+
*/
|
|
10526
|
+
function flattenInformationalCards(operations, options = {}) {
|
|
10527
|
+
const byId = componentsById(operations);
|
|
10528
|
+
if (![...byId.values()].some((c) => c.component === "Card")) return operations;
|
|
10529
|
+
const interactive = classifySurfaceCards([...byId.values()], options);
|
|
10530
|
+
const insideInteractive = /* @__PURE__ */ new Set();
|
|
10531
|
+
for (const id of interactive) for (const d of descendantIds(id, byId, options.childIds)) insideInteractive.add(d);
|
|
10532
|
+
const flatten = (c) => c.component === "Card" && typeof c.id === "string" && !interactive.has(c.id) && !insideInteractive.has(c.id) && c.variant == null && c.border == null;
|
|
10533
|
+
return operations.map((op) => {
|
|
10534
|
+
const update = op.updateComponents;
|
|
10535
|
+
if (!isRecord(update) || !Array.isArray(update.components)) return op;
|
|
10536
|
+
if (!update.components.some((c) => isRecord(c) && flatten(c))) return op;
|
|
10537
|
+
return {
|
|
10538
|
+
...op,
|
|
10539
|
+
updateComponents: {
|
|
10540
|
+
...update,
|
|
10541
|
+
components: update.components.map((c) => isRecord(c) && flatten(c) ? {
|
|
10542
|
+
...c,
|
|
10543
|
+
variant: "section"
|
|
10544
|
+
} : c)
|
|
10545
|
+
}
|
|
10546
|
+
};
|
|
10547
|
+
});
|
|
10548
|
+
}
|
|
10549
|
+
/** Text-bearing components that belong in the chat's markdown, not a surface. */
|
|
10550
|
+
const PROSE_TEXT_COMPONENTS = new Set([
|
|
10551
|
+
"Title",
|
|
10552
|
+
"Text",
|
|
10553
|
+
"Caption",
|
|
10554
|
+
"Markdown"
|
|
10555
|
+
]);
|
|
10556
|
+
/** One line of text: list items and headings cannot span lines in markdown. */
|
|
10557
|
+
function oneLine(text) {
|
|
10558
|
+
return text.trim().replace(/\s*\n\s*/g, " ");
|
|
10559
|
+
}
|
|
10560
|
+
/**
|
|
10561
|
+
* A literal List entry as list-item markdown: a non-empty string, or
|
|
10562
|
+
* `{ label, description? }` with literal strings only. Anything carrying
|
|
10563
|
+
* behaviour or decoration (`icon`, `action`, other keys, bound values) is null.
|
|
10564
|
+
*/
|
|
10565
|
+
function listEntryMarkdown(entry) {
|
|
10566
|
+
if (typeof entry === "string") return entry.trim() ? oneLine(entry) : null;
|
|
10567
|
+
if (!isRecord(entry)) return null;
|
|
10568
|
+
for (const key of Object.keys(entry)) if (key !== "label" && key !== "description") return null;
|
|
10569
|
+
if (typeof entry.label !== "string" || !entry.label.trim()) return null;
|
|
10570
|
+
const label = oneLine(entry.label);
|
|
10571
|
+
if (entry.description === void 0) return label;
|
|
10572
|
+
if (typeof entry.description !== "string") return null;
|
|
10573
|
+
return entry.description.trim() ? `**${label}** — ${oneLine(entry.description)}` : label;
|
|
10574
|
+
}
|
|
10575
|
+
/**
|
|
10576
|
+
* A List of literal text items as a markdown list (`marker: "number"` →
|
|
10577
|
+
* `1. …`, otherwise `- …`), or null when it binds its items, renders
|
|
10578
|
+
* `children`, or any item is not plain text.
|
|
10579
|
+
*/
|
|
10580
|
+
function listToMarkdown(c) {
|
|
10581
|
+
const children = c.children;
|
|
10582
|
+
if (children != null && !(Array.isArray(children) && children.length === 0)) return null;
|
|
10583
|
+
if (!Array.isArray(c.items) || c.items.length === 0) return null;
|
|
10584
|
+
const lines = [];
|
|
10585
|
+
for (const entry of c.items) {
|
|
10586
|
+
const line = listEntryMarkdown(entry);
|
|
10587
|
+
if (line === null) return null;
|
|
10588
|
+
lines.push(line);
|
|
10589
|
+
}
|
|
10590
|
+
if (c.marker === "number") {
|
|
10591
|
+
const start = typeof c.start === "number" && Number.isInteger(c.start) ? c.start : 1;
|
|
10592
|
+
return lines.map((line, i) => `${start + i}. ${line}`).join("\n");
|
|
10593
|
+
}
|
|
10594
|
+
return lines.map((line) => `- ${line}`).join("\n");
|
|
10595
|
+
}
|
|
10596
|
+
/** The prose item a component converts to, or null when it is not prose. */
|
|
10597
|
+
function toProseItem(c) {
|
|
10598
|
+
if (!c) return null;
|
|
10599
|
+
if (c.accessibility !== void 0) return null;
|
|
10600
|
+
if (c.component === "Divider") return { kind: "divider" };
|
|
10601
|
+
if (c.component === "Spacer") return { kind: "spacer" };
|
|
10602
|
+
if (c.component === "List") {
|
|
10603
|
+
if (c.direction !== void 0 && c.direction !== "vertical") return null;
|
|
10604
|
+
const markdown = listToMarkdown(c);
|
|
10605
|
+
return markdown === null ? null : {
|
|
10606
|
+
kind: "text",
|
|
10607
|
+
markdown
|
|
10608
|
+
};
|
|
10609
|
+
}
|
|
10610
|
+
if (typeof c.component !== "string") return null;
|
|
10611
|
+
if (!PROSE_TEXT_COMPONENTS.has(c.component)) return null;
|
|
10612
|
+
if (typeof c.text !== "string" || c.text.trim() === "") return null;
|
|
10613
|
+
const text = c.text.trim();
|
|
10614
|
+
switch (c.component) {
|
|
10615
|
+
case "Title": {
|
|
10616
|
+
const size = typeof c.size === "string" ? c.size : "md";
|
|
10617
|
+
return {
|
|
10618
|
+
kind: "text",
|
|
10619
|
+
markdown: `${size === "sm" ? "####" : size === "md" || size === "lg" ? "###" : "##"} ${text}`
|
|
10620
|
+
};
|
|
10621
|
+
}
|
|
10622
|
+
case "Text":
|
|
10623
|
+
if (directChildIds(c).length > 0) return null;
|
|
10624
|
+
return {
|
|
10625
|
+
kind: "text",
|
|
10626
|
+
markdown: c.strong === true ? `**${text}**` : text
|
|
10627
|
+
};
|
|
10628
|
+
default: return {
|
|
10629
|
+
kind: "text",
|
|
10630
|
+
markdown: text
|
|
10631
|
+
};
|
|
10632
|
+
}
|
|
10633
|
+
}
|
|
10634
|
+
/** Prose items as markdown: separators only survive between two text items. */
|
|
10635
|
+
function proseItemsToMarkdown(items) {
|
|
10636
|
+
const blocks = [];
|
|
10637
|
+
let pendingDivider = false;
|
|
10638
|
+
for (const item of items) if ((item === null || item === void 0 ? void 0 : item.kind) === "text") {
|
|
10639
|
+
if (pendingDivider && blocks.length > 0) blocks.push("---");
|
|
10640
|
+
pendingDivider = false;
|
|
10641
|
+
blocks.push(item.markdown);
|
|
10642
|
+
} else if ((item === null || item === void 0 ? void 0 : item.kind) === "divider") pendingDivider = true;
|
|
10643
|
+
return blocks.join("\n\n");
|
|
10644
|
+
}
|
|
10645
|
+
/** Column, column-direction Box, or an informational Card (section/unset variant). */
|
|
10646
|
+
function isVerticalStack(c, interactiveCards) {
|
|
10647
|
+
if (c.accessibility !== void 0) return false;
|
|
10648
|
+
if (c.component === "Column") return true;
|
|
10649
|
+
if (c.component === "Box") return c.direction == null || c.direction === "col";
|
|
10650
|
+
if (c.component === "Card") return (c.variant == null || c.variant === "section") && typeof c.id === "string" && !interactiveCards.has(c.id);
|
|
10651
|
+
return false;
|
|
10652
|
+
}
|
|
10653
|
+
/** The child-id list of a stack (`children`, or a lone `child`), else null. */
|
|
10654
|
+
/**
|
|
10655
|
+
* The children of a stack in render order: `child` first (a Card renders
|
|
10656
|
+
* its `child` before its `children`), then `children`.
|
|
10657
|
+
*/
|
|
10658
|
+
function stackChildren(c) {
|
|
10659
|
+
const first = typeof c.child === "string" ? [c.child] : [];
|
|
10660
|
+
if (Array.isArray(c.children)) return [...first, ...c.children];
|
|
10661
|
+
if (first.length > 0 && c.children === void 0) return first;
|
|
10662
|
+
return null;
|
|
10663
|
+
}
|
|
10664
|
+
/**
|
|
10665
|
+
* Partitions the stack's children into alternating prose and surface runs.
|
|
10666
|
+
* A run of consecutive prose items is prose only when it holds text: a run of
|
|
10667
|
+
* separators alone (Divider/Spacer between two UI components, or at the very
|
|
10668
|
+
* start/end of the stack) stays with the surface it sits in.
|
|
10669
|
+
*/
|
|
10670
|
+
function partitionChildren(items) {
|
|
10671
|
+
const runs = [];
|
|
10672
|
+
let i = 0;
|
|
10673
|
+
while (i < items.length) {
|
|
10674
|
+
const candidate = items[i] !== null;
|
|
10675
|
+
let hasText = false;
|
|
10676
|
+
let j = i;
|
|
10677
|
+
while (j < items.length && items[j] !== null === candidate) {
|
|
10678
|
+
var _items$j;
|
|
10679
|
+
if (((_items$j = items[j]) === null || _items$j === void 0 ? void 0 : _items$j.kind) === "text") hasText = true;
|
|
10680
|
+
j++;
|
|
10681
|
+
}
|
|
10682
|
+
const prose = candidate && hasText;
|
|
10683
|
+
const last = runs[runs.length - 1];
|
|
10684
|
+
if (!prose && last && !last.prose) last.end = j;
|
|
10685
|
+
else runs.push({
|
|
10686
|
+
prose,
|
|
10687
|
+
start: i,
|
|
10688
|
+
end: j
|
|
10689
|
+
});
|
|
10690
|
+
i = j;
|
|
10691
|
+
}
|
|
10692
|
+
return runs;
|
|
10693
|
+
}
|
|
10694
|
+
/**
|
|
10695
|
+
* Markdown mode: split a surface into markdown and surface segments so that
|
|
10696
|
+
* only real UI renders as A2UI and everything else is the chat's markdown.
|
|
10697
|
+
*
|
|
10698
|
+
* From `root`, descend through single-child vertical containers (Column,
|
|
10699
|
+
* column Box, informational Card) to the first one with several children:
|
|
10700
|
+
* the stack. Its children are partitioned, in order, into runs of prose and
|
|
10701
|
+
* runs of UI. Prose is `Title`, `Text`, `Caption`, `Markdown` with literal
|
|
10702
|
+
* text, a `List` of literal text items, plus `Divider`/`Spacer` next to them:
|
|
10703
|
+
* `Title` → heading by size (sm `####`, md/lg `###`, larger `##`), `Text` →
|
|
10704
|
+
* paragraph (`strong` → `**…**`), `Caption`/`Markdown` → paragraph, `List` →
|
|
10705
|
+
* `- …` (or `1. …` for `marker: "number"`, `**label** — description` for
|
|
10706
|
+
* described items), and a `Divider` between two prose blocks → `---`.
|
|
10707
|
+
*
|
|
10708
|
+
* Not prose: `{path}`-bound text or items, a Text with inline children, a
|
|
10709
|
+
* List with `children`/icons/actions, a template entry, a component with an
|
|
10710
|
+
* `accessibility` envelope, and a child whose component has not streamed
|
|
10711
|
+
* yet. Separators with no text beside them stay in
|
|
10712
|
+
* the surface. An interactive Card (see `classifySurfaceCards`) is never
|
|
10713
|
+
* entered.
|
|
10714
|
+
*
|
|
10715
|
+
* Each prose run becomes a markdown segment; each UI run becomes a surface
|
|
10716
|
+
* segment whose `root` is a copy of the stack (its other props kept, `child`
|
|
10717
|
+
* dropped) with only that run's `children`, followed by every component
|
|
10718
|
+
* reachable from them. When nothing is prose the input comes back as the one
|
|
10719
|
+
* surface segment (same array); when everything is (or `root` itself is),
|
|
10720
|
+
* there are only markdown segments.
|
|
10721
|
+
*
|
|
10722
|
+
* Pure and linear in the number of components, so it runs on every stream
|
|
10723
|
+
* update.
|
|
10724
|
+
*
|
|
10725
|
+
* @param components - The components of one surface, root included.
|
|
10726
|
+
* @returns The segments in render order.
|
|
10727
|
+
*
|
|
10728
|
+
* @example
|
|
10729
|
+
* ```ts
|
|
10730
|
+
* for (const segment of segmentSurfaceProse(components)) {
|
|
10731
|
+
* if (segment.kind === "markdown") renderMarkdown(segment.markdown);
|
|
10732
|
+
* else renderSurface(segment.components);
|
|
10733
|
+
* }
|
|
10734
|
+
* ```
|
|
10735
|
+
*/
|
|
10736
|
+
function segmentSurfaceProse(components, options = {}) {
|
|
10737
|
+
const unchanged = [{
|
|
10738
|
+
kind: "surface",
|
|
10739
|
+
components
|
|
10740
|
+
}];
|
|
10741
|
+
const byId = /* @__PURE__ */ new Map();
|
|
10742
|
+
for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
|
|
10743
|
+
const root = byId.get(_copilotkit_shared.GENERATIVE_UI_ROOT_ID);
|
|
10744
|
+
if (!root) return unchanged;
|
|
10745
|
+
if (components.some((c) => {
|
|
10746
|
+
var _options$childIds;
|
|
10747
|
+
return isRecord(c) && ((_options$childIds = options.childIds) === null || _options$childIds === void 0 ? void 0 : _options$childIds.call(options, c)) === "unknown";
|
|
10748
|
+
})) return unchanged;
|
|
10749
|
+
const rootItem = toProseItem(root);
|
|
10750
|
+
if ((rootItem === null || rootItem === void 0 ? void 0 : rootItem.kind) === "text") return [{
|
|
10751
|
+
kind: "markdown",
|
|
10752
|
+
markdown: rootItem.markdown
|
|
10753
|
+
}];
|
|
10754
|
+
const interactiveCards = classifySurfaceCards(components, options);
|
|
10755
|
+
let stack = root;
|
|
10756
|
+
let stackId = _copilotkit_shared.GENERATIVE_UI_ROOT_ID;
|
|
10757
|
+
let children;
|
|
10758
|
+
const visited = /* @__PURE__ */ new Set();
|
|
10759
|
+
while (true) {
|
|
10760
|
+
if (!isVerticalStack(stack, interactiveCards)) return unchanged;
|
|
10761
|
+
visited.add(stackId);
|
|
10762
|
+
const list = stackChildren(stack);
|
|
10763
|
+
if (!list) return unchanged;
|
|
10764
|
+
children = list;
|
|
10765
|
+
const nextId = list.length === 1 ? list[0] : void 0;
|
|
10766
|
+
if (typeof nextId !== "string") break;
|
|
10767
|
+
const next = byId.get(nextId);
|
|
10768
|
+
if (!next || visited.has(nextId) || toProseItem(next)) break;
|
|
10769
|
+
stack = next;
|
|
10770
|
+
stackId = nextId;
|
|
10771
|
+
}
|
|
10772
|
+
const stackChildIds = children;
|
|
10773
|
+
const items = stackChildIds.map((id) => typeof id === "string" ? toProseItem(byId.get(id)) : null);
|
|
10774
|
+
const runs = partitionChildren(items);
|
|
10775
|
+
if (!runs.some((run) => run.prose)) return unchanged;
|
|
10776
|
+
const surfaceRuns = runs.filter((run) => !run.prose);
|
|
10777
|
+
const owners = /* @__PURE__ */ new Map();
|
|
10778
|
+
surfaceRuns.forEach((run, index) => {
|
|
10779
|
+
const pending = stackChildIds.slice(run.start, run.end).map(referencedId).filter((id) => id !== void 0);
|
|
10780
|
+
const seen = /* @__PURE__ */ new Set();
|
|
10781
|
+
while (pending.length > 0) {
|
|
10782
|
+
const id = pending.pop();
|
|
10783
|
+
if (id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID || id === stackId || seen.has(id)) continue;
|
|
10784
|
+
seen.add(id);
|
|
10785
|
+
const list = owners.get(id);
|
|
10786
|
+
if (list) list.push(index);
|
|
10787
|
+
else owners.set(id, [index]);
|
|
10788
|
+
const c = byId.get(id);
|
|
10789
|
+
if (c) pending.push(...directChildIds(c, options.childIds));
|
|
10790
|
+
}
|
|
10791
|
+
});
|
|
10792
|
+
const surfaceComponents = surfaceRuns.map((run) => {
|
|
10793
|
+
const { child: _child, ...stackRest } = stack;
|
|
10794
|
+
const nextRoot = {
|
|
10795
|
+
...stackRest,
|
|
10796
|
+
id: _copilotkit_shared.GENERATIVE_UI_ROOT_ID,
|
|
10797
|
+
children: stackChildIds.slice(run.start, run.end)
|
|
10798
|
+
};
|
|
10799
|
+
delete nextRoot.child;
|
|
10800
|
+
return [nextRoot];
|
|
10801
|
+
});
|
|
10802
|
+
for (const c of components) {
|
|
10803
|
+
var _owners$get;
|
|
10804
|
+
if (!isRecord(c) || typeof c.id !== "string" || byId.get(c.id) !== c) continue;
|
|
10805
|
+
const ownerIndexes = (_owners$get = owners.get(c.id)) !== null && _owners$get !== void 0 ? _owners$get : [];
|
|
10806
|
+
for (const index of ownerIndexes) surfaceComponents[index].push(c);
|
|
10807
|
+
}
|
|
10808
|
+
let surfaceIndex = 0;
|
|
10809
|
+
return runs.map((run) => {
|
|
10810
|
+
if (run.prose) return {
|
|
10811
|
+
kind: "markdown",
|
|
10812
|
+
markdown: proseItemsToMarkdown(items.slice(run.start, run.end))
|
|
10813
|
+
};
|
|
10814
|
+
return {
|
|
10815
|
+
kind: "surface",
|
|
10816
|
+
components: surfaceComponents[surfaceIndex++]
|
|
10817
|
+
};
|
|
10818
|
+
});
|
|
10819
|
+
}
|
|
10820
|
+
|
|
10821
|
+
//#endregion
|
|
10822
|
+
exports.A2UI_FENCE_LANGUAGE = A2UI_FENCE_LANGUAGE;
|
|
9135
10823
|
exports.AgentRegistry = AgentRegistry;
|
|
9136
10824
|
exports.AgentThreadLockedError = AgentThreadLockedError;
|
|
9137
10825
|
exports.ContextStore = ContextStore;
|
|
@@ -9141,7 +10829,6 @@ exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionS
|
|
|
9141
10829
|
exports.CopilotKitHeaderResolutionError = CopilotKitHeaderResolutionError;
|
|
9142
10830
|
exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
|
|
9143
10831
|
exports.IntelligenceAgent = IntelligenceAgent;
|
|
9144
|
-
exports.IntelligenceReplayFailedError = IntelligenceReplayFailedError;
|
|
9145
10832
|
exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
|
|
9146
10833
|
exports.MemoryError = MemoryError;
|
|
9147
10834
|
exports.ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;
|
|
@@ -9150,6 +10837,7 @@ exports.StateManager = StateManager;
|
|
|
9150
10837
|
exports.SuggestionEngine = SuggestionEngine;
|
|
9151
10838
|
exports.ToolCallStatus = ToolCallStatus;
|
|
9152
10839
|
exports.WebMCPRegistry = WebMCPRegistry;
|
|
10840
|
+
exports.classifySurfaceCards = classifySurfaceCards;
|
|
9153
10841
|
exports.completePartialMarkdown = completePartialMarkdown;
|
|
9154
10842
|
exports.createActionGroup = createActionGroup;
|
|
9155
10843
|
exports.createEffect = createEffect;
|
|
@@ -9163,6 +10851,11 @@ exports.emitInspectorViewThread = emitInspectorViewThread;
|
|
|
9163
10851
|
exports.emitInspectorViewThreadResult = emitInspectorViewThreadResult;
|
|
9164
10852
|
exports.empty = empty;
|
|
9165
10853
|
exports.ensureObjectArgs = ensureObjectArgs;
|
|
10854
|
+
exports.extractCompleteArrayItems = extractCompleteArrayItems;
|
|
10855
|
+
exports.extractFenceOperations = extractFenceOperations;
|
|
10856
|
+
exports.extractStringField = extractStringField;
|
|
10857
|
+
exports.flattenInformationalCards = flattenInformationalCards;
|
|
10858
|
+
exports.getMarkdownOperationSurfaceId = getMarkdownOperationSurfaceId;
|
|
9166
10859
|
exports.getWebMCPModelContext = getWebMCPModelContext;
|
|
9167
10860
|
exports.isAbortError = isAbortError;
|
|
9168
10861
|
exports.isInspectorThreadBridgeEnabled = isInspectorThreadBridgeEnabled;
|
|
@@ -9174,8 +10867,11 @@ exports.onInspectorStopViewing = onInspectorStopViewing;
|
|
|
9174
10867
|
exports.onInspectorViewThread = onInspectorViewThread;
|
|
9175
10868
|
exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
|
|
9176
10869
|
exports.parseToolArguments = parseToolArguments;
|
|
10870
|
+
exports.prepareSurfaceOperations = prepareSurfaceOperations;
|
|
9177
10871
|
exports.props = props;
|
|
10872
|
+
exports.segmentSurfaceProse = segmentSurfaceProse;
|
|
9178
10873
|
exports.select = select;
|
|
10874
|
+
exports.splitA2UIMarkdown = splitA2UIMarkdown;
|
|
9179
10875
|
exports.ɵCOPILOTKIT_FEATURES = ɵCOPILOTKIT_FEATURES;
|
|
9180
10876
|
exports.ɵInterruptState = ɵInterruptState;
|
|
9181
10877
|
exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;
|