@copilotkit/core 1.80.0 → 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.umd.js CHANGED
@@ -3206,6 +3206,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3206
3206
  }
3207
3207
  };
3208
3208
 
3209
+ //#endregion
3210
+ //#region src/core/agent-scope.ts
3211
+ /**
3212
+ * True when an entry scoped to `agentIds` goes to a run of `agentId`. An
3213
+ * entry without `agentIds` goes to every agent; an entry with them does not
3214
+ * go to a run without an agent id. Internal, not exported.
3215
+ */
3216
+ function isForAgent(agentIds, agentId) {
3217
+ return agentIds === void 0 || agentId !== void 0 && agentIds.includes(agentId);
3218
+ }
3219
+
3209
3220
  //#endregion
3210
3221
  //#region src/core/context-store.ts
3211
3222
  /**
@@ -3244,7 +3255,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3244
3255
  * protocol-shaped `{ description, value }` entries go over the wire.
3245
3256
  */
3246
3257
  getContextForAgent(agentId) {
3247
- return Object.values(this._context).filter((entry) => !entry.agentIds || agentId !== void 0 && entry.agentIds.includes(agentId)).map(({ description, value }) => ({
3258
+ return Object.values(this._context).filter((entry) => isForAgent(entry.agentIds, agentId)).map(({ description, value }) => ({
3248
3259
  description,
3249
3260
  value
3250
3261
  }));
@@ -3435,7 +3446,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3435
3446
  await suggestionAgent.runAgent({
3436
3447
  context: friends.getContextForAgent(consumerAgentId),
3437
3448
  forwardedProps: {
3438
- ...friends.properties,
3449
+ ...friends.getPropertiesForAgent(consumerAgentId),
3439
3450
  toolChoice: {
3440
3451
  type: "function",
3441
3452
  function: { name: "copilotkitSuggest" }
@@ -4155,7 +4166,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4155
4166
  newMessages: []
4156
4167
  };
4157
4168
  const runAgentResult = await agent.connectAgent({
4158
- forwardedProps: this._internal.properties,
4169
+ forwardedProps: this._internal.getPropertiesForAgent(agent.agentId),
4159
4170
  tools: this.buildFrontendTools(agent.agentId),
4160
4171
  context: this._internal.getContextForAgent(agent.agentId)
4161
4172
  }, this.createAgentErrorSubscriber(agent));
@@ -4276,7 +4287,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4276
4287
  const pinRunIdOnWire = runId !== void 0 && !continuationHandoff;
4277
4288
  const agentRunInput = {
4278
4289
  forwardedProps: {
4279
- ...this._internal.properties,
4290
+ ...this._internal.getPropertiesForAgent(agent.agentId),
4280
4291
  ...forwardedProps
4281
4292
  },
4282
4293
  ...resume !== void 0 ? { resume } : {},
@@ -7315,6 +7326,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7315
7326
 
7316
7327
  //#endregion
7317
7328
  //#region src/core/core.ts
7329
+ /** True for an object literal. Arrays, `null`, and class instances are not plain objects. */
7330
+ function isPlainObject(value) {
7331
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
7332
+ }
7318
7333
  let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode) {
7319
7334
  CopilotKitCoreErrorCode["RUNTIME_INFO_FETCH_FAILED"] = "runtime_info_fetch_failed";
7320
7335
  CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
@@ -7381,6 +7396,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7381
7396
  _defineProperty(this, "_credentials", void 0);
7382
7397
  _defineProperty(this, "_messageFilter", void 0);
7383
7398
  _defineProperty(this, "_properties", void 0);
7399
+ _defineProperty(this, "_scopedProperties", /* @__PURE__ */ new Map());
7384
7400
  _defineProperty(this, "_defaultThrottleMs", void 0);
7385
7401
  _defineProperty(this, "_debug", void 0);
7386
7402
  _defineProperty(this, "subscribers", /* @__PURE__ */ new Set());
@@ -7393,6 +7409,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7393
7409
  _defineProperty(this, "learningBridge", void 0);
7394
7410
  _defineProperty(this, "notifiedTrajectoryId", null);
7395
7411
  _defineProperty(this, "learningConfiguredListeners", /* @__PURE__ */ new Set());
7412
+ _defineProperty(this, "_generativeUIDebugSource", void 0);
7413
+ _defineProperty(this, "generativeUIDebugListeners", /* @__PURE__ */ new Set());
7396
7414
  _defineProperty(this, "_memoryStore", void 0);
7397
7415
  _defineProperty(this, "previousAgentIds", /* @__PURE__ */ new Set());
7398
7416
  this.headerSource = new HeaderSourceResolver((error) => {
@@ -7719,6 +7737,59 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7719
7737
  this._messageFilter = messageFilter;
7720
7738
  this.agentRegistry.applyMessageFilterToAgents(this.agentRegistry.agents);
7721
7739
  }
7740
+ /**
7741
+ * Add run properties that go only to the runs of `agentIds`. When
7742
+ * `agentIds` is omitted, every agent gets them. They merge on top of the
7743
+ * base `properties`.
7744
+ *
7745
+ * When an entry value and the existing value under the same key are both
7746
+ * plain objects, their keys merge one level deep. So several entries can
7747
+ * add keys under one namespace (for example `copilotkit`).
7748
+ *
7749
+ * @param entry - The properties and the optional agent ids.
7750
+ * @returns The id to pass to `removeScopedProperties`.
7751
+ *
7752
+ * @example
7753
+ * const id = copilotkit.addScopedProperties({
7754
+ * properties: { copilotkit: { theme: "dark" } },
7755
+ * agentIds: ["research"],
7756
+ * });
7757
+ * copilotkit.removeScopedProperties(id);
7758
+ */
7759
+ addScopedProperties({ properties, agentIds }) {
7760
+ let id = (0, _copilotkit_shared.randomUUID)();
7761
+ for (let n = 1; this._scopedProperties.has(id); n++) id = `${id}-${n}`;
7762
+ this._scopedProperties.set(id, {
7763
+ properties,
7764
+ ...agentIds ? { agentIds } : {}
7765
+ });
7766
+ return id;
7767
+ }
7768
+ /** Remove an entry that `addScopedProperties` added. An unknown id does nothing. */
7769
+ removeScopedProperties(id) {
7770
+ this._scopedProperties.delete(id);
7771
+ }
7772
+ /**
7773
+ * Build the forwarded properties for a run of the given agent: the base
7774
+ * properties plus every scoped entry that matches the agent. An entry with
7775
+ * `agentIds` does not match when `agentId` is omitted.
7776
+ */
7777
+ getPropertiesForAgent(agentId) {
7778
+ const merged = { ...this._properties };
7779
+ const entries = this._scopedProperties.values();
7780
+ for (const entry of entries) {
7781
+ if (!isForAgent(entry.agentIds, agentId)) continue;
7782
+ const properties = Object.entries(entry.properties);
7783
+ for (const [key, value] of properties) {
7784
+ const base = merged[key];
7785
+ merged[key] = isPlainObject(base) && isPlainObject(value) ? {
7786
+ ...base,
7787
+ ...value
7788
+ } : value;
7789
+ }
7790
+ }
7791
+ return merged;
7792
+ }
7722
7793
  setProperties(properties) {
7723
7794
  this._properties = properties;
7724
7795
  this.notifySubscribers((subscriber) => {
@@ -7801,6 +7872,30 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7801
7872
  this.learningConfiguredListeners.delete(listener);
7802
7873
  };
7803
7874
  }
7875
+ /**
7876
+ * @internal The generative UI of the framework package, for the inspector.
7877
+ * `undefined` when no provider has a `generativeUI` config.
7878
+ */
7879
+ get ɵgenerativeUIDebugSource() {
7880
+ return this._generativeUIDebugSource;
7881
+ }
7882
+ /** @internal Set by the framework package. `undefined` removes it. */
7883
+ ɵsetGenerativeUIDebugSource(source) {
7884
+ if (source === this._generativeUIDebugSource) return;
7885
+ this._generativeUIDebugSource = source;
7886
+ for (const listener of [...this.generativeUIDebugListeners]) try {
7887
+ listener();
7888
+ } catch (error) {
7889
+ console.error("Generative UI debug listener error:", error);
7890
+ }
7891
+ }
7892
+ /** @internal Calls `listener` when {@link ɵgenerativeUIDebugSource} is set or removed. */
7893
+ ɵsubscribeToGenerativeUIDebugSource(listener) {
7894
+ this.generativeUIDebugListeners.add(listener);
7895
+ return () => {
7896
+ this.generativeUIDebugListeners.delete(listener);
7897
+ };
7898
+ }
7804
7899
  /** The active capture's Trajectory ID, or null while capture is stopped. */
7805
7900
  get trajectoryId() {
7806
7901
  return this.learningBridge.trajectoryId;
@@ -9444,6 +9539,1287 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
9444
9539
  }
9445
9540
 
9446
9541
  //#endregion
9542
+ //#region src/a2ui-markdown/fence-parser.ts
9543
+ /** Language of a fenced code block that carries A2UI operations. */
9544
+ const A2UI_FENCE_LANGUAGE = "a2ui";
9545
+ /** Column-0 fence opener: a run of 3+ backticks or tildes, then the info string. */
9546
+ const FENCE_OPEN = /^(`{3,}|~{3,})(.*)$/;
9547
+ /** Info-string token that names the placement target of an a2ui fence. */
9548
+ const TARGET_TOKEN = /^target=(.+)$/;
9549
+ function isCloser(line, fence) {
9550
+ const trimmed = line.trim();
9551
+ if (trimmed.length < fence.length) return false;
9552
+ for (const ch of trimmed) if (ch !== fence.char) return false;
9553
+ return true;
9554
+ }
9555
+ /** The id of the first `target=<id>` token. Other tokens are ignored. */
9556
+ function readTarget(tokens) {
9557
+ for (const token of tokens) {
9558
+ const match = TARGET_TOKEN.exec(token);
9559
+ if (match) return match[1];
9560
+ }
9561
+ }
9562
+ function a2uiSegment(fence, text, closed) {
9563
+ const segment = {
9564
+ type: "a2ui",
9565
+ index: fence.index,
9566
+ text,
9567
+ closed
9568
+ };
9569
+ if (fence.target !== void 0) segment.target = fence.target;
9570
+ return segment;
9571
+ }
9572
+ /**
9573
+ * Split a (possibly still streaming) markdown string into prose segments and
9574
+ * top-level ```a2ui fences. Fences of other languages stay inside prose
9575
+ * segments byte-for-byte, and a2ui markers inside them are ignored. Only
9576
+ * column-0 fences are recognised, so a fence indented inside a list item is
9577
+ * left to the markdown renderer.
9578
+ *
9579
+ * The first info-string token must be exactly `a2ui`. A later
9580
+ * `target=<id>` token sets `target` on the segment (for example
9581
+ * ```` ```a2ui target=recommendations ````). Other tokens are ignored.
9582
+ *
9583
+ * An a2ui segment's `text` is the fence body. For a closed fence it ends with
9584
+ * "\n" when non-empty. For an open (still streaming or aborted) fence it is
9585
+ * everything after the opener line, minus a half-streamed closing marker.
9586
+ *
9587
+ * @param markdown - The assistant message text, complete or still streaming.
9588
+ * @returns The segments in source order.
9589
+ *
9590
+ * @example
9591
+ * ```ts
9592
+ * for (const segment of splitA2UIMarkdown(message.content)) {
9593
+ * if (segment.type === "a2ui") renderSurface(segment.text, segment.target);
9594
+ * else renderMarkdown(segment.text);
9595
+ * }
9596
+ * ```
9597
+ */
9598
+ function splitA2UIMarkdown(markdown) {
9599
+ const segments = [];
9600
+ let proseStart = 0;
9601
+ let fence = null;
9602
+ let a2uiIndex = 0;
9603
+ const pushProse = (end) => {
9604
+ if (end > proseStart) segments.push({
9605
+ type: "markdown",
9606
+ text: markdown.slice(proseStart, end)
9607
+ });
9608
+ };
9609
+ let lineStart = 0;
9610
+ while (lineStart <= markdown.length) {
9611
+ const newline = markdown.indexOf("\n", lineStart);
9612
+ const lineEnd = newline < 0 ? markdown.length : newline;
9613
+ const hasCR = lineEnd > lineStart && markdown[lineEnd - 1] === "\r";
9614
+ const line = markdown.slice(lineStart, hasCR ? lineEnd - 1 : lineEnd);
9615
+ if (fence) {
9616
+ if (isCloser(line, fence)) {
9617
+ if (fence.index >= 0) {
9618
+ const body = markdown.slice(fence.bodyStart, Math.max(fence.bodyStart, lineStart));
9619
+ segments.push(a2uiSegment(fence, body, true));
9620
+ proseStart = hasCR ? lineEnd - 1 : lineEnd;
9621
+ }
9622
+ fence = null;
9623
+ }
9624
+ } else {
9625
+ const open = FENCE_OPEN.exec(line);
9626
+ if (open) {
9627
+ var _open$, _open$2;
9628
+ const marker = (_open$ = open[1]) !== null && _open$ !== void 0 ? _open$ : "";
9629
+ const info = (_open$2 = open[2]) !== null && _open$2 !== void 0 ? _open$2 : "";
9630
+ const char = marker.charAt(0);
9631
+ if (!(char === "`" && info.includes("`"))) {
9632
+ const [lang = "", ...tokens] = info.trim().split(/\s+/);
9633
+ const isA2UI = lang === A2UI_FENCE_LANGUAGE;
9634
+ if (isA2UI) pushProse(lineStart);
9635
+ fence = {
9636
+ char,
9637
+ length: marker.length,
9638
+ bodyStart: newline < 0 ? markdown.length : lineEnd + 1,
9639
+ index: isA2UI ? a2uiIndex++ : -1,
9640
+ target: isA2UI ? readTarget(tokens) : void 0
9641
+ };
9642
+ }
9643
+ }
9644
+ }
9645
+ if (newline < 0) break;
9646
+ lineStart = newline + 1;
9647
+ }
9648
+ if (fence && fence.index >= 0) {
9649
+ const { char } = fence;
9650
+ let body = markdown.slice(fence.bodyStart);
9651
+ const lastNewline = body.lastIndexOf("\n");
9652
+ const lastLine = body.slice(lastNewline + 1).replace(/\r$/, "");
9653
+ if (lastLine.length > 0 && [...lastLine].every((ch) => ch === char)) body = body.slice(0, lastNewline + 1);
9654
+ segments.push(a2uiSegment(fence, body, false));
9655
+ } else pushProse(markdown.length);
9656
+ return segments;
9657
+ }
9658
+
9659
+ //#endregion
9660
+ //#region src/a2ui-markdown/operations.ts
9661
+ /** The operation keys that change a surface. */
9662
+ const SURFACE_OP_KEYS = [
9663
+ "createSurface",
9664
+ "updateComponents",
9665
+ "updateDataModel",
9666
+ "deleteSurface"
9667
+ ];
9668
+ /** The operation key of an agent-called function. It has no surface. */
9669
+ const FUNCTION_CALL_KEY = "callRendererFunction";
9670
+ const OP_KEYS = [...SURFACE_OP_KEYS, FUNCTION_CALL_KEY];
9671
+ function isRecord(value) {
9672
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9673
+ }
9674
+ function isWhitespace(ch) {
9675
+ return ch === " " || ch === "\n" || ch === "\r" || ch === " ";
9676
+ }
9677
+ function skipWhitespace(s, i) {
9678
+ while (i < s.length && isWhitespace(s[i])) i++;
9679
+ return i;
9680
+ }
9681
+ /** Index of the closing quote of the JSON string opening at `start`, or -1. */
9682
+ function findStringEnd(s, start) {
9683
+ for (let i = start + 1; i < s.length; i++) {
9684
+ if (s[i] === "\\") {
9685
+ i++;
9686
+ continue;
9687
+ }
9688
+ if (s[i] === "\"") return i;
9689
+ }
9690
+ return -1;
9691
+ }
9692
+ /**
9693
+ * Find the first `"key":` whose value starts with `opener` and return the index
9694
+ * of that opener, or -1.
9695
+ */
9696
+ function findKeyValue(s, key, opener) {
9697
+ const needle = `"${key}"`;
9698
+ let from = 0;
9699
+ while (true) {
9700
+ const k = s.indexOf(needle, from);
9701
+ if (k < 0) return -1;
9702
+ let i = skipWhitespace(s, k + needle.length);
9703
+ if (s[i] === ":") {
9704
+ i = skipWhitespace(s, i + 1);
9705
+ if (s[i] === opener) return i;
9706
+ }
9707
+ from = k + 1;
9708
+ }
9709
+ }
9710
+ /**
9711
+ * Read `"key":"value"` from partial JSON. The first match anywhere in the
9712
+ * text wins, at any depth.
9713
+ *
9714
+ * @param partialJson - JSON text that can still be streaming.
9715
+ * @param key - The field name.
9716
+ * @returns The string value, or null until its closing quote has arrived.
9717
+ *
9718
+ * @example
9719
+ * ```ts
9720
+ * extractStringField('{"createSurface":{"surfaceId":"plan","cat', "surfaceId"); // "plan"
9721
+ * ```
9722
+ */
9723
+ function extractStringField(partialJson, key) {
9724
+ const start = findKeyValue(partialJson, key, "\"");
9725
+ if (start < 0) return null;
9726
+ const end = findStringEnd(partialJson, start);
9727
+ if (end < 0) return null;
9728
+ try {
9729
+ const value = JSON.parse(partialJson.slice(start, end + 1));
9730
+ return typeof value === "string" ? value : null;
9731
+ } catch (_unused) {
9732
+ return null;
9733
+ }
9734
+ }
9735
+ function pushItem(raw, items) {
9736
+ const trimmed = raw.trim();
9737
+ if (!trimmed) return;
9738
+ try {
9739
+ items.push(JSON.parse(trimmed));
9740
+ } catch (_unused2) {}
9741
+ }
9742
+ /**
9743
+ * Find `"key":[` in partial JSON and return every complete item of that array
9744
+ * so far, plus whether the array has closed. Items of a `components` array get
9745
+ * structural-key depth repair: a component that lost closing braces is fixed
9746
+ * when its `id`, `component`, `child` or `children` key shows where it ends.
9747
+ *
9748
+ * @param partialJson - JSON text that can still be streaming.
9749
+ * @param key - The name of the array field.
9750
+ * @returns `{ items, closed }`, or null when the key (with an array value)
9751
+ * has not appeared yet.
9752
+ *
9753
+ * @example
9754
+ * ```ts
9755
+ * const result = extractCompleteArrayItems(streamedText, "components");
9756
+ * if (result) render(result.items);
9757
+ * ```
9758
+ */
9759
+ function extractCompleteArrayItems(partialJson, key) {
9760
+ const open = findKeyValue(partialJson, key, "[");
9761
+ if (open < 0) return null;
9762
+ return completeArrayItemsAt(partialJson, open, { repairComponents: key === "components" });
9763
+ }
9764
+ /** Index of the last non-whitespace character before `i`, or -1. */
9765
+ function prevNonWhitespace(s, i) {
9766
+ let j = i - 1;
9767
+ while (j >= 0 && isWhitespace(s[j])) j--;
9768
+ return j;
9769
+ }
9770
+ /**
9771
+ * Keys that only ever belong at a component's top level. Seen nested inside
9772
+ * the component's objects, they mean the model forgot closing braces.
9773
+ */
9774
+ const STRUCTURAL_KEYS = new Set([
9775
+ "id",
9776
+ "component",
9777
+ "child",
9778
+ "children"
9779
+ ]);
9780
+ /** Whether a value starting with `ch` has the shape `key` takes on a component. */
9781
+ function structuralValueFits(key, ch) {
9782
+ if (key === "children") return ch === "[" || ch === "{";
9783
+ return ch === "\"";
9784
+ }
9785
+ /** `{"id":` — a new component object starting at `i`. */
9786
+ const COMPONENT_START = /^\{\s*"id"\s*:/;
9787
+ /**
9788
+ * Structural-key depth repair for one component item. While scanning, a
9789
+ * structural key (`id`, `component`, `child`, `children`) found as an object
9790
+ * key below the item's top level, with only objects (no arrays) between it
9791
+ * and the item root, a value of the expected shape, and not already present
9792
+ * at the top level, means closing braces were dropped: the missing `}` are
9793
+ * synthesized right before it so it lands at the top level. Containers still
9794
+ * open at the end are closed. Returns null when a string never terminates.
9795
+ */
9796
+ function repairComponentItem(item) {
9797
+ const stack = [];
9798
+ const topKeys = /* @__PURE__ */ new Set();
9799
+ let out = "";
9800
+ let copied = 0;
9801
+ for (let i = 0; i < item.length; i++) {
9802
+ const c = item[i];
9803
+ if (c === "\"") {
9804
+ const end = findStringEnd(item, i);
9805
+ if (end < 0) return null;
9806
+ const prev = prevNonWhitespace(item, i);
9807
+ const prevCh = item[prev];
9808
+ const colon = skipWhitespace(item, end + 1);
9809
+ if (stack[stack.length - 1] === "{" && (prevCh === "," || prevCh === "{") && item[colon] === ":") {
9810
+ let key;
9811
+ try {
9812
+ key = JSON.parse(item.slice(i, end + 1));
9813
+ } catch (_unused3) {
9814
+ return null;
9815
+ }
9816
+ if (typeof key === "string") {
9817
+ if (stack.length === 1) topKeys.add(key);
9818
+ else if (STRUCTURAL_KEYS.has(key) && !topKeys.has(key) && stack.every((x) => x === "{") && structuralValueFits(key, item[skipWhitespace(item, colon + 1)])) {
9819
+ const closers = "}".repeat(stack.length - 1);
9820
+ if (prevCh === ",") {
9821
+ out += item.slice(copied, prev) + closers;
9822
+ copied = prev;
9823
+ } else {
9824
+ out += item.slice(copied, i) + closers + ",";
9825
+ copied = i;
9826
+ }
9827
+ stack.length = 1;
9828
+ topKeys.add(key);
9829
+ }
9830
+ }
9831
+ }
9832
+ i = end;
9833
+ continue;
9834
+ }
9835
+ if (c === "{" || c === "[") stack.push(c);
9836
+ else if (c === "}" || c === "]") {
9837
+ stack.pop();
9838
+ if (stack.length === 0) return out + item.slice(copied, i + 1);
9839
+ }
9840
+ }
9841
+ const closers = stack.reduceRight((text, opener) => text + (opener === "{" ? "}" : "]"), "");
9842
+ return out + item.slice(copied) + closers;
9843
+ }
9844
+ function parseRecord(text) {
9845
+ if (text === null) return void 0;
9846
+ try {
9847
+ const value = JSON.parse(text);
9848
+ return isRecord(value) ? value : void 0;
9849
+ } catch (_unused4) {
9850
+ return;
9851
+ }
9852
+ }
9853
+ /**
9854
+ * Complete items of the (possibly unterminated) array whose "[" is at `open`.
9855
+ * With `repairComponents`, an item that balanced but does not parse is retried
9856
+ * with structural-key repair, and a `,{"id":` where an item expects a key
9857
+ * ends that (unbalanced) item there, so one malformed component cannot
9858
+ * swallow the rest of the array; the cut item is kept only if repair makes
9859
+ * it parse.
9860
+ */
9861
+ function completeArrayItemsAt(partialJson, open, options) {
9862
+ const { repairComponents } = options;
9863
+ const s = partialJson;
9864
+ const items = [];
9865
+ const stack = [];
9866
+ let inString = false;
9867
+ let itemStart = -1;
9868
+ const finishItem = (end, balanced) => {
9869
+ const raw = s.slice(itemStart, end);
9870
+ if (!repairComponents) {
9871
+ pushItem(raw, items);
9872
+ return;
9873
+ }
9874
+ if (balanced) try {
9875
+ items.push(JSON.parse(raw));
9876
+ return;
9877
+ } catch (_unused5) {}
9878
+ const repaired = parseRecord(repairComponentItem(raw.trim()));
9879
+ if (repaired !== void 0) items.push(repaired);
9880
+ };
9881
+ for (let i = open + 1; i < s.length; i++) {
9882
+ const c = s[i];
9883
+ if (inString) {
9884
+ if (c === "\\") i++;
9885
+ else if (c === "\"") inString = false;
9886
+ continue;
9887
+ }
9888
+ if (c === "\"") {
9889
+ inString = true;
9890
+ if (stack.length === 0 && itemStart < 0) itemStart = i;
9891
+ continue;
9892
+ }
9893
+ if (c === "{" || c === "[") {
9894
+ if (repairComponents && c === "{" && stack[stack.length - 1] === "{" && COMPONENT_START.test(s.slice(i, i + 24))) {
9895
+ const prev = prevNonWhitespace(s, i);
9896
+ if (s[prev] === ",") {
9897
+ finishItem(prev, false);
9898
+ stack.length = 0;
9899
+ itemStart = i;
9900
+ stack.push(c);
9901
+ continue;
9902
+ }
9903
+ }
9904
+ if (stack.length === 0) itemStart = i;
9905
+ stack.push(c);
9906
+ continue;
9907
+ }
9908
+ if (c === "}" || c === "]") {
9909
+ if (stack.length === 0) {
9910
+ if (c === "]") {
9911
+ if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
9912
+ return {
9913
+ items,
9914
+ closed: true
9915
+ };
9916
+ }
9917
+ return {
9918
+ items,
9919
+ closed: false
9920
+ };
9921
+ }
9922
+ stack.pop();
9923
+ if (stack.length === 0) {
9924
+ finishItem(i + 1, true);
9925
+ itemStart = -1;
9926
+ }
9927
+ continue;
9928
+ }
9929
+ if (stack.length === 0) {
9930
+ if (c === ",") {
9931
+ if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
9932
+ itemStart = -1;
9933
+ } else if (itemStart < 0 && !isWhitespace(c)) itemStart = i;
9934
+ }
9935
+ }
9936
+ return {
9937
+ items,
9938
+ closed: false
9939
+ };
9940
+ }
9941
+ /** The first operation key whose value is an object, with that value. */
9942
+ function getOperationEntry(op) {
9943
+ for (const key of OP_KEYS) {
9944
+ const inner = op[key];
9945
+ if (isRecord(inner)) return {
9946
+ key,
9947
+ inner
9948
+ };
9949
+ }
9950
+ return null;
9951
+ }
9952
+ /**
9953
+ * The surfaceId an operation targets: the one nested under its operation key,
9954
+ * else a top-level `surfaceId`. A `callRendererFunction` operation targets no
9955
+ * surface, so it gets undefined.
9956
+ *
9957
+ * It is named `getMarkdownOperationSurfaceId` because `@copilotkit/shared`
9958
+ * already exports a strict `getOperationSurfaceId`. This one also reads a
9959
+ * top-level `surfaceId`, which models sometimes write.
9960
+ *
9961
+ * @param op - An operation from an a2ui fence.
9962
+ * @returns The surfaceId, or undefined when the operation names none or is a
9963
+ * function call.
9964
+ *
9965
+ * @example
9966
+ * ```ts
9967
+ * getMarkdownOperationSurfaceId({ updateDataModel: { surfaceId: "plan" } }); // "plan"
9968
+ * ```
9969
+ */
9970
+ function getMarkdownOperationSurfaceId(op) {
9971
+ var _getOperationEntry;
9972
+ if (((_getOperationEntry = getOperationEntry(op)) === null || _getOperationEntry === void 0 ? void 0 : _getOperationEntry.key) === FUNCTION_CALL_KEY) return void 0;
9973
+ for (const key of SURFACE_OP_KEYS) {
9974
+ const inner = op[key];
9975
+ if (isRecord(inner) && typeof inner.surfaceId === "string") return inner.surfaceId;
9976
+ }
9977
+ return typeof op.surfaceId === "string" ? op.surfaceId : void 0;
9978
+ }
9979
+ /**
9980
+ * Index just past the JSON value starting at `start`, or -1 when the value is
9981
+ * still incomplete. A primitive at the very end of the input counts as
9982
+ * incomplete, since more digits or letters may still stream in.
9983
+ */
9984
+ function findValueEnd(s, start) {
9985
+ const c = s[start];
9986
+ if (c === "\"") {
9987
+ const end = findStringEnd(s, start);
9988
+ return end < 0 ? -1 : end + 1;
9989
+ }
9990
+ if (c === "{" || c === "[") {
9991
+ let depth = 0;
9992
+ for (let i = start; i < s.length; i++) {
9993
+ const ch = s[i];
9994
+ if (ch === "\"") {
9995
+ const end = findStringEnd(s, i);
9996
+ if (end < 0) return -1;
9997
+ i = end;
9998
+ } else if (ch === "{" || ch === "[") depth++;
9999
+ else if (ch === "}" || ch === "]") {
10000
+ depth--;
10001
+ if (depth === 0) return i + 1;
10002
+ }
10003
+ }
10004
+ return -1;
10005
+ }
10006
+ let i = start;
10007
+ while (i < s.length && !isWhitespace(s[i]) && !",}]".includes(s[i])) i++;
10008
+ return i >= s.length ? -1 : i;
10009
+ }
10010
+ /**
10011
+ * Walk the direct entries of the (possibly unterminated) JSON object whose "{"
10012
+ * is at `objStart`, calling `visit` with each key and the index where its value
10013
+ * starts. Nested objects and arrays are skipped whole, so keys inside them are
10014
+ * never visited. Stops when `visit` returns true, at the object's end, or where
10015
+ * the input runs out.
10016
+ */
10017
+ function visitDirectEntries(s, objStart, visit) {
10018
+ let i = objStart + 1;
10019
+ while (i < s.length) {
10020
+ i = skipWhitespace(s, i);
10021
+ const c = s[i];
10022
+ if (c === ",") {
10023
+ i++;
10024
+ continue;
10025
+ }
10026
+ if (c !== "\"") return;
10027
+ const keyEnd = findStringEnd(s, i);
10028
+ if (keyEnd < 0) return;
10029
+ let key;
10030
+ try {
10031
+ key = JSON.parse(s.slice(i, keyEnd + 1));
10032
+ } catch (_unused6) {
10033
+ return;
10034
+ }
10035
+ i = skipWhitespace(s, keyEnd + 1);
10036
+ if (s[i] !== ":") return;
10037
+ i = skipWhitespace(s, i + 1);
10038
+ if (i >= s.length) return;
10039
+ if (typeof key === "string" && visit(key, i)) return;
10040
+ const valueEnd = findValueEnd(s, i);
10041
+ if (valueEnd < 0) return;
10042
+ i = valueEnd;
10043
+ }
10044
+ }
10045
+ /**
10046
+ * Value start of a direct `key` of the object at `objStart` whose value begins
10047
+ * with `opener` (any value when omitted), or -1.
10048
+ */
10049
+ function findDirectKeyValue(s, objStart, key, opener) {
10050
+ let found = -1;
10051
+ visitDirectEntries(s, objStart, (k, valueStart) => {
10052
+ if (k !== key) return false;
10053
+ if (opener === void 0 || s[valueStart] === opener) found = valueStart;
10054
+ return true;
10055
+ });
10056
+ return found;
10057
+ }
10058
+ /** A direct string field of the object at `objStart`, once its closing quote has arrived. */
10059
+ function readDirectString(s, objStart, key) {
10060
+ if (objStart < 0) return null;
10061
+ const start = findDirectKeyValue(s, objStart, key, "\"");
10062
+ if (start < 0) return null;
10063
+ const end = findValueEnd(s, start);
10064
+ if (end < 0) return null;
10065
+ try {
10066
+ const value = JSON.parse(s.slice(start, end));
10067
+ return typeof value === "string" ? value : null;
10068
+ } catch (_unused7) {
10069
+ return null;
10070
+ }
10071
+ }
10072
+ /** A direct object field of the object at `objStart`, once the whole object has arrived. */
10073
+ function readDirectRecord(s, objStart, key) {
10074
+ const start = findDirectKeyValue(s, objStart, key, "{");
10075
+ if (start < 0) return void 0;
10076
+ const end = findValueEnd(s, start);
10077
+ if (end < 0) return void 0;
10078
+ return parseRecord(s.slice(start, end));
10079
+ }
10080
+ /**
10081
+ * The complete part of a (possibly unterminated) JSON value: the parsed value
10082
+ * when it is complete; for an open object, its complete entries plus the
10083
+ * complete items of any streaming array entry; otherwise undefined.
10084
+ */
10085
+ function completePartOfValue(s, start) {
10086
+ const end = findValueEnd(s, start);
10087
+ if (end >= 0) try {
10088
+ return JSON.parse(s.slice(start, end));
10089
+ } catch (_unused8) {
10090
+ return;
10091
+ }
10092
+ if (s[start] !== "{") return void 0;
10093
+ const out = {};
10094
+ visitDirectEntries(s, start, (key, valueStart) => {
10095
+ const valueEnd = findValueEnd(s, valueStart);
10096
+ if (valueEnd >= 0) try {
10097
+ out[key] = JSON.parse(s.slice(valueStart, valueEnd));
10098
+ } catch (_unused9) {}
10099
+ else if (s[valueStart] === "[") {
10100
+ const { items } = completeArrayItemsAt(s, valueStart, { repairComponents: false });
10101
+ if (items.length > 0) out[key] = items;
10102
+ }
10103
+ return false;
10104
+ });
10105
+ return Object.keys(out).length > 0 ? out : void 0;
10106
+ }
10107
+ /**
10108
+ * Best-effort operation from an unfinished or malformed top-level object.
10109
+ * Fields are read only from the operation's own keys (`version` at the top
10110
+ * level, `surfaceId`, `catalogId`, `path`, `dataModel` and `components` inside
10111
+ * the operation object), never from component props or data-model values that
10112
+ * happen to share a name.
10113
+ *
10114
+ * A `createSurface` keeps its complete components and a `dataModel` that has
10115
+ * fully arrived, so a surface created in one line renders while it streams.
10116
+ * A `callRendererFunction` gives nothing: a function must not run with half
10117
+ * of its args.
10118
+ */
10119
+ function partialOperation(line) {
10120
+ var _readDirectString;
10121
+ const root = skipWhitespace(line, 0);
10122
+ if (line[root] !== "{") return null;
10123
+ const version = (_readDirectString = readDirectString(line, root, "version")) !== null && _readDirectString !== void 0 ? _readDirectString : _copilotkit_shared.A2UI_VERSION;
10124
+ const components = findDirectKeyValue(line, root, "updateComponents", "{");
10125
+ if (components >= 0) {
10126
+ const arrayStart = findDirectKeyValue(line, components, "components", "[");
10127
+ if (arrayStart < 0) return null;
10128
+ const { items } = completeArrayItemsAt(line, arrayStart, { repairComponents: true });
10129
+ if (items.length === 0) return null;
10130
+ const surfaceId = readDirectString(line, components, "surfaceId");
10131
+ return {
10132
+ version,
10133
+ updateComponents: {
10134
+ ...surfaceId ? { surfaceId } : {},
10135
+ components: items
10136
+ }
10137
+ };
10138
+ }
10139
+ const data = findDirectKeyValue(line, root, "updateDataModel", "{");
10140
+ if (data >= 0) {
10141
+ const valueStart = findDirectKeyValue(line, data, "value");
10142
+ if (valueStart < 0) return null;
10143
+ const value = completePartOfValue(line, valueStart);
10144
+ if (value === void 0) return null;
10145
+ const surfaceId = readDirectString(line, data, "surfaceId");
10146
+ const path = readDirectString(line, data, "path");
10147
+ return {
10148
+ version,
10149
+ updateDataModel: {
10150
+ ...surfaceId ? { surfaceId } : {},
10151
+ ...path ? { path } : {},
10152
+ value
10153
+ }
10154
+ };
10155
+ }
10156
+ const create = findDirectKeyValue(line, root, "createSurface", "{");
10157
+ if (create >= 0) {
10158
+ const surfaceId = readDirectString(line, create, "surfaceId");
10159
+ if (!surfaceId) return null;
10160
+ const catalogId = readDirectString(line, create, "catalogId");
10161
+ const dataModel = readDirectRecord(line, create, "dataModel");
10162
+ const componentsStart = findDirectKeyValue(line, create, "components", "[");
10163
+ const components = componentsStart < 0 ? [] : completeArrayItemsAt(line, componentsStart, { repairComponents: true }).items;
10164
+ return {
10165
+ version,
10166
+ createSurface: {
10167
+ surfaceId,
10168
+ ...catalogId ? { catalogId } : {},
10169
+ ...dataModel ? { dataModel } : {},
10170
+ ...components.length > 0 ? { components } : {}
10171
+ }
10172
+ };
10173
+ }
10174
+ return null;
10175
+ }
10176
+ /**
10177
+ * A line that opens a new top-level operation: `{"version":"v…` or
10178
+ * `{"<operation>":{`. Seen at the start of a line while an earlier object is
10179
+ * still unbalanced, it means that object is malformed and has ended.
10180
+ */
10181
+ const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"v\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
10182
+ /**
10183
+ * Scan the top-level object whose "{" is at `start`. Returns the index just
10184
+ * past it and whether it balanced. An unbalanced object ends early (at the
10185
+ * start of the line) when a line opens a new operation; otherwise it runs to
10186
+ * the end of the input. JSON strings cannot contain raw newlines, so a newline
10187
+ * inside a string ends it: a stray quote then breaks one line, not the rest of
10188
+ * the fence.
10189
+ */
10190
+ function scanTopLevelObject(s, start) {
10191
+ let depth = 0;
10192
+ let inString = false;
10193
+ for (let i = start; i < s.length; i++) {
10194
+ const c = s[i];
10195
+ if (inString) {
10196
+ if (c === "\\" && s[i + 1] !== "\n") i++;
10197
+ else if (c === "\"" || c === "\n") inString = false;
10198
+ if (c !== "\n") continue;
10199
+ }
10200
+ if (c === "\n") {
10201
+ const next = skipWhitespace(s, i + 1);
10202
+ if (OPERATION_START.test(s.slice(next, next + 40))) return {
10203
+ end: i + 1,
10204
+ balanced: false
10205
+ };
10206
+ continue;
10207
+ }
10208
+ if (c === "\"") inString = true;
10209
+ else if (c === "{" || c === "[") depth++;
10210
+ else if (c === "}" || c === "]") {
10211
+ depth--;
10212
+ if (depth === 0) return {
10213
+ end: i + 1,
10214
+ balanced: true
10215
+ };
10216
+ }
10217
+ }
10218
+ return {
10219
+ end: s.length,
10220
+ balanced: false
10221
+ };
10222
+ }
10223
+ /**
10224
+ * Parse the body of an a2ui fence as a stream of top-level JSON values, so
10225
+ * operations may be one per line (the documented format), several per line,
10226
+ * pretty-printed over many lines, or wrapped in a top-level array (which is
10227
+ * flattened). Whitespace and commas between objects are ignored.
10228
+ *
10229
+ * - A balanced object is `JSON.parse`d. When that fails (e.g. a stray quote),
10230
+ * its raw text goes to `invalidLines` and whatever `partialOperation` can
10231
+ * salvage (complete components, data-model entries, createSurface fields)
10232
+ * is kept.
10233
+ * - An unbalanced object followed by a line that opens a new operation is
10234
+ * treated the same way.
10235
+ * - The trailing unbalanced object (still streaming, or never closed) is
10236
+ * `partialObject` and yields a partial operation when it has usable data.
10237
+ * - Other text between objects is skipped and reported in `recovered` (and in
10238
+ * `invalidLines`, which predates it).
10239
+ *
10240
+ * `partialLine` is a deprecated alias of `partialObject`.
10241
+ *
10242
+ * @param fenceText - The body of an a2ui fence (`text` of an a2ui
10243
+ * `MarkdownSegment`), complete or still streaming.
10244
+ * @returns `{ operations, partialObject, partialLine, invalidLines, recovered }`.
10245
+ *
10246
+ * @example
10247
+ * ```ts
10248
+ * const { operations } = extractFenceOperations(segment.text);
10249
+ * ```
10250
+ */
10251
+ function extractFenceOperations(fenceText) {
10252
+ const s = fenceText;
10253
+ const operations = [];
10254
+ const invalidLines = [];
10255
+ const recovered = [];
10256
+ let partialObject = null;
10257
+ const salvage = (raw) => {
10258
+ invalidLines.push(raw.trim());
10259
+ const partial = partialOperation(raw);
10260
+ if (partial) operations.push(partial);
10261
+ };
10262
+ let junkStart = -1;
10263
+ const flushJunk = (end) => {
10264
+ if (junkStart < 0) return;
10265
+ const junk = s.slice(junkStart, end).trim();
10266
+ junkStart = -1;
10267
+ if (!junk) return;
10268
+ recovered.push(junk);
10269
+ invalidLines.push(junk);
10270
+ };
10271
+ let i = 0;
10272
+ while (i < s.length) {
10273
+ const c = s[i];
10274
+ if (c === "{") {
10275
+ flushJunk(i);
10276
+ const { end, balanced } = scanTopLevelObject(s, i);
10277
+ const raw = s.slice(i, end);
10278
+ if (balanced) {
10279
+ let parsed;
10280
+ try {
10281
+ parsed = JSON.parse(raw);
10282
+ } catch (_unused10) {
10283
+ parsed = void 0;
10284
+ }
10285
+ if (isRecord(parsed)) operations.push(parsed);
10286
+ else salvage(raw);
10287
+ } else if (end < s.length) salvage(raw);
10288
+ else {
10289
+ partialObject = raw;
10290
+ const partial = partialOperation(raw);
10291
+ if (partial) operations.push(partial);
10292
+ }
10293
+ i = end;
10294
+ continue;
10295
+ }
10296
+ if (c === "\n" || c === "[" || c === "]") flushJunk(i);
10297
+ else if (junkStart < 0 && !isWhitespace(c) && c !== ",") junkStart = i;
10298
+ i++;
10299
+ }
10300
+ flushJunk(s.length);
10301
+ return {
10302
+ operations,
10303
+ partialObject,
10304
+ partialLine: partialObject,
10305
+ invalidLines,
10306
+ recovered
10307
+ };
10308
+ }
10309
+ /**
10310
+ * Normalise a fence's operations for the renderer: drop unknown messages, fill
10311
+ * in `version` and missing `surfaceId`s, keep only the first `createSurface`,
10312
+ * keep its `catalogId` when `catalogIds` lists it (else use `catalogId`), synthesize
10313
+ * `createSurface` when the model omitted it, and report the
10314
+ * surfaceId (the first one found, else `fallbackSurfaceId`).
10315
+ *
10316
+ * `callRendererFunction` operations target no surface. They get no surfaceId,
10317
+ * do not cause a synthesized `createSurface`, and come back in
10318
+ * `functionCalls` (in fence order), never in `operations`.
10319
+ *
10320
+ * @param input.operations - Operations from `extractFenceOperations`.
10321
+ * @param input.fallbackSurfaceId - The surfaceId to use when no operation
10322
+ * names one.
10323
+ * @param input.catalogId - The client catalog. It replaces a catalogId of the
10324
+ * model that `catalogIds` does not list.
10325
+ * @param input.catalogIds - The catalogs that the model can name. Left out,
10326
+ * only `catalogId`.
10327
+ * @returns `{ surfaceId, operations, functionCalls }`.
10328
+ *
10329
+ * @example
10330
+ * ```ts
10331
+ * const { surfaceId, operations, functionCalls } = prepareSurfaceOperations({
10332
+ * operations: extractFenceOperations(segment.text).operations,
10333
+ * fallbackSurfaceId: `${messageId}-${segment.index}`,
10334
+ * catalogId,
10335
+ * });
10336
+ * ```
10337
+ */
10338
+ function prepareSurfaceOperations(input) {
10339
+ var _input$catalogIds, _operations$map$find;
10340
+ const { operations, fallbackSurfaceId, catalogId } = input;
10341
+ const catalogIds = (_input$catalogIds = input.catalogIds) !== null && _input$catalogIds !== void 0 ? _input$catalogIds : [catalogId];
10342
+ const surfaceId = (_operations$map$find = operations.map(getMarkdownOperationSurfaceId).find((id) => !!id)) !== null && _operations$map$find !== void 0 ? _operations$map$find : fallbackSurfaceId;
10343
+ const out = [];
10344
+ const functionCalls = [];
10345
+ let hasCreate = false;
10346
+ for (const op of operations) {
10347
+ const entry = getOperationEntry(op);
10348
+ if (!entry) continue;
10349
+ const { key } = entry;
10350
+ const inner = { ...entry.inner };
10351
+ const version = typeof op.version === "string" ? op.version : _copilotkit_shared.A2UI_VERSION;
10352
+ if (key === FUNCTION_CALL_KEY) {
10353
+ functionCalls.push({
10354
+ version,
10355
+ [key]: inner
10356
+ });
10357
+ continue;
10358
+ }
10359
+ if (typeof inner.surfaceId !== "string") inner.surfaceId = surfaceId;
10360
+ if (key === "createSurface") {
10361
+ if (hasCreate) {
10362
+ const { surfaceId: id, dataModel, components } = inner;
10363
+ if (dataModel !== void 0) out.push({
10364
+ version,
10365
+ updateDataModel: {
10366
+ surfaceId: id,
10367
+ path: "/",
10368
+ value: dataModel
10369
+ }
10370
+ });
10371
+ if (Array.isArray(components) && components.length > 0) out.push({
10372
+ version,
10373
+ updateComponents: {
10374
+ surfaceId: id,
10375
+ components
10376
+ }
10377
+ });
10378
+ continue;
10379
+ }
10380
+ hasCreate = true;
10381
+ if (!catalogIds.includes(inner.catalogId)) inner.catalogId = catalogId;
10382
+ }
10383
+ out.push({
10384
+ version,
10385
+ [key]: inner
10386
+ });
10387
+ }
10388
+ if (!hasCreate && out.length > 0) out.unshift({
10389
+ version: _copilotkit_shared.A2UI_VERSION,
10390
+ createSurface: {
10391
+ surfaceId,
10392
+ catalogId
10393
+ }
10394
+ });
10395
+ return {
10396
+ surfaceId,
10397
+ operations: out,
10398
+ functionCalls
10399
+ };
10400
+ }
10401
+ /**
10402
+ * Components a user operates. A Card containing one of these is an
10403
+ * interactive panel and keeps its box; every other Card is informational.
10404
+ */
10405
+ const INTERACTIVE_COMPONENTS = new Set([
10406
+ "Button",
10407
+ "Pressable",
10408
+ "Form",
10409
+ "TextField",
10410
+ "TextArea",
10411
+ "Select",
10412
+ "CheckBox",
10413
+ "Radio",
10414
+ "RadioGroup",
10415
+ "Slider",
10416
+ "SegmentedControl",
10417
+ "ChoicePicker",
10418
+ "DateTimeInput"
10419
+ ]);
10420
+ /** A component id referenced by a `child`/`children` entry or a table cell. */
10421
+ function referencedId(value) {
10422
+ if (typeof value === "string") return value;
10423
+ if (isRecord(value)) {
10424
+ if (typeof value.componentId === "string") return value.componentId;
10425
+ if (typeof value.id === "string") return value.id;
10426
+ }
10427
+ }
10428
+ /** Ids of a table cell / column that renders a component (`{componentId}` or `{id}`). */
10429
+ function cellComponentId(value) {
10430
+ return isRecord(value) ? referencedId(value) : void 0;
10431
+ }
10432
+ /**
10433
+ * Ids a component renders directly: `child`, `children` (string ids, an
10434
+ * array, or a `{componentId}` template), component cells of a Table's
10435
+ * `rows`/`columns`, and the ids that `extra` finds in its typed references.
10436
+ */
10437
+ function directChildIds(component, extra) {
10438
+ const ids = [];
10439
+ const add = (id) => {
10440
+ if (id) ids.push(id);
10441
+ };
10442
+ const extraIds = extra === null || extra === void 0 ? void 0 : extra(component);
10443
+ if (Array.isArray(extraIds)) extraIds.forEach(add);
10444
+ add(referencedId(component.child));
10445
+ const children = component.children;
10446
+ if (Array.isArray(children)) children.forEach((c) => add(referencedId(c)));
10447
+ else add(referencedId(children));
10448
+ if (Array.isArray(component.columns)) component.columns.forEach((c) => add(cellComponentId(c)));
10449
+ if (Array.isArray(component.rows)) {
10450
+ for (const row of component.rows) if (Array.isArray(row)) row.forEach((c) => add(cellComponentId(c)));
10451
+ }
10452
+ return ids;
10453
+ }
10454
+ /** Components of every updateComponents operation, by id (last definition wins). */
10455
+ function componentsById(operations) {
10456
+ const byId = /* @__PURE__ */ new Map();
10457
+ for (const op of operations) {
10458
+ const update = op.updateComponents;
10459
+ const list = isRecord(update) ? update.components : void 0;
10460
+ if (!Array.isArray(list)) continue;
10461
+ for (const c of list) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
10462
+ }
10463
+ return byId;
10464
+ }
10465
+ function descendantIds(rootId, byId, extra) {
10466
+ var _byId$get;
10467
+ const seen = /* @__PURE__ */ new Set();
10468
+ const stack = [...directChildIds((_byId$get = byId.get(rootId)) !== null && _byId$get !== void 0 ? _byId$get : {}, extra)];
10469
+ while (stack.length > 0) {
10470
+ const id = stack.pop();
10471
+ if (seen.has(id) || id === rootId) continue;
10472
+ seen.add(id);
10473
+ const c = byId.get(id);
10474
+ if (c) stack.push(...directChildIds(c, extra));
10475
+ }
10476
+ return seen;
10477
+ }
10478
+ /**
10479
+ * Ids of the `Card` components that are interactive panels: at least one
10480
+ * descendant (via `child`, `children` or table component cells) is a control
10481
+ * (Button, Pressable, Form, TextField, TextArea, Select, CheckBox, Radio,
10482
+ * RadioGroup, Slider, SegmentedControl, DateTimeInput).
10483
+ *
10484
+ * @param components - The components of one surface.
10485
+ * @returns The ids of the interactive cards.
10486
+ *
10487
+ * @example
10488
+ * ```ts
10489
+ * const interactive = classifySurfaceCards(components);
10490
+ * const keepsBox = interactive.has("quote-form");
10491
+ * ```
10492
+ */
10493
+ function classifySurfaceCards(components, options = {}) {
10494
+ const byId = /* @__PURE__ */ new Map();
10495
+ for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
10496
+ const interactive = /* @__PURE__ */ new Set();
10497
+ for (const [id, c] of byId) {
10498
+ if (c.component !== "Card") continue;
10499
+ for (const d of descendantIds(id, byId, options.childIds)) {
10500
+ var _byId$get2;
10501
+ const type = (_byId$get2 = byId.get(d)) === null || _byId$get2 === void 0 ? void 0 : _byId$get2.component;
10502
+ if (typeof type === "string" && INTERACTIVE_COMPONENTS.has(type)) {
10503
+ interactive.add(id);
10504
+ break;
10505
+ }
10506
+ }
10507
+ }
10508
+ return interactive;
10509
+ }
10510
+ /**
10511
+ * Markdown mode: only interactive panels keep a box. Every `Card` that is not
10512
+ * an interactive panel (see `classifySurfaceCards`), sets no `variant` or
10513
+ * `border` of its own and is not nested inside an interactive panel becomes
10514
+ * `variant: "section"` (a heading plus content without a box). Operations
10515
+ * other than updateComponents pass through unchanged.
10516
+ *
10517
+ * @param operations - The operations of one surface.
10518
+ * @returns The operations with informational cards set to `variant: "section"`.
10519
+ * When no card changes, it returns the same array.
10520
+ *
10521
+ * @example
10522
+ * ```ts
10523
+ * const operations = flattenInformationalCards(prepared.operations);
10524
+ * ```
10525
+ */
10526
+ function flattenInformationalCards(operations, options = {}) {
10527
+ const byId = componentsById(operations);
10528
+ if (![...byId.values()].some((c) => c.component === "Card")) return operations;
10529
+ const interactive = classifySurfaceCards([...byId.values()], options);
10530
+ const insideInteractive = /* @__PURE__ */ new Set();
10531
+ for (const id of interactive) for (const d of descendantIds(id, byId, options.childIds)) insideInteractive.add(d);
10532
+ const flatten = (c) => c.component === "Card" && typeof c.id === "string" && !interactive.has(c.id) && !insideInteractive.has(c.id) && c.variant == null && c.border == null;
10533
+ return operations.map((op) => {
10534
+ const update = op.updateComponents;
10535
+ if (!isRecord(update) || !Array.isArray(update.components)) return op;
10536
+ if (!update.components.some((c) => isRecord(c) && flatten(c))) return op;
10537
+ return {
10538
+ ...op,
10539
+ updateComponents: {
10540
+ ...update,
10541
+ components: update.components.map((c) => isRecord(c) && flatten(c) ? {
10542
+ ...c,
10543
+ variant: "section"
10544
+ } : c)
10545
+ }
10546
+ };
10547
+ });
10548
+ }
10549
+ /** Text-bearing components that belong in the chat's markdown, not a surface. */
10550
+ const PROSE_TEXT_COMPONENTS = new Set([
10551
+ "Title",
10552
+ "Text",
10553
+ "Caption",
10554
+ "Markdown"
10555
+ ]);
10556
+ /** One line of text: list items and headings cannot span lines in markdown. */
10557
+ function oneLine(text) {
10558
+ return text.trim().replace(/\s*\n\s*/g, " ");
10559
+ }
10560
+ /**
10561
+ * A literal List entry as list-item markdown: a non-empty string, or
10562
+ * `{ label, description? }` with literal strings only. Anything carrying
10563
+ * behaviour or decoration (`icon`, `action`, other keys, bound values) is null.
10564
+ */
10565
+ function listEntryMarkdown(entry) {
10566
+ if (typeof entry === "string") return entry.trim() ? oneLine(entry) : null;
10567
+ if (!isRecord(entry)) return null;
10568
+ for (const key of Object.keys(entry)) if (key !== "label" && key !== "description") return null;
10569
+ if (typeof entry.label !== "string" || !entry.label.trim()) return null;
10570
+ const label = oneLine(entry.label);
10571
+ if (entry.description === void 0) return label;
10572
+ if (typeof entry.description !== "string") return null;
10573
+ return entry.description.trim() ? `**${label}** — ${oneLine(entry.description)}` : label;
10574
+ }
10575
+ /**
10576
+ * A List of literal text items as a markdown list (`marker: "number"` →
10577
+ * `1. …`, otherwise `- …`), or null when it binds its items, renders
10578
+ * `children`, or any item is not plain text.
10579
+ */
10580
+ function listToMarkdown(c) {
10581
+ const children = c.children;
10582
+ if (children != null && !(Array.isArray(children) && children.length === 0)) return null;
10583
+ if (!Array.isArray(c.items) || c.items.length === 0) return null;
10584
+ const lines = [];
10585
+ for (const entry of c.items) {
10586
+ const line = listEntryMarkdown(entry);
10587
+ if (line === null) return null;
10588
+ lines.push(line);
10589
+ }
10590
+ if (c.marker === "number") {
10591
+ const start = typeof c.start === "number" && Number.isInteger(c.start) ? c.start : 1;
10592
+ return lines.map((line, i) => `${start + i}. ${line}`).join("\n");
10593
+ }
10594
+ return lines.map((line) => `- ${line}`).join("\n");
10595
+ }
10596
+ /** The prose item a component converts to, or null when it is not prose. */
10597
+ function toProseItem(c) {
10598
+ if (!c) return null;
10599
+ if (c.accessibility !== void 0) return null;
10600
+ if (c.component === "Divider") return { kind: "divider" };
10601
+ if (c.component === "Spacer") return { kind: "spacer" };
10602
+ if (c.component === "List") {
10603
+ if (c.direction !== void 0 && c.direction !== "vertical") return null;
10604
+ const markdown = listToMarkdown(c);
10605
+ return markdown === null ? null : {
10606
+ kind: "text",
10607
+ markdown
10608
+ };
10609
+ }
10610
+ if (typeof c.component !== "string") return null;
10611
+ if (!PROSE_TEXT_COMPONENTS.has(c.component)) return null;
10612
+ if (typeof c.text !== "string" || c.text.trim() === "") return null;
10613
+ const text = c.text.trim();
10614
+ switch (c.component) {
10615
+ case "Title": {
10616
+ const size = typeof c.size === "string" ? c.size : "md";
10617
+ return {
10618
+ kind: "text",
10619
+ markdown: `${size === "sm" ? "####" : size === "md" || size === "lg" ? "###" : "##"} ${text}`
10620
+ };
10621
+ }
10622
+ case "Text":
10623
+ if (directChildIds(c).length > 0) return null;
10624
+ return {
10625
+ kind: "text",
10626
+ markdown: c.strong === true ? `**${text}**` : text
10627
+ };
10628
+ default: return {
10629
+ kind: "text",
10630
+ markdown: text
10631
+ };
10632
+ }
10633
+ }
10634
+ /** Prose items as markdown: separators only survive between two text items. */
10635
+ function proseItemsToMarkdown(items) {
10636
+ const blocks = [];
10637
+ let pendingDivider = false;
10638
+ for (const item of items) if ((item === null || item === void 0 ? void 0 : item.kind) === "text") {
10639
+ if (pendingDivider && blocks.length > 0) blocks.push("---");
10640
+ pendingDivider = false;
10641
+ blocks.push(item.markdown);
10642
+ } else if ((item === null || item === void 0 ? void 0 : item.kind) === "divider") pendingDivider = true;
10643
+ return blocks.join("\n\n");
10644
+ }
10645
+ /** Column, column-direction Box, or an informational Card (section/unset variant). */
10646
+ function isVerticalStack(c, interactiveCards) {
10647
+ if (c.accessibility !== void 0) return false;
10648
+ if (c.component === "Column") return true;
10649
+ if (c.component === "Box") return c.direction == null || c.direction === "col";
10650
+ if (c.component === "Card") return (c.variant == null || c.variant === "section") && typeof c.id === "string" && !interactiveCards.has(c.id);
10651
+ return false;
10652
+ }
10653
+ /** The child-id list of a stack (`children`, or a lone `child`), else null. */
10654
+ /**
10655
+ * The children of a stack in render order: `child` first (a Card renders
10656
+ * its `child` before its `children`), then `children`.
10657
+ */
10658
+ function stackChildren(c) {
10659
+ const first = typeof c.child === "string" ? [c.child] : [];
10660
+ if (Array.isArray(c.children)) return [...first, ...c.children];
10661
+ if (first.length > 0 && c.children === void 0) return first;
10662
+ return null;
10663
+ }
10664
+ /**
10665
+ * Partitions the stack's children into alternating prose and surface runs.
10666
+ * A run of consecutive prose items is prose only when it holds text: a run of
10667
+ * separators alone (Divider/Spacer between two UI components, or at the very
10668
+ * start/end of the stack) stays with the surface it sits in.
10669
+ */
10670
+ function partitionChildren(items) {
10671
+ const runs = [];
10672
+ let i = 0;
10673
+ while (i < items.length) {
10674
+ const candidate = items[i] !== null;
10675
+ let hasText = false;
10676
+ let j = i;
10677
+ while (j < items.length && items[j] !== null === candidate) {
10678
+ var _items$j;
10679
+ if (((_items$j = items[j]) === null || _items$j === void 0 ? void 0 : _items$j.kind) === "text") hasText = true;
10680
+ j++;
10681
+ }
10682
+ const prose = candidate && hasText;
10683
+ const last = runs[runs.length - 1];
10684
+ if (!prose && last && !last.prose) last.end = j;
10685
+ else runs.push({
10686
+ prose,
10687
+ start: i,
10688
+ end: j
10689
+ });
10690
+ i = j;
10691
+ }
10692
+ return runs;
10693
+ }
10694
+ /**
10695
+ * Markdown mode: split a surface into markdown and surface segments so that
10696
+ * only real UI renders as A2UI and everything else is the chat's markdown.
10697
+ *
10698
+ * From `root`, descend through single-child vertical containers (Column,
10699
+ * column Box, informational Card) to the first one with several children:
10700
+ * the stack. Its children are partitioned, in order, into runs of prose and
10701
+ * runs of UI. Prose is `Title`, `Text`, `Caption`, `Markdown` with literal
10702
+ * text, a `List` of literal text items, plus `Divider`/`Spacer` next to them:
10703
+ * `Title` → heading by size (sm `####`, md/lg `###`, larger `##`), `Text` →
10704
+ * paragraph (`strong` → `**…**`), `Caption`/`Markdown` → paragraph, `List` →
10705
+ * `- …` (or `1. …` for `marker: "number"`, `**label** — description` for
10706
+ * described items), and a `Divider` between two prose blocks → `---`.
10707
+ *
10708
+ * Not prose: `{path}`-bound text or items, a Text with inline children, a
10709
+ * List with `children`/icons/actions, a template entry, a component with an
10710
+ * `accessibility` envelope, and a child whose component has not streamed
10711
+ * yet. Separators with no text beside them stay in
10712
+ * the surface. An interactive Card (see `classifySurfaceCards`) is never
10713
+ * entered.
10714
+ *
10715
+ * Each prose run becomes a markdown segment; each UI run becomes a surface
10716
+ * segment whose `root` is a copy of the stack (its other props kept, `child`
10717
+ * dropped) with only that run's `children`, followed by every component
10718
+ * reachable from them. When nothing is prose the input comes back as the one
10719
+ * surface segment (same array); when everything is (or `root` itself is),
10720
+ * there are only markdown segments.
10721
+ *
10722
+ * Pure and linear in the number of components, so it runs on every stream
10723
+ * update.
10724
+ *
10725
+ * @param components - The components of one surface, root included.
10726
+ * @returns The segments in render order.
10727
+ *
10728
+ * @example
10729
+ * ```ts
10730
+ * for (const segment of segmentSurfaceProse(components)) {
10731
+ * if (segment.kind === "markdown") renderMarkdown(segment.markdown);
10732
+ * else renderSurface(segment.components);
10733
+ * }
10734
+ * ```
10735
+ */
10736
+ function segmentSurfaceProse(components, options = {}) {
10737
+ const unchanged = [{
10738
+ kind: "surface",
10739
+ components
10740
+ }];
10741
+ const byId = /* @__PURE__ */ new Map();
10742
+ for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
10743
+ const root = byId.get(_copilotkit_shared.GENERATIVE_UI_ROOT_ID);
10744
+ if (!root) return unchanged;
10745
+ if (components.some((c) => {
10746
+ var _options$childIds;
10747
+ return isRecord(c) && ((_options$childIds = options.childIds) === null || _options$childIds === void 0 ? void 0 : _options$childIds.call(options, c)) === "unknown";
10748
+ })) return unchanged;
10749
+ const rootItem = toProseItem(root);
10750
+ if ((rootItem === null || rootItem === void 0 ? void 0 : rootItem.kind) === "text") return [{
10751
+ kind: "markdown",
10752
+ markdown: rootItem.markdown
10753
+ }];
10754
+ const interactiveCards = classifySurfaceCards(components, options);
10755
+ let stack = root;
10756
+ let stackId = _copilotkit_shared.GENERATIVE_UI_ROOT_ID;
10757
+ let children;
10758
+ const visited = /* @__PURE__ */ new Set();
10759
+ while (true) {
10760
+ if (!isVerticalStack(stack, interactiveCards)) return unchanged;
10761
+ visited.add(stackId);
10762
+ const list = stackChildren(stack);
10763
+ if (!list) return unchanged;
10764
+ children = list;
10765
+ const nextId = list.length === 1 ? list[0] : void 0;
10766
+ if (typeof nextId !== "string") break;
10767
+ const next = byId.get(nextId);
10768
+ if (!next || visited.has(nextId) || toProseItem(next)) break;
10769
+ stack = next;
10770
+ stackId = nextId;
10771
+ }
10772
+ const stackChildIds = children;
10773
+ const items = stackChildIds.map((id) => typeof id === "string" ? toProseItem(byId.get(id)) : null);
10774
+ const runs = partitionChildren(items);
10775
+ if (!runs.some((run) => run.prose)) return unchanged;
10776
+ const surfaceRuns = runs.filter((run) => !run.prose);
10777
+ const owners = /* @__PURE__ */ new Map();
10778
+ surfaceRuns.forEach((run, index) => {
10779
+ const pending = stackChildIds.slice(run.start, run.end).map(referencedId).filter((id) => id !== void 0);
10780
+ const seen = /* @__PURE__ */ new Set();
10781
+ while (pending.length > 0) {
10782
+ const id = pending.pop();
10783
+ if (id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID || id === stackId || seen.has(id)) continue;
10784
+ seen.add(id);
10785
+ const list = owners.get(id);
10786
+ if (list) list.push(index);
10787
+ else owners.set(id, [index]);
10788
+ const c = byId.get(id);
10789
+ if (c) pending.push(...directChildIds(c, options.childIds));
10790
+ }
10791
+ });
10792
+ const surfaceComponents = surfaceRuns.map((run) => {
10793
+ const { child: _child, ...stackRest } = stack;
10794
+ const nextRoot = {
10795
+ ...stackRest,
10796
+ id: _copilotkit_shared.GENERATIVE_UI_ROOT_ID,
10797
+ children: stackChildIds.slice(run.start, run.end)
10798
+ };
10799
+ delete nextRoot.child;
10800
+ return [nextRoot];
10801
+ });
10802
+ for (const c of components) {
10803
+ var _owners$get;
10804
+ if (!isRecord(c) || typeof c.id !== "string" || byId.get(c.id) !== c) continue;
10805
+ const ownerIndexes = (_owners$get = owners.get(c.id)) !== null && _owners$get !== void 0 ? _owners$get : [];
10806
+ for (const index of ownerIndexes) surfaceComponents[index].push(c);
10807
+ }
10808
+ let surfaceIndex = 0;
10809
+ return runs.map((run) => {
10810
+ if (run.prose) return {
10811
+ kind: "markdown",
10812
+ markdown: proseItemsToMarkdown(items.slice(run.start, run.end))
10813
+ };
10814
+ return {
10815
+ kind: "surface",
10816
+ components: surfaceComponents[surfaceIndex++]
10817
+ };
10818
+ });
10819
+ }
10820
+
10821
+ //#endregion
10822
+ exports.A2UI_FENCE_LANGUAGE = A2UI_FENCE_LANGUAGE;
9447
10823
  exports.AgentRegistry = AgentRegistry;
9448
10824
  exports.AgentThreadLockedError = AgentThreadLockedError;
9449
10825
  exports.ContextStore = ContextStore;
@@ -9461,6 +10837,7 @@ exports.StateManager = StateManager;
9461
10837
  exports.SuggestionEngine = SuggestionEngine;
9462
10838
  exports.ToolCallStatus = ToolCallStatus;
9463
10839
  exports.WebMCPRegistry = WebMCPRegistry;
10840
+ exports.classifySurfaceCards = classifySurfaceCards;
9464
10841
  exports.completePartialMarkdown = completePartialMarkdown;
9465
10842
  exports.createActionGroup = createActionGroup;
9466
10843
  exports.createEffect = createEffect;
@@ -9474,6 +10851,11 @@ exports.emitInspectorViewThread = emitInspectorViewThread;
9474
10851
  exports.emitInspectorViewThreadResult = emitInspectorViewThreadResult;
9475
10852
  exports.empty = empty;
9476
10853
  exports.ensureObjectArgs = ensureObjectArgs;
10854
+ exports.extractCompleteArrayItems = extractCompleteArrayItems;
10855
+ exports.extractFenceOperations = extractFenceOperations;
10856
+ exports.extractStringField = extractStringField;
10857
+ exports.flattenInformationalCards = flattenInformationalCards;
10858
+ exports.getMarkdownOperationSurfaceId = getMarkdownOperationSurfaceId;
9477
10859
  exports.getWebMCPModelContext = getWebMCPModelContext;
9478
10860
  exports.isAbortError = isAbortError;
9479
10861
  exports.isInspectorThreadBridgeEnabled = isInspectorThreadBridgeEnabled;
@@ -9485,8 +10867,11 @@ exports.onInspectorStopViewing = onInspectorStopViewing;
9485
10867
  exports.onInspectorViewThread = onInspectorViewThread;
9486
10868
  exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
9487
10869
  exports.parseToolArguments = parseToolArguments;
10870
+ exports.prepareSurfaceOperations = prepareSurfaceOperations;
9488
10871
  exports.props = props;
10872
+ exports.segmentSurfaceProse = segmentSurfaceProse;
9489
10873
  exports.select = select;
10874
+ exports.splitA2UIMarkdown = splitA2UIMarkdown;
9490
10875
  exports.ɵCOPILOTKIT_FEATURES = ɵCOPILOTKIT_FEATURES;
9491
10876
  exports.ɵInterruptState = ɵInterruptState;
9492
10877
  exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;