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