@copilotkit/core 1.84.2-canary.1793807121 → 1.84.2-canary.openbot-intel-fixes

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_a2ui_markdown = require('./a2ui-markdown-DkMXFQih.cjs');
2
3
  let _tanstack_pacer = require("@tanstack/pacer");
3
4
  let _ag_ui_client = require("@ag-ui/client");
4
5
  let _copilotkit_shared = require("@copilotkit/shared");
@@ -7,7 +8,6 @@ let rxjs_operators = require("rxjs/operators");
7
8
  let phoenix = require("phoenix");
8
9
  let zod_to_json_schema = require("zod-to-json-schema");
9
10
  let _copilotkit_learning = require("@copilotkit/learning");
10
- let jsonrepair = require("jsonrepair");
11
11
 
12
12
  //#region src/utils/http-agent.ts
13
13
  /**
@@ -27,15 +27,6 @@ function ɵisHttpAgent(agent) {
27
27
 
28
28
  //#endregion
29
29
  //#region src/utils/connect-replay.ts
30
- const connectRunErrorPhases = /* @__PURE__ */ new WeakMap();
31
- /**
32
- * The phase in which a connection received `event`, as recorded when it
33
- * arrived. Events that did not come through a connection with replay
34
- * boundaries report `unknown`.
35
- */
36
- function ɵgetConnectRunErrorPhase(event) {
37
- return connectRunErrorPhases.get(event) ?? "unknown";
38
- }
39
30
  /**
40
31
  * Runs an agent's `connect()` stream through the AbstractAgent apply pipeline
41
32
  * with the `verifyEvents` step omitted.
@@ -90,7 +81,6 @@ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber,
90
81
  let result;
91
82
  const previousMessageIds = new Set(agent.messages.map((m) => m.id));
92
83
  let isReplaying = true;
93
- let reportsReplayPhase = false;
94
84
  const liveErrors = /* @__PURE__ */ new WeakSet();
