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