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