@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.cjs CHANGED
@@ -3076,6 +3076,17 @@ var AgentRegistry = class {
3076
3076
  }
3077
3077
  };
3078
3078
 
3079
+ //#endregion
3080
+ //#region src/core/agent-scope.ts
3081
+ /**
3082
+ * True when an entry scoped to `agentIds` goes to a run of `agentId`. An
3083
+ * entry without `agentIds` goes to every agent; an entry with them does not
3084
+ * go to a run without an agent id. Internal, not exported.
3085
+ */
3086
+ function isForAgent(agentIds, agentId) {
3087
+ return agentIds === void 0 || agentId !== void 0 && agentIds.includes(agentId);
3088
+ }
3089
+
3079
3090
  //#endregion
3080
3091
  //#region src/core/context-store.ts
3081
3092
  /**
@@ -3114,7 +3125,7 @@ var ContextStore = class {
3114
3125
  * protocol-shaped `{ description, value }` entries go over the wire.
3115
3126
  */
3116
3127
  getContextForAgent(agentId) {
3117
- return Object.values(this._context).filter((entry) => !entry.agentIds || agentId !== void 0 && entry.agentIds.includes(agentId)).map(({ description, value }) => ({
3128
+ return Object.values(this._context).filter((entry) => isForAgent(entry.agentIds, agentId)).map(({ description, value }) => ({
3118
3129
  description,
3119
3130
  value
3120
3131
  }));
@@ -3299,7 +3310,7 @@ var SuggestionEngine = class {
3299
3310
  await suggestionAgent.runAgent({
3300
3311
  context: friends.getContextForAgent(consumerAgentId),
3301
3312
  forwardedProps: {
3302
- ...friends.properties,
3313
+ ...friends.getPropertiesForAgent(consumerAgentId),
3303
3314
  toolChoice: {
3304
3315
  type: "function",
3305
3316
  function: { name: "copilotkitSuggest" }
@@ -4075,7 +4086,7 @@ var RunHandler = class {
4075
4086
  newMessages: []
4076
4087
  };
4077
4088
  const runAgentResult = await agent.connectAgent({
4078
- forwardedProps: this._internal.properties,
4089
+ forwardedProps: this._internal.getPropertiesForAgent(agent.agentId),
4079
4090
  tools: this.buildFrontendTools(agent.agentId),
4080
4091
  context: this._internal.getContextForAgent(agent.agentId)
4081
4092
  }, this.createAgentErrorSubscriber(agent));
@@ -4191,7 +4202,7 @@ var RunHandler = class {
4191
4202
  const pinRunIdOnWire = runId !== void 0 && !continuationHandoff;
4192
4203
  const agentRunInput = {
4193
4204
  forwardedProps: {
4194
- ...this._internal.properties,
4205
+ ...this._internal.getPropertiesForAgent(agent.agentId),
4195
4206
  ...forwardedProps
4196
4207
  },
4197
4208
  ...resume !== void 0 ? { resume } : {},
@@ -7125,6 +7136,10 @@ const ɵselectMemoriesRealtimeStatus = selectMemoriesRealtimeStatus;
7125
7136
 
7126
7137
  //#endregion
7127
7138
  //#region src/core/core.ts
7139
+ /** True for an object literal. Arrays, `null`, and class instances are not plain objects. */
7140
+ function isPlainObject(value) {
7141
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
7142
+ }
7128
7143
  let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode) {
7129
7144
  CopilotKitCoreErrorCode["RUNTIME_INFO_FETCH_FAILED"] = "runtime_info_fetch_failed";
7130
7145
  CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
@@ -7190,6 +7205,7 @@ var CopilotKitCore = class {
7190
7205
  _credentials;
7191
7206
  _messageFilter;
7192
7207
  _properties;
7208
+ _scopedProperties = /* @__PURE__ */ new Map();
7193
7209
  _defaultThrottleMs;
7194
7210
  _debug;
7195
7211
  subscribers = /* @__PURE__ */ new Set();
@@ -7202,6 +7218,8 @@ var CopilotKitCore = class {
7202
7218
  learningBridge;
7203
7219
  notifiedTrajectoryId = null;
7204
7220
  learningConfiguredListeners = /* @__PURE__ */ new Set();
7221
+ _generativeUIDebugSource;
7222
+ generativeUIDebugListeners = /* @__PURE__ */ new Set();
7205
7223
  /**
7206
7224
  * The single core-owned memory store, created lazily on first
7207
7225
  * `getMemoryStore()` and kept user-scoped for the lifetime of the core.
@@ -7535,6 +7553,59 @@ var CopilotKitCore = class {
7535
7553
  this._messageFilter = messageFilter;
7536
7554
  this.agentRegistry.applyMessageFilterToAgents(this.agentRegistry.agents);
7537
7555
  }
7556
+ /**
7557
+ * Add run properties that go only to the runs of `agentIds`. When
7558
+ * `agentIds` is omitted, every agent gets them. They merge on top of the
7559
+ * base `properties`.
7560
+ *
7561
+ * When an entry value and the existing value under the same key are both
7562
+ * plain objects, their keys merge one level deep. So several entries can
7563
+ * add keys under one namespace (for example `copilotkit`).
7564
+ *
7565
+ * @param entry - The properties and the optional agent ids.
7566
+ * @returns The id to pass to `removeScopedProperties`.
7567
+ *
7568
+ * @example
7569
+ * const id = copilotkit.addScopedProperties({
7570
+ * properties: { copilotkit: { theme: "dark" } },
7571
+ * agentIds: ["research"],
7572
+ * });
7573
+ * copilotkit.removeScopedProperties(id);
7574
+ */
7575
+ addScopedProperties({ properties, agentIds }) {
7576
+ let id = (0, _copilotkit_shared.randomUUID)();
7577
+ for (let n = 1; this._scopedProperties.has(id); n++) id = `${id}-${n}`;
7578
+ this._scopedProperties.set(id, {
7579
+ properties,
7580
+ ...agentIds ? { agentIds } : {}
7581
+ });
7582
+ return id;
7583
+ }
7584
+ /** Remove an entry that `addScopedProperties` added. An unknown id does nothing. */
7585
+ removeScopedProperties(id) {
7586
+ this._scopedProperties.delete(id);
7587
+ }
7588
+ /**
7589
+ * Build the forwarded properties for a run of the given agent: the base
7590
+ * properties plus every scoped entry that matches the agent. An entry with
7591
+ * `agentIds` does not match when `agentId` is omitted.
7592
+ */
7593
+ getPropertiesForAgent(agentId) {
7594
+ const merged = { ...this._properties };
7595
+ const entries = this._scopedProperties.values();
7596
+ for (const entry of entries) {
7597
+ if (!isForAgent(entry.agentIds, agentId)) continue;
7598
+ const properties = Object.entries(entry.properties);
7599
+ for (const [key, value] of properties) {
7600
+ const base = merged[key];
7601
+ merged[key] = isPlainObject(base) && isPlainObject(value) ? {
7602
+ ...base,
7603
+ ...value
7604
+ } : value;
7605
+ }
7606
+ }
7607
+ return merged;
7608
+ }
7538
7609
  setProperties(properties) {
7539
7610
  this._properties = properties;
7540
7611
  this.notifySubscribers((subscriber) => subscriber.onPropertiesChanged?.({
@@ -7614,6 +7685,30 @@ var CopilotKitCore = class {
7614
7685
  this.learningConfiguredListeners.delete(listener);
7615
7686
  };
7616
7687
  }
7688
+ /**
7689
+ * @internal The generative UI of the framework package, for the inspector.
7690
+ * `undefined` when no provider has a `generativeUI` config.
7691
+ */
7692
+ get ɵgenerativeUIDebugSource() {
7693
+ return this._generativeUIDebugSource;
7694
+ }
7695
+ /** @internal Set by the framework package. `undefined` removes it. */
7696
+ ɵsetGenerativeUIDebugSource(source) {
7697
+ if (source === this._generativeUIDebugSource) return;
7698
+ this._generativeUIDebugSource = source;
7699
+ for (const listener of [...this.generativeUIDebugListeners]) try {
7700
+ listener();
7701
+ } catch (error) {
7702
+ console.error("Generative UI debug listener error:", error);
7703
+ }
7704
+ }
7705
+ /** @internal Calls `listener` when {@link ɵgenerativeUIDebugSource} is set or removed. */
7706
+ ɵsubscribeToGenerativeUIDebugSource(listener) {
7707
+ this.generativeUIDebugListeners.add(listener);
7708
+ return () => {
7709
+ this.generativeUIDebugListeners.delete(listener);
7710
+ };
7711
+ }
7617
7712
  /** The active capture's Trajectory ID, or null while capture is stopped. */
7618
7713
  get trajectoryId() {
7619
7714
  return this.learningBridge.trajectoryId;
@@ -9200,6 +9295,1276 @@ function onInspectorViewThreadResult(handler) {
9200
9295
  }
9201
9296
 
9202
9297
  //#endregion
9298
+ //#region src/a2ui-markdown/fence-parser.ts
9299
+ /** Language of a fenced code block that carries A2UI operations. */
9300
+ const A2UI_FENCE_LANGUAGE = "a2ui";
9301
+ /** Column-0 fence opener: a run of 3+ backticks or tildes, then the info string. */
9302
+ const FENCE_OPEN = /^(`{3,}|~{3,})(.*)$/;
9303
+ /** Info-string token that names the placement target of an a2ui fence. */
9304
+ const TARGET_TOKEN = /^target=(.+)$/;
9305
+ function isCloser(line, fence) {
9306
+ const trimmed = line.trim();
9307
+ if (trimmed.length < fence.length) return false;
9308
+ for (const ch of trimmed) if (ch !== fence.char) return false;
9309
+ return true;
9310
+ }
9311
+ /** The id of the first `target=<id>` token. Other tokens are ignored. */
9312
+ function readTarget(tokens) {
9313
+ for (const token of tokens) {
9314
+ const match = TARGET_TOKEN.exec(token);
9315
+ if (match) return match[1];
9316
+ }
9317
+ }
9318
+ function a2uiSegment(fence, text, closed) {
9319
+ const segment = {
9320
+ type: "a2ui",
9321
+ index: fence.index,
9322
+ text,
9323
+ closed
9324
+ };
9325
+ if (fence.target !== void 0) segment.target = fence.target;
9326
+ return segment;
9327
+ }
9328
+ /**
9329
+ * Split a (possibly still streaming) markdown string into prose segments and
9330
+ * top-level ```a2ui fences. Fences of other languages stay inside prose
9331
+ * segments byte-for-byte, and a2ui markers inside them are ignored. Only
9332
+ * column-0 fences are recognised, so a fence indented inside a list item is
9333
+ * left to the markdown renderer.
9334
+ *
9335
+ * The first info-string token must be exactly `a2ui`. A later
9336
+ * `target=<id>` token sets `target` on the segment (for example
9337
+ * ```` ```a2ui target=recommendations ````). Other tokens are ignored.
9338
+ *
9339
+ * An a2ui segment's `text` is the fence body. For a closed fence it ends with
9340
+ * "\n" when non-empty. For an open (still streaming or aborted) fence it is
9341
+ * everything after the opener line, minus a half-streamed closing marker.
9342
+ *
9343
+ * @param markdown - The assistant message text, complete or still streaming.
9344
+ * @returns The segments in source order.
9345
+ *
9346
+ * @example
9347
+ * ```ts
9348
+ * for (const segment of splitA2UIMarkdown(message.content)) {
9349
+ * if (segment.type === "a2ui") renderSurface(segment.text, segment.target);
9350
+ * else renderMarkdown(segment.text);
9351
+ * }
9352
+ * ```
9353
+ */
9354
+ function splitA2UIMarkdown(markdown) {
9355
+ const segments = [];
9356
+ let proseStart = 0;
9357
+ let fence = null;
9358
+ let a2uiIndex = 0;
9359
+ const pushProse = (end) => {
9360
+ if (end > proseStart) segments.push({
9361
+ type: "markdown",
9362
+ text: markdown.slice(proseStart, end)
9363
+ });
9364
+ };
9365
+ let lineStart = 0;
9366
+ while (lineStart <= markdown.length) {
9367
+ const newline = markdown.indexOf("\n", lineStart);
9368
+ const lineEnd = newline < 0 ? markdown.length : newline;
9369
+ const hasCR = lineEnd > lineStart && markdown[lineEnd - 1] === "\r";
9370
+ const line = markdown.slice(lineStart, hasCR ? lineEnd - 1 : lineEnd);
9371
+ if (fence) {
9372
+ if (isCloser(line, fence)) {
9373
+ if (fence.index >= 0) {
9374
+ const body = markdown.slice(fence.bodyStart, Math.max(fence.bodyStart, lineStart));
9375
+ segments.push(a2uiSegment(fence, body, true));
9376
+ proseStart = hasCR ? lineEnd - 1 : lineEnd;
9377
+ }
9378
+ fence = null;
9379
+ }
9380
+ } else {
9381
+ const open = FENCE_OPEN.exec(line);
9382
+ if (open) {
9383
+ const marker = open[1] ?? "";
9384
+ const info = open[2] ?? "";
9385
+ const char = marker.charAt(0);
9386
+ if (!(char === "`" && info.includes("`"))) {
9387
+ const [lang = "", ...tokens] = info.trim().split(/\s+/);
9388
+ const isA2UI = lang === A2UI_FENCE_LANGUAGE;
9389
+ if (isA2UI) pushProse(lineStart);
9390
+ fence = {
9391
+ char,
9392
+ length: marker.length,
9393
+ bodyStart: newline < 0 ? markdown.length : lineEnd + 1,
9394
+ index: isA2UI ? a2uiIndex++ : -1,
9395
+ target: isA2UI ? readTarget(tokens) : void 0
9396
+ };
9397
+ }
9398
+ }
9399
+ }
9400
+ if (newline < 0) break;
9401
+ lineStart = newline + 1;
9402
+ }
9403
+ if (fence && fence.index >= 0) {
9404
+ const { char } = fence;
9405
+ let body = markdown.slice(fence.bodyStart);
9406
+ const lastNewline = body.lastIndexOf("\n");
9407
+ const lastLine = body.slice(lastNewline + 1).replace(/\r$/, "");
9408
+ if (lastLine.length > 0 && [...lastLine].every((ch) => ch === char)) body = body.slice(0, lastNewline + 1);
9409
+ segments.push(a2uiSegment(fence, body, false));
9410
+ } else pushProse(markdown.length);
9411
+ return segments;
9412
+ }
9413
+
9414
+ //#endregion
9415
+ //#region src/a2ui-markdown/operations.ts
9416
+ /** The operation keys that change a surface. */
9417
+ const SURFACE_OP_KEYS = [
9418
+ "createSurface",
9419
+ "updateComponents",
9420
+ "updateDataModel",
9421
+ "deleteSurface"
9422
+ ];
9423
+ /** The operation key of an agent-called function. It has no surface. */
9424
+ const FUNCTION_CALL_KEY = "callRendererFunction";
9425
+ const OP_KEYS = [...SURFACE_OP_KEYS, FUNCTION_CALL_KEY];
9426
+ function isRecord(value) {
9427
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9428
+ }
9429
+ function isWhitespace(ch) {
9430
+ return ch === " " || ch === "\n" || ch === "\r" || ch === " ";
9431
+ }
9432
+ function skipWhitespace(s, i) {
9433
+ while (i < s.length && isWhitespace(s[i])) i++;
9434
+ return i;
9435
+ }
9436
+ /** Index of the closing quote of the JSON string opening at `start`, or -1. */
9437
+ function findStringEnd(s, start) {
9438
+ for (let i = start + 1; i < s.length; i++) {
9439
+ if (s[i] === "\\") {
9440
+ i++;
9441
+ continue;
9442
+ }
9443
+ if (s[i] === "\"") return i;
9444
+ }
9445
+ return -1;
9446
+ }
9447
+ /**
9448
+ * Find the first `"key":` whose value starts with `opener` and return the index
9449
+ * of that opener, or -1.
9450
+ */
9451
+ function findKeyValue(s, key, opener) {
9452
+ const needle = `"${key}"`;
9453
+ let from = 0;
9454
+ while (true) {
9455
+ const k = s.indexOf(needle, from);
9456
+ if (k < 0) return -1;
9457
+ let i = skipWhitespace(s, k + needle.length);
9458
+ if (s[i] === ":") {
9459
+ i = skipWhitespace(s, i + 1);
9460
+ if (s[i] === opener) return i;
9461
+ }
9462
+ from = k + 1;
9463
+ }
9464
+ }
9465
+ /**
9466
+ * Read `"key":"value"` from partial JSON. The first match anywhere in the
9467
+ * text wins, at any depth.
9468
+ *
9469
+ * @param partialJson - JSON text that can still be streaming.
9470
+ * @param key - The field name.
9471
+ * @returns The string value, or null until its closing quote has arrived.
9472
+ *
9473
+ * @example
9474
+ * ```ts
9475
+ * extractStringField('{"createSurface":{"surfaceId":"plan","cat', "surfaceId"); // "plan"
9476
+ * ```
9477
+ */
9478
+ function extractStringField(partialJson, key) {
9479
+ const start = findKeyValue(partialJson, key, "\"");
9480
+ if (start < 0) return null;
9481
+ const end = findStringEnd(partialJson, start);
9482
+ if (end < 0) return null;
9483
+ try {
9484
+ const value = JSON.parse(partialJson.slice(start, end + 1));
9485
+ return typeof value === "string" ? value : null;
9486
+ } catch {
9487
+ return null;
9488
+ }
9489
+ }
9490
+ function pushItem(raw, items) {
9491
+ const trimmed = raw.trim();
9492
+ if (!trimmed) return;
9493
+ try {
9494
+ items.push(JSON.parse(trimmed));
9495
+ } catch {}
9496
+ }
9497
+ /**
9498
+ * Find `"key":[` in partial JSON and return every complete item of that array
9499
+ * so far, plus whether the array has closed. Items of a `components` array get
9500
+ * structural-key depth repair: a component that lost closing braces is fixed
9501
+ * when its `id`, `component`, `child` or `children` key shows where it ends.
9502
+ *
9503
+ * @param partialJson - JSON text that can still be streaming.
9504
+ * @param key - The name of the array field.
9505
+ * @returns `{ items, closed }`, or null when the key (with an array value)
9506
+ * has not appeared yet.
9507
+ *
9508
+ * @example
9509
+ * ```ts
9510
+ * const result = extractCompleteArrayItems(streamedText, "components");
9511
+ * if (result) render(result.items);
9512
+ * ```
9513
+ */
9514
+ function extractCompleteArrayItems(partialJson, key) {
9515
+ const open = findKeyValue(partialJson, key, "[");
9516
+ if (open < 0) return null;
9517
+ return completeArrayItemsAt(partialJson, open, { repairComponents: key === "components" });
9518
+ }
9519
+ /** Index of the last non-whitespace character before `i`, or -1. */
9520
+ function prevNonWhitespace(s, i) {
9521
+ let j = i - 1;
9522
+ while (j >= 0 && isWhitespace(s[j])) j--;
9523
+ return j;
9524
+ }
9525
+ /**
9526
+ * Keys that only ever belong at a component's top level. Seen nested inside
9527
+ * the component's objects, they mean the model forgot closing braces.
9528
+ */
9529
+ const STRUCTURAL_KEYS = new Set([
9530
+ "id",
9531
+ "component",
9532
+ "child",
9533
+ "children"
9534
+ ]);
9535
+ /** Whether a value starting with `ch` has the shape `key` takes on a component. */
9536
+ function structuralValueFits(key, ch) {
9537
+ if (key === "children") return ch === "[" || ch === "{";
9538
+ return ch === "\"";
9539
+ }
9540
+ /** `{"id":` — a new component object starting at `i`. */
9541
+ const COMPONENT_START = /^\{\s*"id"\s*:/;
9542
+ /**
9543
+ * Structural-key depth repair for one component item. While scanning, a
9544
+ * structural key (`id`, `component`, `child`, `children`) found as an object
9545
+ * key below the item's top level, with only objects (no arrays) between it
9546
+ * and the item root, a value of the expected shape, and not already present
9547
+ * at the top level, means closing braces were dropped: the missing `}` are
9548
+ * synthesized right before it so it lands at the top level. Containers still
9549
+ * open at the end are closed. Returns null when a string never terminates.
9550
+ */
9551
+ function repairComponentItem(item) {
9552
+ const stack = [];
9553
+ const topKeys = /* @__PURE__ */ new Set();
9554
+ let out = "";
9555
+ let copied = 0;
9556
+ for (let i = 0; i < item.length; i++) {
9557
+ const c = item[i];
9558
+ if (c === "\"") {
9559
+ const end = findStringEnd(item, i);
9560
+ if (end < 0) return null;
9561
+ const prev = prevNonWhitespace(item, i);
9562
+ const prevCh = item[prev];
9563
+ const colon = skipWhitespace(item, end + 1);
9564
+ if (stack[stack.length - 1] === "{" && (prevCh === "," || prevCh === "{") && item[colon] === ":") {
9565
+ let key;
9566
+ try {
9567
+ key = JSON.parse(item.slice(i, end + 1));
9568
+ } catch {
9569
+ return null;
9570
+ }
9571
+ if (typeof key === "string") {
9572
+ if (stack.length === 1) topKeys.add(key);
9573
+ else if (STRUCTURAL_KEYS.has(key) && !topKeys.has(key) && stack.every((x) => x === "{") && structuralValueFits(key, item[skipWhitespace(item, colon + 1)])) {
9574
+ const closers = "}".repeat(stack.length - 1);
9575
+ if (prevCh === ",") {
9576
+ out += item.slice(copied, prev) + closers;
9577
+ copied = prev;
9578
+ } else {
9579
+ out += item.slice(copied, i) + closers + ",";
9580
+ copied = i;
9581
+ }
9582
+ stack.length = 1;
9583
+ topKeys.add(key);
9584
+ }
9585
+ }
9586
+ }
9587
+ i = end;
9588
+ continue;
9589
+ }
9590
+ if (c === "{" || c === "[") stack.push(c);
9591
+ else if (c === "}" || c === "]") {
9592
+ stack.pop();
9593
+ if (stack.length === 0) return out + item.slice(copied, i + 1);
9594
+ }
9595
+ }
9596
+ const closers = stack.reduceRight((text, opener) => text + (opener === "{" ? "}" : "]"), "");
9597
+ return out + item.slice(copied) + closers;
9598
+ }
9599
+ function parseRecord(text) {
9600
+ if (text === null) return void 0;
9601
+ try {
9602
+ const value = JSON.parse(text);
9603
+ return isRecord(value) ? value : void 0;
9604
+ } catch {
9605
+ return;
9606
+ }
9607
+ }
9608
+ /**
9609
+ * Complete items of the (possibly unterminated) array whose "[" is at `open`.
9610
+ * With `repairComponents`, an item that balanced but does not parse is retried
9611
+ * with structural-key repair, and a `,{"id":` where an item expects a key
9612
+ * ends that (unbalanced) item there, so one malformed component cannot
9613
+ * swallow the rest of the array; the cut item is kept only if repair makes
9614
+ * it parse.
9615
+ */
9616
+ function completeArrayItemsAt(partialJson, open, options) {
9617
+ const { repairComponents } = options;
9618
+ const s = partialJson;
9619
+ const items = [];
9620
+ const stack = [];
9621
+ let inString = false;
9622
+ let itemStart = -1;
9623
+ const finishItem = (end, balanced) => {
9624
+ const raw = s.slice(itemStart, end);
9625
+ if (!repairComponents) {
9626
+ pushItem(raw, items);
9627
+ return;
9628
+ }
9629
+ if (balanced) try {
9630
+ items.push(JSON.parse(raw));
9631
+ return;
9632
+ } catch {}
9633
+ const repaired = parseRecord(repairComponentItem(raw.trim()));
9634
+ if (repaired !== void 0) items.push(repaired);
9635
+ };
9636
+ for (let i = open + 1; i < s.length; i++) {
9637
+ const c = s[i];
9638
+ if (inString) {
9639
+ if (c === "\\") i++;
9640
+ else if (c === "\"") inString = false;
9641
+ continue;
9642
+ }
9643
+ if (c === "\"") {
9644
+ inString = true;
9645
+ if (stack.length === 0 && itemStart < 0) itemStart = i;
9646
+ continue;
9647
+ }
9648
+ if (c === "{" || c === "[") {
9649
+ if (repairComponents && c === "{" && stack[stack.length - 1] === "{" && COMPONENT_START.test(s.slice(i, i + 24))) {
9650
+ const prev = prevNonWhitespace(s, i);
9651
+ if (s[prev] === ",") {
9652
+ finishItem(prev, false);
9653
+ stack.length = 0;
9654
+ itemStart = i;
9655
+ stack.push(c);
9656
+ continue;
9657
+ }
9658
+ }
9659
+ if (stack.length === 0) itemStart = i;
9660
+ stack.push(c);
9661
+ continue;
9662
+ }
9663
+ if (c === "}" || c === "]") {
9664
+ if (stack.length === 0) {
9665
+ if (c === "]") {
9666
+ if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
9667
+ return {
9668
+ items,
9669
+ closed: true
9670
+ };
9671
+ }
9672
+ return {
9673
+ items,
9674
+ closed: false
9675
+ };
9676
+ }
9677
+ stack.pop();
9678
+ if (stack.length === 0) {
9679
+ finishItem(i + 1, true);
9680
+ itemStart = -1;
9681
+ }
9682
+ continue;
9683
+ }
9684
+ if (stack.length === 0) {
9685
+ if (c === ",") {
9686
+ if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
9687
+ itemStart = -1;
9688
+ } else if (itemStart < 0 && !isWhitespace(c)) itemStart = i;
9689
+ }
9690
+ }
9691
+ return {
9692
+ items,
9693
+ closed: false
9694
+ };
9695
+ }
9696
+ /** The first operation key whose value is an object, with that value. */
9697
+ function getOperationEntry(op) {
9698
+ for (const key of OP_KEYS) {
9699
+ const inner = op[key];
9700
+ if (isRecord(inner)) return {
9701
+ key,
9702
+ inner
9703
+ };
9704
+ }
9705
+ return null;
9706
+ }
9707
+ /**
9708
+ * The surfaceId an operation targets: the one nested under its operation key,
9709
+ * else a top-level `surfaceId`. A `callRendererFunction` operation targets no
9710
+ * surface, so it gets undefined.
9711
+ *
9712
+ * It is named `getMarkdownOperationSurfaceId` because `@copilotkit/shared`
9713
+ * already exports a strict `getOperationSurfaceId`. This one also reads a
9714
+ * top-level `surfaceId`, which models sometimes write.
9715
+ *
9716
+ * @param op - An operation from an a2ui fence.
9717
+ * @returns The surfaceId, or undefined when the operation names none or is a
9718
+ * function call.
9719
+ *
9720
+ * @example
9721
+ * ```ts
9722
+ * getMarkdownOperationSurfaceId({ updateDataModel: { surfaceId: "plan" } }); // "plan"
9723
+ * ```
9724
+ */
9725
+ function getMarkdownOperationSurfaceId(op) {
9726
+ if (getOperationEntry(op)?.key === FUNCTION_CALL_KEY) return void 0;
9727
+ for (const key of SURFACE_OP_KEYS) {
9728
+ const inner = op[key];
9729
+ if (isRecord(inner) && typeof inner.surfaceId === "string") return inner.surfaceId;
9730
+ }
9731
+ return typeof op.surfaceId === "string" ? op.surfaceId : void 0;
9732
+ }
9733
+ /**
9734
+ * Index just past the JSON value starting at `start`, or -1 when the value is
9735
+ * still incomplete. A primitive at the very end of the input counts as
9736
+ * incomplete, since more digits or letters may still stream in.
9737
+ */
9738
+ function findValueEnd(s, start) {
9739
+ const c = s[start];
9740
+ if (c === "\"") {
9741
+ const end = findStringEnd(s, start);
9742
+ return end < 0 ? -1 : end + 1;
9743
+ }
9744
+ if (c === "{" || c === "[") {
9745
+ let depth = 0;
9746
+ for (let i = start; i < s.length; i++) {
9747
+ const ch = s[i];
9748
+ if (ch === "\"") {
9749
+ const end = findStringEnd(s, i);
9750
+ if (end < 0) return -1;
9751
+ i = end;
9752
+ } else if (ch === "{" || ch === "[") depth++;
9753
+ else if (ch === "}" || ch === "]") {
9754
+ depth--;
9755
+ if (depth === 0) return i + 1;
9756
+ }
9757
+ }
9758
+ return -1;
9759
+ }
9760
+ let i = start;
9761
+ while (i < s.length && !isWhitespace(s[i]) && !",}]".includes(s[i])) i++;
9762
+ return i >= s.length ? -1 : i;
9763
+ }
9764
+ /**
9765
+ * Walk the direct entries of the (possibly unterminated) JSON object whose "{"
9766
+ * is at `objStart`, calling `visit` with each key and the index where its value
9767
+ * starts. Nested objects and arrays are skipped whole, so keys inside them are
9768
+ * never visited. Stops when `visit` returns true, at the object's end, or where
9769
+ * the input runs out.
9770
+ */
9771
+ function visitDirectEntries(s, objStart, visit) {
9772
+ let i = objStart + 1;
9773
+ while (i < s.length) {
9774
+ i = skipWhitespace(s, i);
9775
+ const c = s[i];
9776
+ if (c === ",") {
9777
+ i++;
9778
+ continue;
9779
+ }
9780
+ if (c !== "\"") return;
9781
+ const keyEnd = findStringEnd(s, i);
9782
+ if (keyEnd < 0) return;
9783
+ let key;
9784
+ try {
9785
+ key = JSON.parse(s.slice(i, keyEnd + 1));
9786
+ } catch {
9787
+ return;
9788
+ }
9789
+ i = skipWhitespace(s, keyEnd + 1);
9790
+ if (s[i] !== ":") return;
9791
+ i = skipWhitespace(s, i + 1);
9792
+ if (i >= s.length) return;
9793
+ if (typeof key === "string" && visit(key, i)) return;
9794
+ const valueEnd = findValueEnd(s, i);
9795
+ if (valueEnd < 0) return;
9796
+ i = valueEnd;
9797
+ }
9798
+ }
9799
+ /**
9800
+ * Value start of a direct `key` of the object at `objStart` whose value begins
9801
+ * with `opener` (any value when omitted), or -1.
9802
+ */
9803
+ function findDirectKeyValue(s, objStart, key, opener) {
9804
+ let found = -1;
9805
+ visitDirectEntries(s, objStart, (k, valueStart) => {
9806
+ if (k !== key) return false;
9807
+ if (opener === void 0 || s[valueStart] === opener) found = valueStart;
9808
+ return true;
9809
+ });
9810
+ return found;
9811
+ }
9812
+ /** A direct string field of the object at `objStart`, once its closing quote has arrived. */
9813
+ function readDirectString(s, objStart, key) {
9814
+ if (objStart < 0) return null;
9815
+ const start = findDirectKeyValue(s, objStart, key, "\"");
9816
+ if (start < 0) return null;
9817
+ const end = findValueEnd(s, start);
9818
+ if (end < 0) return null;
9819
+ try {
9820
+ const value = JSON.parse(s.slice(start, end));
9821
+ return typeof value === "string" ? value : null;
9822
+ } catch {
9823
+ return null;
9824
+ }
9825
+ }
9826
+ /** A direct object field of the object at `objStart`, once the whole object has arrived. */
9827
+ function readDirectRecord(s, objStart, key) {
9828
+ const start = findDirectKeyValue(s, objStart, key, "{");
9829
+ if (start < 0) return void 0;
9830
+ const end = findValueEnd(s, start);
9831
+ if (end < 0) return void 0;
9832
+ return parseRecord(s.slice(start, end));
9833
+ }
9834
+ /**
9835
+ * The complete part of a (possibly unterminated) JSON value: the parsed value
9836
+ * when it is complete; for an open object, its complete entries plus the
9837
+ * complete items of any streaming array entry; otherwise undefined.
9838
+ */
9839
+ function completePartOfValue(s, start) {
9840
+ const end = findValueEnd(s, start);
9841
+ if (end >= 0) try {
9842
+ return JSON.parse(s.slice(start, end));
9843
+ } catch {
9844
+ return;
9845
+ }
9846
+ if (s[start] !== "{") return void 0;
9847
+ const out = {};
9848
+ visitDirectEntries(s, start, (key, valueStart) => {
9849
+ const valueEnd = findValueEnd(s, valueStart);
9850
+ if (valueEnd >= 0) try {
9851
+ out[key] = JSON.parse(s.slice(valueStart, valueEnd));
9852
+ } catch {}
9853
+ else if (s[valueStart] === "[") {
9854
+ const { items } = completeArrayItemsAt(s, valueStart, { repairComponents: false });
9855
+ if (items.length > 0) out[key] = items;
9856
+ }
9857
+ return false;
9858
+ });
9859
+ return Object.keys(out).length > 0 ? out : void 0;
9860
+ }
9861
+ /**
9862
+ * Best-effort operation from an unfinished or malformed top-level object.
9863
+ * Fields are read only from the operation's own keys (`version` at the top
9864
+ * level, `surfaceId`, `catalogId`, `path`, `dataModel` and `components` inside
9865
+ * the operation object), never from component props or data-model values that
9866
+ * happen to share a name.
9867
+ *
9868
+ * A `createSurface` keeps its complete components and a `dataModel` that has
9869
+ * fully arrived, so a surface created in one line renders while it streams.
9870
+ * A `callRendererFunction` gives nothing: a function must not run with half
9871
+ * of its args.
9872
+ */
9873
+ function partialOperation(line) {
9874
+ const root = skipWhitespace(line, 0);
9875
+ if (line[root] !== "{") return null;
9876
+ const version = readDirectString(line, root, "version") ?? _copilotkit_shared.A2UI_VERSION;
9877
+ const components = findDirectKeyValue(line, root, "updateComponents", "{");
9878
+ if (components >= 0) {
9879
+ const arrayStart = findDirectKeyValue(line, components, "components", "[");
9880
+ if (arrayStart < 0) return null;
9881
+ const { items } = completeArrayItemsAt(line, arrayStart, { repairComponents: true });
9882
+ if (items.length === 0) return null;
9883
+ const surfaceId = readDirectString(line, components, "surfaceId");
9884
+ return {
9885
+ version,
9886
+ updateComponents: {
9887
+ ...surfaceId ? { surfaceId } : {},
9888
+ components: items
9889
+ }
9890
+ };
9891
+ }
9892
+ const data = findDirectKeyValue(line, root, "updateDataModel", "{");
9893
+ if (data >= 0) {
9894
+ const valueStart = findDirectKeyValue(line, data, "value");
9895
+ if (valueStart < 0) return null;
9896
+ const value = completePartOfValue(line, valueStart);
9897
+ if (value === void 0) return null;
9898
+ const surfaceId = readDirectString(line, data, "surfaceId");
9899
+ const path = readDirectString(line, data, "path");
9900
+ return {
9901
+ version,
9902
+ updateDataModel: {
9903
+ ...surfaceId ? { surfaceId } : {},
9904
+ ...path ? { path } : {},
9905
+ value
9906
+ }
9907
+ };
9908
+ }
9909
+ const create = findDirectKeyValue(line, root, "createSurface", "{");
9910
+ if (create >= 0) {
9911
+ const surfaceId = readDirectString(line, create, "surfaceId");
9912
+ if (!surfaceId) return null;
9913
+ const catalogId = readDirectString(line, create, "catalogId");
9914
+ const dataModel = readDirectRecord(line, create, "dataModel");
9915
+ const componentsStart = findDirectKeyValue(line, create, "components", "[");
9916
+ const components = componentsStart < 0 ? [] : completeArrayItemsAt(line, componentsStart, { repairComponents: true }).items;
9917
+ return {
9918
+ version,
9919
+ createSurface: {
9920
+ surfaceId,
9921
+ ...catalogId ? { catalogId } : {},
9922
+ ...dataModel ? { dataModel } : {},
9923
+ ...components.length > 0 ? { components } : {}
9924
+ }
9925
+ };
9926
+ }
9927
+ return null;
9928
+ }
9929
+ /**
9930
+ * A line that opens a new top-level operation: `{"version":"v…` or
9931
+ * `{"<operation>":{`. Seen at the start of a line while an earlier object is
9932
+ * still unbalanced, it means that object is malformed and has ended.
9933
+ */
9934
+ const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"v\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
9935
+ /**
9936
+ * Scan the top-level object whose "{" is at `start`. Returns the index just
9937
+ * past it and whether it balanced. An unbalanced object ends early (at the
9938
+ * start of the line) when a line opens a new operation; otherwise it runs to
9939
+ * the end of the input. JSON strings cannot contain raw newlines, so a newline
9940
+ * inside a string ends it: a stray quote then breaks one line, not the rest of
9941
+ * the fence.
9942
+ */
9943
+ function scanTopLevelObject(s, start) {
9944
+ let depth = 0;
9945
+ let inString = false;
9946
+ for (let i = start; i < s.length; i++) {
9947
+ const c = s[i];
9948
+ if (inString) {
9949
+ if (c === "\\" && s[i + 1] !== "\n") i++;
9950
+ else if (c === "\"" || c === "\n") inString = false;
9951
+ if (c !== "\n") continue;
9952
+ }
9953
+ if (c === "\n") {
9954
+ const next = skipWhitespace(s, i + 1);
9955
+ if (OPERATION_START.test(s.slice(next, next + 40))) return {
9956
+ end: i + 1,
9957
+ balanced: false
9958
+ };
9959
+ continue;
9960
+ }
9961
+ if (c === "\"") inString = true;
9962
+ else if (c === "{" || c === "[") depth++;
9963
+ else if (c === "}" || c === "]") {
9964
+ depth--;
9965
+ if (depth === 0) return {
9966
+ end: i + 1,
9967
+ balanced: true
9968
+ };
9969
+ }
9970
+ }
9971
+ return {
9972
+ end: s.length,
9973
+ balanced: false
9974
+ };
9975
+ }
9976
+ /**
9977
+ * Parse the body of an a2ui fence as a stream of top-level JSON values, so
9978
+ * operations may be one per line (the documented format), several per line,
9979
+ * pretty-printed over many lines, or wrapped in a top-level array (which is
9980
+ * flattened). Whitespace and commas between objects are ignored.
9981
+ *
9982
+ * - A balanced object is `JSON.parse`d. When that fails (e.g. a stray quote),
9983
+ * its raw text goes to `invalidLines` and whatever `partialOperation` can
9984
+ * salvage (complete components, data-model entries, createSurface fields)
9985
+ * is kept.
9986
+ * - An unbalanced object followed by a line that opens a new operation is
9987
+ * treated the same way.
9988
+ * - The trailing unbalanced object (still streaming, or never closed) is
9989
+ * `partialObject` and yields a partial operation when it has usable data.
9990
+ * - Other text between objects is skipped and reported in `recovered` (and in
9991
+ * `invalidLines`, which predates it).
9992
+ *
9993
+ * `partialLine` is a deprecated alias of `partialObject`.
9994
+ *
9995
+ * @param fenceText - The body of an a2ui fence (`text` of an a2ui
9996
+ * `MarkdownSegment`), complete or still streaming.
9997
+ * @returns `{ operations, partialObject, partialLine, invalidLines, recovered }`.
9998
+ *
9999
+ * @example
10000
+ * ```ts
10001
+ * const { operations } = extractFenceOperations(segment.text);
10002
+ * ```
10003
+ */
10004
+ function extractFenceOperations(fenceText) {
10005
+ const s = fenceText;
10006
+ const operations = [];
10007
+ const invalidLines = [];
10008
+ const recovered = [];
10009
+ let partialObject = null;
10010
+ const salvage = (raw) => {
10011
+ invalidLines.push(raw.trim());
10012
+ const partial = partialOperation(raw);
10013
+ if (partial) operations.push(partial);
10014
+ };
10015
+ let junkStart = -1;
10016
+ const flushJunk = (end) => {
10017
+ if (junkStart < 0) return;
10018
+ const junk = s.slice(junkStart, end).trim();
10019
+ junkStart = -1;
10020
+ if (!junk) return;
10021
+ recovered.push(junk);
10022
+ invalidLines.push(junk);
10023
+ };
10024
+ let i = 0;
10025
+ while (i < s.length) {
10026
+ const c = s[i];
10027
+ if (c === "{") {
10028
+ flushJunk(i);
10029
+ const { end, balanced } = scanTopLevelObject(s, i);
10030
+ const raw = s.slice(i, end);
10031
+ if (balanced) {
10032
+ let parsed;
10033
+ try {
10034
+ parsed = JSON.parse(raw);
10035
+ } catch {
10036
+ parsed = void 0;
10037
+ }
10038
+ if (isRecord(parsed)) operations.push(parsed);
10039
+ else salvage(raw);
10040
+ } else if (end < s.length) salvage(raw);
10041
+ else {
10042
+ partialObject = raw;
10043
+ const partial = partialOperation(raw);
10044
+ if (partial) operations.push(partial);
10045
+ }
10046
+ i = end;
10047
+ continue;
10048
+ }
10049
+ if (c === "\n" || c === "[" || c === "]") flushJunk(i);
10050
+ else if (junkStart < 0 && !isWhitespace(c) && c !== ",") junkStart = i;
10051
+ i++;
10052
+ }
10053
+ flushJunk(s.length);
10054
+ return {
10055
+ operations,
10056
+ partialObject,
10057
+ partialLine: partialObject,
10058
+ invalidLines,
10059
+ recovered
10060
+ };
10061
+ }
10062
+ /**
10063
+ * Normalise a fence's operations for the renderer: drop unknown messages, fill
10064
+ * in `version` and missing `surfaceId`s, keep only the first `createSurface`,
10065
+ * keep its `catalogId` when `catalogIds` lists it (else use `catalogId`), synthesize
10066
+ * `createSurface` when the model omitted it, and report the
10067
+ * surfaceId (the first one found, else `fallbackSurfaceId`).
10068
+ *
10069
+ * `callRendererFunction` operations target no surface. They get no surfaceId,
10070
+ * do not cause a synthesized `createSurface`, and come back in
10071
+ * `functionCalls` (in fence order), never in `operations`.
10072
+ *
10073
+ * @param input.operations - Operations from `extractFenceOperations`.
10074
+ * @param input.fallbackSurfaceId - The surfaceId to use when no operation
10075
+ * names one.
10076
+ * @param input.catalogId - The client catalog. It replaces a catalogId of the
10077
+ * model that `catalogIds` does not list.
10078
+ * @param input.catalogIds - The catalogs that the model can name. Left out,
10079
+ * only `catalogId`.
10080
+ * @returns `{ surfaceId, operations, functionCalls }`.
10081
+ *
10082
+ * @example
10083
+ * ```ts
10084
+ * const { surfaceId, operations, functionCalls } = prepareSurfaceOperations({
10085
+ * operations: extractFenceOperations(segment.text).operations,
10086
+ * fallbackSurfaceId: `${messageId}-${segment.index}`,
10087
+ * catalogId,
10088
+ * });
10089
+ * ```
10090
+ */
10091
+ function prepareSurfaceOperations(input) {
10092
+ const { operations, fallbackSurfaceId, catalogId } = input;
10093
+ const catalogIds = input.catalogIds ?? [catalogId];
10094
+ const surfaceId = operations.map(getMarkdownOperationSurfaceId).find((id) => !!id) ?? fallbackSurfaceId;
10095
+ const out = [];
10096
+ const functionCalls = [];
10097
+ let hasCreate = false;
10098
+ for (const op of operations) {
10099
+ const entry = getOperationEntry(op);
10100
+ if (!entry) continue;
10101
+ const { key } = entry;
10102
+ const inner = { ...entry.inner };
10103
+ const version = typeof op.version === "string" ? op.version : _copilotkit_shared.A2UI_VERSION;
10104
+ if (key === FUNCTION_CALL_KEY) {
10105
+ functionCalls.push({
10106
+ version,
10107
+ [key]: inner
10108
+ });
10109
+ continue;
10110
+ }
10111
+ if (typeof inner.surfaceId !== "string") inner.surfaceId = surfaceId;
10112
+ if (key === "createSurface") {
10113
+ if (hasCreate) {
10114
+ const { surfaceId: id, dataModel, components } = inner;
10115
+ if (dataModel !== void 0) out.push({
10116
+ version,
10117
+ updateDataModel: {
10118
+ surfaceId: id,
10119
+ path: "/",
10120
+ value: dataModel
10121
+ }
10122
+ });
10123
+ if (Array.isArray(components) && components.length > 0) out.push({
10124
+ version,
10125
+ updateComponents: {
10126
+ surfaceId: id,
10127
+ components
10128
+ }
10129
+ });
10130
+ continue;
10131
+ }
10132
+ hasCreate = true;
10133
+ if (!catalogIds.includes(inner.catalogId)) inner.catalogId = catalogId;
10134
+ }
10135
+ out.push({
10136
+ version,
10137
+ [key]: inner
10138
+ });
10139
+ }
10140
+ if (!hasCreate && out.length > 0) out.unshift({
10141
+ version: _copilotkit_shared.A2UI_VERSION,
10142
+ createSurface: {
10143
+ surfaceId,
10144
+ catalogId
10145
+ }
10146
+ });
10147
+ return {
10148
+ surfaceId,
10149
+ operations: out,
10150
+ functionCalls
10151
+ };
10152
+ }
10153
+ /**
10154
+ * Components a user operates. A Card containing one of these is an
10155
+ * interactive panel and keeps its box; every other Card is informational.
10156
+ */
10157
+ const INTERACTIVE_COMPONENTS = new Set([
10158
+ "Button",
10159
+ "Pressable",
10160
+ "Form",
10161
+ "TextField",
10162
+ "TextArea",
10163
+ "Select",
10164
+ "CheckBox",
10165
+ "Radio",
10166
+ "RadioGroup",
10167
+ "Slider",
10168
+ "SegmentedControl",
10169
+ "ChoicePicker",
10170
+ "DateTimeInput"
10171
+ ]);
10172
+ /** A component id referenced by a `child`/`children` entry or a table cell. */
10173
+ function referencedId(value) {
10174
+ if (typeof value === "string") return value;
10175
+ if (isRecord(value)) {
10176
+ if (typeof value.componentId === "string") return value.componentId;
10177
+ if (typeof value.id === "string") return value.id;
10178
+ }
10179
+ }
10180
+ /** Ids of a table cell / column that renders a component (`{componentId}` or `{id}`). */
10181
+ function cellComponentId(value) {
10182
+ return isRecord(value) ? referencedId(value) : void 0;
10183
+ }
10184
+ /**
10185
+ * Ids a component renders directly: `child`, `children` (string ids, an
10186
+ * array, or a `{componentId}` template), component cells of a Table's
10187
+ * `rows`/`columns`, and the ids that `extra` finds in its typed references.
10188
+ */
10189
+ function directChildIds(component, extra) {
10190
+ const ids = [];
10191
+ const add = (id) => {
10192
+ if (id) ids.push(id);
10193
+ };
10194
+ const extraIds = extra?.(component);
10195
+ if (Array.isArray(extraIds)) extraIds.forEach(add);
10196
+ add(referencedId(component.child));
10197
+ const children = component.children;
10198
+ if (Array.isArray(children)) children.forEach((c) => add(referencedId(c)));
10199
+ else add(referencedId(children));
10200
+ if (Array.isArray(component.columns)) component.columns.forEach((c) => add(cellComponentId(c)));
10201
+ if (Array.isArray(component.rows)) {
10202
+ for (const row of component.rows) if (Array.isArray(row)) row.forEach((c) => add(cellComponentId(c)));
10203
+ }
10204
+ return ids;
10205
+ }
10206
+ /** Components of every updateComponents operation, by id (last definition wins). */
10207
+ function componentsById(operations) {
10208
+ const byId = /* @__PURE__ */ new Map();
10209
+ for (const op of operations) {
10210
+ const update = op.updateComponents;
10211
+ const list = isRecord(update) ? update.components : void 0;
10212
+ if (!Array.isArray(list)) continue;
10213
+ for (const c of list) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
10214
+ }
10215
+ return byId;
10216
+ }
10217
+ function descendantIds(rootId, byId, extra) {
10218
+ const seen = /* @__PURE__ */ new Set();
10219
+ const stack = [...directChildIds(byId.get(rootId) ?? {}, extra)];
10220
+ while (stack.length > 0) {
10221
+ const id = stack.pop();
10222
+ if (seen.has(id) || id === rootId) continue;
10223
+ seen.add(id);
10224
+ const c = byId.get(id);
10225
+ if (c) stack.push(...directChildIds(c, extra));
10226
+ }
10227
+ return seen;
10228
+ }
10229
+ /**
10230
+ * Ids of the `Card` components that are interactive panels: at least one
10231
+ * descendant (via `child`, `children` or table component cells) is a control
10232
+ * (Button, Pressable, Form, TextField, TextArea, Select, CheckBox, Radio,
10233
+ * RadioGroup, Slider, SegmentedControl, DateTimeInput).
10234
+ *
10235
+ * @param components - The components of one surface.
10236
+ * @returns The ids of the interactive cards.
10237
+ *
10238
+ * @example
10239
+ * ```ts
10240
+ * const interactive = classifySurfaceCards(components);
10241
+ * const keepsBox = interactive.has("quote-form");
10242
+ * ```
10243
+ */
10244
+ function classifySurfaceCards(components, options = {}) {
10245
+ const byId = /* @__PURE__ */ new Map();
10246
+ for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
10247
+ const interactive = /* @__PURE__ */ new Set();
10248
+ for (const [id, c] of byId) {
10249
+ if (c.component !== "Card") continue;
10250
+ for (const d of descendantIds(id, byId, options.childIds)) {
10251
+ const type = byId.get(d)?.component;
10252
+ if (typeof type === "string" && INTERACTIVE_COMPONENTS.has(type)) {
10253
+ interactive.add(id);
10254
+ break;
10255
+ }
10256
+ }
10257
+ }
10258
+ return interactive;
10259
+ }
10260
+ /**
10261
+ * Markdown mode: only interactive panels keep a box. Every `Card` that is not
10262
+ * an interactive panel (see `classifySurfaceCards`), sets no `variant` or
10263
+ * `border` of its own and is not nested inside an interactive panel becomes
10264
+ * `variant: "section"` (a heading plus content without a box). Operations
10265
+ * other than updateComponents pass through unchanged.
10266
+ *
10267
+ * @param operations - The operations of one surface.
10268
+ * @returns The operations with informational cards set to `variant: "section"`.
10269
+ * When no card changes, it returns the same array.
10270
+ *
10271
+ * @example
10272
+ * ```ts
10273
+ * const operations = flattenInformationalCards(prepared.operations);
10274
+ * ```
10275
+ */
10276
+ function flattenInformationalCards(operations, options = {}) {
10277
+ const byId = componentsById(operations);
10278
+ if (![...byId.values()].some((c) => c.component === "Card")) return operations;
10279
+ const interactive = classifySurfaceCards([...byId.values()], options);
10280
+ const insideInteractive = /* @__PURE__ */ new Set();
10281
+ for (const id of interactive) for (const d of descendantIds(id, byId, options.childIds)) insideInteractive.add(d);
10282
+ const flatten = (c) => c.component === "Card" && typeof c.id === "string" && !interactive.has(c.id) && !insideInteractive.has(c.id) && c.variant == null && c.border == null;
10283
+ return operations.map((op) => {
10284
+ const update = op.updateComponents;
10285
+ if (!isRecord(update) || !Array.isArray(update.components)) return op;
10286
+ if (!update.components.some((c) => isRecord(c) && flatten(c))) return op;
10287
+ return {
10288
+ ...op,
10289
+ updateComponents: {
10290
+ ...update,
10291
+ components: update.components.map((c) => isRecord(c) && flatten(c) ? {
10292
+ ...c,
10293
+ variant: "section"
10294
+ } : c)
10295
+ }
10296
+ };
10297
+ });
10298
+ }
10299
+ /** Text-bearing components that belong in the chat's markdown, not a surface. */
10300
+ const PROSE_TEXT_COMPONENTS = new Set([
10301
+ "Title",
10302
+ "Text",
10303
+ "Caption",
10304
+ "Markdown"
10305
+ ]);
10306
+ /** One line of text: list items and headings cannot span lines in markdown. */
10307
+ function oneLine(text) {
10308
+ return text.trim().replace(/\s*\n\s*/g, " ");
10309
+ }
10310
+ /**
10311
+ * A literal List entry as list-item markdown: a non-empty string, or
10312
+ * `{ label, description? }` with literal strings only. Anything carrying
10313
+ * behaviour or decoration (`icon`, `action`, other keys, bound values) is null.
10314
+ */
10315
+ function listEntryMarkdown(entry) {
10316
+ if (typeof entry === "string") return entry.trim() ? oneLine(entry) : null;
10317
+ if (!isRecord(entry)) return null;
10318
+ for (const key of Object.keys(entry)) if (key !== "label" && key !== "description") return null;
10319
+ if (typeof entry.label !== "string" || !entry.label.trim()) return null;
10320
+ const label = oneLine(entry.label);
10321
+ if (entry.description === void 0) return label;
10322
+ if (typeof entry.description !== "string") return null;
10323
+ return entry.description.trim() ? `**${label}** — ${oneLine(entry.description)}` : label;
10324
+ }
10325
+ /**
10326
+ * A List of literal text items as a markdown list (`marker: "number"` →
10327
+ * `1. …`, otherwise `- …`), or null when it binds its items, renders
10328
+ * `children`, or any item is not plain text.
10329
+ */
10330
+ function listToMarkdown(c) {
10331
+ const children = c.children;
10332
+ if (children != null && !(Array.isArray(children) && children.length === 0)) return null;
10333
+ if (!Array.isArray(c.items) || c.items.length === 0) return null;
10334
+ const lines = [];
10335
+ for (const entry of c.items) {
10336
+ const line = listEntryMarkdown(entry);
10337
+ if (line === null) return null;
10338
+ lines.push(line);
10339
+ }
10340
+ if (c.marker === "number") {
10341
+ const start = typeof c.start === "number" && Number.isInteger(c.start) ? c.start : 1;
10342
+ return lines.map((line, i) => `${start + i}. ${line}`).join("\n");
10343
+ }
10344
+ return lines.map((line) => `- ${line}`).join("\n");
10345
+ }
10346
+ /** The prose item a component converts to, or null when it is not prose. */
10347
+ function toProseItem(c) {
10348
+ if (!c) return null;
10349
+ if (c.accessibility !== void 0) return null;
10350
+ if (c.component === "Divider") return { kind: "divider" };
10351
+ if (c.component === "Spacer") return { kind: "spacer" };
10352
+ if (c.component === "List") {
10353
+ if (c.direction !== void 0 && c.direction !== "vertical") return null;
10354
+ const markdown = listToMarkdown(c);
10355
+ return markdown === null ? null : {
10356
+ kind: "text",
10357
+ markdown
10358
+ };
10359
+ }
10360
+ if (typeof c.component !== "string") return null;
10361
+ if (!PROSE_TEXT_COMPONENTS.has(c.component)) return null;
10362
+ if (typeof c.text !== "string" || c.text.trim() === "") return null;
10363
+ const text = c.text.trim();
10364
+ switch (c.component) {
10365
+ case "Title": {
10366
+ const size = typeof c.size === "string" ? c.size : "md";
10367
+ return {
10368
+ kind: "text",
10369
+ markdown: `${size === "sm" ? "####" : size === "md" || size === "lg" ? "###" : "##"} ${text}`
10370
+ };
10371
+ }
10372
+ case "Text":
10373
+ if (directChildIds(c).length > 0) return null;
10374
+ return {
10375
+ kind: "text",
10376
+ markdown: c.strong === true ? `**${text}**` : text
10377
+ };
10378
+ default: return {
10379
+ kind: "text",
10380
+ markdown: text
10381
+ };
10382
+ }
10383
+ }
10384
+ /** Prose items as markdown: separators only survive between two text items. */
10385
+ function proseItemsToMarkdown(items) {
10386
+ const blocks = [];
10387
+ let pendingDivider = false;
10388
+ for (const item of items) if (item?.kind === "text") {
10389
+ if (pendingDivider && blocks.length > 0) blocks.push("---");
10390
+ pendingDivider = false;
10391
+ blocks.push(item.markdown);
10392
+ } else if (item?.kind === "divider") pendingDivider = true;
10393
+ return blocks.join("\n\n");
10394
+ }
10395
+ /** Column, column-direction Box, or an informational Card (section/unset variant). */
10396
+ function isVerticalStack(c, interactiveCards) {
10397
+ if (c.accessibility !== void 0) return false;
10398
+ if (c.component === "Column") return true;
10399
+ if (c.component === "Box") return c.direction == null || c.direction === "col";
10400
+ if (c.component === "Card") return (c.variant == null || c.variant === "section") && typeof c.id === "string" && !interactiveCards.has(c.id);
10401
+ return false;
10402
+ }
10403
+ /** The child-id list of a stack (`children`, or a lone `child`), else null. */
10404
+ /**
10405
+ * The children of a stack in render order: `child` first (a Card renders
10406
+ * its `child` before its `children`), then `children`.
10407
+ */
10408
+ function stackChildren(c) {
10409
+ const first = typeof c.child === "string" ? [c.child] : [];
10410
+ if (Array.isArray(c.children)) return [...first, ...c.children];
10411
+ if (first.length > 0 && c.children === void 0) return first;
10412
+ return null;
10413
+ }
10414
+ /**
10415
+ * Partitions the stack's children into alternating prose and surface runs.
10416
+ * A run of consecutive prose items is prose only when it holds text: a run of
10417
+ * separators alone (Divider/Spacer between two UI components, or at the very
10418
+ * start/end of the stack) stays with the surface it sits in.
10419
+ */
10420
+ function partitionChildren(items) {
10421
+ const runs = [];
10422
+ let i = 0;
10423
+ while (i < items.length) {
10424
+ const candidate = items[i] !== null;
10425
+ let hasText = false;
10426
+ let j = i;
10427
+ while (j < items.length && items[j] !== null === candidate) {
10428
+ if (items[j]?.kind === "text") hasText = true;
10429
+ j++;
10430
+ }
10431
+ const prose = candidate && hasText;
10432
+ const last = runs[runs.length - 1];
10433
+ if (!prose && last && !last.prose) last.end = j;
10434
+ else runs.push({
10435
+ prose,
10436
+ start: i,
10437
+ end: j
10438
+ });
10439
+ i = j;
10440
+ }
10441
+ return runs;
10442
+ }
10443
+ /**
10444
+ * Markdown mode: split a surface into markdown and surface segments so that
10445
+ * only real UI renders as A2UI and everything else is the chat's markdown.
10446
+ *
10447
+ * From `root`, descend through single-child vertical containers (Column,
10448
+ * column Box, informational Card) to the first one with several children:
10449
+ * the stack. Its children are partitioned, in order, into runs of prose and
10450
+ * runs of UI. Prose is `Title`, `Text`, `Caption`, `Markdown` with literal
10451
+ * text, a `List` of literal text items, plus `Divider`/`Spacer` next to them:
10452
+ * `Title` → heading by size (sm `####`, md/lg `###`, larger `##`), `Text` →
10453
+ * paragraph (`strong` → `**…**`), `Caption`/`Markdown` → paragraph, `List` →
10454
+ * `- …` (or `1. …` for `marker: "number"`, `**label** — description` for
10455
+ * described items), and a `Divider` between two prose blocks → `---`.
10456
+ *
10457
+ * Not prose: `{path}`-bound text or items, a Text with inline children, a
10458
+ * List with `children`/icons/actions, a template entry, a component with an
10459
+ * `accessibility` envelope, and a child whose component has not streamed
10460
+ * yet. Separators with no text beside them stay in
10461
+ * the surface. An interactive Card (see `classifySurfaceCards`) is never
10462
+ * entered.
10463
+ *
10464
+ * Each prose run becomes a markdown segment; each UI run becomes a surface
10465
+ * segment whose `root` is a copy of the stack (its other props kept, `child`
10466
+ * dropped) with only that run's `children`, followed by every component
10467
+ * reachable from them. When nothing is prose the input comes back as the one
10468
+ * surface segment (same array); when everything is (or `root` itself is),
10469
+ * there are only markdown segments.
10470
+ *
10471
+ * Pure and linear in the number of components, so it runs on every stream
10472
+ * update.
10473
+ *
10474
+ * @param components - The components of one surface, root included.
10475
+ * @returns The segments in render order.
10476
+ *
10477
+ * @example
10478
+ * ```ts
10479
+ * for (const segment of segmentSurfaceProse(components)) {
10480
+ * if (segment.kind === "markdown") renderMarkdown(segment.markdown);
10481
+ * else renderSurface(segment.components);
10482
+ * }
10483
+ * ```
10484
+ */
10485
+ function segmentSurfaceProse(components, options = {}) {
10486
+ const unchanged = [{
10487
+ kind: "surface",
10488
+ components
10489
+ }];
10490
+ const byId = /* @__PURE__ */ new Map();
10491
+ for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
10492
+ const root = byId.get(_copilotkit_shared.GENERATIVE_UI_ROOT_ID);
10493
+ if (!root) return unchanged;
10494
+ if (components.some((c) => isRecord(c) && options.childIds?.(c) === "unknown")) return unchanged;
10495
+ const rootItem = toProseItem(root);
10496
+ if (rootItem?.kind === "text") return [{
10497
+ kind: "markdown",
10498
+ markdown: rootItem.markdown
10499
+ }];
10500
+ const interactiveCards = classifySurfaceCards(components, options);
10501
+ let stack = root;
10502
+ let stackId = _copilotkit_shared.GENERATIVE_UI_ROOT_ID;
10503
+ let children;
10504
+ const visited = /* @__PURE__ */ new Set();
10505
+ while (true) {
10506
+ if (!isVerticalStack(stack, interactiveCards)) return unchanged;
10507
+ visited.add(stackId);
10508
+ const list = stackChildren(stack);
10509
+ if (!list) return unchanged;
10510
+ children = list;
10511
+ const nextId = list.length === 1 ? list[0] : void 0;
10512
+ if (typeof nextId !== "string") break;
10513
+ const next = byId.get(nextId);
10514
+ if (!next || visited.has(nextId) || toProseItem(next)) break;
10515
+ stack = next;
10516
+ stackId = nextId;
10517
+ }
10518
+ const stackChildIds = children;
10519
+ const items = stackChildIds.map((id) => typeof id === "string" ? toProseItem(byId.get(id)) : null);
10520
+ const runs = partitionChildren(items);
10521
+ if (!runs.some((run) => run.prose)) return unchanged;
10522
+ const surfaceRuns = runs.filter((run) => !run.prose);
10523
+ const owners = /* @__PURE__ */ new Map();
10524
+ surfaceRuns.forEach((run, index) => {
10525
+ const pending = stackChildIds.slice(run.start, run.end).map(referencedId).filter((id) => id !== void 0);
10526
+ const seen = /* @__PURE__ */ new Set();
10527
+ while (pending.length > 0) {
10528
+ const id = pending.pop();
10529
+ if (id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID || id === stackId || seen.has(id)) continue;
10530
+ seen.add(id);
10531
+ const list = owners.get(id);
10532
+ if (list) list.push(index);
10533
+ else owners.set(id, [index]);
10534
+ const c = byId.get(id);
10535
+ if (c) pending.push(...directChildIds(c, options.childIds));
10536
+ }
10537
+ });
10538
+ const surfaceComponents = surfaceRuns.map((run) => {
10539
+ const { child: _child, ...stackRest } = stack;
10540
+ const nextRoot = {
10541
+ ...stackRest,
10542
+ id: _copilotkit_shared.GENERATIVE_UI_ROOT_ID,
10543
+ children: stackChildIds.slice(run.start, run.end)
10544
+ };
10545
+ delete nextRoot.child;
10546
+ return [nextRoot];
10547
+ });
10548
+ for (const c of components) {
10549
+ if (!isRecord(c) || typeof c.id !== "string" || byId.get(c.id) !== c) continue;
10550
+ const ownerIndexes = owners.get(c.id) ?? [];
10551
+ for (const index of ownerIndexes) surfaceComponents[index].push(c);
10552
+ }
10553
+ let surfaceIndex = 0;
10554
+ return runs.map((run) => {
10555
+ if (run.prose) return {
10556
+ kind: "markdown",
10557
+ markdown: proseItemsToMarkdown(items.slice(run.start, run.end))
10558
+ };
10559
+ return {
10560
+ kind: "surface",
10561
+ components: surfaceComponents[surfaceIndex++]
10562
+ };
10563
+ });
10564
+ }
10565
+
10566
+ //#endregion
10567
+ exports.A2UI_FENCE_LANGUAGE = A2UI_FENCE_LANGUAGE;
9203
10568
  exports.AgentRegistry = AgentRegistry;
9204
10569
  exports.AgentThreadLockedError = AgentThreadLockedError;
9205
10570
  exports.ContextStore = ContextStore;
@@ -9217,6 +10582,7 @@ exports.StateManager = StateManager;
9217
10582
  exports.SuggestionEngine = SuggestionEngine;
9218
10583
  exports.ToolCallStatus = ToolCallStatus;
9219
10584
  exports.WebMCPRegistry = WebMCPRegistry;
10585
+ exports.classifySurfaceCards = classifySurfaceCards;
9220
10586
  exports.completePartialMarkdown = completePartialMarkdown;
9221
10587
  exports.createActionGroup = createActionGroup;
9222
10588
  exports.createEffect = createEffect;
@@ -9230,6 +10596,11 @@ exports.emitInspectorViewThread = emitInspectorViewThread;
9230
10596
  exports.emitInspectorViewThreadResult = emitInspectorViewThreadResult;
9231
10597
  exports.empty = empty;
9232
10598
  exports.ensureObjectArgs = ensureObjectArgs;
10599
+ exports.extractCompleteArrayItems = extractCompleteArrayItems;
10600
+ exports.extractFenceOperations = extractFenceOperations;
10601
+ exports.extractStringField = extractStringField;
10602
+ exports.flattenInformationalCards = flattenInformationalCards;
10603
+ exports.getMarkdownOperationSurfaceId = getMarkdownOperationSurfaceId;
9233
10604
  exports.getWebMCPModelContext = getWebMCPModelContext;
9234
10605
  exports.isAbortError = isAbortError;
9235
10606
  exports.isInspectorThreadBridgeEnabled = isInspectorThreadBridgeEnabled;
@@ -9241,8 +10612,11 @@ exports.onInspectorStopViewing = onInspectorStopViewing;
9241
10612
  exports.onInspectorViewThread = onInspectorViewThread;
9242
10613
  exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
9243
10614
  exports.parseToolArguments = parseToolArguments;
10615
+ exports.prepareSurfaceOperations = prepareSurfaceOperations;
9244
10616
  exports.props = props;
10617
+ exports.segmentSurfaceProse = segmentSurfaceProse;
9245
10618
  exports.select = select;
10619
+ exports.splitA2UIMarkdown = splitA2UIMarkdown;
9246
10620
  exports.ɵCOPILOTKIT_FEATURES = ɵCOPILOTKIT_FEATURES;
9247
10621
  exports.ɵInterruptState = ɵInterruptState;
9248
10622
  exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;