@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.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Throttler } from "@tanstack/pacer";
2
2
  import { AGUIConnectNotImplementedError, AbstractAgent, CompatibilityBoundary, EventType, HttpAgent, buildResumeArray, isInterruptExpired, randomUUID, runHttpRequest, structuredClone_, transformChunks, transformHttpEventStream } from "@ag-ui/client";
3
- import { RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, logger, parseInspectorMetadataV1, partialJSONParse, phoenixExponentialBackoff, randomUUID as randomUUID$1, resolveDebugConfig, schemaToJsonSchema, stripIntelligenceRoutingFields } from "@copilotkit/shared";
3
+ import { A2UI_VERSION, GENERATIVE_UI_ROOT_ID, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, THREAD_ALREADY_RUNNING_ERROR_CODE, logger, parseInspectorMetadataV1, partialJSONParse, phoenixExponentialBackoff, randomUUID as randomUUID$1, resolveDebugConfig, schemaToJsonSchema, stripIntelligenceRoutingFields } from "@copilotkit/shared";
4
4
  import { BehaviorSubject, EMPTY, NEVER, Notification, Observable, Subject, Subscription, asapScheduler, combineLatest, concat, defer, dematerialize, firstValueFrom, from, lastValueFrom, merge, observeOn, of, switchMap, throwError } from "rxjs";
5
5
  import { catchError, concatMap, concatWith, delay, distinctUntilChanged, endWith, filter, finalize, ignoreElements, map, mergeMap, observeOn as observeOn$1, scan, share, shareReplay, startWith, switchMap as switchMap$1, take, takeUntil, tap, timeout, withLatestFrom } from "rxjs/operators";
6
6
  import { Socket } from "phoenix";