95
85
  const subscribers = [
96
86
  {
@@ -138,19 +128,15 @@ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber,
138
128
  };
139
129
  const lifecycle = {
140
130
  onReplayStarted: () => {
141
- reportsReplayPhase = true;
142
131
  isReplaying = true;
143
132
  agent.isRunning = true;
144
133
  },
145
134
  onReplayFinished: () => {
146
- reportsReplayPhase = true;
147
135
  isReplaying = false;
148
136
  }
149
137
  };
150
138
  const source$ = (0, rxjs.defer)(() => new _ag_ui_client.CompatibilityBoundary().run(input, { run: () => connect ? connect(input, lifecycle) : self.connect(input) })).pipe((0, rxjs_operators.tap)((event) => {
151
- if (event.type !== _ag_ui_client.EventType.RUN_ERROR) return;
152
- if (!isReplaying) liveErrors.add(event);
153
- if (reportsReplayPhase) connectRunErrorPhases.set(event, isReplaying ? "replay" : "live");
139
+ if (!isReplaying && event.type === _ag_ui_client.EventType.RUN_ERROR) liveErrors.add(event);
154
140
  }), (0, _ag_ui_client.transformChunks)(self.debugLogger), (0, rxjs_operators.takeUntil)(activeRunDetach$));
155
141
  const applied$ = self.apply(input, source$, subscribers);
156
142
  await (0, rxjs.lastValueFrom)(self.processApplyEvents(input, applied$, subscribers).pipe((0, rxjs_operators.catchError)((error) => {
@@ -317,20 +303,6 @@ var AgentThreadLockedError = class extends Error {
317
303
  }
318
304
  };
319
305
  /**
320
- * The gateway could not replay a live run's events, so the client cannot
321
- * verify the run it is following. The run itself may still be going on the
322
- * server; reconnecting to the thread shows its real state.
323
- */
324
- var IntelligenceReplayFailedError = class extends Error {
325
- code = "INTELLIGENCE_REPLAY_FAILED";
326
- constructor(threadId, runId) {
327
- super("The run's events could not be replayed. Reconnect to the thread to check the run's status.");
328
- this.threadId = threadId;
329
- this.runId = runId;
330
- this.name = "IntelligenceReplayFailedError";
331
- }
332
- };
333
- /**
334
306
  * Type guard for {@link RunCompletionAware}. Returns true when `agent` exposes
335
307
  * an `activeRunCompletionPromise` property, so callers can await an in-flight
336
308
  * run without an `as unknown as` cast. Returns false for agents that don't
@@ -344,6 +316,12 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
344
316
  socket = null;
345
317
  activeChannel = null;
346
318
  canonicalRunId = null;
319
+ /**
320
+ * Counts the runs and connects this agent has started. A stop settles later
321
+ * than it is sent, so it compares this to tell whether a newer run has taken
322
+ * over the agent in the meantime.
323
+ */
324
+ runGeneration = 0;
347
325
  sharedState;
348
326
  constructor(config, sharedState = { lastSeenEventIds: /* @__PURE__ */ new Map() }) {
349
327
  super();
@@ -413,18 +391,27 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
413
391
  return ɵconnectWithoutEventVerification(this, effectiveParameters, subscriber, (input, lifecycle) => this.connect(input, lifecycle));
414
392
  }
415
393
  abortRun() {
416
- if (this.activeChannel && this.canonicalRunId) {
417
- const fallback = setTimeout(() => clear(), 5e3);
418
- const clear = () => {
419
- clearTimeout(fallback);
420
- this.detachActiveRun();
421
- this.cleanup();
422
- };
423
- this.activeChannel.push(STOP_RUN_EVENT, { run_id: this.canonicalRunId }).receive("ok", clear).receive("error", clear).receive("timeout", clear);
424
- } else {
394
+ const channel = this.activeChannel;
395
+ const runId = this.canonicalRunId;
396
+ if (!channel || !runId) {
425
397
  this.detachActiveRun();
426
398
  this.cleanup();
399
+ return;
427
400
  }
401
+ const socket = this.socket;
402
+ const generation = this.runGeneration;
403
+ let settled = false;
404
+ const clear = () => {
405
+ if (settled) return;
406
+ settled = true;
407
+ clearTimeout(fallback);
408
+ if (this.runGeneration === generation) {
409
+ this.detachActiveRun();
410
+ this.cleanup();
411
+ } else this.cleanupOwned(channel, socket, runId);
412
+ };
413
+ const fallback = setTimeout(clear, 5e3);
414
+ channel.push(STOP_RUN_EVENT, { run_id: runId }).receive("ok", clear).receive("error", clear).receive("timeout", clear);
428
415
  }
429
416
  /**
430
417
  * Trigger the run via REST, then join the realtime thread channel and relay
@@ -432,6 +419,7 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
432
419
  */
433
420
  run(input) {
434
421
  if (!isMcpResourceRead(input)) {
422
+ this.runGeneration += 1;
435
423
  this.threadId = input.threadId;
436
424
  this.canonicalRunId = input.runId;
437
425
  }
@@ -472,6 +460,7 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
472
460
  * entire history every time the chat re-opens a socket.
473
461
  */
474
462
  connect(input, lifecycle) {
463
+ this.runGeneration += 1;
475
464
  this.threadId = input.threadId;
476
465
  this.canonicalRunId = null;
477
466
  const replayCursor = this.getReconnectCursor(input);
@@ -493,9 +482,10 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
493
482
  /**
494
483
  * Tear down a specific channel + socket pair that belongs to one pipeline.
495
484
  * Only nulls instance references when they still point to the owned resource,
496
- * so a concurrent pipeline's resources are never clobbered.
485
+ * and the run ID only while it is still the owner's, so a concurrent
486
+ * pipeline's resources are never clobbered.
497
487
  */
498
- cleanupOwned(ownChannel, ownSocket) {
488
+ cleanupOwned(ownChannel, ownSocket, ownRunId) {
499
489
  if (ownChannel) {
500
490
  ownChannel.leave();
501
491
  if (this.activeChannel === ownChannel) this.activeChannel = null;
@@ -504,10 +494,10 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
504
494
  ownSocket.disconnect();
505
495
  if (this.socket === ownSocket) this.socket = null;
506
496
  }
507
- this.canonicalRunId = null;
497
+ if (this.canonicalRunId === ownRunId) this.canonicalRunId = null;
508
498
  }
509
499
  cleanup() {
510
- this.cleanupOwned(this.activeChannel, this.socket);
500
+ this.cleanupOwned(this.activeChannel, this.socket, this.canonicalRunId);
511
501
  }
512
502
  requestJoinCredentials$(mode, input, replayCursor) {
513
503
  return (0, rxjs.defer)(async () => {
@@ -600,6 +590,7 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
600
590
  options.lifecycle?.onReplayStarted?.();
601
591
  let ownSocket = null;
602
592
  let ownChannel = null;
593
+ const ownRunId = this.canonicalRunId;
603
594
  let replayFinished = false;
604
595
  let warnedAboutIdle = false;
605
596
  let idleWarning;
@@ -656,11 +647,6 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
656
647
  };
657
648
  const replayFailed$ = channel$.pipe((0, rxjs_operators.switchMap)(({ channel }) => this.observeChannelEvent$(channel, REPLAY_FAILED_EVENT)), (0, rxjs_operators.tap)(() => {
658
649
  controlCursor.replayFailed = true;
659
- if (options.streamMode === "run") {
660
- if (reconnectCursor === null) this.clearReconnectCursor(input.threadId);
661
- else this.advanceLastSeenEventId(input.threadId, reconnectCursor);
662
- throw new IntelligenceReplayFailedError(input.threadId, input.runId ?? null);
663
- }
664
650
  }));
665
651
  const replayComplete$ = this.observeControlEvent$(input.threadId, channel$, REPLAY_COMPLETE_EVENT, controlCursor).pipe((0, rxjs_operators.tap)(() => {
666
652
  replayFinished = true;
@@ -687,7 +673,7 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
687
673
  const terminal$ = (0, rxjs.merge)(threadCompleted$, streamIdleCompletion$);
688
674
  return (0, rxjs.merge)(replayFailed$.pipe((0, rxjs_operators.ignoreElements)(), (0, rxjs_operators.takeUntil)(terminal$)), replayComplete$.pipe((0, rxjs_operators.ignoreElements)(), (0, rxjs_operators.takeUntil)(terminal$)), this.joinThreadChannel$(channel$), this.observeSocketHealth$(socket$, options.onSocketOpen).pipe((0, rxjs_operators.takeUntil)(terminal$)), threadEvents$.pipe((0, rxjs_operators.takeUntil)(streamIdleCompletion$)), streamIdleCompletion$.pipe((0, rxjs_operators.ignoreElements)(), (0, rxjs_operators.takeUntil)(threadCompleted$))).pipe((0, rxjs_operators.finalize)(() => {
689
675
  clearIdleWarning();
690
- this.cleanupOwned(ownChannel, ownSocket);
676
+ this.cleanupOwned(ownChannel, ownSocket, ownRunId);
691
677
  }));
692
678
  });
693
679
  }
@@ -3996,17 +3982,6 @@ var WebMCPRegistry = class {
3996
3982
  */
3997
3983
  const liveHITLStops = /* @__PURE__ */ new WeakMap();
3998
3984
  /**
3999
- * Edits `agent.messages` by replacing the array instead of changing it in
4000
- * place. The current array may be the one the agent emitted with its last
4001
- * update, which subscribers and stored snapshots still hold. Like the in-place
4002
- * edit it replaces, this notifies no subscriber.
4003
- */
4004
- function editAgentMessages(agent, edit) {
4005
- const messages = [...agent.messages];
4006
- edit(messages);
4007
- agent.messages = messages;
4008
- }
4009
- /**
4010
3985
  * The message a failed tool call reports. An error thrown with an empty
4011
3986
  * message still means the call failed, so it gets a fallback rather than an
4012
3987
  * empty string, which everything downstream reads as success.
@@ -4382,7 +4357,7 @@ var RunHandler = class {
4382
4357
  forwardedProps: this._internal.getPropertiesForAgent(agent.agentId),
4383
4358
  tools: this.buildFrontendTools(agent.agentId),
4384
4359
  context: this._internal.getContextForAgent(agent.agentId)
4385
- }, this.createAgentErrorSubscriber(agent, "connect"));
4360
+ }, this.createAgentErrorSubscriber(agent));
4386
4361
  if (this._connectionGenerations.get(agent) !== connection || (agent.threadId ?? null) !== incomingThreadId) return runAgentResult;
4387
4362
  const controller = new AbortController();
4388
4363
  const replay = this._interactionAbortControllers.get(agent) ?? {
@@ -4486,7 +4461,7 @@ var RunHandler = class {
4486
4461
  agent
4487
4462
  }), "Subscriber onAgentRunStarted error:");
4488
4463
  let logicalRunId = resumedRunId ?? runId;
4489
- const agentSubscriber = this.createAgentErrorSubscriber(agent, "run", controller.signal);
4464
+ const agentSubscriber = this.createAgentErrorSubscriber(agent, controller.signal);
4490
4465
  let started = false;
4491
4466
  const onRunStartedEvent = agentSubscriber.onRunStartedEvent;
4492
4467
  const onRunInitialized = agentSubscriber.onRunInitialized;
@@ -4606,7 +4581,7 @@ var RunHandler = class {
4606
4581
  if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
4607
4582
  existingResult = void 0;
4608
4583
  const agentMsgIdx = agent.messages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
4609
- if (agentMsgIdx !== -1) editAgentMessages(agent, (messages) => messages.splice(agentMsgIdx, 1));
4584
+ if (agentMsgIdx !== -1) agent.messages.splice(agentMsgIdx, 1);
4610
4585
  }
4611
4586
  if (!existingResult) {
4612
4587
  executing.add(executionKey);
@@ -4820,7 +4795,7 @@ var RunHandler = class {
4820
4795
  content: handlerResult.content,
4821
4796
  ...handlerResult.error ? { error: handlerResult.error } : {}
4822
4797
  };
4823
- editAgentMessages(agent, (messages) => messages.splice(insertAt, 0, toolMessage));
4798
+ agent.messages.splice(insertAt, 0, toolMessage);
4824
4799
  if (!handlerResult.error && tool?.followUp !== false) return true;
4825
4800
  }
4826
4801
  return false;
@@ -4913,7 +4888,7 @@ var RunHandler = class {
4913
4888
  content: toolCallResult,
4914
4889
  ...errorMessage ? { error: errorMessage } : {}
4915
4890
  };
4916
- editAgentMessages(agent, (messages) => messages.splice(insertAt, 0, toolMessage));
4891
+ agent.messages.splice(insertAt, 0, toolMessage);
4917
4892
  if (!errorMessage && wildcardTool?.followUp !== false) return true;
4918
4893
  }
4919
4894
  return false;
@@ -4967,7 +4942,7 @@ var RunHandler = class {
4967
4942
  content: "",
4968
4943
  toolCalls: [assistantToolCall]
4969
4944
  };
4970
- editAgentMessages(agent, (messages) => messages.push(assistantMessage));
4945
+ agent.messages.push(assistantMessage);
4971
4946
  let handlerResult = {
4972
4947
  content: "",
4973
4948
  result: "",
@@ -4990,8 +4965,8 @@ var RunHandler = class {
4990
4965
  ...handlerResult.error ? { error: handlerResult.error } : {}
4991
4966
  };
4992
4967
  const assistantIndex = agent.messages.findIndex((m) => m.id === assistantMessage.id);
4993
- if (assistantIndex !== -1) editAgentMessages(agent, (messages) => messages.splice(assistantIndex + 1, 0, toolResultMessage));
4994
- else editAgentMessages(agent, (messages) => messages.push(toolResultMessage));
4968
+ if (assistantIndex !== -1) agent.messages.splice(assistantIndex + 1, 0, toolResultMessage);
4969
+ else agent.messages.push(toolResultMessage);
4995
4970
  if (!handlerResult.error && followUp !== false) {
4996
4971
  if (typeof followUp === "string" && followUp !== "generate") {
4997
4972
  const userMessage = {
@@ -4999,7 +4974,7 @@ var RunHandler = class {
4999
4974
  role: "user",
5000
4975
  content: followUp
5001
4976
  };
5002
- editAgentMessages(agent, (messages) => messages.push(userMessage));
4977
+ agent.messages.push(userMessage);
5003
4978
  }
5004
4979
  await this._internal.waitForPendingFrameworkUpdates();
5005
4980
  await this.runAgent({ agent });
@@ -5069,7 +5044,7 @@ var RunHandler = class {
5069
5044
  /**
5070
5045
  * Create an agent error subscriber
5071
5046
  */
5072
- createAgentErrorSubscriber(agent, stream, runSignal) {
5047
+ createAgentErrorSubscriber(agent, runSignal) {
5073
5048
  const emitAgentError = async (error, code, extraContext = {}) => {
5074
5049
  const context = { ...extraContext };
5075
5050
  if (agent.agentId) context.agentId = agent.agentId;
@@ -5099,8 +5074,7 @@ var RunHandler = class {
5099
5074
  await emitAgentError(rawError, CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT, {
5100
5075
  source: "onRunErrorEvent",
5101
5076
  event,
5102
- runtimeErrorCode: event?.code,
5103
- phase: stream === "run" ? "live" : ɵgetConnectRunErrorPhase(event)
5077
+ runtimeErrorCode: event?.code
5104
5078
  });
5105
5079
  }
5106
5080
  };
@@ -7486,12 +7460,6 @@ let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode)
7486
7460
  CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
7487
7461
  CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
7488
7462
  CopilotKitCoreErrorCode["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
7489
- /**
7490
- * An agent emitted RUN_ERROR. `context.phase` (`RunErrorPhase`) is
7491
- * `"replay"` when the error belongs to stored thread history replayed on
7492
- * connect, `"live"` when the run is happening now, and `"unknown"` when the
7493
- * transport cannot tell. Show a live-failure notice only for `"live"`.
7494
- */
7495
7463
  CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
7496
7464
  CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
7497
7465
  CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
@@ -9537,1362 +9505,7 @@ function onInspectorViewThreadResult(handler) {
9537
9505
  }
9538
9506
 
9539
9507
  //#endregion
9540
- //#region src/a2ui-markdown/fence-parser.ts
9541
- /** Language of a fenced code block that carries A2UI operations. */
9542
- const A2UI_FENCE_LANGUAGE = "a2ui";
9543
- /** Column-0 fence opener: a run of 3+ backticks or tildes, then the info string. */
9544
- const FENCE_OPEN = /^(`{3,}|~{3,})(.*)$/;
9545
- /** Info-string token that names the placement target of an a2ui fence. */
9546
- const TARGET_TOKEN = /^target=(.+)$/;
9547
- function isCloser(line, fence) {
9548
- const trimmed = line.trim();
9549
- if (trimmed.length < fence.length) return false;
9550
- for (const ch of trimmed) if (ch !== fence.char) return false;
9551
- return true;
9552
- }
9553
- /** The id of the first `target=<id>` token. Other tokens are ignored. */
9554
- function readTarget(tokens) {
9555
- for (const token of tokens) {
9556
- const match = TARGET_TOKEN.exec(token);
9557
- if (match) return match[1];
9558
- }
9559
- }
9560
- function a2uiSegment(fence, text, closed) {
9561
- const segment = {
9562
- type: "a2ui",
9563
- index: fence.index,
9564
- text,
9565
- closed
9566
- };
9567
- if (fence.target !== void 0) segment.target = fence.target;
9568
- return segment;
9569
- }
9570
- /**
9571
- * Split a (possibly still streaming) markdown string into prose segments and
9572
- * top-level ```a2ui fences. Fences of other languages stay inside prose
9573
- * segments byte-for-byte, and a2ui markers inside them are ignored. Only
9574
- * column-0 fences are recognised, so a fence indented inside a list item is
9575
- * left to the markdown renderer.
9576
- *
9577
- * The first info-string token must be exactly `a2ui`. A later
9578
- * `target=<id>` token sets `target` on the segment (for example
9579
- * ```` ```a2ui target=recommendations ````). Other tokens are ignored.
9580
- *
9581
- * An a2ui segment's `text` is the fence body. For a closed fence it ends with
9582
- * "\n" when non-empty. For an open (still streaming or aborted) fence it is
9583
- * everything after the opener line, minus a half-streamed closing marker.
9584
- *
9585
- * @param markdown - The assistant message text, complete or still streaming.
9586
- * @returns The segments in source order.
9587
- *
9588
- * @example
9589
- * ```ts
9590
- * for (const segment of splitA2UIMarkdown(message.content)) {
9591
- * if (segment.type === "a2ui") renderSurface(segment.text, segment.target);
9592
- * else renderMarkdown(segment.text);
9593
- * }
9594
- * ```
9595
- */
9596
- function splitA2UIMarkdown(markdown) {
9597
- const segments = [];
9598
- let proseStart = 0;
9599
- let fence = null;
9600
- let a2uiIndex = 0;
9601
- const pushProse = (end) => {
9602
- if (end > proseStart) segments.push({
9603
- type: "markdown",
9604
- text: markdown.slice(proseStart, end)
9605
- });
9606
- };
9607
- let lineStart = 0;
9608
- while (lineStart <= markdown.length) {
9609
- const newline = markdown.indexOf("\n", lineStart);
9610
- const lineEnd = newline < 0 ? markdown.length : newline;
9611
- const hasCR = lineEnd > lineStart && markdown[lineEnd - 1] === "\r";
9612
- const line = markdown.slice(lineStart, hasCR ? lineEnd - 1 : lineEnd);
9613
- if (fence) {
9614
- if (isCloser(line, fence)) {
9615
- if (fence.index >= 0) {
9616
- const body = markdown.slice(fence.bodyStart, Math.max(fence.bodyStart, lineStart));
9617
- segments.push(a2uiSegment(fence, body, true));
9618
- proseStart = hasCR ? lineEnd - 1 : lineEnd;
9619
- }
9620
- fence = null;
9621
- }
9622
- } else {
9623
- const open = FENCE_OPEN.exec(line);
9624
- if (open) {
9625
- const marker = open[1] ?? "";
9626
- const info = open[2] ?? "";
9627
- const char = marker.charAt(0);
9628
- if (!(char === "`" && info.includes("`"))) {
9629
- const [lang = "", ...tokens] = info.trim().split(/\s+/);
9630
- const isA2UI = lang === A2UI_FENCE_LANGUAGE;
9631
- if (isA2UI) pushProse(lineStart);
9632
- fence = {
9633
- char,
9634
- length: marker.length,
9635
- bodyStart: newline < 0 ? markdown.length : lineEnd + 1,
9636
- index: isA2UI ? a2uiIndex++ : -1,
9637
- target: isA2UI ? readTarget(tokens) : void 0
9638
- };
9639
- }
9640
- }
9641
- }
9642
- if (newline < 0) break;
9643
- lineStart = newline + 1;
9644
- }
9645
- if (fence && fence.index >= 0) {
9646
- const { char } = fence;
9647
- let body = markdown.slice(fence.bodyStart);
9648
- const lastNewline = body.lastIndexOf("\n");
9649
- const lastLine = body.slice(lastNewline + 1).replace(/\r$/, "");
9650
- if (lastLine.length > 0 && [...lastLine].every((ch) => ch === char)) body = body.slice(0, lastNewline + 1);
9651
- segments.push(a2uiSegment(fence, body, false));
9652
- } else pushProse(markdown.length);
9653
- return segments;
9654
- }
9655
-
9656
- //#endregion
9657
- //#region src/a2ui-markdown/operations.ts
9658
- /** The operation keys that change a surface. */
9659
- const SURFACE_OP_KEYS = [
9660
- "createSurface",
9661
- "updateComponents",
9662
- "updateDataModel",
9663
- "deleteSurface"
9664
- ];
9665
- /** The operation key of an agent-called function. It has no surface. */
9666
- const FUNCTION_CALL_KEY = "callRendererFunction";
9667
- const OP_KEYS = [...SURFACE_OP_KEYS, FUNCTION_CALL_KEY];
9668
- function isRecord(value) {
9669
- return typeof value === "object" && value !== null && !Array.isArray(value);
9670
- }
9671
- function isWhitespace(ch) {
9672
- return ch === " " || ch === "\n" || ch === "\r" || ch === " ";
9673
- }
9674
- function skipWhitespace(s, i) {
9675
- while (i < s.length && isWhitespace(s[i])) i++;
9676
- return i;
9677
- }
9678
- /** Index of the closing quote of the JSON string opening at `start`, or -1. */
9679
- function findStringEnd(s, start) {
9680
- for (let i = start + 1; i < s.length; i++) {
9681
- if (s[i] === "\\") {
9682
- i++;
9683
- continue;
9684
- }
9685
- if (s[i] === "\"") return i;
9686
- }
9687
- return -1;
9688
- }
9689
- /**
9690
- * Find the first `"key":` whose value starts with `opener` and return the index
9691
- * of that opener, or -1.
9692
- */
9693
- function findKeyValue(s, key, opener) {
9694
- const needle = `"${key}"`;
9695
- let from = 0;
9696
- while (true) {
9697
- const k = s.indexOf(needle, from);
9698
- if (k < 0) return -1;
9699
- let i = skipWhitespace(s, k + needle.length);
9700
- if (s[i] === ":") {
9701
- i = skipWhitespace(s, i + 1);
9702
- if (s[i] === opener) return i;
9703
- }
9704
- from = k + 1;
9705
- }
9706
- }
9707
- /**
9708
- * Read `"key":"value"` from partial JSON. The first match anywhere in the
9709
- * text wins, at any depth.
9710
- *
9711
- * @param partialJson - JSON text that can still be streaming.
9712
- * @param key - The field name.
9713
- * @returns The string value, or null until its closing quote has arrived.
9714
- *
9715
- * @example
9716
- * ```ts
9717
- * extractStringField('{"createSurface":{"surfaceId":"plan","cat', "surfaceId"); // "plan"
9718
- * ```
9719
- */
9720
- function extractStringField(partialJson, key) {
9721
- const start = findKeyValue(partialJson, key, "\"");
9722
- if (start < 0) return null;
9723
- const end = findStringEnd(partialJson, start);
9724
- if (end < 0) return null;
9725
- try {
9726
- const value = JSON.parse(partialJson.slice(start, end + 1));
9727
- return typeof value === "string" ? value : null;
9728
- } catch {
9729
- return null;
9730
- }
9731
- }
9732
- function pushItem(raw, items) {
9733
- const trimmed = raw.trim();
9734
- if (!trimmed) return;
9735
- try {
9736
- items.push(JSON.parse(trimmed));
9737
- } catch {}
9738
- }
9739
- /**
9740
- * Find `"key":[` in partial JSON and return every complete item of that array
9741
- * so far, plus whether the array has closed. Items of a `components` array get
9742
- * structural-key depth repair: a component that lost closing braces is fixed
9743
- * when its `id`, `component`, `child` or `children` key shows where it ends.
9744
- *
9745
- * @param partialJson - JSON text that can still be streaming.
9746
- * @param key - The name of the array field.
9747
- * @returns `{ items, closed }`, or null when the key (with an array value)
9748
- * has not appeared yet.
9749
- *
9750
- * @example
9751
- * ```ts
9752
- * const result = extractCompleteArrayItems(streamedText, "components");
9753
- * if (result) render(result.items);
9754
- * ```
9755
- */
9756
- function extractCompleteArrayItems(partialJson, key) {
9757
- const open = findKeyValue(partialJson, key, "[");
9758
- if (open < 0) return null;
9759
- return completeArrayItemsAt(partialJson, open, { repairComponents: key === "components" });
9760
- }
9761
- /** Index of the last non-whitespace character before `i`, or -1. */
9762
- function prevNonWhitespace(s, i) {
9763
- let j = i - 1;
9764
- while (j >= 0 && isWhitespace(s[j])) j--;
9765
- return j;
9766
- }
9767
- /**
9768
- * Keys that only ever belong at a component's top level. Seen nested inside
9769
- * the component's objects, they mean the model forgot closing braces.
9770
- */
9771
- const STRUCTURAL_KEYS = new Set([
9772
- "id",
9773
- "component",
9774
- "child",
9775
- "children"
9776
- ]);
9777
- /** Whether a value starting with `ch` has the shape `key` takes on a component. */
9778
- function structuralValueFits(key, ch) {
9779
- if (key === "children") return ch === "[" || ch === "{";
9780
- return ch === "\"";
9781
- }
9782
- /** `{"id":` — a new component object starting at `i`. */
9783
- const COMPONENT_START = /^\{\s*"id"\s*:/;
9784
- /**
9785
- * Structural-key depth repair for one component item. While scanning, a
9786
- * structural key (`id`, `component`, `child`, `children`) found as an object
9787
- * key below the item's top level, with only objects (no arrays) between it
9788
- * and the item root, a value of the expected shape, and not already present
9789
- * at the top level, means closing braces were dropped: the missing `}` are
9790
- * synthesized right before it so it lands at the top level. Containers still
9791
- * open at the end are closed. Returns null when a string never terminates.
9792
- */
9793
- function repairComponentItem(item) {
9794
- const stack = [];
9795
- const topKeys = /* @__PURE__ */ new Set();
9796
- let out = "";
9797
- let copied = 0;
9798
- for (let i = 0; i < item.length; i++) {
9799
- const c = item[i];
9800
- if (c === "\"") {
9801
- const end = findStringEnd(item, i);
9802
- if (end < 0) return null;
9803
- const prev = prevNonWhitespace(item, i);
9804
- const prevCh = item[prev];
9805
- const colon = skipWhitespace(item, end + 1);
9806
- if (stack[stack.length - 1] === "{" && (prevCh === "," || prevCh === "{") && item[colon] === ":") {
9807
- let key;
9808
- try {
9809
- key = JSON.parse(item.slice(i, end + 1));
9810
- } catch {
9811
- return null;
9812
- }
9813
- if (typeof key === "string") {
9814
- if (stack.length === 1) topKeys.add(key);
9815
- else if (STRUCTURAL_KEYS.has(key) && !topKeys.has(key) && stack.every((x) => x === "{") && structuralValueFits(key, item[skipWhitespace(item, colon + 1)])) {
9816
- const closers = "}".repeat(stack.length - 1);
9817
- if (prevCh === ",") {
9818
- out += item.slice(copied, prev) + closers;
9819
- copied = prev;
9820
- } else {
9821
- out += item.slice(copied, i) + closers + ",";
9822
- copied = i;
9823
- }
9824
- stack.length = 1;
9825
- topKeys.add(key);
9826
- }
9827
- }
9828
- }
9829
- i = end;
9830
- continue;
9831
- }
9832
- if (c === "{" || c === "[") stack.push(c);
9833
- else if (c === "}" || c === "]") {
9834
- stack.pop();
9835
- if (stack.length === 0) return out + item.slice(copied, i + 1);
9836
- }
9837
- }
9838
- const closers = stack.reduceRight((text, opener) => text + (opener === "{" ? "}" : "]"), "");
9839
- return out + item.slice(copied) + closers;
9840
- }
9841
- function parseRecord(text) {
9842
- if (text === null) return void 0;
9843
- try {
9844
- const value = JSON.parse(text);
9845
- return isRecord(value) ? value : void 0;
9846
- } catch {
9847
- return;
9848
- }
9849
- }
9850
- /**
9851
- * Complete items of the (possibly unterminated) array whose "[" is at `open`.
9852
- * With `repairComponents`, an item that balanced but does not parse is retried
9853
- * with structural-key repair, and a `,{"id":` where an item expects a key
9854
- * ends that (unbalanced) item there, so one malformed component cannot
9855
- * swallow the rest of the array; the cut item is kept only if repair makes
9856
- * it parse.
9857
- */
9858
- function completeArrayItemsAt(partialJson, open, options) {
9859
- const { repairComponents } = options;
9860
- const s = partialJson;
9861
- const items = [];
9862
- const stack = [];
9863
- let inString = false;
9864
- let itemStart = -1;
9865
- const finishItem = (end, balanced) => {
9866
- const raw = s.slice(itemStart, end);
9867
- if (!repairComponents) {
9868
- pushItem(raw, items);
9869
- return;
9870
- }
9871
- if (balanced) try {
9872
- items.push(JSON.parse(raw));
9873
- return;
9874
- } catch {}
9875
- const repaired = parseRecord(repairComponentItem(raw.trim()));
9876
- if (repaired !== void 0) items.push(repaired);
9877
- };
9878
- for (let i = open + 1; i < s.length; i++) {
9879
- const c = s[i];
9880
- if (inString) {
9881
- if (c === "\\") i++;
9882
- else if (c === "\"") inString = false;
9883
- continue;
9884
- }
9885
- if (c === "\"") {
9886
- inString = true;
9887
- if (stack.length === 0 && itemStart < 0) itemStart = i;
9888
- continue;
9889
- }
9890
- if (c === "{" || c === "[") {
9891
- if (repairComponents && c === "{" && stack[stack.length - 1] === "{" && COMPONENT_START.test(s.slice(i, i + 24))) {
9892
- const prev = prevNonWhitespace(s, i);
9893
- if (s[prev] === ",") {
9894
- finishItem(prev, false);
9895
- stack.length = 0;
9896
- itemStart = i;
9897
- stack.push(c);
9898
- continue;
9899
- }
9900
- }
9901
- if (stack.length === 0) itemStart = i;
9902
- stack.push(c);
9903
- continue;
9904
- }
9905
- if (c === "}" || c === "]") {
9906
- if (stack.length === 0) {
9907
- if (c === "]") {
9908
- if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
9909
- return {
9910
- items,
9911
- closed: true
9912
- };
9913
- }
9914
- return {
9915
- items,
9916
- closed: false
9917
- };
9918
- }
9919
- stack.pop();
9920
- if (stack.length === 0) {
9921
- finishItem(i + 1, true);
9922
- itemStart = -1;
9923
- }
9924
- continue;
9925
- }
9926
- if (stack.length === 0) {
9927
- if (c === ",") {
9928
- if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
9929
- itemStart = -1;
9930
- } else if (itemStart < 0 && !isWhitespace(c)) itemStart = i;
9931
- }
9932
- }
9933
- return {
9934
- items,
9935
- closed: false
9936
- };
9937
- }
9938
- /** The first operation key whose value is an object, with that value. */
9939
- function getOperationEntry(op) {
9940
- for (const key of OP_KEYS) {
9941
- const inner = op[key];
9942
- if (isRecord(inner)) return {
9943
- key,
9944
- inner
9945
- };
9946
- }
9947
- return null;
9948
- }
9949
- /**
9950
- * The surfaceId an operation targets: the one nested under its operation key,
9951
- * else a top-level `surfaceId`. A `callRendererFunction` operation targets no
9952
- * surface, so it gets undefined.
9953
- *
9954
- * It is named `getMarkdownOperationSurfaceId` because `@copilotkit/shared`
9955
- * already exports a strict `getOperationSurfaceId`. This one also reads a
9956
- * top-level `surfaceId`, which models sometimes write.
9957
- *
9958
- * @param op - An operation from an a2ui fence.
9959
- * @returns The surfaceId, or undefined when the operation names none or is a
9960
- * function call.
9961
- *
9962
- * @example
9963
- * ```ts
9964
- * getMarkdownOperationSurfaceId({ updateDataModel: { surfaceId: "plan" } }); // "plan"
9965
- * ```
9966
- */
9967
- function getMarkdownOperationSurfaceId(op) {
9968
- if (getOperationEntry(op)?.key === FUNCTION_CALL_KEY) return void 0;
9969
- for (const key of SURFACE_OP_KEYS) {
9970
- const inner = op[key];
9971
- if (isRecord(inner) && typeof inner.surfaceId === "string") return inner.surfaceId;
9972
- }
9973
- return typeof op.surfaceId === "string" ? op.surfaceId : void 0;
9974
- }
9975
- /**
9976
- * Index just past the JSON value starting at `start`, or -1 when the value is
9977
- * still incomplete. A primitive at the very end of the input counts as
9978
- * incomplete, since more digits or letters may still stream in.
9979
- */
9980
- function findValueEnd(s, start) {
9981
- const c = s[start];
9982
- if (c === "\"") {
9983
- const end = findStringEnd(s, start);
9984
- return end < 0 ? -1 : end + 1;
9985
- }
9986
- if (c === "{" || c === "[") {
9987
- let depth = 0;
9988
- for (let i = start; i < s.length; i++) {
9989
- const ch = s[i];
9990
- if (ch === "\"") {
9991
- const end = findStringEnd(s, i);
9992
- if (end < 0) return -1;
9993
- i = end;
9994
- } else if (ch === "{" || ch === "[") depth++;
9995
- else if (ch === "}" || ch === "]") {
9996
- depth--;
9997
- if (depth === 0) return i + 1;
9998
- }
9999
- }
10000
- return -1;
10001
- }
10002
- let i = start;
10003
- while (i < s.length && !isWhitespace(s[i]) && !",}]".includes(s[i])) i++;
10004
- return i >= s.length ? -1 : i;
10005
- }
10006
- /**
10007
- * Walk the direct entries of the (possibly unterminated) JSON object whose "{"
10008
- * is at `objStart`, calling `visit` with each key and the index where its value
10009
- * starts. Nested objects and arrays are skipped whole, so keys inside them are
10010
- * never visited. Stops when `visit` returns true, at the object's end, or where
10011
- * the input runs out.
10012
- */
10013
- function visitDirectEntries(s, objStart, visit) {
10014
- let i = objStart + 1;
10015
- while (i < s.length) {
10016
- i = skipWhitespace(s, i);
10017
- const c = s[i];
10018
- if (c === ",") {
10019
- i++;
10020
- continue;
10021
- }
10022
- if (c !== "\"") return;
10023
- const keyEnd = findStringEnd(s, i);
10024
- if (keyEnd < 0) return;
10025
- let key;
10026
- try {
10027
- key = JSON.parse(s.slice(i, keyEnd + 1));
10028
- } catch {
10029
- return;
10030
- }
10031
- i = skipWhitespace(s, keyEnd + 1);
10032
- if (s[i] !== ":") return;
10033
- i = skipWhitespace(s, i + 1);
10034
- if (i >= s.length) return;
10035
- if (typeof key === "string" && visit(key, i)) return;
10036
- const valueEnd = findValueEnd(s, i);
10037
- if (valueEnd < 0) return;
10038
- i = valueEnd;
10039
- }
10040
- }
10041
- /**
10042
- * Value start of a direct `key` of the object at `objStart` whose value begins
10043
- * with `opener` (any value when omitted), or -1.
10044
- */
10045
- function findDirectKeyValue(s, objStart, key, opener) {
10046
- let found = -1;
10047
- visitDirectEntries(s, objStart, (k, valueStart) => {
10048
- if (k !== key) return false;
10049
- if (opener === void 0 || s[valueStart] === opener) found = valueStart;
10050
- return true;
10051
- });
10052
- return found;
10053
- }
10054
- /** A direct string field of the object at `objStart`, once its closing quote has arrived. */
10055
- function readDirectString(s, objStart, key) {
10056
- if (objStart < 0) return null;
10057
- const start = findDirectKeyValue(s, objStart, key, "\"");
10058
- if (start < 0) return null;
10059
- const end = findValueEnd(s, start);
10060
- if (end < 0) return null;
10061
- try {
10062
- const value = JSON.parse(s.slice(start, end));
10063
- return typeof value === "string" ? value : null;
10064
- } catch {
10065
- return null;
10066
- }
10067
- }
10068
- /** A direct object field of the object at `objStart`, once the whole object has arrived. */
10069
- function readDirectRecord(s, objStart, key) {
10070
- const start = findDirectKeyValue(s, objStart, key, "{");
10071
- if (start < 0) return void 0;
10072
- const end = findValueEnd(s, start);
10073
- if (end < 0) return void 0;
10074
- return parseRecord(s.slice(start, end));
10075
- }
10076
- /**
10077
- * The complete part of a (possibly unterminated) JSON value: the parsed value
10078
- * when it is complete; for an open object, its complete entries plus the
10079
- * complete items of any streaming array entry; otherwise undefined.
10080
- */
10081
- function completePartOfValue(s, start) {
10082
- const end = findValueEnd(s, start);
10083
- if (end >= 0) try {
10084
- return JSON.parse(s.slice(start, end));
10085
- } catch {
10086
- return;
10087
- }
10088
- if (s[start] !== "{") return void 0;
10089
- const out = {};
10090
- visitDirectEntries(s, start, (key, valueStart) => {
10091
- const valueEnd = findValueEnd(s, valueStart);
10092
- if (valueEnd >= 0) try {
10093
- out[key] = JSON.parse(s.slice(valueStart, valueEnd));
10094
- } catch {}
10095
- else if (s[valueStart] === "[") {
10096
- const { items } = completeArrayItemsAt(s, valueStart, { repairComponents: false });
10097
- if (items.length > 0) out[key] = items;
10098
- }
10099
- return false;
10100
- });
10101
- return Object.keys(out).length > 0 ? out : void 0;
10102
- }
10103
- /**
10104
- * Best-effort operation from an unfinished or malformed top-level object.
10105
- * Fields are read only from the operation's own keys (`version` at the top
10106
- * level, `surfaceId`, `catalogId`, `path`, `dataModel` and `components` inside
10107
- * the operation object), never from component props or data-model values that
10108
- * happen to share a name.
10109
- *
10110
- * A `createSurface` keeps its complete components and a `dataModel` that has
10111
- * fully arrived, so a surface created in one line renders while it streams.
10112
- * A `callRendererFunction` gives nothing: a function must not run with half
10113
- * of its args.
10114
- */
10115
- function partialOperation(line) {
10116
- const root = skipWhitespace(line, 0);
10117
- if (line[root] !== "{") return null;
10118
- const version = readDirectString(line, root, "version") ?? _copilotkit_shared.A2UI_VERSION;
10119
- const components = findDirectKeyValue(line, root, "updateComponents", "{");
10120
- if (components >= 0) {
10121
- const arrayStart = findDirectKeyValue(line, components, "components", "[");
10122
- if (arrayStart < 0) return null;
10123
- const { items } = completeArrayItemsAt(line, arrayStart, { repairComponents: true });
10124
- if (items.length === 0) return null;
10125
- const surfaceId = readDirectString(line, components, "surfaceId");
10126
- return {
10127
- version,
10128
- updateComponents: {
10129
- ...surfaceId ? { surfaceId } : {},
10130
- components: items
10131
- }
10132
- };
10133
- }
10134
- const data = findDirectKeyValue(line, root, "updateDataModel", "{");
10135
- if (data >= 0) {
10136
- const valueStart = findDirectKeyValue(line, data, "value");
10137
- if (valueStart < 0) return null;
10138
- const value = completePartOfValue(line, valueStart);
10139
- if (value === void 0) return null;
10140
- const surfaceId = readDirectString(line, data, "surfaceId");
10141
- const path = readDirectString(line, data, "path");
10142
- return {
10143
- version,
10144
- updateDataModel: {
10145
- ...surfaceId ? { surfaceId } : {},
10146
- ...path ? { path } : {},
10147
- value
10148
- }
10149
- };
10150
- }
10151
- const create = findDirectKeyValue(line, root, "createSurface", "{");
10152
- if (create >= 0) {
10153
- const surfaceId = readDirectString(line, create, "surfaceId");
10154
- if (!surfaceId) return null;
10155
- const catalogId = readDirectString(line, create, "catalogId");
10156
- const dataModel = readDirectRecord(line, create, "dataModel");
10157
- const componentsStart = findDirectKeyValue(line, create, "components", "[");
10158
- const components = componentsStart < 0 ? [] : completeArrayItemsAt(line, componentsStart, { repairComponents: true }).items;
10159
- return {
10160
- version,
10161
- createSurface: {
10162
- surfaceId,
10163
- ...catalogId ? { catalogId } : {},
10164
- ...dataModel ? { dataModel } : {},
10165
- ...components.length > 0 ? { components } : {}
10166
- }
10167
- };
10168
- }
10169
- return null;
10170
- }
10171
- /**
10172
- * A line that opens a new top-level operation: `{"version":"1…` or
10173
- * `{"<operation>":{`. Seen at the start of a line while an earlier object is
10174
- * still unbalanced, it means that object is malformed and has ended.
10175
- */
10176
- const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
10177
- /**
10178
- * Scan the top-level object whose "{" is at `start`. Returns the index just
10179
- * past it and whether it balanced. An unbalanced object ends early (at the
10180
- * start of the line) when a line opens a new operation; otherwise it runs to
10181
- * the end of the input. JSON strings cannot contain raw newlines, so a newline
10182
- * inside a string ends it: a stray quote then breaks one line, not the rest of
10183
- * the fence.
10184
- */
10185
- function scanTopLevelObject(s, start) {
10186
- let depth = 0;
10187
- let inString = false;
10188
- for (let i = start; i < s.length; i++) {
10189
- const c = s[i];
10190
- if (inString) {
10191
- if (c === "\\" && s[i + 1] !== "\n") i++;
10192
- else if (c === "\"" || c === "\n") inString = false;
10193
- if (c !== "\n") continue;
10194
- }
10195
- if (c === "\n") {
10196
- const next = skipWhitespace(s, i + 1);
10197
- if (OPERATION_START.test(s.slice(next, next + 40))) return {
10198
- end: i + 1,
10199
- balanced: false
10200
- };
10201
- continue;
10202
- }
10203
- if (c === "\"") inString = true;
10204
- else if (c === "{" || c === "[") depth++;
10205
- else if (c === "}" || c === "]") {
10206
- depth--;
10207
- if (depth === 0) return {
10208
- end: i + 1,
10209
- balanced: true
10210
- };
10211
- }
10212
- }
10213
- return {
10214
- end: s.length,
10215
- balanced: false
10216
- };
10217
- }
10218
- const OPERATION_NAMES = [
10219
- "createSurface",
10220
- "updateComponents",
10221
- "updateDataModel",
10222
- "deleteSurface",
10223
- "callRendererFunction"
10224
- ];
10225
- /** Whether a value is shaped like one A2UI operation, with named components. */
10226
- function isOperationShape(value) {
10227
- if (!isRecord(value) || value.version !== _copilotkit_shared.A2UI_VERSION) return false;
10228
- const names = OPERATION_NAMES.filter((name) => name in value);
10229
- if (names.length !== 1 || Object.keys(value).length !== 2) return false;
10230
- const body = value[names[0]];
10231
- if (!isRecord(body)) return false;
10232
- if (names[0] === "callRendererFunction") return true;
10233
- if (typeof body.surfaceId !== "string") return false;
10234
- const components = body.components;
10235
- return components === void 0 || Array.isArray(components) && components.every((c) => isRecord(c) && typeof c.id === "string" && typeof c.component === "string");
10236
- }
10237
- /** Openers minus closers ({ and [ against } and ]) outside strings. */
10238
- function closerImbalance(line) {
10239
- let depth = 0;
10240
- let inString = false;
10241
- for (let i = 0; i < line.length; i++) {
10242
- const c = line[i];
10243
- if (inString) {
10244
- if (c === "\\") i++;
10245
- else if (c === "\"") inString = false;
10246
- } else if (c === "\"") inString = true;
10247
- else if (c === "{" || c === "[") depth++;
10248
- else if (c === "}" || c === "]") depth--;
10249
- }
10250
- return depth;
10251
- }
10252
- /** The text with closers and whitespace removed, to compare a repair. */
10253
- function withoutClosers(text) {
10254
- return text.replace(/[\]}\s]/g, "");
10255
- }
10256
- /**
10257
- * Whether a component of the operation holds a structural key (`id`,
10258
- * `component`, `child`, `children`) in a nested object: a closer added at
10259
- * the end instead of where it was dropped. The scan below repairs those.
10260
- */
10261
- function nestsStructuralKey(value) {
10262
- const nests = (v) => isRecord(v) && Object.entries(v).some(([k, x]) => STRUCTURAL_KEYS.has(k) || nests(x));
10263
- const components = (isRecord(value) ? Object.values(value).find(isRecord) : void 0)?.components;
10264
- return Array.isArray(components) && components.some((c) => isRecord(c) && Object.values(c).some((prop) => nests(prop)));
10265
- }
10266
- /**
10267
- * Repairs the complete lines of a fence that are not valid JSON (a missing
10268
- * or extra brace) with jsonrepair, when the repair only adds or removes
10269
- * closers and the result is shaped like an operation. A line still streaming in (no newline yet) is left alone.
10270
- */
10271
- function repairFenceLines(fenceText) {
10272
- const repaired = [];
10273
- const lines = fenceText.split("\n");
10274
- if (fenceText.trimStart().startsWith("[")) return {
10275
- text: fenceText,
10276
- repaired
10277
- };
10278
- for (let n = 0; n < lines.length - 1; n++) {
10279
- const line = lines[n];
10280
- if (!line.trim().startsWith("{")) continue;
10281
- try {
10282
- JSON.parse(line);
10283
- continue;
10284
- } catch {}
10285
- const imbalance = closerImbalance(line);
10286
- if (Math.abs(imbalance) !== 1) continue;
10287
- const next = lines.slice(n + 1).find((l) => l.trim() !== "");
10288
- if (imbalance > 0 && next !== void 0 && !next.trim().startsWith("{")) continue;
10289
- try {
10290
- const fixed = (0, jsonrepair.jsonrepair)(line);
10291
- const value = JSON.parse(fixed);
10292
- if (withoutClosers(fixed) === withoutClosers(line) && isOperationShape(value) && !nestsStructuralKey(value) && !(isRecord(value) && "callRendererFunction" in value)) {
10293
- repaired.push(line.trim());
10294
- lines[n] = JSON.stringify(value);
10295
- }
10296
- } catch {}
10297
- }
10298
- return {
10299
- text: lines.join("\n"),
10300
- repaired
10301
- };
10302
- }
10303
- /**
10304
- * Parse the body of an a2ui fence as a stream of top-level JSON values, so
10305
- * operations may be one per line (the documented format), several per line,
10306
- * pretty-printed over many lines, or wrapped in a top-level array (which is
10307
- * flattened). Whitespace and commas between objects are ignored.
10308
- *
10309
- * - A balanced object is `JSON.parse`d. When that fails (e.g. a stray quote),
10310
- * its raw text goes to `invalidLines` and whatever `partialOperation` can
10311
- * salvage (complete components, data-model entries, createSurface fields)
10312
- * is kept.
10313
- * - An unbalanced object followed by a line that opens a new operation is
10314
- * treated the same way.
10315
- * - The trailing unbalanced object (still streaming, or never closed) is
10316
- * `partialObject` and yields a partial operation when it has usable data.
10317
- * - Other text between objects is skipped and reported in `recovered` (and in
10318
- * `invalidLines`, which predates it).
10319
- *
10320
- * `partialLine` is a deprecated alias of `partialObject`.
10321
- *
10322
- * @param fenceText - The body of an a2ui fence (`text` of an a2ui
10323
- * `MarkdownSegment`), complete or still streaming.
10324
- * @returns `{ operations, partialObject, partialLine, invalidLines, recovered }`.
10325
- *
10326
- * @example
10327
- * ```ts
10328
- * const { operations } = extractFenceOperations(segment.text);
10329
- * ```
10330
- */
10331
- function extractFenceOperations(fenceText) {
10332
- const { text: s, repaired: repairedLines } = repairFenceLines(fenceText);
10333
- const operations = [];
10334
- const invalidLines = [];
10335
- const recovered = [];
10336
- let partialObject = null;
10337
- const salvage = (raw) => {
10338
- invalidLines.push(raw.trim());
10339
- const partial = partialOperation(raw);
10340
- if (partial) operations.push(partial);
10341
- };
10342
- let junkStart = -1;
10343
- const flushJunk = (end) => {
10344
- if (junkStart < 0) return;
10345
- const junk = s.slice(junkStart, end).trim();
10346
- junkStart = -1;
10347
- if (!junk) return;
10348
- recovered.push(junk);
10349
- invalidLines.push(junk);
10350
- };
10351
- let i = 0;
10352
- while (i < s.length) {
10353
- const c = s[i];
10354
- if (c === "{") {
10355
- flushJunk(i);
10356
- const { end, balanced } = scanTopLevelObject(s, i);
10357
- const raw = s.slice(i, end);
10358
- if (balanced) {
10359
- let parsed;
10360
- try {
10361
- parsed = JSON.parse(raw);
10362
- } catch {
10363
- parsed = void 0;
10364
- }
10365
- if (isRecord(parsed)) operations.push(parsed);
10366
- else salvage(raw);
10367
- } else if (end < s.length) salvage(raw);
10368
- else {
10369
- partialObject = raw;
10370
- const partial = partialOperation(raw);
10371
- if (partial) operations.push(partial);
10372
- }
10373
- i = end;
10374
- continue;
10375
- }
10376
- if (c === "\n" || c === "[" || c === "]") flushJunk(i);
10377
- else if (junkStart < 0 && !isWhitespace(c) && c !== ",") junkStart = i;
10378
- i++;
10379
- }
10380
- flushJunk(s.length);
10381
- return {
10382
- operations,
10383
- partialObject,
10384
- partialLine: partialObject,
10385
- invalidLines,
10386
- recovered,
10387
- repairedLines
10388
- };
10389
- }
10390
- /**
10391
- * Normalise a fence's operations for the renderer: drop unknown messages, fill
10392
- * in `version` and missing `surfaceId`s, keep only the first `createSurface`,
10393
- * keep its `catalogId` when `catalogIds` lists it (else use `catalogId`), synthesize
10394
- * `createSurface` when the model omitted it, and report the
10395
- * surfaceId (the first one found, else `fallbackSurfaceId`).
10396
- *
10397
- * `callRendererFunction` operations target no surface. They get no surfaceId,
10398
- * do not cause a synthesized `createSurface`, and come back in
10399
- * `functionCalls` (in fence order), never in `operations`.
10400
- *
10401
- * @param input.operations - Operations from `extractFenceOperations`.
10402
- * @param input.fallbackSurfaceId - The surfaceId to use when no operation
10403
- * names one.
10404
- * @param input.catalogId - The client catalog. It replaces a catalogId of the
10405
- * model that `catalogIds` does not list.
10406
- * @param input.catalogIds - The catalogs that the model can name. Left out,
10407
- * only `catalogId`.
10408
- * @returns `{ surfaceId, operations, functionCalls }`.
10409
- *
10410
- * @example
10411
- * ```ts
10412
- * const { surfaceId, operations, functionCalls } = prepareSurfaceOperations({
10413
- * operations: extractFenceOperations(segment.text).operations,
10414
- * fallbackSurfaceId: `${messageId}-${segment.index}`,
10415
- * catalogId,
10416
- * });
10417
- * ```
10418
- */
10419
- function prepareSurfaceOperations(input) {
10420
- const { operations, fallbackSurfaceId, catalogId } = input;
10421
- const catalogIds = input.catalogIds ?? [catalogId];
10422
- const surfaceId = operations.map(getMarkdownOperationSurfaceId).find((id) => !!id) ?? fallbackSurfaceId;
10423
- const out = [];
10424
- const functionCalls = [];
10425
- let hasCreate = false;
10426
- for (const op of operations) {
10427
- const entry = getOperationEntry(op);
10428
- if (!entry) continue;
10429
- const { key } = entry;
10430
- const inner = { ...entry.inner };
10431
- const version = typeof op.version === "string" ? op.version : _copilotkit_shared.A2UI_VERSION;
10432
- if (key === FUNCTION_CALL_KEY) {
10433
- functionCalls.push({
10434
- version,
10435
- [key]: inner
10436
- });
10437
- continue;
10438
- }
10439
- if (typeof inner.surfaceId !== "string") inner.surfaceId = surfaceId;
10440
- if (key === "createSurface") {
10441
- if (hasCreate) {
10442
- const { surfaceId: id, dataModel, components } = inner;
10443
- if (dataModel !== void 0) out.push({
10444
- version,
10445
- updateDataModel: {
10446
- surfaceId: id,
10447
- path: "/",
10448
- value: dataModel
10449
- }
10450
- });
10451
- if (Array.isArray(components) && components.length > 0) out.push({
10452
- version,
10453
- updateComponents: {
10454
- surfaceId: id,
10455
- components
10456
- }
10457
- });
10458
- continue;
10459
- }
10460
- hasCreate = true;
10461
- if (!catalogIds.includes(inner.catalogId)) inner.catalogId = catalogId;
10462
- }
10463
- out.push({
10464
- version,
10465
- [key]: inner
10466
- });
10467
- }
10468
- if (!hasCreate && out.length > 0) out.unshift({
10469
- version: _copilotkit_shared.A2UI_VERSION,
10470
- createSurface: {
10471
- surfaceId,
10472
- catalogId
10473
- }
10474
- });
10475
- return {
10476
- surfaceId,
10477
- operations: out,
10478
- functionCalls
10479
- };
10480
- }
10481
- /**
10482
- * Components a user operates. A Card containing one of these is an
10483
- * interactive panel and keeps its box; every other Card is informational.
10484
- */
10485
- const INTERACTIVE_COMPONENTS = new Set([
10486
- "Button",
10487
- "Pressable",
10488
- "Form",
10489
- "TextField",
10490
- "TextArea",
10491
- "Select",
10492
- "CheckBox",
10493
- "Radio",
10494
- "RadioGroup",
10495
- "Slider",
10496
- "SegmentedControl",
10497
- "ChoicePicker",
10498
- "DateTimeInput"
10499
- ]);
10500
- /** A component id referenced by a `child`/`children` entry or a table cell. */
10501
- function referencedId(value) {
10502
- if (typeof value === "string") return value;
10503
- if (isRecord(value)) {
10504
- if (typeof value.componentId === "string") return value.componentId;
10505
- if (typeof value.id === "string") return value.id;
10506
- }
10507
- }
10508
- /** Ids of a table cell / column that renders a component (`{componentId}` or `{id}`). */
10509
- function cellComponentId(value) {
10510
- return isRecord(value) ? referencedId(value) : void 0;
10511
- }
10512
- /**
10513
- * Ids a component renders directly: `child`, `children` (string ids, an
10514
- * array, or a `{componentId}` template), component cells of a Table's
10515
- * `rows`/`columns`, and the ids that `extra` finds in its typed references.
10516
- */
10517
- function directChildIds(component, extra) {
10518
- const ids = [];
10519
- const add = (id) => {
10520
- if (id) ids.push(id);
10521
- };
10522
- const extraIds = extra?.(component);
10523
- if (Array.isArray(extraIds)) extraIds.forEach(add);
10524
- add(referencedId(component.child));
10525
- const children = component.children;
10526
- if (Array.isArray(children)) children.forEach((c) => add(referencedId(c)));
10527
- else add(referencedId(children));
10528
- if (Array.isArray(component.columns)) component.columns.forEach((c) => add(cellComponentId(c)));
10529
- if (Array.isArray(component.rows)) {
10530
- for (const row of component.rows) if (Array.isArray(row)) row.forEach((c) => add(cellComponentId(c)));
10531
- }
10532
- return ids;
10533
- }
10534
- /** Components of every updateComponents operation, by id (last definition wins). */
10535
- function componentsById(operations) {
10536
- const byId = /* @__PURE__ */ new Map();
10537
- for (const op of operations) {
10538
- const update = op.updateComponents;
10539
- const list = isRecord(update) ? update.components : void 0;
10540
- if (!Array.isArray(list)) continue;
10541
- for (const c of list) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
10542
- }
10543
- return byId;
10544
- }
10545
- function descendantIds(rootId, byId, extra) {
10546
- const seen = /* @__PURE__ */ new Set();
10547
- const stack = [...directChildIds(byId.get(rootId) ?? {}, extra)];
10548
- while (stack.length > 0) {
10549
- const id = stack.pop();
10550
- if (seen.has(id) || id === rootId) continue;
10551
- seen.add(id);
10552
- const c = byId.get(id);
10553
- if (c) stack.push(...directChildIds(c, extra));
10554
- }
10555
- return seen;
10556
- }
10557
- /**
10558
- * Ids of the `Card` components that are interactive panels: at least one
10559
- * descendant (via `child`, `children` or table component cells) is a control
10560
- * (Button, Pressable, Form, TextField, TextArea, Select, CheckBox, Radio,
10561
- * RadioGroup, Slider, SegmentedControl, DateTimeInput).
10562
- *
10563
- * @param components - The components of one surface.
10564
- * @returns The ids of the interactive cards.
10565
- *
10566
- * @example
10567
- * ```ts
10568
- * const interactive = classifySurfaceCards(components);
10569
- * const keepsBox = interactive.has("quote-form");
10570
- * ```
10571
- */
10572
- function classifySurfaceCards(components, options = {}) {
10573
- const byId = /* @__PURE__ */ new Map();
10574
- for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
10575
- const interactive = /* @__PURE__ */ new Set();
10576
- for (const [id, c] of byId) {
10577
- if (c.component !== "Card") continue;
10578
- for (const d of descendantIds(id, byId, options.childIds)) {
10579
- const type = byId.get(d)?.component;
10580
- if (typeof type === "string" && INTERACTIVE_COMPONENTS.has(type)) {
10581
- interactive.add(id);
10582
- break;
10583
- }
10584
- }
10585
- }
10586
- return interactive;
10587
- }
10588
- /**
10589
- * Markdown mode: only interactive panels keep a box. Every `Card` that is not
10590
- * an interactive panel (see `classifySurfaceCards`), sets no `variant` or
10591
- * `border` of its own and is not nested inside an interactive panel becomes
10592
- * `variant: "section"` (a heading plus content without a box). Operations
10593
- * other than updateComponents pass through unchanged.
10594
- *
10595
- * @param operations - The operations of one surface.
10596
- * @returns The operations with informational cards set to `variant: "section"`.
10597
- * When no card changes, it returns the same array.
10598
- *
10599
- * @example
10600
- * ```ts
10601
- * const operations = flattenInformationalCards(prepared.operations);
10602
- * ```
10603
- */
10604
- function flattenInformationalCards(operations, options = {}) {
10605
- const byId = componentsById(operations);
10606
- if (![...byId.values()].some((c) => c.component === "Card")) return operations;
10607
- const interactive = classifySurfaceCards([...byId.values()], options);
10608
- const insideInteractive = /* @__PURE__ */ new Set();
10609
- for (const id of interactive) for (const d of descendantIds(id, byId, options.childIds)) insideInteractive.add(d);
10610
- const flatten = (c) => c.component === "Card" && typeof c.id === "string" && !interactive.has(c.id) && !insideInteractive.has(c.id) && c.variant == null && c.border == null;
10611
- return operations.map((op) => {
10612
- const update = op.updateComponents;
10613
- if (!isRecord(update) || !Array.isArray(update.components)) return op;
10614
- if (!update.components.some((c) => isRecord(c) && flatten(c))) return op;
10615
- return {
10616
- ...op,
10617
- updateComponents: {
10618
- ...update,
10619
- components: update.components.map((c) => isRecord(c) && flatten(c) ? {
10620
- ...c,
10621
- variant: "section"
10622
- } : c)
10623
- }
10624
- };
10625
- });
10626
- }
10627
- /** Text-bearing components that belong in the chat's markdown, not a surface. */
10628
- const PROSE_TEXT_COMPONENTS = new Set([
10629
- "Title",
10630
- "Text",
10631
- "Caption",
10632
- "Markdown"
10633
- ]);
10634
- /** One line of text: list items and headings cannot span lines in markdown. */
10635
- function oneLine(text) {
10636
- return text.trim().replace(/\s*\n\s*/g, " ");
10637
- }
10638
- /**
10639
- * A literal List entry as list-item markdown: a non-empty string, or
10640
- * `{ label, description? }` with literal strings only. Anything carrying
10641
- * behaviour or decoration (`icon`, `action`, other keys, bound values) is null.
10642
- */
10643
- function listEntryMarkdown(entry) {
10644
- if (typeof entry === "string") return entry.trim() ? oneLine(entry) : null;
10645
- if (!isRecord(entry)) return null;
10646
- for (const key of Object.keys(entry)) if (key !== "label" && key !== "description") return null;
10647
- if (typeof entry.label !== "string" || !entry.label.trim()) return null;
10648
- const label = oneLine(entry.label);
10649
- if (entry.description === void 0) return label;
10650
- if (typeof entry.description !== "string") return null;
10651
- return entry.description.trim() ? `**${label}** — ${oneLine(entry.description)}` : label;
10652
- }
10653
- /**
10654
- * A List of literal text items as a markdown list (`marker: "number"` →
10655
- * `1. …`, otherwise `- …`), or null when it binds its items, renders
10656
- * `children`, or any item is not plain text.
10657
- */
10658
- function listToMarkdown(c) {
10659
- const children = c.children;
10660
- if (children != null && !(Array.isArray(children) && children.length === 0)) return null;
10661
- if (!Array.isArray(c.items) || c.items.length === 0) return null;
10662
- const lines = [];
10663
- for (const entry of c.items) {
10664
- const line = listEntryMarkdown(entry);
10665
- if (line === null) return null;
10666
- lines.push(line);
10667
- }
10668
- if (c.marker === "number") {
10669
- const start = typeof c.start === "number" && Number.isInteger(c.start) ? c.start : 1;
10670
- return lines.map((line, i) => `${start + i}. ${line}`).join("\n");
10671
- }
10672
- return lines.map((line) => `- ${line}`).join("\n");
10673
- }
10674
- /** The prose item a component converts to, or null when it is not prose. */
10675
- function toProseItem(c) {
10676
- if (!c) return null;
10677
- if (c.accessibility !== void 0) return null;
10678
- if (c.component === "Divider") return { kind: "divider" };
10679
- if (c.component === "Spacer") return { kind: "spacer" };
10680
- if (c.component === "List") {
10681
- if (c.direction !== void 0 && c.direction !== "vertical") return null;
10682
- const markdown = listToMarkdown(c);
10683
- return markdown === null ? null : {
10684
- kind: "text",
10685
- markdown
10686
- };
10687
- }
10688
- if (typeof c.component !== "string") return null;
10689
- if (!PROSE_TEXT_COMPONENTS.has(c.component)) return null;
10690
- if (typeof c.text !== "string" || c.text.trim() === "") return null;
10691
- const text = c.text.trim();
10692
- switch (c.component) {
10693
- case "Title": {
10694
- const size = typeof c.size === "string" ? c.size : "md";
10695
- return {
10696
- kind: "text",
10697
- markdown: `${size === "sm" ? "####" : size === "md" || size === "lg" ? "###" : "##"} ${text}`
10698
- };
10699
- }
10700
- case "Text":
10701
- if (directChildIds(c).length > 0) return null;
10702
- return {
10703
- kind: "text",
10704
- markdown: c.strong === true ? `**${text}**` : text
10705
- };
10706
- default: return {
10707
- kind: "text",
10708
- markdown: text
10709
- };
10710
- }
10711
- }
10712
- /** Prose items as markdown: separators only survive between two text items. */
10713
- function proseItemsToMarkdown(items) {
10714
- const blocks = [];
10715
- let pendingDivider = false;
10716
- for (const item of items) if (item?.kind === "text") {
10717
- if (pendingDivider && blocks.length > 0) blocks.push("---");
10718
- pendingDivider = false;
10719
- blocks.push(item.markdown);
10720
- } else if (item?.kind === "divider") pendingDivider = true;
10721
- return blocks.join("\n\n");
10722
- }
10723
- /** Column, column-direction Box, or an informational Card (section/unset variant). */
10724
- function isVerticalStack(c, interactiveCards) {
10725
- if (c.accessibility !== void 0) return false;
10726
- if (c.component === "Column") return true;
10727
- if (c.component === "Box") return c.direction == null || c.direction === "col";
10728
- if (c.component === "Card") return (c.variant == null || c.variant === "section") && typeof c.id === "string" && !interactiveCards.has(c.id);
10729
- return false;
10730
- }
10731
- /** The child-id list of a stack (`children`, or a lone `child`), else null. */
10732
- /**
10733
- * The children of a stack in render order: `child` first (a Card renders
10734
- * its `child` before its `children`), then `children`.
10735
- */
10736
- function stackChildren(c) {
10737
- const first = typeof c.child === "string" ? [c.child] : [];
10738
- if (Array.isArray(c.children)) return [...first, ...c.children];
10739
- if (first.length > 0 && c.children === void 0) return first;
10740
- return null;
10741
- }
10742
- /**
10743
- * Partitions the stack's children into alternating prose and surface runs.
10744
- * A run of consecutive prose items is prose only when it holds text: a run of
10745
- * separators alone (Divider/Spacer between two UI components, or at the very
10746
- * start/end of the stack) stays with the surface it sits in.
10747
- */
10748
- function partitionChildren(items) {
10749
- const runs = [];
10750
- let i = 0;
10751
- while (i < items.length) {
10752
- const candidate = items[i] !== null;
10753
- let hasText = false;
10754
- let j = i;
10755
- while (j < items.length && items[j] !== null === candidate) {
10756
- if (items[j]?.kind === "text") hasText = true;
10757
- j++;
10758
- }
10759
- const prose = candidate && hasText;
10760
- const last = runs[runs.length - 1];
10761
- if (!prose && last && !last.prose) last.end = j;
10762
- else runs.push({
10763
- prose,
10764
- start: i,
10765
- end: j
10766
- });
10767
- i = j;
10768
- }
10769
- return runs;
10770
- }
10771
- /**
10772
- * Markdown mode: split a surface into markdown and surface segments so that
10773
- * only real UI renders as A2UI and everything else is the chat's markdown.
10774
- *
10775
- * From `root`, descend through single-child vertical containers (Column,
10776
- * column Box, informational Card) to the first one with several children:
10777
- * the stack. Its children are partitioned, in order, into runs of prose and
10778
- * runs of UI. Prose is `Title`, `Text`, `Caption`, `Markdown` with literal
10779
- * text, a `List` of literal text items, plus `Divider`/`Spacer` next to them:
10780
- * `Title` → heading by size (sm `####`, md/lg `###`, larger `##`), `Text` →
10781
- * paragraph (`strong` → `**…**`), `Caption`/`Markdown` → paragraph, `List` →
10782
- * `- …` (or `1. …` for `marker: "number"`, `**label** — description` for
10783
- * described items), and a `Divider` between two prose blocks → `---`.
10784
- *
10785
- * Not prose: `{path}`-bound text or items, a Text with inline children, a
10786
- * List with `children`/icons/actions, a template entry, a component with an
10787
- * `accessibility` envelope, and a child whose component has not streamed
10788
- * yet. Separators with no text beside them stay in
10789
- * the surface. An interactive Card (see `classifySurfaceCards`) is never
10790
- * entered.
10791
- *
10792
- * Each prose run becomes a markdown segment; each UI run becomes a surface
10793
- * segment whose `root` is a copy of the stack (its other props kept, `child`
10794
- * dropped) with only that run's `children`, followed by every component
10795
- * reachable from them. When nothing is prose the input comes back as the one
10796
- * surface segment (same array); when everything is (or `root` itself is),
10797
- * there are only markdown segments.
10798
- *
10799
- * Pure and linear in the number of components, so it runs on every stream
10800
- * update.
10801
- *
10802
- * @param components - The components of one surface, root included.
10803
- * @returns The segments in render order.
10804
- *
10805
- * @example
10806
- * ```ts
10807
- * for (const segment of segmentSurfaceProse(components)) {
10808
- * if (segment.kind === "markdown") renderMarkdown(segment.markdown);
10809
- * else renderSurface(segment.components);
10810
- * }
10811
- * ```
10812
- */
10813
- function segmentSurfaceProse(components, options = {}) {
10814
- const unchanged = [{
10815
- kind: "surface",
10816
- components
10817
- }];
10818
- const byId = /* @__PURE__ */ new Map();
10819
- for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
10820
- const root = byId.get(_copilotkit_shared.GENERATIVE_UI_ROOT_ID);
10821
- if (!root) return unchanged;
10822
- if (components.some((c) => isRecord(c) && options.childIds?.(c) === "unknown")) return unchanged;
10823
- const rootItem = toProseItem(root);
10824
- if (rootItem?.kind === "text") return [{
10825
- kind: "markdown",
10826
- markdown: rootItem.markdown
10827
- }];
10828
- const interactiveCards = classifySurfaceCards(components, options);
10829
- let stack = root;
10830
- let stackId = _copilotkit_shared.GENERATIVE_UI_ROOT_ID;
10831
- let children;
10832
- const visited = /* @__PURE__ */ new Set();
10833
- while (true) {
10834
- if (!isVerticalStack(stack, interactiveCards)) return unchanged;
10835
- visited.add(stackId);
10836
- const list = stackChildren(stack);
10837
- if (!list) return unchanged;
10838
- children = list;
10839
- const nextId = list.length === 1 ? list[0] : void 0;
10840
- if (typeof nextId !== "string") break;
10841
- const next = byId.get(nextId);
10842
- if (!next || visited.has(nextId) || toProseItem(next)) break;
10843
- stack = next;
10844
- stackId = nextId;
10845
- }
10846
- const stackChildIds = children;
10847
- const items = stackChildIds.map((id) => typeof id === "string" ? toProseItem(byId.get(id)) : null);
10848
- const runs = partitionChildren(items);
10849
- if (!runs.some((run) => run.prose)) return unchanged;
10850
- const surfaceRuns = runs.filter((run) => !run.prose);
10851
- const owners = /* @__PURE__ */ new Map();
10852
- surfaceRuns.forEach((run, index) => {
10853
- const pending = stackChildIds.slice(run.start, run.end).map(referencedId).filter((id) => id !== void 0);
10854
- const seen = /* @__PURE__ */ new Set();
10855
- while (pending.length > 0) {
10856
- const id = pending.pop();
10857
- if (id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID || id === stackId || seen.has(id)) continue;
10858
- seen.add(id);
10859
- const list = owners.get(id);
10860
- if (list) list.push(index);
10861
- else owners.set(id, [index]);
10862
- const c = byId.get(id);
10863
- if (c) pending.push(...directChildIds(c, options.childIds));
10864
- }
10865
- });
10866
- const surfaceComponents = surfaceRuns.map((run) => {
10867
- const { child: _child, ...stackRest } = stack;
10868
- const nextRoot = {
10869
- ...stackRest,
10870
- id: _copilotkit_shared.GENERATIVE_UI_ROOT_ID,
10871
- children: stackChildIds.slice(run.start, run.end)
10872
- };
10873
- delete nextRoot.child;
10874
- return [nextRoot];
10875
- });
10876
- for (const c of components) {
10877
- if (!isRecord(c) || typeof c.id !== "string" || byId.get(c.id) !== c) continue;
10878
- const ownerIndexes = owners.get(c.id) ?? [];
10879
- for (const index of ownerIndexes) surfaceComponents[index].push(c);
10880
- }
10881
- let surfaceIndex = 0;
10882
- return runs.map((run) => {
10883
- if (run.prose) return {
10884
- kind: "markdown",
10885
- markdown: proseItemsToMarkdown(items.slice(run.start, run.end))
10886
- };
10887
- return {
10888
- kind: "surface",
10889
- components: surfaceComponents[surfaceIndex++]
10890
- };
10891
- });
10892
- }
10893
-
10894
- //#endregion
10895
- exports.A2UI_FENCE_LANGUAGE = A2UI_FENCE_LANGUAGE;
9508
+ exports.A2UI_FENCE_LANGUAGE = require_a2ui_markdown.A2UI_FENCE_LANGUAGE;
10896
9509
  exports.AgentRegistry = AgentRegistry;
10897
9510
  exports.AgentThreadLockedError = AgentThreadLockedError;
10898
9511
  exports.ContextStore = ContextStore;
@@ -10902,7 +9515,6 @@ exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionS
10902
9515
  exports.CopilotKitHeaderResolutionError = CopilotKitHeaderResolutionError;
10903
9516
  exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
10904
9517
  exports.IntelligenceAgent = IntelligenceAgent;
10905
- exports.IntelligenceReplayFailedError = IntelligenceReplayFailedError;
10906
9518
  exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
10907
9519
  exports.MemoryError = MemoryError;
10908
9520
  exports.ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;
@@ -10911,7 +9523,7 @@ exports.StateManager = StateManager;
10911
9523
  exports.SuggestionEngine = SuggestionEngine;
10912
9524
  exports.ToolCallStatus = ToolCallStatus;
10913
9525
  exports.WebMCPRegistry = WebMCPRegistry;
10914
- exports.classifySurfaceCards = classifySurfaceCards;
9526
+ exports.classifySurfaceCards = require_a2ui_markdown.classifySurfaceCards;
10915
9527
  exports.completePartialMarkdown = completePartialMarkdown;
10916
9528
  exports.createActionGroup = createActionGroup;
10917
9529
  exports.createEffect = createEffect;
@@ -10925,11 +9537,11 @@ exports.emitInspectorViewThread = emitInspectorViewThread;
10925
9537
  exports.emitInspectorViewThreadResult = emitInspectorViewThreadResult;
10926
9538
  exports.empty = empty;
10927
9539
  exports.ensureObjectArgs = ensureObjectArgs;
10928
- exports.extractCompleteArrayItems = extractCompleteArrayItems;
10929
- exports.extractFenceOperations = extractFenceOperations;
10930
- exports.extractStringField = extractStringField;
10931
- exports.flattenInformationalCards = flattenInformationalCards;
10932
- exports.getMarkdownOperationSurfaceId = getMarkdownOperationSurfaceId;
9540
+ exports.extractCompleteArrayItems = require_a2ui_markdown.extractCompleteArrayItems;
9541
+ exports.extractFenceOperations = require_a2ui_markdown.extractFenceOperations;
9542
+ exports.extractStringField = require_a2ui_markdown.extractStringField;
9543
+ exports.flattenInformationalCards = require_a2ui_markdown.flattenInformationalCards;
9544
+ exports.getMarkdownOperationSurfaceId = require_a2ui_markdown.getMarkdownOperationSurfaceId;
10933
9545
  exports.getWebMCPModelContext = getWebMCPModelContext;
10934
9546
  exports.isAbortError = isAbortError;
10935
9547
  exports.isInspectorThreadBridgeEnabled = isInspectorThreadBridgeEnabled;
@@ -10941,11 +9553,11 @@ exports.onInspectorStopViewing = onInspectorStopViewing;
10941
9553
  exports.onInspectorViewThread = onInspectorViewThread;
10942
9554
  exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
10943
9555
  exports.parseToolArguments = parseToolArguments;
10944
- exports.prepareSurfaceOperations = prepareSurfaceOperations;
9556
+ exports.prepareSurfaceOperations = require_a2ui_markdown.prepareSurfaceOperations;
10945
9557
  exports.props = props;
10946
- exports.segmentSurfaceProse = segmentSurfaceProse;
9558
+ exports.segmentSurfaceProse = require_a2ui_markdown.segmentSurfaceProse;
10947
9559
  exports.select = select;
10948
- exports.splitA2UIMarkdown = splitA2UIMarkdown;
9560
+ exports.splitA2UIMarkdown = require_a2ui_markdown.splitA2UIMarkdown;
10949
9561
  exports.ɵCOPILOTKIT_FEATURES = ɵCOPILOTKIT_FEATURES;
10950
9562
  exports.ɵInterruptState = ɵInterruptState;
10951
9563
  exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;