@@ -25,15 +25,6 @@ function ɵisHttpAgent(agent) {
25
25
 
26
26
  //#endregion
27
27
  //#region src/utils/connect-replay.ts
28
- const connectRunErrorPhases = /* @__PURE__ */ new WeakMap();
29
- /**
30
- * The phase in which a connection received `event`, as recorded when it
31
- * arrived. Events that did not come through a connection with replay
32
- * boundaries report `unknown`.
33
- */
34
- function ɵgetConnectRunErrorPhase(event) {
35
- return connectRunErrorPhases.get(event) ?? "unknown";
36
- }
37
28
  /**
38
29
  * Runs an agent's `connect()` stream through the AbstractAgent apply pipeline
39
30
  * with the `verifyEvents` step omitted.
@@ -88,7 +79,6 @@ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber,
88
79
  let result;
89
80
  const previousMessageIds = new Set(agent.messages.map((m) => m.id));
90
81
  let isReplaying = true;
91
- let reportsReplayPhase = false;
92
82
  const liveErrors = /* @__PURE__ */ new WeakSet();
93
83
  const subscribers = [
94
84
  {
@@ -136,19 +126,15 @@ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber,
136
126
  };
137
127
  const lifecycle = {
138
128
  onReplayStarted: () => {
139
- reportsReplayPhase = true;
140
129
  isReplaying = true;
141
130
  agent.isRunning = true;
142
131
  },
143
132
  onReplayFinished: () => {
144
- reportsReplayPhase = true;
145
133
  isReplaying = false;
146
134
  }
147
135
  };
148
136
  const source$ = defer(() => new CompatibilityBoundary().run(input, { run: () => connect ? connect(input, lifecycle) : self.connect(input) })).pipe(tap((event) => {
149
- if (event.type !== EventType.RUN_ERROR) return;
150
- if (!isReplaying) liveErrors.add(event);
151
- if (reportsReplayPhase) connectRunErrorPhases.set(event, isReplaying ? "replay" : "live");
137
+ if (!isReplaying && event.type === EventType.RUN_ERROR) liveErrors.add(event);
152
138
  }), transformChunks(self.debugLogger), takeUntil(activeRunDetach$));
153
139
  const applied$ = self.apply(input, source$, subscribers);
154
140
  await lastValueFrom(self.processApplyEvents(input, applied$, subscribers).pipe(catchError((error) => {
@@ -315,20 +301,6 @@ var AgentThreadLockedError = class extends Error {
315
301
  }
316
302
  };
317
303
  /**
318
- * The gateway could not replay a live run's events, so the client cannot
319
- * verify the run it is following. The run itself may still be going on the
320
- * server; reconnecting to the thread shows its real state.
321
- */
322
- var IntelligenceReplayFailedError = class extends Error {
323
- code = "INTELLIGENCE_REPLAY_FAILED";
324
- constructor(threadId, runId) {
325
- super("The run's events could not be replayed. Reconnect to the thread to check the run's status.");
326
- this.threadId = threadId;
327
- this.runId = runId;
328
- this.name = "IntelligenceReplayFailedError";
329
- }
330
- };
331
- /**
332
304
  * Type guard for {@link RunCompletionAware}. Returns true when `agent` exposes
333
305
  * an `activeRunCompletionPromise` property, so callers can await an in-flight
334
306
  * run without an `as unknown as` cast. Returns false for agents that don't
@@ -654,7 +626,6 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
654
626
  };
655
627
  const replayFailed$ = channel$.pipe(switchMap$1(({ channel }) => this.observeChannelEvent$(channel, REPLAY_FAILED_EVENT)), tap(() => {
656
628
  controlCursor.replayFailed = true;
657
- if (options.streamMode === "run") throw new IntelligenceReplayFailedError(credentials.threadId, credentials.runId);
658
629
  }));
659
630
  const replayComplete$ = this.observeControlEvent$(input.threadId, channel$, REPLAY_COMPLETE_EVENT, controlCursor).pipe(tap(() => {
660
631
  replayFinished = true;
@@ -883,6 +854,7 @@ function ɵrepairToolCallPairs(kept, full) {
883
854
  }
884
855
  const repaired = [];
885
856
  const emitted = /* @__PURE__ */ new Set();
857
+ const expandedMessages = /* @__PURE__ */ new Set();
886
858
  const emit = (message) => {
887
859
  if (emitted.has(message.id)) return;
888
860
  emitted.add(message.id);
@@ -891,6 +863,8 @@ function ɵrepairToolCallPairs(kept, full) {
891
863
  /** Emit an assistant turn together with every result it is owed. */
892
864
  const emitWithResults = (message) => {
893
865
  emit(message);
866
+ if (expandedMessages.has(message)) return;
867
+ expandedMessages.add(message);
894
868
  for (const callId of toolCallIdsOf(message)) {
895
869
  const result = callIdToResult.get(callId);
896
870
  if (result) emit(result);
@@ -911,6 +885,198 @@ function ɵrepairToolCallPairs(kept, full) {
911
885
  }
912
886
  return repaired;
913
887
  }
888
+ /**
889
+ * Move each detached tool result to sit behind the assistant call that issued
890
+ * it — usually back to an earlier call, and forward only when no earlier call
891
+ * has its id and exactly one call in the list does — and change nothing else.
892
+ * Used for unfiltered sends, and on a configured filter's output only when
893
+ * {@link ɵrepairToolCallPairs}, which filtered sends go through otherwise,
894
+ * throws.
895
+ *
896
+ * The client store can detach a tool result from its call on its own: when a
897
+ * backend's `MESSAGES_SNAPSHOT` carries a tool message under a different id
898
+ * than the streamed `TOOL_CALL_RESULT`, the `@ag-ui/client` merge drops the
899
+ * copy placed after its call and appends the snapshot's copy at the end,
900
+ * leaving `assistant(tool_call), assistant(text), tool(result)`. A backend that
901
+ * rebuilds its state from that payload discards every result it cannot pair.
902
+ *
903
+ * The pairing rule mirrors the `@ag-ui/client` snapshot pass
904
+ * (ag-ui-protocol/ag-ui#3114):
905
+ *
906
+ * - Everything is by list position. The same object or id appearing twice is
907
+ * two independent slots, including an assistant call the merge duplicated,
908
+ * so a duplicated call can be left unanswered. Nothing is dropped,
909
+ * deduplicated, or added, and only tool-role messages ever change position.
910
+ * - Transparent entries are `activity` and `reasoning` messages and anything
911
+ * that is not a plain object (`null`, arrays, primitives). They are never
912
+ * the anchor, never separate a call from its result, and stay in place.
913
+ * Reasoning stored between a call and its result is the next step's: in a
914
+ * multi-step turn whose calls share one assistant message, Mastra leaves
915
+ * `assistant(c1, c2), tool(c1), reasoning, tool(c2)`. Moving the result in
916
+ * front of it leaves the reasoning trailing, and Mastra drops it.
917
+ * - The anchor is the last non-transparent message so far that is not `tool`.
918
+ * Each tool call an assistant issues opens a slot for its call id, and a
919
+ * result pairs with slots for its `toolCallId` alone. `subagentRunId` is
920
+ * ignored: results CopilotKit creates itself (frontend tool results,
921
+ * interrupt responses) do not carry one, and on a result it names the run
922
+ * that executed the tool, which may differ from the run that issued the
923
+ * call. Known limitation: a parent call and a subagent call that reuse one
924
+ * id are indistinguishable, so their drifted results can be swapped.
925
+ * - Pass 1, left to right: a result with an open slot issued at the anchor is
926
+ * in place; it takes that slot and stays put. A result with an open slot
927
+ * issued earlier is detached. A result with no slot for its id issued
928
+ * earlier at all is early. Any other result — every earlier slot for its id
929
+ * already answered — stays put. Detached results take no slot in this
930
+ * pass: they could only ever take a slot issued before the current anchor,
931
+ * which no later in-place result can want.
932
+ * - Pass 2, backward, per id: the detached results, from the newest back,
933
+ * each take the newest still-open slot issued before them; one that finds
934
+ * none stays put. So when several results for a reused id (providers reuse
935
+ * `call_0` every turn) are all detached, they keep their stored order
936
+ * across the calls, and a later turn's lone result goes to the later call
937
+ * rather than to an earlier one that was abandoned.
938
+ * - Pass 3, forward, per id: an early result moves forward only when its id
939
+ * is unambiguous — exactly one call slot in the whole list has it, that
940
+ * slot is issued after the result, and it is still open after passes 1-2.
941
+ * The first early result for the id, left to right, takes it; any other
942
+ * early result for that id stays put. This repairs a result whose call
943
+ * was re-issued after it (a snapshot that re-ids the assistant message but
944
+ * keeps the result's id). With a reused id (providers reuse `call_0` every
945
+ * turn) nothing moves forward: in `[t0, t1, a1(c), user, a2(c)]` nothing
946
+ * says t1 answers a2, and a2 may be a pending call (a frontend tool, an
947
+ * interrupt, a human-in-the-loop call waiting on the user). Only early
948
+ * results move forward: an extra result for a call that is already
949
+ * answered never does.
950
+ * - A moved result goes behind its issuer, after the tool and transparent
951
+ * entries already following it, but in front of any reasoning among those
952
+ * transparent entries: reasoning belongs to the message after it, so a
953
+ * moved result never lands between a reasoning message and its owner.
954
+ * Results moved behind one issuer keep their stored order. Any other
955
+ * message between a call and its result separates them, so a
956
+ * backward-moved result moves before it and a forward-moved result moves
957
+ * past it.
958
+ * - The rule cannot tell a duplicate result from a detached one. A second
959
+ * result for an already-answered call moves back to an older still-open
960
+ * slot for its id if there is one, even across user turns; it never moves
961
+ * forward.
962
+ * - Malformed entries are ignored rather than thrown on. Non-array
963
+ * `toolCalls`, call entries without a string `id`, and results without a
964
+ * string `toolCallId` open or take no slot.
965
+ *
966
+ * Returns `messages` itself when nothing moved.
967
+ */
968
+ function ɵkeepToolResultsWithCalls(messages) {
969
+ const slots = /* @__PURE__ */ new Map();
970
+ const openCount = /* @__PURE__ */ new Map();
971
+ const close = (callId, slot) => {
972
+ slot.open = false;
973
+ openCount.set(callId, openCount.get(callId) - 1);
974
+ };
975
+ const detached = /* @__PURE__ */ new Map();
976
+ const early = /* @__PURE__ */ new Map();
977
+ let anchor = -1;
978
+ for (let index = 0; index < messages.length; index++) {
979
+ const message = messages[index];
980
+ if (isTransparent(message)) continue;
981
+ const role = roleOf(message);
982
+ if (role !== "tool") {
983
+ anchor = index;
984
+ const calls = role === "assistant" ? message.toolCalls : void 0;
985
+ if (!Array.isArray(calls)) continue;
986
+ for (const call of calls) {
987
+ if (typeof call !== "object" || call === null) continue;
988
+ const callId = call.id;
989
+ if (typeof callId !== "string") continue;
990
+ push(slots, callId, {
991
+ issuer: index,
992
+ open: true
993
+ });
994
+ openCount.set(callId, (openCount.get(callId) ?? 0) + 1);
995
+ }
996
+ continue;
997
+ }
998
+ const callId = message.toolCallId;
999
+ if (typeof callId !== "string") continue;
1000
+ const forId = slots.get(callId);
1001
+ if (!forId) {
1002
+ push(early, callId, index);
1003
+ continue;
1004
+ }
1005
+ let atAnchor;
1006
+ for (let s = forId.length - 1; s >= 0; s--) {
1007
+ const slot = forId[s];
1008
+ if (slot.issuer !== anchor) break;
1009
+ if (slot.open) atAnchor = slot;
1010
+ }
1011
+ if (atAnchor) {
1012
+ close(callId, atAnchor);
1013
+ continue;
1014
+ }
1015
+ if (openCount.get(callId) > 0) push(detached, callId, index);
1016
+ }
1017
+ const movedBehind = /* @__PURE__ */ new Map();
1018
+ const moved = /* @__PURE__ */ new Set();
1019
+ const take = (callId, slot, index) => {
1020
+ close(callId, slot);
1021
+ moved.add(index);
1022
+ push(movedBehind, slot.issuer, index);
1023
+ };
1024
+ for (const [callId, results] of detached) {
1025
+ const forId = slots.get(callId);
1026
+ let s = forId.length - 1;
1027
+ for (let r = results.length - 1; r >= 0; r--) {
1028
+ const index = results[r];
1029
+ while (s >= 0 && (!forId[s].open || forId[s].issuer >= index)) s--;
1030
+ if (s < 0) break;
1031
+ take(callId, forId[s], index);
1032
+ }
1033
+ }
1034
+ for (const [callId, results] of early) {
1035
+ const forId = slots.get(callId);
1036
+ if (forId?.length !== 1 || !forId[0].open) continue;
1037
+ take(callId, forId[0], results[0]);
1038
+ }
1039
+ if (moved.size === 0) return messages;
1040
+ const result = [];
1041
+ let openIssuer = -1;
1042
+ const flush = () => {
1043
+ const behind = movedBehind.get(openIssuer);
1044
+ if (!behind) return;
1045
+ let at = result.length;
1046
+ for (let tail = result.length - 1; tail >= 0; tail--) {
1047
+ if (!isTransparent(result[tail])) break;
1048
+ if (roleOf(result[tail]) === "reasoning") at = tail;
1049
+ }
1050
+ result.splice(at, 0, ...[...behind].sort((a, b) => a - b).map((index) => messages[index]));
1051
+ };
1052
+ for (let index = 0; index < messages.length; index++) {
1053
+ if (moved.has(index)) continue;
1054
+ const message = messages[index];
1055
+ if (!isTransparent(message) && roleOf(message) !== "tool") {
1056
+ flush();
1057
+ openIssuer = index;
1058
+ }
1059
+ result.push(message);
1060
+ }
1061
+ flush();
1062
+ return result;
1063
+ }
1064
+ function push(map, key, value) {
1065
+ const list = map.get(key);
1066
+ if (list) list.push(value);
1067
+ else map.set(key, [value]);
1068
+ }
1069
+ /**
1070
+ * Activity and reasoning messages and anything that is not a plain object
1071
+ * (`null`, arrays, primitives) never anchor or separate.
1072
+ */
1073
+ function isTransparent(message) {
1074
+ return typeof message !== "object" || message === null || Array.isArray(message) || message.role === "activity" || message.role === "reasoning";
1075
+ }
1076
+ function roleOf(message) {
1077
+ if (typeof message !== "object" || message === null) return void 0;
1078
+ return message.role;
1079
+ }
914
1080
 
915
1081
  //#endregion
916
1082
  //#region src/agent.ts
@@ -1053,7 +1219,21 @@ var ProxiedCopilotRuntimeAgent = class ProxiedCopilotRuntimeAgent extends HttpAg
1053
1219
  this._messageFilter = filter;
1054
1220
  }
1055
1221
  /**
1056
- * Narrow the outbound payload with the configured message filter.
1222
+ * Build the outbound payload, keeping every tool result with the call that
1223
+ * issued it.
1224
+ *
1225
+ * - **No filter** (or a filter whose output is unusable, which falls back to
1226
+ * the full thread): `ɵkeepToolResultsWithCalls` re-places tool results
1227
+ * that drifted from their call and changes nothing else. The client store
1228
+ * can detach them on its own when a `MESSAGES_SNAPSHOT` re-ids a tool
1229
+ * message, and a backend that rebuilds state from such a payload drops
1230
+ * every result it cannot pair.
1231
+ * - **Filter**: `ɵrepairToolCallPairs(kept, full)` restores the call or the
1232
+ * results a filter trimmed. Its known limitations are tracked in
1233
+ * https://github.com/CopilotKit/CopilotKit/issues/7891.
1234
+ * - **Filter repair throws**: the filter's output goes through
1235
+ * `ɵkeepToolResultsWithCalls` instead, keeping its trimming and
1236
+ * redaction; if that throws too, the output is sent as is.
1057
1237
  *
1058
1238
  * **Called from the HTTP paths only, and that placement is the Intelligence
1059
1239
  * exemption.** An earlier revision applied the filter in
@@ -1076,28 +1256,83 @@ var ProxiedCopilotRuntimeAgent = class ProxiedCopilotRuntimeAgent extends HttpAg
1076
1256
  * cannot reach the messages the UI renders no matter what it does with the
1077
1257
  * array it is handed. The filter gets a *second* deep clone on top of that,
1078
1258
  * because `input.messages` is also the repair baseline and the untrimmed
1079
- * fallback: sharing the message objects let a filter that mutates a kept
1080
- * message's `toolCallId` corrupt the baseline, and an orphaned tool result
1081
- * then went out on the wire — a payload the provider rejects, which is
1082
- * exactly the failure this whole mechanism exists to prevent.
1083
- */
1084
- #applyMessageFilter(input) {
1085
- const filter = this._messageFilter;
1086
- if (!filter) return input;
1259
+ * fallback: sharing the message objects let a filter that rewrote the tool
1260
+ * call id of an assistant message it dropped hide that issuer from the
1261
+ * repair, and the kept tool result then went out orphaned — a payload the
1262
+ * provider rejects, which is exactly the failure this whole mechanism
1263
+ * exists to prevent.
1264
+ */
1265
+ #prepareOutboundMessages(input) {
1266
+ const full = input.messages;
1267
+ const kept = this.#applyMessageFilter(full);
1268
+ const agentId = this.agentId ?? "";
1087
1269
  try {
1088
- const kept = filter(structuredClone_(input.messages), { agentId: this.agentId ?? "" });
1089
- if (!Array.isArray(kept)) {
1090
- console.warn("ProxiedCopilotRuntimeAgent: messageFilter returned a non-array value; sending the full message history instead.");
1091
- return input;
1092
- }
1270
+ const messages = kept === void 0 ? ɵkeepToolResultsWithCalls(full) : ɵrepairToolCallPairs(kept, full);
1093
1271
  return {
1094
1272
  ...input,
1095
- messages: ɵrepairToolCallPairs(kept, input.messages)
1273
+ messages
1096
1274
  };
1275
+ } catch (error) {
1276
+ if (kept === void 0) {
1277
+ console.warn(`ProxiedCopilotRuntimeAgent: tool-call repair failed for agent "${agentId}"; sending the message history unrepaired instead.`, error);
1278
+ return input;
1279
+ }
1280
+ try {
1281
+ const messages = ɵkeepToolResultsWithCalls(kept);
1282
+ console.warn(`ProxiedCopilotRuntimeAgent: tool-call repair failed for agent "${agentId}"; sending the filtered message history with only drifted tool results moved instead.`, error);
1283
+ return {
1284
+ ...input,
1285
+ messages
1286
+ };
1287
+ } catch (moveError) {
1288
+ console.warn(`ProxiedCopilotRuntimeAgent: tool-call repair failed for agent "${agentId}"; sending the filtered message history unrepaired instead.`, error, moveError);
1289
+ return {
1290
+ ...input,
1291
+ messages: kept
1292
+ };
1293
+ }
1294
+ }
1295
+ }
1296
+ /**
1297
+ * Run the configured filter. Returns `undefined` when there is no filter,
1298
+ * copying the thread for it fails, or the filter's output cannot be used,
1299
+ * meaning "send the full thread".
1300
+ *
1301
+ * A filter that throws, returns a non-array, or returns an array with an
1302
+ * entry that is not a message object (a hole or a nested array included)
1303
+ * falls back to the untrimmed thread rather than failing the run. Trimming
1304
+ * is an optimization, and taking the user's message down with it would be
1305
+ * the worse outcome; the warning is what surfaces the bug.
1306
+ */
1307
+ #applyMessageFilter(full) {
1308
+ const filter = this._messageFilter;
1309
+ if (!filter) return void 0;
1310
+ let copy;
1311
+ try {
1312
+ copy = structuredClone_(full);
1313
+ } catch (error) {
1314
+ console.warn("ProxiedCopilotRuntimeAgent: could not copy the message history for messageFilter; sending the full message history instead.", error);
1315
+ return;
1316
+ }
1317
+ let kept;
1318
+ try {
1319
+ kept = filter(copy, { agentId: this.agentId ?? "" });
1097
1320
  } catch (error) {
1098
1321
  console.warn("ProxiedCopilotRuntimeAgent: messageFilter failed; sending the full message history instead.", error);
1099
- return input;
1322
+ return;
1100
1323
  }
1324
+ if (!Array.isArray(kept)) {
1325
+ console.warn("ProxiedCopilotRuntimeAgent: messageFilter returned a non-array value; sending the full message history instead.");
1326
+ return;
1327
+ }
1328
+ for (let index = 0; index < kept.length; index++) {
1329
+ const entry = kept[index];
1330
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
1331
+ console.warn("ProxiedCopilotRuntimeAgent: messageFilter returned an entry that is not a message; sending the full message history instead.");
1332
+ return;
1333
+ }
1334
+ }
1335
+ return kept;
1101
1336
  }
1102
1337
  requestInit(input) {
1103
1338
  return {
@@ -1255,7 +1490,7 @@ var ProxiedCopilotRuntimeAgent = class ProxiedCopilotRuntimeAgent extends HttpAg
1255
1490
  return defer(() => from(this.resolveDelegate())).pipe(switchMap$1((delegate) => withAbortErrorHandling(delegate.connect(input, lifecycle))));
1256
1491
  }
1257
1492
  #connectViaHttp(unfiltered) {
1258
- const input = this.#applyMessageFilter(unfiltered);
1493
+ const input = this.#prepareOutboundMessages(unfiltered);
1259
1494
  this.activeRun = void 0;
1260
1495
  const routedId = this.routedAgentId();
1261
1496
  let httpEvents;
@@ -1288,7 +1523,7 @@ var ProxiedCopilotRuntimeAgent = class ProxiedCopilotRuntimeAgent extends HttpAg
1288
1523
  return defer(() => from(this.resolveDelegate())).pipe(switchMap$1((delegate) => withAbortErrorHandling(delegate.run(input))));
1289
1524
  }
1290
1525
  #runViaHttp(unfiltered) {
1291
- const input = this.#applyMessageFilter(unfiltered);
1526
+ const input = this.#prepareOutboundMessages(unfiltered);
1292
1527
  const activeRun = {
1293
1528
  threadId: input.threadId,
1294
1529
  runId: input.runId
@@ -2840,6 +3075,17 @@ var AgentRegistry = class {
2840
3075
  }
2841
3076
  };
2842
3077
 
3078
+ //#endregion
3079
+ //#region src/core/agent-scope.ts
3080
+ /**
3081
+ * True when an entry scoped to `agentIds` goes to a run of `agentId`. An
3082
+ * entry without `agentIds` goes to every agent; an entry with them does not
3083
+ * go to a run without an agent id. Internal, not exported.
3084
+ */
3085
+ function isForAgent(agentIds, agentId) {
3086
+ return agentIds === void 0 || agentId !== void 0 && agentIds.includes(agentId);
3087
+ }
3088
+
2843
3089
  //#endregion
2844
3090
  //#region src/core/context-store.ts
2845
3091
  /**
@@ -2878,7 +3124,7 @@ var ContextStore = class {
2878
3124
  * protocol-shaped `{ description, value }` entries go over the wire.
2879
3125
  */
2880
3126
  getContextForAgent(agentId) {
2881
- return Object.values(this._context).filter((entry) => !entry.agentIds || agentId !== void 0 && entry.agentIds.includes(agentId)).map(({ description, value }) => ({
3127
+ return Object.values(this._context).filter((entry) => isForAgent(entry.agentIds, agentId)).map(({ description, value }) => ({
2882
3128
  description,
2883
3129
  value
2884
3130
  }));
@@ -3063,7 +3309,7 @@ var SuggestionEngine = class {
3063
3309
  await suggestionAgent.runAgent({
3064
3310
  context: friends.getContextForAgent(consumerAgentId),
3065
3311
  forwardedProps: {
3066
- ...friends.properties,
3312
+ ...friends.getPropertiesForAgent(consumerAgentId),
3067
3313
  toolChoice: {
3068
3314
  type: "function",
3069
3315
  function: { name: "copilotkitSuggest" }
@@ -3480,15 +3726,12 @@ var WebMCPRegistry = class {
3480
3726
  */
3481
3727
  const liveHITLStops = /* @__PURE__ */ new WeakMap();
3482
3728
  /**
3483
- * Edits `agent.messages` by replacing the array instead of changing it in
3484
- * place. The current array may be the one the agent emitted with its last
3485
- * update, which subscribers and stored snapshots still hold. Like the in-place
3486
- * edit it replaces, this notifies no subscriber.
3729
+ * The message a failed tool call reports. An error thrown with an empty
3730
+ * message still means the call failed, so it gets a fallback rather than an
3731
+ * empty string, which everything downstream reads as success.
3487
3732
  */
3488
- function editAgentMessages(agent, edit) {
3489
- const messages = [...agent.messages];
3490
- edit(messages);
3491
- agent.messages = messages;
3733
+ function toolFailureMessage(error) {
3734
+ return error.message || "Tool call failed";
3492
3735
  }
3493
3736
  function discardAbortedResult(signal, discardOnAbort, errorMessage) {
3494
3737
  return !!(discardOnAbort && signal?.aborted && !(liveHITLStops.get(signal)?.() && errorMessage));
@@ -3569,18 +3812,28 @@ var RunHandler = class {
3569
3812
  */
3570
3813
  _warnedMissingToolParameters = /* @__PURE__ */ new Set();
3571
3814
  /**
3572
- * Tracks whether the current run (including in-flight tool execution)
3573
- * has been aborted via `stopAgent()` or `agent.abortRun()`. Created
3574
- * fresh in `runAgent()`, aborted by `abortCurrentRun()`.
3815
+ * Abort controllers of each agent's in-flight run chains (a run plus its
3816
+ * recursive follow-ups), recording whether a chain, including its tool
3817
+ * execution, was aborted via `stopAgent()` or `agent.abortRun()`. Every run
3818
+ * that is not a follow-up gets a fresh controller, so a run started after
3819
+ * Stop is not born aborted while the stopped chain is still settling. Keyed
3820
+ * by agent so that stopping one agent never cancels another agent's run on
3821
+ * the same core.
3822
+ */
3823
+ _runAbortControllers = /* @__PURE__ */ new WeakMap();
3824
+ /**
3825
+ * Per-agent `runAgent` depth (in-flight runs plus their recursive
3826
+ * follow-ups), so that the `agent.abortRun()` intercept is installed while
3827
+ * any of the agent's runs is in flight and removed once none is, and so
3828
+ * that runaway follow-up chains trip `MAX_FOLLOW_UP_DEPTH`.
3575
3829
  */
3576
- _runAbortController = null;
3830
+ _runDepths = /* @__PURE__ */ new WeakMap();
3577
3831
  /**
3578
- * Tracks recursive `runAgent` depth so that the abort controller and
3579
- * `agent.abortRun()` intercept are only set up / torn down at the
3580
- * top-level call, not on follow-up recursive calls from
3581
- * `processAgentResult`.
3832
+ * Each agent's own `abortRun`, saved while RunHandler's intercept is
3833
+ * installed. Restored only once none of the agent's runs is in flight, so an
3834
+ * overlapping run keeps the intercept after an earlier run finishes.
3582
3835
  */
3583
- _runDepth = 0;
3836
+ _originalAbortRuns = /* @__PURE__ */ new WeakMap();
3584
3837
  /**
3585
3838
  * Keeps tools that opt in via `webmcp` registered on the page's WebMCP model
3586
3839
  * context (`document.modelContext`), in addition to the normal agent
@@ -3620,7 +3873,7 @@ var RunHandler = class {
3620
3873
  * not start a follow-up run.
3621
3874
  */
3622
3875
  abortCurrentRun(agent) {
3623
- this._runAbortController?.abort();
3876
+ this.abortAgentRuns(agent);
3624
3877
  const replay = this._interactionAbortControllers.get(agent);
3625
3878
  if (replay) {
3626
3879
  for (const controller of replay.controllers) controller.abort();
@@ -3628,6 +3881,15 @@ var RunHandler = class {
3628
3881
  this._executingToolCalls.delete(agent);
3629
3882
  }
3630
3883
  }
3884
+ abortAgentRuns(agent) {
3885
+ for (const controller of this._runAbortControllers.get(agent) ?? []) controller.abort();
3886
+ }
3887
+ /** Signal of the agent's most recently started in-flight run, if any. */
3888
+ latestRunSignal(agent) {
3889
+ let latest;
3890
+ for (const controller of this._runAbortControllers.get(agent) ?? []) latest = controller;
3891
+ return latest?.signal;
3892
+ }
3631
3893
  /**
3632
3894
  * Typed access to CopilotKitCore's internal ("friend") methods.
3633
3895
  * Centralises the single unavoidable cast so call-sites stay clean.
@@ -3823,10 +4085,10 @@ var RunHandler = class {
3823
4085
  newMessages: []
3824
4086
  };
3825
4087
  const runAgentResult = await agent.connectAgent({
3826
- forwardedProps: this._internal.properties,
4088
+ forwardedProps: this._internal.getPropertiesForAgent(agent.agentId),
3827
4089
  tools: this.buildFrontendTools(agent.agentId),
3828
4090
  context: this._internal.getContextForAgent(agent.agentId)
3829
- }, this.createAgentErrorSubscriber(agent, "connect"));
4091
+ }, this.createAgentErrorSubscriber(agent));
3830
4092
  if (this._connectionGenerations.get(agent) !== connection || (agent.threadId ?? null) !== incomingThreadId) return runAgentResult;
3831
4093
  const controller = new AbortController();
3832
4094
  const replay = this._interactionAbortControllers.get(agent) ?? {
@@ -3875,7 +4137,7 @@ var RunHandler = class {
3875
4137
  /**
3876
4138
  * Run an agent
3877
4139
  */
3878
- async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff) {
4140
+ async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff, followUpOf) {
3879
4141
  if (agent.agentId) this._internal.suggestionEngine.clearSuggestions(agent.agentId);
3880
4142
  try {
3881
4143
  const headersApplied = this._internal.prepareAgentHeadersForRun(agent);
@@ -3899,25 +4161,30 @@ var RunHandler = class {
3899
4161
  forwardedProps
3900
4162
  });
3901
4163
  const logicalHandoff = continuationHandoff ?? (resumedRunId ? this._internal.stateManager.markNextRunAsContinuation(agent, resumedRunId) : void 0);
3902
- const isTopLevel = this._runDepth === 0;
3903
- let originalAbortRun;
3904
- if (isTopLevel) {
3905
- this._runAbortController = new AbortController();
3906
- const controller = this._runAbortController;
3907
- originalAbortRun = agent.abortRun.bind(agent);
4164
+ const isFollowUp = followUpOf !== void 0;
4165
+ const controller = followUpOf ?? new AbortController();
4166
+ const depth = this._runDepths.get(agent) ?? 0;
4167
+ this._runDepths.set(agent, depth + 1);
4168
+ if (!isFollowUp) {
4169
+ const controllers = this._runAbortControllers.get(agent) ?? /* @__PURE__ */ new Set();
4170
+ controllers.add(controller);
4171
+ this._runAbortControllers.set(agent, controllers);
4172
+ }
4173
+ if (depth === 0) {
4174
+ const originalAbortRun = agent.abortRun;
4175
+ this._originalAbortRuns.set(agent, originalAbortRun);
3908
4176
  agent.abortRun = () => {
3909
- controller.abort();
3910
- originalAbortRun();
4177
+ this.abortAgentRuns(agent);
4178
+ originalAbortRun.call(agent);
3911
4179
  };
3912
- await this._internal.notifySubscribers((subscriber) => subscriber.onAgentRunStarted?.({
4180
+ }
4181
+ try {
4182
+ if (depth === 0) await this._internal.notifySubscribers((subscriber) => subscriber.onAgentRunStarted?.({
3913
4183
  copilotkit: this.core,
3914
4184
  agent
3915
4185
  }), "Subscriber onAgentRunStarted error:");
3916
- }
3917
- this._runDepth++;
3918
- try {
3919
4186
  let logicalRunId = resumedRunId ?? runId;
3920
- const agentSubscriber = this.createAgentErrorSubscriber(agent, "run");
4187
+ const agentSubscriber = this.createAgentErrorSubscriber(agent, controller.signal);
3921
4188
  let started = false;
3922
4189
  const onRunStartedEvent = agentSubscriber.onRunStartedEvent;
3923
4190
  const onRunInitialized = agentSubscriber.onRunInitialized;
@@ -3934,7 +4201,7 @@ var RunHandler = class {
3934
4201
  const pinRunIdOnWire = runId !== void 0 && !continuationHandoff;
3935
4202
  const agentRunInput = {
3936
4203
  forwardedProps: {
3937
- ...this._internal.properties,
4204
+ ...this._internal.getPropertiesForAgent(agent.agentId),
3938
4205
  ...forwardedProps
3939
4206
  },
3940
4207
  ...resume !== void 0 ? { resume } : {},
@@ -3947,7 +4214,8 @@ var RunHandler = class {
3947
4214
  return await this.processAgentResult({
3948
4215
  runAgentResult,
3949
4216
  agent,
3950
- runId: logicalRunId
4217
+ runId: logicalRunId,
4218
+ runController: controller
3951
4219
  });
3952
4220
  } catch (error) {
3953
4221
  logicalHandoff?.cancel();
@@ -3964,22 +4232,34 @@ var RunHandler = class {
3964
4232
  newMessages: []
3965
4233
  };
3966
4234
  } finally {
3967
- this._runDepth--;
3968
- if (isTopLevel && originalAbortRun) agent.abortRun = originalAbortRun;
4235
+ const remainingDepth = (this._runDepths.get(agent) ?? 1) - 1;
4236
+ this._runDepths.set(agent, remainingDepth);
4237
+ if (!isFollowUp) {
4238
+ const controllers = this._runAbortControllers.get(agent);
4239
+ controllers?.delete(controller);
4240
+ if (controllers?.size === 0) this._runAbortControllers.delete(agent);
4241
+ }
4242
+ if (remainingDepth === 0) {
4243
+ const originalAbortRun = this._originalAbortRuns.get(agent);
4244
+ if (originalAbortRun) {
4245
+ agent.abortRun = originalAbortRun;
4246
+ this._originalAbortRuns.delete(agent);
4247
+ }
4248
+ }
3969
4249
  }
3970
4250
  }
3971
4251
  /**
3972
4252
  * Process agent result and execute tools
3973
4253
  */
3974
- async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", signal = this._runAbortController?.signal }) {
4254
+ async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", runController, signal = runController?.signal }) {
3975
4255
  const { newMessages } = runAgentResult;
3976
4256
  const agentId = agent.agentId;
3977
4257
  let needsFollowUp = false;
3978
4258
  const threadId = agent.threadId;
3979
4259
  const executing = this._executingToolCalls.get(agent) ?? /* @__PURE__ */ new Set();
3980
4260
  this._executingToolCalls.set(agent, executing);
3981
- if (toolExecutionMode === "restore" && agent.messages.some((message) => message.role === "assistant" && message.toolCalls?.some((call) => executing.has(JSON.stringify([threadId, call.id])) && !agent.messages.some((result) => result.role === "tool" && result.toolCallId === call.id && !this.isFrontendPlaceholderResult(result))))) return runAgentResult;
3982
- const messagesToProcess = toolExecutionMode === "restore" ? [...agent.messages] : newMessages;
4261
+ const messagesToProcess = toolExecutionMode === "restore" ? agent.messages.filter((message) => message.role === "assistant" && this.isInLatestUserTurn(agent.messages, message.id)) : newMessages;
4262
+ if (toolExecutionMode === "restore" && messagesToProcess.some((message) => message.role === "assistant" && message.toolCalls?.some((call) => executing.has(JSON.stringify([threadId, call.id])) && !agent.messages.some((result) => result.role === "tool" && result.toolCallId === call.id && !this.isFrontendPlaceholderResult(result))))) return runAgentResult;
3983
4263
  for (const message of messagesToProcess) if (message.role === "assistant") for (const toolCall of message.toolCalls || []) {
3984
4264
  const tool = this.getTool({
3985
4265
  toolName: toolCall.function.name,
@@ -3995,16 +4275,16 @@ var RunHandler = class {
3995
4275
  return wildcardTool;
3996
4276
  };
3997
4277
  const executableTool = tool ?? getWildcardTool();
3998
- if (toolExecutionMode === "restore" && (!executableTool?.handler || executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
4278
+ if (toolExecutionMode === "restore" && (!executableTool || executableTool.handler && executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
3999
4279
  const executionKey = JSON.stringify([threadId, toolCall.id]);
4000
- if (signal?.aborted || agent.threadId !== threadId || executing.has(executionKey)) continue;
4280
+ if (signal?.aborted || agent.threadId !== threadId || toolExecutionMode === "restore" && !this.isInLatestUserTurn(agent.messages, message.id) || executing.has(executionKey)) continue;
4001
4281
  const existingResultIndex = newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
4002
4282
  let existingResult = agent.messages.find((m) => m.role === "tool" && m.toolCallId === toolCall.id) ?? newMessages[existingResultIndex];
4003
- if (existingResult && executableTool?.handler && this.isFrontendPlaceholderResult(existingResult)) {
4283
+ if (existingResult && this.isFrontendPlaceholderResult(existingResult) && (toolExecutionMode === "restore" || executableTool?.handler)) {
4004
4284
  if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
4005
4285
  existingResult = void 0;
4006
4286
  const agentMsgIdx = agent.messages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
4007
- if (agentMsgIdx !== -1) editAgentMessages(agent, (messages) => messages.splice(agentMsgIdx, 1));
4287
+ if (agentMsgIdx !== -1) agent.messages.splice(agentMsgIdx, 1);
4008
4288
  }
4009
4289
  if (!existingResult) {
4010
4290
  executing.add(executionKey);
@@ -4047,18 +4327,43 @@ var RunHandler = class {
4047
4327
  if (interactionController?.signal.aborted) return runAgentResult;
4048
4328
  }
4049
4329
  }
4050
- if (needsFollowUp && agent.threadId === threadId && !signal?.aborted) if (this._runDepth >= MAX_FOLLOW_UP_DEPTH) logger.warn(`[CopilotKit] Follow-up depth limit (${MAX_FOLLOW_UP_DEPTH}) reached for agent "${agentId}". Stopping recursive follow-up runs to prevent an infinite loop. This usually indicates a tool that keeps requesting a follow-up (e.g. the LLM repeatedly calling the same tool). Consider setting "followUp: false" on the offending tool.`);
4330
+ if (needsFollowUp && agent.threadId === threadId && !signal?.aborted) if ((this._runDepths.get(agent) ?? 0) >= MAX_FOLLOW_UP_DEPTH) logger.warn(`[CopilotKit] Follow-up depth limit (${MAX_FOLLOW_UP_DEPTH}) reached for agent "${agentId}". Stopping recursive follow-up runs to prevent an infinite loop. This usually indicates a tool that keeps requesting a follow-up (e.g. the LLM repeatedly calling the same tool). Consider setting "followUp: false" on the offending tool.`);
4051
4331
  else {
4052
4332
  await this._internal.waitForPendingFrameworkUpdates();
4333
+ if (toolExecutionMode === "restore" && !messagesToProcess.some((message) => this.isInLatestUserTurn(agent.messages, message.id))) return runAgentResult;
4053
4334
  const continuationHandoff = this._internal.stateManager.markNextRunAsContinuation(agent, runId);
4054
4335
  return await this.runAgent({
4055
4336
  agent,
4056
4337
  ...runId !== void 0 ? { runId } : {}
4057
- }, continuationHandoff);
4338
+ }, continuationHandoff, runController);
4058
4339
  }
4059
4340
  this._internal.suggestionEngine.reloadSuggestions(agentId);
4060
4341
  return runAgentResult;
4061
4342
  }
4343
+ /** A later user message supersedes pending work from an older turn. */
4344
+ isInLatestUserTurn(messages, messageId) {
4345
+ for (let index = messages.length - 1; index >= 0; index--) {
4346
+ const message = messages[index];
4347
+ if (message?.role === "user") return false;
4348
+ if (message?.id === messageId) return true;
4349
+ }
4350
+ return false;
4351
+ }
4352
+ /** Locate a missing result before saved results for later calls in its batch. */
4353
+ toolResultInsertionIndex(messages, messageIndex, toolCallId) {
4354
+ const parent = messages[messageIndex];
4355
+ const calls = parent?.role === "assistant" ? parent.toolCalls ?? [] : [];
4356
+ const callIndex = calls.findIndex((call) => call.id === toolCallId);
4357
+ let insertAt = messageIndex + 1;
4358
+ while (insertAt < messages.length) {
4359
+ const result = messages[insertAt];
4360
+ if (result?.role !== "tool") break;
4361
+ if (calls.findIndex((call) => call.id === result.toolCallId) > callIndex) break;
4362
+ insertAt++;
4363
+ }
4364
+ return insertAt;
4365
+ }
4366
+ /** Identify transport placeholders that must not count as completed answers. */
4062
4367
  isFrontendPlaceholderResult(message) {
4063
4368
  return message.role === "tool" && isForwardedToClientPlaceholder(message.content);
4064
4369
  }
@@ -4067,7 +4372,7 @@ var RunHandler = class {
4067
4372
  * Handles arg parsing, subscriber notifications, handler invocation, result stringification,
4068
4373
  * and error handling.
4069
4374
  */
4070
- async executeToolHandler({ tool, toolCall, agent, agentId, handlerArgs, toolType, messageId, signal = this._runAbortController?.signal, discardOnAbort = false, isReplay = false }) {
4375
+ async executeToolHandler({ tool, toolCall, agent, agentId, handlerArgs, toolType, messageId, signal = this.latestRunSignal(agent), discardOnAbort = false, isReplay = false }) {
4071
4376
  let toolCallResult = "";
4072
4377
  let toolCallText = "";
4073
4378
  let errorMessage;
@@ -4077,7 +4382,7 @@ var RunHandler = class {
4077
4382
  parsedArgs = parseToolArguments(handlerArgs, toolCall.function.name);
4078
4383
  } catch (error) {
4079
4384
  const parseError = error instanceof Error ? error : new Error(String(error));
4080
- errorMessage = parseError.message;
4385
+ errorMessage = toolFailureMessage(parseError);
4081
4386
  isArgumentError = true;
4082
4387
  await this._internal.emitError({
4083
4388
  error: parseError,
@@ -4109,7 +4414,7 @@ var RunHandler = class {
4109
4414
  ({content: toolCallResult, text: toolCallText} = toToolResultContent(result));
4110
4415
  } catch (error) {
4111
4416
  const handlerError = error instanceof Error ? error : new Error(String(error));
4112
- errorMessage = handlerError.message;
4417
+ errorMessage = toolFailureMessage(handlerError);
4113
4418
  if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) await this._internal.emitError({
4114
4419
  error: handlerError,
4115
4420
  code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,
@@ -4165,16 +4470,16 @@ var RunHandler = class {
4165
4470
  });
4166
4471
  {
4167
4472
  const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
4168
- if (discardAbortedResult(signal, discardOnAbort, handlerResult.error) || agent.threadId !== threadId || messageIndex === -1 || agent.messages.some((m) => m.role === "tool" && m.toolCallId === toolCall.id && !this.isFrontendPlaceholderResult(m))) return false;
4169
- let insertAt = messageIndex + 1;
4170
- while (insertAt < agent.messages.length && agent.messages[insertAt]?.role === "tool") insertAt++;
4473
+ 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;
4474
+ const insertAt = this.toolResultInsertionIndex(agent.messages, messageIndex, toolCall.id);
4171
4475
  const toolMessage = {
4172
4476
  id: randomUUID$1(),
4173
4477
  role: "tool",
4174
4478
  toolCallId: toolCall.id,
4175
- content: handlerResult.content
4479
+ content: handlerResult.content,
4480
+ ...handlerResult.error ? { error: handlerResult.error } : {}
4176
4481
  };
4177
- editAgentMessages(agent, (messages) => messages.splice(insertAt, 0, toolMessage));
4482
+ agent.messages.splice(insertAt, 0, toolMessage);
4178
4483
  if (!handlerResult.error && tool?.followUp !== false) return true;
4179
4484
  }
4180
4485
  return false;
@@ -4197,7 +4502,7 @@ var RunHandler = class {
4197
4502
  parsedArgs = parseToolArguments(toolCall.function.arguments, toolCall.function.name);
4198
4503
  } catch (error) {
4199
4504
  const parseError = error instanceof Error ? error : new Error(String(error));
4200
- errorMessage = parseError.message;
4505
+ errorMessage = toolFailureMessage(parseError);
4201
4506
  await this._internal.emitError({
4202
4507
  error: parseError,
4203
4508
  code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,
@@ -4232,7 +4537,7 @@ var RunHandler = class {
4232
4537
  ({content: toolCallResult, text: toolCallText} = toToolResultContent(result));
4233
4538
  } catch (error) {
4234
4539
  const handlerError = error instanceof Error ? error : new Error(String(error));
4235
- errorMessage = handlerError.message;
4540
+ errorMessage = toolFailureMessage(handlerError);
4236
4541
  if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) await this._internal.emitError({
4237
4542
  error: handlerError,
4238
4543
  code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,
@@ -4258,16 +4563,16 @@ var RunHandler = class {
4258
4563
  }
4259
4564
  {
4260
4565
  const messageIndex = agent.messages.findIndex((m) => m.id === message.id);
4261
- if (discardAbortedResult(signal, discardOnAbort, errorMessage) || agent.threadId !== threadId || messageIndex === -1 || agent.messages.some((m) => m.role === "tool" && m.toolCallId === toolCall.id && !this.isFrontendPlaceholderResult(m))) return false;
4262
- let insertAt = messageIndex + 1;
4263
- while (insertAt < agent.messages.length && agent.messages[insertAt]?.role === "tool") insertAt++;
4566
+ 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;
4567
+ const insertAt = this.toolResultInsertionIndex(agent.messages, messageIndex, toolCall.id);
4264
4568
  const toolMessage = {
4265
4569
  id: randomUUID$1(),
4266
4570
  role: "tool",
4267
4571
  toolCallId: toolCall.id,
4268
- content: toolCallResult
4572
+ content: toolCallResult,
4573
+ ...errorMessage ? { error: errorMessage } : {}
4269
4574
  };
4270
- editAgentMessages(agent, (messages) => messages.splice(insertAt, 0, toolMessage));
4575
+ agent.messages.splice(insertAt, 0, toolMessage);
4271
4576
  if (!errorMessage && wildcardTool?.followUp !== false) return true;
4272
4577
  }
4273
4578
  return false;
@@ -4321,7 +4626,7 @@ var RunHandler = class {
4321
4626
  content: "",
4322
4627
  toolCalls: [assistantToolCall]
4323
4628
  };
4324
- editAgentMessages(agent, (messages) => messages.push(assistantMessage));
4629
+ agent.messages.push(assistantMessage);
4325
4630
  let handlerResult = {
4326
4631
  content: "",
4327
4632
  result: "",
@@ -4340,11 +4645,12 @@ var RunHandler = class {
4340
4645
  id: randomUUID$1(),
4341
4646
  role: "tool",
4342
4647
  toolCallId,
4343
- content: handlerResult.content
4648
+ content: handlerResult.content,
4649
+ ...handlerResult.error ? { error: handlerResult.error } : {}
4344
4650
  };
4345
4651
  const assistantIndex = agent.messages.findIndex((m) => m.id === assistantMessage.id);
4346
- if (assistantIndex !== -1) editAgentMessages(agent, (messages) => messages.splice(assistantIndex + 1, 0, toolResultMessage));
4347
- else editAgentMessages(agent, (messages) => messages.push(toolResultMessage));
4652
+ if (assistantIndex !== -1) agent.messages.splice(assistantIndex + 1, 0, toolResultMessage);
4653
+ else agent.messages.push(toolResultMessage);
4348
4654
  if (!handlerResult.error && followUp !== false) {
4349
4655
  if (typeof followUp === "string" && followUp !== "generate") {
4350
4656
  const userMessage = {
@@ -4352,7 +4658,7 @@ var RunHandler = class {
4352
4658
  role: "user",
4353
4659
  content: followUp
4354
4660
  };
4355
- editAgentMessages(agent, (messages) => messages.push(userMessage));
4661
+ agent.messages.push(userMessage);
4356
4662
  }
4357
4663
  await this._internal.waitForPendingFrameworkUpdates();
4358
4664
  await this.runAgent({ agent });
@@ -4422,7 +4728,7 @@ var RunHandler = class {
4422
4728
  /**
4423
4729
  * Create an agent error subscriber
4424
4730
  */
4425
- createAgentErrorSubscriber(agent, stream) {
4731
+ createAgentErrorSubscriber(agent, runSignal) {
4426
4732
  const emitAgentError = async (error, code, extraContext = {}) => {
4427
4733
  const context = { ...extraContext };
4428
4734
  if (agent.agentId) context.agentId = agent.agentId;
@@ -4437,7 +4743,14 @@ var RunHandler = class {
4437
4743
  await emitAgentError(error, error instanceof AgentThreadLockedError ? CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED : CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT, { source: "onRunFailed" });
4438
4744
  },
4439
4745
  onRunErrorEvent: async ({ event }) => {
4440
- if (this._runAbortController?.signal.aborted === true || event?.code === "abort") return;
4746
+ if ((runSignal?.aborted ?? false) || event?.code === "abort") return;
4747
+ if (event?.code === THREAD_ALREADY_RUNNING_ERROR_CODE) {
4748
+ await emitAgentError(new AgentThreadLockedError(agent.threadId), CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED, {
4749
+ source: "onRunErrorEvent",
4750
+ event
4751
+ });
4752
+ return;
4753
+ }
4441
4754
  const eventError = event?.rawEvent instanceof Error ? event.rawEvent : event?.rawEvent?.error instanceof Error ? event.rawEvent.error : void 0;
4442
4755
  const errorMessage = typeof event?.rawEvent?.error === "string" ? event.rawEvent.error : event?.message ?? "Agent run error";
4443
4756
  const rawError = eventError ?? new Error(errorMessage);
@@ -4445,8 +4758,7 @@ var RunHandler = class {
4445
4758
  await emitAgentError(rawError, CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT, {
4446
4759
  source: "onRunErrorEvent",
4447
4760
  event,
4448
- runtimeErrorCode: event?.code,
4449
- phase: stream === "run" ? "live" : ɵgetConnectRunErrorPhase(event)
4761
+ runtimeErrorCode: event?.code
4450
4762
  });
4451
4763
  }
4452
4764
  };
@@ -5461,6 +5773,17 @@ var LearningBridge = class {
5461
5773
  get isConfigured() {
5462
5774
  return this.config !== void 0;
5463
5775
  }
5776
+ /**
5777
+ * Whether events may carry agent message text: not when the capture's config
5778
+ * sets `capture.agentText` to false. A running custom-sink capture keeps the
5779
+ * choice it started with; otherwise the current config decides.
5780
+ */
5781
+ get capturesAgentText() {
5782
+ const config = this.activeConfig ?? this.config;
5783
+ if (config === void 0) return false;
5784
+ const capture = config.capture;
5785
+ return !(typeof capture === "object" && capture !== null && capture.agentText === false);
5786
+ }
5464
5787
  get isLegacyCaptureActive() {
5465
5788
  return this.collector !== null && this.collector.trajectoryId !== null;
5466
5789
  }
@@ -5566,13 +5889,19 @@ var LearningBridge = class {
5566
5889
  this.toolCalls.clear();
5567
5890
  this.executingTools.clear();
5568
5891
  }
5569
- /** A developer event. Only an explicit legacy sink adds open-Thread context. */
5892
+ /**
5893
+ * A developer event. Only an explicit legacy sink adds open-Thread context;
5894
+ * an event that names its own Thread gets no ambiguity next to it.
5895
+ */
5570
5896
  emit(name, value) {
5571
5897
  this.connection.emit(name, value);
5572
- if (value !== null && typeof value === "object" && !Array.isArray(value)) this.collector?.emit(name, {
5573
- ...this.openThreadContext(),
5574
- ...value
5575
- });
5898
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
5899
+ const context = typeof value["threadId"] === "string" ? {} : this.openThreadContext();
5900
+ this.collector?.emit(name, {
5901
+ ...context,
5902
+ ...value
5903
+ });
5904
+ }
5576
5905
  }
5577
5906
  registerOpenThread(params) {
5578
5907
  const entry = { ...params };
@@ -5653,7 +5982,7 @@ var LearningBridge = class {
5653
5982
  }
5654
5983
  emitMessage(agent, message) {
5655
5984
  const content = typeof message.content === "string" ? message.content : "";
5656
- const includeText = this.activeConfig?.capture?.agentText !== false && typeof message.content === "string";
5985
+ const includeText = this.capturesAgentText && typeof message.content === "string";
5657
5986
  this.collector?.ɵemit("agent.message", {
5658
5987
  messageId: message.id,
5659
5988
  runId: this.runIdForMessage(agent, message.id),
@@ -6806,17 +7135,15 @@ const ɵselectMemoriesRealtimeStatus = selectMemoriesRealtimeStatus;
6806
7135
 
6807
7136
  //#endregion
6808
7137
  //#region src/core/core.ts
7138
+ /** True for an object literal. Arrays, `null`, and class instances are not plain objects. */
7139
+ function isPlainObject(value) {
7140
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
7141
+ }
6809
7142
  let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode) {
6810
7143
  CopilotKitCoreErrorCode["RUNTIME_INFO_FETCH_FAILED"] = "runtime_info_fetch_failed";
6811
7144
  CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
6812
7145
  CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
6813
7146
  CopilotKitCoreErrorCode["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
6814
- /**
6815
- * An agent emitted RUN_ERROR. `context.phase` (`RunErrorPhase`) is
6816
- * `"replay"` when the error belongs to stored thread history replayed on
6817
- * connect, `"live"` when the run is happening now, and `"unknown"` when the
6818
- * transport cannot tell. Show a live-failure notice only for `"live"`.
6819
- */
6820
7147
  CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
6821
7148
  CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
6822
7149
  CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
@@ -6877,6 +7204,7 @@ var CopilotKitCore = class {
6877
7204
  _credentials;
6878
7205
  _messageFilter;
6879
7206
  _properties;
7207
+ _scopedProperties = /* @__PURE__ */ new Map();
6880
7208
  _defaultThrottleMs;
6881
7209
  _debug;
6882
7210
  subscribers = /* @__PURE__ */ new Set();
@@ -6889,6 +7217,8 @@ var CopilotKitCore = class {
6889
7217
  learningBridge;
6890
7218
  notifiedTrajectoryId = null;
6891
7219
  learningConfiguredListeners = /* @__PURE__ */ new Set();
7220
+ _generativeUIDebugSource;
7221
+ generativeUIDebugListeners = /* @__PURE__ */ new Set();
6892
7222
  /**
6893
7223
  * The single core-owned memory store, created lazily on first
6894
7224
  * `getMemoryStore()` and kept user-scoped for the lifetime of the core.
@@ -7222,6 +7552,59 @@ var CopilotKitCore = class {
7222
7552
  this._messageFilter = messageFilter;
7223
7553
  this.agentRegistry.applyMessageFilterToAgents(this.agentRegistry.agents);
7224
7554
  }
7555
+ /**
7556
+ * Add run properties that go only to the runs of `agentIds`. When
7557
+ * `agentIds` is omitted, every agent gets them. They merge on top of the
7558
+ * base `properties`.
7559
+ *
7560
+ * When an entry value and the existing value under the same key are both
7561
+ * plain objects, their keys merge one level deep. So several entries can
7562
+ * add keys under one namespace (for example `copilotkit`).
7563
+ *
7564
+ * @param entry - The properties and the optional agent ids.
7565
+ * @returns The id to pass to `removeScopedProperties`.
7566
+ *
7567
+ * @example
7568
+ * const id = copilotkit.addScopedProperties({
7569
+ * properties: { copilotkit: { theme: "dark" } },
7570
+ * agentIds: ["research"],
7571
+ * });
7572
+ * copilotkit.removeScopedProperties(id);
7573
+ */
7574
+ addScopedProperties({ properties, agentIds }) {
7575
+ let id = randomUUID$1();
7576
+ for (let n = 1; this._scopedProperties.has(id); n++) id = `${id}-${n}`;
7577
+ this._scopedProperties.set(id, {
7578
+ properties,
7579
+ ...agentIds ? { agentIds } : {}
7580
+ });
7581
+ return id;
7582
+ }
7583
+ /** Remove an entry that `addScopedProperties` added. An unknown id does nothing. */
7584
+ removeScopedProperties(id) {
7585
+ this._scopedProperties.delete(id);
7586
+ }
7587
+ /**
7588
+ * Build the forwarded properties for a run of the given agent: the base
7589
+ * properties plus every scoped entry that matches the agent. An entry with
7590
+ * `agentIds` does not match when `agentId` is omitted.
7591
+ */
7592
+ getPropertiesForAgent(agentId) {
7593
+ const merged = { ...this._properties };
7594
+ const entries = this._scopedProperties.values();
7595
+ for (const entry of entries) {
7596
+ if (!isForAgent(entry.agentIds, agentId)) continue;
7597
+ const properties = Object.entries(entry.properties);
7598
+ for (const [key, value] of properties) {
7599
+ const base = merged[key];
7600
+ merged[key] = isPlainObject(base) && isPlainObject(value) ? {
7601
+ ...base,
7602
+ ...value
7603
+ } : value;
7604
+ }
7605
+ }
7606
+ return merged;
7607
+ }
7225
7608
  setProperties(properties) {
7226
7609
  this._properties = properties;
7227
7610
  this.notifySubscribers((subscriber) => subscriber.onPropertiesChanged?.({
@@ -7285,6 +7668,15 @@ var CopilotKitCore = class {
7285
7668
  get ɵlearningConfigured() {
7286
7669
  return this.learningBridge.isConfigured;
7287
7670
  }
7671
+ /**
7672
+ * @internal Whether captured events may carry agent message text: false
7673
+ * without a `learning` config, or when a custom sink sets
7674
+ * `capture.agentText` to false. A running custom-sink capture keeps the
7675
+ * choice it started with.
7676
+ */
7677
+ get ɵlearningCapturesAgentText() {
7678
+ return this.learningBridge.capturesAgentText;
7679
+ }
7288
7680
  /** @internal Calls `listener` when {@link ɵlearningConfigured} changes. */
7289
7681
  ɵsubscribeToLearningConfigured(listener) {
7290
7682
  this.learningConfiguredListeners.add(listener);
@@ -7292,6 +7684,30 @@ var CopilotKitCore = class {
7292
7684
  this.learningConfiguredListeners.delete(listener);
7293
7685
  };
7294
7686
  }
7687
+ /**
7688
+ * @internal The generative UI of the framework package, for the inspector.
7689
+ * `undefined` when no provider has a `generativeUI` config.
7690
+ */
7691
+ get ɵgenerativeUIDebugSource() {
7692
+ return this._generativeUIDebugSource;
7693
+ }
7694
+ /** @internal Set by the framework package. `undefined` removes it. */
7695
+ ɵsetGenerativeUIDebugSource(source) {
7696
+ if (source === this._generativeUIDebugSource) return;
7697
+ this._generativeUIDebugSource = source;
7698
+ for (const listener of [...this.generativeUIDebugListeners]) try {
7699
+ listener();
7700
+ } catch (error) {
7701
+ console.error("Generative UI debug listener error:", error);
7702
+ }
7703
+ }
7704
+ /** @internal Calls `listener` when {@link ɵgenerativeUIDebugSource} is set or removed. */
7705
+ ɵsubscribeToGenerativeUIDebugSource(listener) {
7706
+ this.generativeUIDebugListeners.add(listener);
7707
+ return () => {
7708
+ this.generativeUIDebugListeners.delete(listener);
7709
+ };
7710
+ }
7295
7711
  /** The active capture's Trajectory ID, or null while capture is stopped. */
7296
7712
  get trajectoryId() {
7297
7713
  return this.learningBridge.trajectoryId;
@@ -8878,5 +9294,1274 @@ function onInspectorViewThreadResult(handler) {
8878
9294
  }
8879
9295
 
8880
9296
  //#endregion
8881
- export { AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent, IntelligenceReplayFailedError, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, WebMCPRegistry, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, props, select, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵisCopilotKitFeature, ɵisHttpAgent, isRetryableStatus as ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵthreadAdapterEvents, ɵwithHeaderDefaults };
9297
+ //#region src/a2ui-markdown/fence-parser.ts
9298
+ /** Language of a fenced code block that carries A2UI operations. */
9299
+ const A2UI_FENCE_LANGUAGE = "a2ui";
9300
+ /** Column-0 fence opener: a run of 3+ backticks or tildes, then the info string. */
9301
+ const FENCE_OPEN = /^(`{3,}|~{3,})(.*)$/;
9302
+ /** Info-string token that names the placement target of an a2ui fence. */
9303
+ const TARGET_TOKEN = /^target=(.+)$/;
9304
+ function isCloser(line, fence) {
9305
+ const trimmed = line.trim();
9306
+ if (trimmed.length < fence.length) return false;
9307
+ for (const ch of trimmed) if (ch !== fence.char) return false;
9308
+ return true;
9309
+ }
9310
+ /** The id of the first `target=<id>` token. Other tokens are ignored. */
9311
+ function readTarget(tokens) {
9312
+ for (const token of tokens) {
9313
+ const match = TARGET_TOKEN.exec(token);
9314
+ if (match) return match[1];
9315
+ }
9316
+ }
9317
+ function a2uiSegment(fence, text, closed) {
9318
+ const segment = {
9319
+ type: "a2ui",
9320
+ index: fence.index,
9321
+ text,
9322
+ closed
9323
+ };
9324
+ if (fence.target !== void 0) segment.target = fence.target;
9325
+ return segment;
9326
+ }
9327
+ /**
9328
+ * Split a (possibly still streaming) markdown string into prose segments and
9329
+ * top-level ```a2ui fences. Fences of other languages stay inside prose
9330
+ * segments byte-for-byte, and a2ui markers inside them are ignored. Only
9331
+ * column-0 fences are recognised, so a fence indented inside a list item is
9332
+ * left to the markdown renderer.
9333
+ *
9334
+ * The first info-string token must be exactly `a2ui`. A later
9335
+ * `target=<id>` token sets `target` on the segment (for example
9336
+ * ```` ```a2ui target=recommendations ````). Other tokens are ignored.
9337
+ *
9338
+ * An a2ui segment's `text` is the fence body. For a closed fence it ends with
9339
+ * "\n" when non-empty. For an open (still streaming or aborted) fence it is
9340
+ * everything after the opener line, minus a half-streamed closing marker.
9341
+ *
9342
+ * @param markdown - The assistant message text, complete or still streaming.
9343
+ * @returns The segments in source order.
9344
+ *
9345
+ * @example
9346
+ * ```ts
9347
+ * for (const segment of splitA2UIMarkdown(message.content)) {
9348
+ * if (segment.type === "a2ui") renderSurface(segment.text, segment.target);
9349
+ * else renderMarkdown(segment.text);
9350
+ * }
9351
+ * ```
9352
+ */
9353
+ function splitA2UIMarkdown(markdown) {
9354
+ const segments = [];
9355
+ let proseStart = 0;
9356
+ let fence = null;
9357
+ let a2uiIndex = 0;
9358
+ const pushProse = (end) => {
9359
+ if (end > proseStart) segments.push({
9360
+ type: "markdown",
9361
+ text: markdown.slice(proseStart, end)
9362
+ });
9363
+ };
9364
+ let lineStart = 0;
9365
+ while (lineStart <= markdown.length) {
9366
+ const newline = markdown.indexOf("\n", lineStart);
9367
+ const lineEnd = newline < 0 ? markdown.length : newline;
9368
+ const hasCR = lineEnd > lineStart && markdown[lineEnd - 1] === "\r";
9369
+ const line = markdown.slice(lineStart, hasCR ? lineEnd - 1 : lineEnd);
9370
+ if (fence) {
9371
+ if (isCloser(line, fence)) {
9372
+ if (fence.index >= 0) {
9373
+ const body = markdown.slice(fence.bodyStart, Math.max(fence.bodyStart, lineStart));
9374
+ segments.push(a2uiSegment(fence, body, true));
9375
+ proseStart = hasCR ? lineEnd - 1 : lineEnd;
9376
+ }
9377
+ fence = null;
9378
+ }
9379
+ } else {
9380
+ const open = FENCE_OPEN.exec(line);
9381
+ if (open) {
9382
+ const marker = open[1] ?? "";
9383
+ const info = open[2] ?? "";
9384
+ const char = marker.charAt(0);
9385
+ if (!(char === "`" && info.includes("`"))) {
9386
+ const [lang = "", ...tokens] = info.trim().split(/\s+/);
9387
+ const isA2UI = lang === A2UI_FENCE_LANGUAGE;
9388
+ if (isA2UI) pushProse(lineStart);
9389
+ fence = {
9390
+ char,
9391
+ length: marker.length,
9392
+ bodyStart: newline < 0 ? markdown.length : lineEnd + 1,
9393
+ index: isA2UI ? a2uiIndex++ : -1,
9394
+ target: isA2UI ? readTarget(tokens) : void 0
9395
+ };
9396
+ }
9397
+ }
9398
+ }
9399
+ if (newline < 0) break;
9400
+ lineStart = newline + 1;
9401
+ }
9402
+ if (fence && fence.index >= 0) {
9403
+ const { char } = fence;
9404
+ let body = markdown.slice(fence.bodyStart);
9405
+ const lastNewline = body.lastIndexOf("\n");
9406
+ const lastLine = body.slice(lastNewline + 1).replace(/\r$/, "");
9407
+ if (lastLine.length > 0 && [...lastLine].every((ch) => ch === char)) body = body.slice(0, lastNewline + 1);
9408
+ segments.push(a2uiSegment(fence, body, false));
9409
+ } else pushProse(markdown.length);
9410
+ return segments;
9411
+ }
9412
+
9413
+ //#endregion
9414
+ //#region src/a2ui-markdown/operations.ts
9415
+ /** The operation keys that change a surface. */
9416
+ const SURFACE_OP_KEYS = [
9417
+ "createSurface",
9418
+ "updateComponents",
9419
+ "updateDataModel",
9420
+ "deleteSurface"
9421
+ ];
9422
+ /** The operation key of an agent-called function. It has no surface. */
9423
+ const FUNCTION_CALL_KEY = "callRendererFunction";
9424
+ const OP_KEYS = [...SURFACE_OP_KEYS, FUNCTION_CALL_KEY];
9425
+ function isRecord(value) {
9426
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9427
+ }
9428
+ function isWhitespace(ch) {
9429
+ return ch === " " || ch === "\n" || ch === "\r" || ch === " ";
9430
+ }
9431
+ function skipWhitespace(s, i) {
9432
+ while (i < s.length && isWhitespace(s[i])) i++;
9433
+ return i;
9434
+ }
9435
+ /** Index of the closing quote of the JSON string opening at `start`, or -1. */
9436
+ function findStringEnd(s, start) {
9437
+ for (let i = start + 1; i < s.length; i++) {
9438
+ if (s[i] === "\\") {
9439
+ i++;
9440
+ continue;
9441
+ }
9442
+ if (s[i] === "\"") return i;
9443
+ }
9444
+ return -1;
9445
+ }
9446
+ /**
9447
+ * Find the first `"key":` whose value starts with `opener` and return the index
9448
+ * of that opener, or -1.
9449
+ */
9450
+ function findKeyValue(s, key, opener) {
9451
+ const needle = `"${key}"`;
9452
+ let from = 0;
9453
+ while (true) {
9454
+ const k = s.indexOf(needle, from);
9455
+ if (k < 0) return -1;
9456
+ let i = skipWhitespace(s, k + needle.length);
9457
+ if (s[i] === ":") {
9458
+ i = skipWhitespace(s, i + 1);
9459
+ if (s[i] === opener) return i;
9460
+ }
9461
+ from = k + 1;
9462
+ }
9463
+ }
9464
+ /**
9465
+ * Read `"key":"value"` from partial JSON. The first match anywhere in the
9466
+ * text wins, at any depth.
9467
+ *
9468
+ * @param partialJson - JSON text that can still be streaming.
9469
+ * @param key - The field name.
9470
+ * @returns The string value, or null until its closing quote has arrived.
9471
+ *
9472
+ * @example
9473
+ * ```ts
9474
+ * extractStringField('{"createSurface":{"surfaceId":"plan","cat', "surfaceId"); // "plan"
9475
+ * ```
9476
+ */
9477
+ function extractStringField(partialJson, key) {
9478
+ const start = findKeyValue(partialJson, key, "\"");
9479
+ if (start < 0) return null;
9480
+ const end = findStringEnd(partialJson, start);
9481
+ if (end < 0) return null;
9482
+ try {
9483
+ const value = JSON.parse(partialJson.slice(start, end + 1));
9484
+ return typeof value === "string" ? value : null;
9485
+ } catch {
9486
+ return null;
9487
+ }
9488
+ }
9489
+ function pushItem(raw, items) {
9490
+ const trimmed = raw.trim();
9491
+ if (!trimmed) return;
9492
+ try {
9493
+ items.push(JSON.parse(trimmed));
9494
+ } catch {}
9495
+ }
9496
+ /**
9497
+ * Find `"key":[` in partial JSON and return every complete item of that array
9498
+ * so far, plus whether the array has closed. Items of a `components` array get
9499
+ * structural-key depth repair: a component that lost closing braces is fixed
9500
+ * when its `id`, `component`, `child` or `children` key shows where it ends.
9501
+ *
9502
+ * @param partialJson - JSON text that can still be streaming.
9503
+ * @param key - The name of the array field.
9504
+ * @returns `{ items, closed }`, or null when the key (with an array value)
9505
+ * has not appeared yet.
9506
+ *
9507
+ * @example
9508
+ * ```ts
9509
+ * const result = extractCompleteArrayItems(streamedText, "components");
9510
+ * if (result) render(result.items);
9511
+ * ```
9512
+ */
9513
+ function extractCompleteArrayItems(partialJson, key) {
9514
+ const open = findKeyValue(partialJson, key, "[");
9515
+ if (open < 0) return null;
9516
+ return completeArrayItemsAt(partialJson, open, { repairComponents: key === "components" });
9517
+ }
9518
+ /** Index of the last non-whitespace character before `i`, or -1. */
9519
+ function prevNonWhitespace(s, i) {
9520
+ let j = i - 1;
9521
+ while (j >= 0 && isWhitespace(s[j])) j--;
9522
+ return j;
9523
+ }
9524
+ /**
9525
+ * Keys that only ever belong at a component's top level. Seen nested inside
9526
+ * the component's objects, they mean the model forgot closing braces.
9527
+ */
9528
+ const STRUCTURAL_KEYS = new Set([
9529
+ "id",
9530
+ "component",
9531
+ "child",
9532
+ "children"
9533
+ ]);
9534
+ /** Whether a value starting with `ch` has the shape `key` takes on a component. */
9535
+ function structuralValueFits(key, ch) {
9536
+ if (key === "children") return ch === "[" || ch === "{";
9537
+ return ch === "\"";
9538
+ }
9539
+ /** `{"id":` — a new component object starting at `i`. */
9540
+ const COMPONENT_START = /^\{\s*"id"\s*:/;
9541
+ /**
9542
+ * Structural-key depth repair for one component item. While scanning, a
9543
+ * structural key (`id`, `component`, `child`, `children`) found as an object
9544
+ * key below the item's top level, with only objects (no arrays) between it
9545
+ * and the item root, a value of the expected shape, and not already present
9546
+ * at the top level, means closing braces were dropped: the missing `}` are
9547
+ * synthesized right before it so it lands at the top level. Containers still
9548
+ * open at the end are closed. Returns null when a string never terminates.
9549
+ */
9550
+ function repairComponentItem(item) {
9551
+ const stack = [];
9552
+ const topKeys = /* @__PURE__ */ new Set();
9553
+ let out = "";
9554
+ let copied = 0;
9555
+ for (let i = 0; i < item.length; i++) {
9556
+ const c = item[i];
9557
+ if (c === "\"") {
9558
+ const end = findStringEnd(item, i);
9559
+ if (end < 0) return null;
9560
+ const prev = prevNonWhitespace(item, i);
9561
+ const prevCh = item[prev];
9562
+ const colon = skipWhitespace(item, end + 1);
9563
+ if (stack[stack.length - 1] === "{" && (prevCh === "," || prevCh === "{") && item[colon] === ":") {
9564
+ let key;
9565
+ try {
9566
+ key = JSON.parse(item.slice(i, end + 1));
9567
+ } catch {
9568
+ return null;
9569
+ }
9570
+ if (typeof key === "string") {
9571
+ if (stack.length === 1) topKeys.add(key);
9572
+ else if (STRUCTURAL_KEYS.has(key) && !topKeys.has(key) && stack.every((x) => x === "{") && structuralValueFits(key, item[skipWhitespace(item, colon + 1)])) {
9573
+ const closers = "}".repeat(stack.length - 1);
9574
+ if (prevCh === ",") {
9575
+ out += item.slice(copied, prev) + closers;
9576
+ copied = prev;
9577
+ } else {
9578
+ out += item.slice(copied, i) + closers + ",";
9579
+ copied = i;
9580
+ }
9581
+ stack.length = 1;
9582
+ topKeys.add(key);
9583
+ }
9584
+ }
9585
+ }
9586
+ i = end;
9587
+ continue;
9588
+ }
9589
+ if (c === "{" || c === "[") stack.push(c);
9590
+ else if (c === "}" || c === "]") {
9591
+ stack.pop();
9592
+ if (stack.length === 0) return out + item.slice(copied, i + 1);
9593
+ }
9594
+ }
9595
+ const closers = stack.reduceRight((text, opener) => text + (opener === "{" ? "}" : "]"), "");
9596
+ return out + item.slice(copied) + closers;
9597
+ }
9598
+ function parseRecord(text) {
9599
+ if (text === null) return void 0;
9600
+ try {
9601
+ const value = JSON.parse(text);
9602
+ return isRecord(value) ? value : void 0;
9603
+ } catch {
9604
+ return;
9605
+ }
9606
+ }
9607
+ /**
9608
+ * Complete items of the (possibly unterminated) array whose "[" is at `open`.
9609
+ * With `repairComponents`, an item that balanced but does not parse is retried
9610
+ * with structural-key repair, and a `,{"id":` where an item expects a key
9611
+ * ends that (unbalanced) item there, so one malformed component cannot
9612
+ * swallow the rest of the array; the cut item is kept only if repair makes
9613
+ * it parse.
9614
+ */
9615
+ function completeArrayItemsAt(partialJson, open, options) {
9616
+ const { repairComponents } = options;
9617
+ const s = partialJson;
9618
+ const items = [];
9619
+ const stack = [];
9620
+ let inString = false;
9621
+ let itemStart = -1;
9622
+ const finishItem = (end, balanced) => {
9623
+ const raw = s.slice(itemStart, end);
9624
+ if (!repairComponents) {
9625
+ pushItem(raw, items);
9626
+ return;
9627
+ }
9628
+ if (balanced) try {
9629
+ items.push(JSON.parse(raw));
9630
+ return;
9631
+ } catch {}
9632
+ const repaired = parseRecord(repairComponentItem(raw.trim()));
9633
+ if (repaired !== void 0) items.push(repaired);
9634
+ };
9635
+ for (let i = open + 1; i < s.length; i++) {
9636
+ const c = s[i];
9637
+ if (inString) {
9638
+ if (c === "\\") i++;
9639
+ else if (c === "\"") inString = false;
9640
+ continue;
9641
+ }
9642
+ if (c === "\"") {
9643
+ inString = true;
9644
+ if (stack.length === 0 && itemStart < 0) itemStart = i;
9645
+ continue;
9646
+ }
9647
+ if (c === "{" || c === "[") {
9648
+ if (repairComponents && c === "{" && stack[stack.length - 1] === "{" && COMPONENT_START.test(s.slice(i, i + 24))) {
9649
+ const prev = prevNonWhitespace(s, i);
9650
+ if (s[prev] === ",") {
9651
+ finishItem(prev, false);
9652
+ stack.length = 0;
9653
+ itemStart = i;
9654
+ stack.push(c);
9655
+ continue;
9656
+ }
9657
+ }
9658
+ if (stack.length === 0) itemStart = i;
9659
+ stack.push(c);
9660
+ continue;
9661
+ }
9662
+ if (c === "}" || c === "]") {
9663
+ if (stack.length === 0) {
9664
+ if (c === "]") {
9665
+ if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
9666
+ return {
9667
+ items,
9668
+ closed: true
9669
+ };
9670
+ }
9671
+ return {
9672
+ items,
9673
+ closed: false
9674
+ };
9675
+ }
9676
+ stack.pop();
9677
+ if (stack.length === 0) {
9678
+ finishItem(i + 1, true);
9679
+ itemStart = -1;
9680
+ }
9681
+ continue;
9682
+ }
9683
+ if (stack.length === 0) {
9684
+ if (c === ",") {
9685
+ if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
9686
+ itemStart = -1;
9687
+ } else if (itemStart < 0 && !isWhitespace(c)) itemStart = i;
9688
+ }
9689
+ }
9690
+ return {
9691
+ items,
9692
+ closed: false
9693
+ };
9694
+ }
9695
+ /** The first operation key whose value is an object, with that value. */
9696
+ function getOperationEntry(op) {
9697
+ for (const key of OP_KEYS) {
9698
+ const inner = op[key];
9699
+ if (isRecord(inner)) return {
9700
+ key,
9701
+ inner
9702
+ };
9703
+ }
9704
+ return null;
9705
+ }
9706
+ /**
9707
+ * The surfaceId an operation targets: the one nested under its operation key,
9708
+ * else a top-level `surfaceId`. A `callRendererFunction` operation targets no
9709
+ * surface, so it gets undefined.
9710
+ *
9711
+ * It is named `getMarkdownOperationSurfaceId` because `@copilotkit/shared`
9712
+ * already exports a strict `getOperationSurfaceId`. This one also reads a
9713
+ * top-level `surfaceId`, which models sometimes write.
9714
+ *
9715
+ * @param op - An operation from an a2ui fence.
9716
+ * @returns The surfaceId, or undefined when the operation names none or is a
9717
+ * function call.
9718
+ *
9719
+ * @example
9720
+ * ```ts
9721
+ * getMarkdownOperationSurfaceId({ updateDataModel: { surfaceId: "plan" } }); // "plan"
9722
+ * ```
9723
+ */
9724
+ function getMarkdownOperationSurfaceId(op) {
9725
+ if (getOperationEntry(op)?.key === FUNCTION_CALL_KEY) return void 0;
9726
+ for (const key of SURFACE_OP_KEYS) {
9727
+ const inner = op[key];
9728
+ if (isRecord(inner) && typeof inner.surfaceId === "string") return inner.surfaceId;
9729
+ }
9730
+ return typeof op.surfaceId === "string" ? op.surfaceId : void 0;
9731
+ }
9732
+ /**
9733
+ * Index just past the JSON value starting at `start`, or -1 when the value is
9734
+ * still incomplete. A primitive at the very end of the input counts as
9735
+ * incomplete, since more digits or letters may still stream in.
9736
+ */
9737
+ function findValueEnd(s, start) {
9738
+ const c = s[start];
9739
+ if (c === "\"") {
9740
+ const end = findStringEnd(s, start);
9741
+ return end < 0 ? -1 : end + 1;
9742
+ }
9743
+ if (c === "{" || c === "[") {
9744
+ let depth = 0;
9745
+ for (let i = start; i < s.length; i++) {
9746
+ const ch = s[i];
9747
+ if (ch === "\"") {
9748
+ const end = findStringEnd(s, i);
9749
+ if (end < 0) return -1;
9750
+ i = end;
9751
+ } else if (ch === "{" || ch === "[") depth++;
9752
+ else if (ch === "}" || ch === "]") {
9753
+ depth--;
9754
+ if (depth === 0) return i + 1;
9755
+ }
9756
+ }
9757
+ return -1;
9758
+ }
9759
+ let i = start;
9760
+ while (i < s.length && !isWhitespace(s[i]) && !",}]".includes(s[i])) i++;
9761
+ return i >= s.length ? -1 : i;
9762
+ }
9763
+ /**
9764
+ * Walk the direct entries of the (possibly unterminated) JSON object whose "{"
9765
+ * is at `objStart`, calling `visit` with each key and the index where its value
9766
+ * starts. Nested objects and arrays are skipped whole, so keys inside them are
9767
+ * never visited. Stops when `visit` returns true, at the object's end, or where
9768
+ * the input runs out.
9769
+ */
9770
+ function visitDirectEntries(s, objStart, visit) {
9771
+ let i = objStart + 1;
9772
+ while (i < s.length) {
9773
+ i = skipWhitespace(s, i);
9774
+ const c = s[i];
9775
+ if (c === ",") {
9776
+ i++;
9777
+ continue;
9778
+ }
9779
+ if (c !== "\"") return;
9780
+ const keyEnd = findStringEnd(s, i);
9781
+ if (keyEnd < 0) return;
9782
+ let key;
9783
+ try {
9784
+ key = JSON.parse(s.slice(i, keyEnd + 1));
9785
+ } catch {
9786
+ return;
9787
+ }
9788
+ i = skipWhitespace(s, keyEnd + 1);
9789
+ if (s[i] !== ":") return;
9790
+ i = skipWhitespace(s, i + 1);
9791
+ if (i >= s.length) return;
9792
+ if (typeof key === "string" && visit(key, i)) return;
9793
+ const valueEnd = findValueEnd(s, i);
9794
+ if (valueEnd < 0) return;
9795
+ i = valueEnd;
9796
+ }
9797
+ }
9798
+ /**
9799
+ * Value start of a direct `key` of the object at `objStart` whose value begins
9800
+ * with `opener` (any value when omitted), or -1.
9801
+ */
9802
+ function findDirectKeyValue(s, objStart, key, opener) {
9803
+ let found = -1;
9804
+ visitDirectEntries(s, objStart, (k, valueStart) => {
9805
+ if (k !== key) return false;
9806
+ if (opener === void 0 || s[valueStart] === opener) found = valueStart;
9807
+ return true;
9808
+ });
9809
+ return found;
9810
+ }
9811
+ /** A direct string field of the object at `objStart`, once its closing quote has arrived. */
9812
+ function readDirectString(s, objStart, key) {
9813
+ if (objStart < 0) return null;
9814
+ const start = findDirectKeyValue(s, objStart, key, "\"");
9815
+ if (start < 0) return null;
9816
+ const end = findValueEnd(s, start);
9817
+ if (end < 0) return null;
9818
+ try {
9819
+ const value = JSON.parse(s.slice(start, end));
9820
+ return typeof value === "string" ? value : null;
9821
+ } catch {
9822
+ return null;
9823
+ }
9824
+ }
9825
+ /** A direct object field of the object at `objStart`, once the whole object has arrived. */
9826
+ function readDirectRecord(s, objStart, key) {
9827
+ const start = findDirectKeyValue(s, objStart, key, "{");
9828
+ if (start < 0) return void 0;
9829
+ const end = findValueEnd(s, start);
9830
+ if (end < 0) return void 0;
9831
+ return parseRecord(s.slice(start, end));
9832
+ }
9833
+ /**
9834
+ * The complete part of a (possibly unterminated) JSON value: the parsed value
9835
+ * when it is complete; for an open object, its complete entries plus the
9836
+ * complete items of any streaming array entry; otherwise undefined.
9837
+ */
9838
+ function completePartOfValue(s, start) {
9839
+ const end = findValueEnd(s, start);
9840
+ if (end >= 0) try {
9841
+ return JSON.parse(s.slice(start, end));
9842
+ } catch {
9843
+ return;
9844
+ }
9845
+ if (s[start] !== "{") return void 0;
9846
+ const out = {};
9847
+ visitDirectEntries(s, start, (key, valueStart) => {
9848
+ const valueEnd = findValueEnd(s, valueStart);
9849
+ if (valueEnd >= 0) try {
9850
+ out[key] = JSON.parse(s.slice(valueStart, valueEnd));
9851
+ } catch {}
9852
+ else if (s[valueStart] === "[") {
9853
+ const { items } = completeArrayItemsAt(s, valueStart, { repairComponents: false });
9854
+ if (items.length > 0) out[key] = items;
9855
+ }
9856
+ return false;
9857
+ });
9858
+ return Object.keys(out).length > 0 ? out : void 0;
9859
+ }
9860
+ /**
9861
+ * Best-effort operation from an unfinished or malformed top-level object.
9862
+ * Fields are read only from the operation's own keys (`version` at the top
9863
+ * level, `surfaceId`, `catalogId`, `path`, `dataModel` and `components` inside
9864
+ * the operation object), never from component props or data-model values that
9865
+ * happen to share a name.
9866
+ *
9867
+ * A `createSurface` keeps its complete components and a `dataModel` that has
9868
+ * fully arrived, so a surface created in one line renders while it streams.
9869
+ * A `callRendererFunction` gives nothing: a function must not run with half
9870
+ * of its args.
9871
+ */
9872
+ function partialOperation(line) {
9873
+ const root = skipWhitespace(line, 0);
9874
+ if (line[root] !== "{") return null;
9875
+ const version = readDirectString(line, root, "version") ?? A2UI_VERSION;
9876
+ const components = findDirectKeyValue(line, root, "updateComponents", "{");
9877
+ if (components >= 0) {
9878
+ const arrayStart = findDirectKeyValue(line, components, "components", "[");
9879
+ if (arrayStart < 0) return null;
9880
+ const { items } = completeArrayItemsAt(line, arrayStart, { repairComponents: true });
9881
+ if (items.length === 0) return null;
9882
+ const surfaceId = readDirectString(line, components, "surfaceId");
9883
+ return {
9884
+ version,
9885
+ updateComponents: {
9886
+ ...surfaceId ? { surfaceId } : {},
9887
+ components: items
9888
+ }
9889
+ };
9890
+ }
9891
+ const data = findDirectKeyValue(line, root, "updateDataModel", "{");
9892
+ if (data >= 0) {
9893
+ const valueStart = findDirectKeyValue(line, data, "value");
9894
+ if (valueStart < 0) return null;
9895
+ const value = completePartOfValue(line, valueStart);
9896
+ if (value === void 0) return null;
9897
+ const surfaceId = readDirectString(line, data, "surfaceId");
9898
+ const path = readDirectString(line, data, "path");
9899
+ return {
9900
+ version,
9901
+ updateDataModel: {
9902
+ ...surfaceId ? { surfaceId } : {},
9903
+ ...path ? { path } : {},
9904
+ value
9905
+ }
9906
+ };
9907
+ }
9908
+ const create = findDirectKeyValue(line, root, "createSurface", "{");
9909
+ if (create >= 0) {
9910
+ const surfaceId = readDirectString(line, create, "surfaceId");
9911
+ if (!surfaceId) return null;
9912
+ const catalogId = readDirectString(line, create, "catalogId");
9913
+ const dataModel = readDirectRecord(line, create, "dataModel");
9914
+ const componentsStart = findDirectKeyValue(line, create, "components", "[");
9915
+ const components = componentsStart < 0 ? [] : completeArrayItemsAt(line, componentsStart, { repairComponents: true }).items;
9916
+ return {
9917
+ version,
9918
+ createSurface: {
9919
+ surfaceId,
9920
+ ...catalogId ? { catalogId } : {},
9921
+ ...dataModel ? { dataModel } : {},
9922
+ ...components.length > 0 ? { components } : {}
9923
+ }
9924
+ };
9925
+ }
9926
+ return null;
9927
+ }
9928
+ /**
9929
+ * A line that opens a new top-level operation: `{"version":"v…` or
9930
+ * `{"<operation>":{`. Seen at the start of a line while an earlier object is
9931
+ * still unbalanced, it means that object is malformed and has ended.
9932
+ */
9933
+ const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"v\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
9934
+ /**
9935
+ * Scan the top-level object whose "{" is at `start`. Returns the index just
9936
+ * past it and whether it balanced. An unbalanced object ends early (at the
9937
+ * start of the line) when a line opens a new operation; otherwise it runs to
9938
+ * the end of the input. JSON strings cannot contain raw newlines, so a newline
9939
+ * inside a string ends it: a stray quote then breaks one line, not the rest of
9940
+ * the fence.
9941
+ */
9942
+ function scanTopLevelObject(s, start) {
9943
+ let depth = 0;
9944
+ let inString = false;
9945
+ for (let i = start; i < s.length; i++) {
9946
+ const c = s[i];
9947
+ if (inString) {
9948
+ if (c === "\\" && s[i + 1] !== "\n") i++;
9949
+ else if (c === "\"" || c === "\n") inString = false;
9950
+ if (c !== "\n") continue;
9951
+ }
9952
+ if (c === "\n") {
9953
+ const next = skipWhitespace(s, i + 1);
9954
+ if (OPERATION_START.test(s.slice(next, next + 40))) return {
9955
+ end: i + 1,
9956
+ balanced: false
9957
+ };
9958
+ continue;
9959
+ }
9960
+ if (c === "\"") inString = true;
9961
+ else if (c === "{" || c === "[") depth++;
9962
+ else if (c === "}" || c === "]") {
9963
+ depth--;
9964
+ if (depth === 0) return {
9965
+ end: i + 1,
9966
+ balanced: true
9967
+ };
9968
+ }
9969
+ }
9970
+ return {
9971
+ end: s.length,
9972
+ balanced: false
9973
+ };
9974
+ }
9975
+ /**
9976
+ * Parse the body of an a2ui fence as a stream of top-level JSON values, so
9977
+ * operations may be one per line (the documented format), several per line,
9978
+ * pretty-printed over many lines, or wrapped in a top-level array (which is
9979
+ * flattened). Whitespace and commas between objects are ignored.
9980
+ *
9981
+ * - A balanced object is `JSON.parse`d. When that fails (e.g. a stray quote),
9982
+ * its raw text goes to `invalidLines` and whatever `partialOperation` can
9983
+ * salvage (complete components, data-model entries, createSurface fields)
9984
+ * is kept.
9985
+ * - An unbalanced object followed by a line that opens a new operation is
9986
+ * treated the same way.
9987
+ * - The trailing unbalanced object (still streaming, or never closed) is
9988
+ * `partialObject` and yields a partial operation when it has usable data.
9989
+ * - Other text between objects is skipped and reported in `recovered` (and in
9990
+ * `invalidLines`, which predates it).
9991
+ *
9992
+ * `partialLine` is a deprecated alias of `partialObject`.
9993
+ *
9994
+ * @param fenceText - The body of an a2ui fence (`text` of an a2ui
9995
+ * `MarkdownSegment`), complete or still streaming.
9996
+ * @returns `{ operations, partialObject, partialLine, invalidLines, recovered }`.
9997
+ *
9998
+ * @example
9999
+ * ```ts
10000
+ * const { operations } = extractFenceOperations(segment.text);
10001
+ * ```
10002
+ */
10003
+ function extractFenceOperations(fenceText) {
10004
+ const s = fenceText;
10005
+ const operations = [];
10006
+ const invalidLines = [];
10007
+ const recovered = [];
10008
+ let partialObject = null;
10009
+ const salvage = (raw) => {
10010
+ invalidLines.push(raw.trim());
10011
+ const partial = partialOperation(raw);
10012
+ if (partial) operations.push(partial);
10013
+ };
10014
+ let junkStart = -1;
10015
+ const flushJunk = (end) => {
10016
+ if (junkStart < 0) return;
10017
+ const junk = s.slice(junkStart, end).trim();
10018
+ junkStart = -1;
10019
+ if (!junk) return;
10020
+ recovered.push(junk);
10021
+ invalidLines.push(junk);
10022
+ };
10023
+ let i = 0;
10024
+ while (i < s.length) {
10025
+ const c = s[i];
10026
+ if (c === "{") {
10027
+ flushJunk(i);
10028
+ const { end, balanced } = scanTopLevelObject(s, i);
10029
+ const raw = s.slice(i, end);
10030
+ if (balanced) {
10031
+ let parsed;
10032
+ try {
10033
+ parsed = JSON.parse(raw);
10034
+ } catch {
10035
+ parsed = void 0;
10036
+ }
10037
+ if (isRecord(parsed)) operations.push(parsed);
10038
+ else salvage(raw);
10039
+ } else if (end < s.length) salvage(raw);
10040
+ else {
10041
+ partialObject = raw;
10042
+ const partial = partialOperation(raw);
10043
+ if (partial) operations.push(partial);
10044
+ }
10045
+ i = end;
10046
+ continue;
10047
+ }
10048
+ if (c === "\n" || c === "[" || c === "]") flushJunk(i);
10049
+ else if (junkStart < 0 && !isWhitespace(c) && c !== ",") junkStart = i;
10050
+ i++;
10051
+ }
10052
+ flushJunk(s.length);
10053
+ return {
10054
+ operations,
10055
+ partialObject,
10056
+ partialLine: partialObject,
10057
+ invalidLines,
10058
+ recovered
10059
+ };
10060
+ }
10061
+ /**
10062
+ * Normalise a fence's operations for the renderer: drop unknown messages, fill
10063
+ * in `version` and missing `surfaceId`s, keep only the first `createSurface`,
10064
+ * keep its `catalogId` when `catalogIds` lists it (else use `catalogId`), synthesize
10065
+ * `createSurface` when the model omitted it, and report the
10066
+ * surfaceId (the first one found, else `fallbackSurfaceId`).
10067
+ *
10068
+ * `callRendererFunction` operations target no surface. They get no surfaceId,
10069
+ * do not cause a synthesized `createSurface`, and come back in
10070
+ * `functionCalls` (in fence order), never in `operations`.
10071
+ *
10072
+ * @param input.operations - Operations from `extractFenceOperations`.
10073
+ * @param input.fallbackSurfaceId - The surfaceId to use when no operation
10074
+ * names one.
10075
+ * @param input.catalogId - The client catalog. It replaces a catalogId of the
10076
+ * model that `catalogIds` does not list.
10077
+ * @param input.catalogIds - The catalogs that the model can name. Left out,
10078
+ * only `catalogId`.
10079
+ * @returns `{ surfaceId, operations, functionCalls }`.
10080
+ *
10081
+ * @example
10082
+ * ```ts
10083
+ * const { surfaceId, operations, functionCalls } = prepareSurfaceOperations({
10084
+ * operations: extractFenceOperations(segment.text).operations,
10085
+ * fallbackSurfaceId: `${messageId}-${segment.index}`,
10086
+ * catalogId,
10087
+ * });
10088
+ * ```
10089
+ */
10090
+ function prepareSurfaceOperations(input) {
10091
+ const { operations, fallbackSurfaceId, catalogId } = input;
10092
+ const catalogIds = input.catalogIds ?? [catalogId];
10093
+ const surfaceId = operations.map(getMarkdownOperationSurfaceId).find((id) => !!id) ?? fallbackSurfaceId;
10094
+ const out = [];
10095
+ const functionCalls = [];
10096
+ let hasCreate = false;
10097
+ for (const op of operations) {
10098
+ const entry = getOperationEntry(op);
10099
+ if (!entry) continue;
10100
+ const { key } = entry;
10101
+ const inner = { ...entry.inner };
10102
+ const version = typeof op.version === "string" ? op.version : A2UI_VERSION;
10103
+ if (key === FUNCTION_CALL_KEY) {
10104
+ functionCalls.push({
10105
+ version,
10106
+ [key]: inner
10107
+ });
10108
+ continue;
10109
+ }
10110
+ if (typeof inner.surfaceId !== "string") inner.surfaceId = surfaceId;
10111
+ if (key === "createSurface") {
10112
+ if (hasCreate) {
10113
+ const { surfaceId: id, dataModel, components } = inner;
10114
+ if (dataModel !== void 0) out.push({
10115
+ version,
10116
+ updateDataModel: {
10117
+ surfaceId: id,
10118
+ path: "/",
10119
+ value: dataModel
10120
+ }
10121
+ });
10122
+ if (Array.isArray(components) && components.length > 0) out.push({
10123
+ version,
10124
+ updateComponents: {
10125
+ surfaceId: id,
10126
+ components
10127
+ }
10128
+ });
10129
+ continue;
10130
+ }
10131
+ hasCreate = true;
10132
+ if (!catalogIds.includes(inner.catalogId)) inner.catalogId = catalogId;
10133
+ }
10134
+ out.push({
10135
+ version,
10136
+ [key]: inner
10137
+ });
10138
+ }
10139
+ if (!hasCreate && out.length > 0) out.unshift({
10140
+ version: A2UI_VERSION,
10141
+ createSurface: {
10142
+ surfaceId,
10143
+ catalogId
10144
+ }
10145
+ });
10146
+ return {
10147
+ surfaceId,
10148
+ operations: out,
10149
+ functionCalls
10150
+ };
10151
+ }
10152
+ /**
10153
+ * Components a user operates. A Card containing one of these is an
10154
+ * interactive panel and keeps its box; every other Card is informational.
10155
+ */
10156
+ const INTERACTIVE_COMPONENTS = new Set([
10157
+ "Button",
10158
+ "Pressable",
10159
+ "Form",
10160
+ "TextField",
10161
+ "TextArea",
10162
+ "Select",
10163
+ "CheckBox",
10164
+ "Radio",
10165
+ "RadioGroup",
10166
+ "Slider",
10167
+ "SegmentedControl",
10168
+ "ChoicePicker",
10169
+ "DateTimeInput"
10170
+ ]);
10171
+ /** A component id referenced by a `child`/`children` entry or a table cell. */
10172
+ function referencedId(value) {
10173
+ if (typeof value === "string") return value;
10174
+ if (isRecord(value)) {
10175
+ if (typeof value.componentId === "string") return value.componentId;
10176
+ if (typeof value.id === "string") return value.id;
10177
+ }
10178
+ }
10179
+ /** Ids of a table cell / column that renders a component (`{componentId}` or `{id}`). */
10180
+ function cellComponentId(value) {
10181
+ return isRecord(value) ? referencedId(value) : void 0;
10182
+ }
10183
+ /**
10184
+ * Ids a component renders directly: `child`, `children` (string ids, an
10185
+ * array, or a `{componentId}` template), component cells of a Table's
10186
+ * `rows`/`columns`, and the ids that `extra` finds in its typed references.
10187
+ */
10188
+ function directChildIds(component, extra) {
10189
+ const ids = [];
10190
+ const add = (id) => {
10191
+ if (id) ids.push(id);
10192
+ };
10193
+ const extraIds = extra?.(component);
10194
+ if (Array.isArray(extraIds)) extraIds.forEach(add);
10195
+ add(referencedId(component.child));
10196
+ const children = component.children;
10197
+ if (Array.isArray(children)) children.forEach((c) => add(referencedId(c)));
10198
+ else add(referencedId(children));
10199
+ if (Array.isArray(component.columns)) component.columns.forEach((c) => add(cellComponentId(c)));
10200
+ if (Array.isArray(component.rows)) {
10201
+ for (const row of component.rows) if (Array.isArray(row)) row.forEach((c) => add(cellComponentId(c)));
10202
+ }
10203
+ return ids;
10204
+ }
10205
+ /** Components of every updateComponents operation, by id (last definition wins). */
10206
+ function componentsById(operations) {
10207
+ const byId = /* @__PURE__ */ new Map();
10208
+ for (const op of operations) {
10209
+ const update = op.updateComponents;
10210
+ const list = isRecord(update) ? update.components : void 0;
10211
+ if (!Array.isArray(list)) continue;
10212
+ for (const c of list) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
10213
+ }
10214
+ return byId;
10215
+ }
10216
+ function descendantIds(rootId, byId, extra) {
10217
+ const seen = /* @__PURE__ */ new Set();
10218
+ const stack = [...directChildIds(byId.get(rootId) ?? {}, extra)];
10219
+ while (stack.length > 0) {
10220
+ const id = stack.pop();
10221
+ if (seen.has(id) || id === rootId) continue;
10222
+ seen.add(id);
10223
+ const c = byId.get(id);
10224
+ if (c) stack.push(...directChildIds(c, extra));
10225
+ }
10226
+ return seen;
10227
+ }
10228
+ /**
10229
+ * Ids of the `Card` components that are interactive panels: at least one
10230
+ * descendant (via `child`, `children` or table component cells) is a control
10231
+ * (Button, Pressable, Form, TextField, TextArea, Select, CheckBox, Radio,
10232
+ * RadioGroup, Slider, SegmentedControl, DateTimeInput).
10233
+ *
10234
+ * @param components - The components of one surface.
10235
+ * @returns The ids of the interactive cards.
10236
+ *
10237
+ * @example
10238
+ * ```ts
10239
+ * const interactive = classifySurfaceCards(components);
10240
+ * const keepsBox = interactive.has("quote-form");
10241
+ * ```
10242
+ */
10243
+ function classifySurfaceCards(components, options = {}) {
10244
+ const byId = /* @__PURE__ */ new Map();
10245
+ for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
10246
+ const interactive = /* @__PURE__ */ new Set();
10247
+ for (const [id, c] of byId) {
10248
+ if (c.component !== "Card") continue;
10249
+ for (const d of descendantIds(id, byId, options.childIds)) {
10250
+ const type = byId.get(d)?.component;
10251
+ if (typeof type === "string" && INTERACTIVE_COMPONENTS.has(type)) {
10252
+ interactive.add(id);
10253
+ break;
10254
+ }
10255
+ }
10256
+ }
10257
+ return interactive;
10258
+ }
10259
+ /**
10260
+ * Markdown mode: only interactive panels keep a box. Every `Card` that is not
10261
+ * an interactive panel (see `classifySurfaceCards`), sets no `variant` or
10262
+ * `border` of its own and is not nested inside an interactive panel becomes
10263
+ * `variant: "section"` (a heading plus content without a box). Operations
10264
+ * other than updateComponents pass through unchanged.
10265
+ *
10266
+ * @param operations - The operations of one surface.
10267
+ * @returns The operations with informational cards set to `variant: "section"`.
10268
+ * When no card changes, it returns the same array.
10269
+ *
10270
+ * @example
10271
+ * ```ts
10272
+ * const operations = flattenInformationalCards(prepared.operations);
10273
+ * ```
10274
+ */
10275
+ function flattenInformationalCards(operations, options = {}) {
10276
+ const byId = componentsById(operations);
10277
+ if (![...byId.values()].some((c) => c.component === "Card")) return operations;
10278
+ const interactive = classifySurfaceCards([...byId.values()], options);
10279
+ const insideInteractive = /* @__PURE__ */ new Set();
10280
+ for (const id of interactive) for (const d of descendantIds(id, byId, options.childIds)) insideInteractive.add(d);
10281
+ const flatten = (c) => c.component === "Card" && typeof c.id === "string" && !interactive.has(c.id) && !insideInteractive.has(c.id) && c.variant == null && c.border == null;
10282
+ return operations.map((op) => {
10283
+ const update = op.updateComponents;
10284
+ if (!isRecord(update) || !Array.isArray(update.components)) return op;
10285
+ if (!update.components.some((c) => isRecord(c) && flatten(c))) return op;
10286
+ return {
10287
+ ...op,
10288
+ updateComponents: {
10289
+ ...update,
10290
+ components: update.components.map((c) => isRecord(c) && flatten(c) ? {
10291
+ ...c,
10292
+ variant: "section"
10293
+ } : c)
10294
+ }
10295
+ };
10296
+ });
10297
+ }
10298
+ /** Text-bearing components that belong in the chat's markdown, not a surface. */
10299
+ const PROSE_TEXT_COMPONENTS = new Set([
10300
+ "Title",
10301
+ "Text",
10302
+ "Caption",
10303
+ "Markdown"
10304
+ ]);
10305
+ /** One line of text: list items and headings cannot span lines in markdown. */
10306
+ function oneLine(text) {
10307
+ return text.trim().replace(/\s*\n\s*/g, " ");
10308
+ }
10309
+ /**
10310
+ * A literal List entry as list-item markdown: a non-empty string, or
10311
+ * `{ label, description? }` with literal strings only. Anything carrying
10312
+ * behaviour or decoration (`icon`, `action`, other keys, bound values) is null.
10313
+ */
10314
+ function listEntryMarkdown(entry) {
10315
+ if (typeof entry === "string") return entry.trim() ? oneLine(entry) : null;
10316
+ if (!isRecord(entry)) return null;
10317
+ for (const key of Object.keys(entry)) if (key !== "label" && key !== "description") return null;
10318
+ if (typeof entry.label !== "string" || !entry.label.trim()) return null;
10319
+ const label = oneLine(entry.label);
10320
+ if (entry.description === void 0) return label;
10321
+ if (typeof entry.description !== "string") return null;
10322
+ return entry.description.trim() ? `**${label}** — ${oneLine(entry.description)}` : label;
10323
+ }
10324
+ /**
10325
+ * A List of literal text items as a markdown list (`marker: "number"` →
10326
+ * `1. …`, otherwise `- …`), or null when it binds its items, renders
10327
+ * `children`, or any item is not plain text.
10328
+ */
10329
+ function listToMarkdown(c) {
10330
+ const children = c.children;
10331
+ if (children != null && !(Array.isArray(children) && children.length === 0)) return null;
10332
+ if (!Array.isArray(c.items) || c.items.length === 0) return null;
10333
+ const lines = [];
10334
+ for (const entry of c.items) {
10335
+ const line = listEntryMarkdown(entry);
10336
+ if (line === null) return null;
10337
+ lines.push(line);
10338
+ }
10339
+ if (c.marker === "number") {
10340
+ const start = typeof c.start === "number" && Number.isInteger(c.start) ? c.start : 1;
10341
+ return lines.map((line, i) => `${start + i}. ${line}`).join("\n");
10342
+ }
10343
+ return lines.map((line) => `- ${line}`).join("\n");
10344
+ }
10345
+ /** The prose item a component converts to, or null when it is not prose. */
10346
+ function toProseItem(c) {
10347
+ if (!c) return null;
10348
+ if (c.accessibility !== void 0) return null;
10349
+ if (c.component === "Divider") return { kind: "divider" };
10350
+ if (c.component === "Spacer") return { kind: "spacer" };
10351
+ if (c.component === "List") {
10352
+ if (c.direction !== void 0 && c.direction !== "vertical") return null;
10353
+ const markdown = listToMarkdown(c);
10354
+ return markdown === null ? null : {
10355
+ kind: "text",
10356
+ markdown
10357
+ };
10358
+ }
10359
+ if (typeof c.component !== "string") return null;
10360
+ if (!PROSE_TEXT_COMPONENTS.has(c.component)) return null;
10361
+ if (typeof c.text !== "string" || c.text.trim() === "") return null;
10362
+ const text = c.text.trim();
10363
+ switch (c.component) {
10364
+ case "Title": {
10365
+ const size = typeof c.size === "string" ? c.size : "md";
10366
+ return {
10367
+ kind: "text",
10368
+ markdown: `${size === "sm" ? "####" : size === "md" || size === "lg" ? "###" : "##"} ${text}`
10369
+ };
10370
+ }
10371
+ case "Text":
10372
+ if (directChildIds(c).length > 0) return null;
10373
+ return {
10374
+ kind: "text",
10375
+ markdown: c.strong === true ? `**${text}**` : text
10376
+ };
10377
+ default: return {
10378
+ kind: "text",
10379
+ markdown: text
10380
+ };
10381
+ }
10382
+ }
10383
+ /** Prose items as markdown: separators only survive between two text items. */
10384
+ function proseItemsToMarkdown(items) {
10385
+ const blocks = [];
10386
+ let pendingDivider = false;
10387
+ for (const item of items) if (item?.kind === "text") {
10388
+ if (pendingDivider && blocks.length > 0) blocks.push("---");
10389
+ pendingDivider = false;
10390
+ blocks.push(item.markdown);
10391
+ } else if (item?.kind === "divider") pendingDivider = true;
10392
+ return blocks.join("\n\n");
10393
+ }
10394
+ /** Column, column-direction Box, or an informational Card (section/unset variant). */
10395
+ function isVerticalStack(c, interactiveCards) {
10396
+ if (c.accessibility !== void 0) return false;
10397
+ if (c.component === "Column") return true;
10398
+ if (c.component === "Box") return c.direction == null || c.direction === "col";
10399
+ if (c.component === "Card") return (c.variant == null || c.variant === "section") && typeof c.id === "string" && !interactiveCards.has(c.id);
10400
+ return false;
10401
+ }
10402
+ /** The child-id list of a stack (`children`, or a lone `child`), else null. */
10403
+ /**
10404
+ * The children of a stack in render order: `child` first (a Card renders
10405
+ * its `child` before its `children`), then `children`.
10406
+ */
10407
+ function stackChildren(c) {
10408
+ const first = typeof c.child === "string" ? [c.child] : [];
10409
+ if (Array.isArray(c.children)) return [...first, ...c.children];
10410
+ if (first.length > 0 && c.children === void 0) return first;
10411
+ return null;
10412
+ }
10413
+ /**
10414
+ * Partitions the stack's children into alternating prose and surface runs.
10415
+ * A run of consecutive prose items is prose only when it holds text: a run of
10416
+ * separators alone (Divider/Spacer between two UI components, or at the very
10417
+ * start/end of the stack) stays with the surface it sits in.
10418
+ */
10419
+ function partitionChildren(items) {
10420
+ const runs = [];
10421
+ let i = 0;
10422
+ while (i < items.length) {
10423
+ const candidate = items[i] !== null;
10424
+ let hasText = false;
10425
+ let j = i;
10426
+ while (j < items.length && items[j] !== null === candidate) {
10427
+ if (items[j]?.kind === "text") hasText = true;
10428
+ j++;
10429
+ }
10430
+ const prose = candidate && hasText;
10431
+ const last = runs[runs.length - 1];
10432
+ if (!prose && last && !last.prose) last.end = j;
10433
+ else runs.push({
10434
+ prose,
10435
+ start: i,
10436
+ end: j
10437
+ });
10438
+ i = j;
10439
+ }
10440
+ return runs;
10441
+ }
10442
+ /**
10443
+ * Markdown mode: split a surface into markdown and surface segments so that
10444
+ * only real UI renders as A2UI and everything else is the chat's markdown.
10445
+ *
10446
+ * From `root`, descend through single-child vertical containers (Column,
10447
+ * column Box, informational Card) to the first one with several children:
10448
+ * the stack. Its children are partitioned, in order, into runs of prose and
10449
+ * runs of UI. Prose is `Title`, `Text`, `Caption`, `Markdown` with literal
10450
+ * text, a `List` of literal text items, plus `Divider`/`Spacer` next to them:
10451
+ * `Title` → heading by size (sm `####`, md/lg `###`, larger `##`), `Text` →
10452
+ * paragraph (`strong` → `**…**`), `Caption`/`Markdown` → paragraph, `List` →
10453
+ * `- …` (or `1. …` for `marker: "number"`, `**label** — description` for
10454
+ * described items), and a `Divider` between two prose blocks → `---`.
10455
+ *
10456
+ * Not prose: `{path}`-bound text or items, a Text with inline children, a
10457
+ * List with `children`/icons/actions, a template entry, a component with an
10458
+ * `accessibility` envelope, and a child whose component has not streamed
10459
+ * yet. Separators with no text beside them stay in
10460
+ * the surface. An interactive Card (see `classifySurfaceCards`) is never
10461
+ * entered.
10462
+ *
10463
+ * Each prose run becomes a markdown segment; each UI run becomes a surface
10464
+ * segment whose `root` is a copy of the stack (its other props kept, `child`
10465
+ * dropped) with only that run's `children`, followed by every component
10466
+ * reachable from them. When nothing is prose the input comes back as the one
10467
+ * surface segment (same array); when everything is (or `root` itself is),
10468
+ * there are only markdown segments.
10469
+ *
10470
+ * Pure and linear in the number of components, so it runs on every stream
10471
+ * update.
10472
+ *
10473
+ * @param components - The components of one surface, root included.
10474
+ * @returns The segments in render order.
10475
+ *
10476
+ * @example
10477
+ * ```ts
10478
+ * for (const segment of segmentSurfaceProse(components)) {
10479
+ * if (segment.kind === "markdown") renderMarkdown(segment.markdown);
10480
+ * else renderSurface(segment.components);
10481
+ * }
10482
+ * ```
10483
+ */
10484
+ function segmentSurfaceProse(components, options = {}) {
10485
+ const unchanged = [{
10486
+ kind: "surface",
10487
+ components
10488
+ }];
10489
+ const byId = /* @__PURE__ */ new Map();
10490
+ for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
10491
+ const root = byId.get(GENERATIVE_UI_ROOT_ID);
10492
+ if (!root) return unchanged;
10493
+ if (components.some((c) => isRecord(c) && options.childIds?.(c) === "unknown")) return unchanged;
10494
+ const rootItem = toProseItem(root);
10495
+ if (rootItem?.kind === "text") return [{
10496
+ kind: "markdown",
10497
+ markdown: rootItem.markdown
10498
+ }];
10499
+ const interactiveCards = classifySurfaceCards(components, options);
10500
+ let stack = root;
10501
+ let stackId = GENERATIVE_UI_ROOT_ID;
10502
+ let children;
10503
+ const visited = /* @__PURE__ */ new Set();
10504
+ while (true) {
10505
+ if (!isVerticalStack(stack, interactiveCards)) return unchanged;
10506
+ visited.add(stackId);
10507
+ const list = stackChildren(stack);
10508
+ if (!list) return unchanged;
10509
+ children = list;
10510
+ const nextId = list.length === 1 ? list[0] : void 0;
10511
+ if (typeof nextId !== "string") break;
10512
+ const next = byId.get(nextId);
10513
+ if (!next || visited.has(nextId) || toProseItem(next)) break;
10514
+ stack = next;
10515
+ stackId = nextId;
10516
+ }
10517
+ const stackChildIds = children;
10518
+ const items = stackChildIds.map((id) => typeof id === "string" ? toProseItem(byId.get(id)) : null);
10519
+ const runs = partitionChildren(items);
10520
+ if (!runs.some((run) => run.prose)) return unchanged;
10521
+ const surfaceRuns = runs.filter((run) => !run.prose);
10522
+ const owners = /* @__PURE__ */ new Map();
10523
+ surfaceRuns.forEach((run, index) => {
10524
+ const pending = stackChildIds.slice(run.start, run.end).map(referencedId).filter((id) => id !== void 0);
10525
+ const seen = /* @__PURE__ */ new Set();
10526
+ while (pending.length > 0) {
10527
+ const id = pending.pop();
10528
+ if (id === GENERATIVE_UI_ROOT_ID || id === stackId || seen.has(id)) continue;
10529
+ seen.add(id);
10530
+ const list = owners.get(id);
10531
+ if (list) list.push(index);
10532
+ else owners.set(id, [index]);
10533
+ const c = byId.get(id);
10534
+ if (c) pending.push(...directChildIds(c, options.childIds));
10535
+ }
10536
+ });
10537
+ const surfaceComponents = surfaceRuns.map((run) => {
10538
+ const { child: _child, ...stackRest } = stack;
10539
+ const nextRoot = {
10540
+ ...stackRest,
10541
+ id: GENERATIVE_UI_ROOT_ID,
10542
+ children: stackChildIds.slice(run.start, run.end)
10543
+ };
10544
+ delete nextRoot.child;
10545
+ return [nextRoot];
10546
+ });
10547
+ for (const c of components) {
10548
+ if (!isRecord(c) || typeof c.id !== "string" || byId.get(c.id) !== c) continue;
10549
+ const ownerIndexes = owners.get(c.id) ?? [];
10550
+ for (const index of ownerIndexes) surfaceComponents[index].push(c);
10551
+ }
10552
+ let surfaceIndex = 0;
10553
+ return runs.map((run) => {
10554
+ if (run.prose) return {
10555
+ kind: "markdown",
10556
+ markdown: proseItemsToMarkdown(items.slice(run.start, run.end))
10557
+ };
10558
+ return {
10559
+ kind: "surface",
10560
+ components: surfaceComponents[surfaceIndex++]
10561
+ };
10562
+ });
10563
+ }
10564
+
10565
+ //#endregion
10566
+ export { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵisCopilotKitFeature, ɵisHttpAgent, isRetryableStatus as ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵthreadAdapterEvents, ɵwithHeaderDefaults };
8882
10567
  //# sourceMappingURL=index.mjs.map