@copilotkit/core 2.0.0-rc.30 → 2.0.0-rc.32

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.
Files changed (36) hide show
  1. package/dist/a2ui-markdown-BxZr1mEU.mjs +1360 -0
  2. package/dist/a2ui-markdown-BxZr1mEU.mjs.map +1 -0
  3. package/dist/a2ui-markdown-DkMXFQih.cjs +1419 -0
  4. package/dist/a2ui-markdown-DkMXFQih.cjs.map +1 -0
  5. package/dist/chat-configuration.cjs +1 -1
  6. package/dist/chat-configuration.d.cts +1 -1
  7. package/dist/chat-configuration.d.mts +1 -1
  8. package/dist/chat-configuration.mjs +1 -1
  9. package/dist/generative-ui/index.cjs +3121 -0
  10. package/dist/generative-ui/index.cjs.map +1 -0
  11. package/dist/generative-ui/index.d.cts +974 -0
  12. package/dist/generative-ui/index.d.cts.map +1 -0
  13. package/dist/generative-ui/index.d.mts +974 -0
  14. package/dist/generative-ui/index.d.mts.map +1 -0
  15. package/dist/generative-ui/index.mjs +3075 -0
  16. package/dist/generative-ui/index.mjs.map +1 -0
  17. package/dist/index.cjs +45 -1381
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.cts +1 -1
  20. package/dist/index.d.mts +1 -1
  21. package/dist/index.mjs +36 -1372
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/index.umd.js +28 -14
  24. package/dist/index.umd.js.map +1 -1
  25. package/dist/{learning-bridge-6XU87AJD.d.cts → learning-bridge-C_WCUqF-.d.cts} +9 -2
  26. package/dist/learning-bridge-C_WCUqF-.d.cts.map +1 -0
  27. package/dist/{learning-bridge-JEJAH81x.d.mts → learning-bridge-D30guTHM.d.mts} +9 -2
  28. package/dist/learning-bridge-D30guTHM.d.mts.map +1 -0
  29. package/dist/{viewport-D9ZX0xqz.mjs → viewport-CksL5y8p.mjs} +1 -1
  30. package/dist/{viewport-D9ZX0xqz.mjs.map → viewport-CksL5y8p.mjs.map} +1 -1
  31. package/dist/{viewport-GwjIosf7.cjs → viewport-D-tuKCeb.cjs} +1 -1
  32. package/dist/{viewport-GwjIosf7.cjs.map → viewport-D-tuKCeb.cjs.map} +1 -1
  33. package/package.json +12 -5
  34. package/tsdown.config.ts +5 -0
  35. package/dist/learning-bridge-6XU87AJD.d.cts.map +0 -1
  36. package/dist/learning-bridge-JEJAH81x.d.mts.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_viewport = require('./viewport-GwjIosf7.cjs');
2
+ const require_a2ui_markdown = require('./a2ui-markdown-DkMXFQih.cjs');
3
+ const require_viewport = require('./viewport-D-tuKCeb.cjs');
3
4
  const require_chat_configuration = require('./chat-configuration.cjs');
4
5
  let _tanstack_pacer = require("@tanstack/pacer");
5
6
  let _ag_ui_client = require("@ag-ui/client");
@@ -8,7 +9,6 @@ let rxjs = require("rxjs");
8
9
  let rxjs_operators = require("rxjs/operators");
9
10
  let phoenix = require("phoenix");
10
11
  let _copilotkit_learning = require("@copilotkit/learning");
11
- let jsonrepair = require("jsonrepair");
12
12
  let _ag_ui_core = require("@ag-ui/core");
13
13
 
14
14
  //#region src/utils/http-agent.ts
@@ -318,6 +318,12 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
318
318
  socket = null;
319
319
  activeChannel = null;
320
320
  canonicalRunId = null;
321
+ /**
322
+ * Counts the runs and connects this agent has started. A stop settles later
323
+ * than it is sent, so it compares this to tell whether a newer run has taken
324
+ * over the agent in the meantime.
325
+ */
326
+ runGeneration = 0;
321
327
  sharedState;
322
328
  constructor(config, sharedState = { lastSeenEventIds: /* @__PURE__ */ new Map() }) {
323
329
  super();
@@ -387,18 +393,27 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
387
393
  return ɵconnectWithoutEventVerification(this, effectiveParameters, subscriber, (input, lifecycle) => this.connect(input, lifecycle));
388
394
  }
389
395
  abortRun() {
390
- if (this.activeChannel && this.canonicalRunId) {
391
- const fallback = setTimeout(() => clear(), 5e3);
392
- const clear = () => {
393
- clearTimeout(fallback);
394
- this.detachActiveRun();
395
- this.cleanup();
396
- };
397
- this.activeChannel.push(STOP_RUN_EVENT, { run_id: this.canonicalRunId }).receive("ok", clear).receive("error", clear).receive("timeout", clear);
398
- } else {
396
+ const channel = this.activeChannel;
397
+ const runId = this.canonicalRunId;
398
+ if (!channel || !runId) {
399
399
  this.detachActiveRun();
400
400
  this.cleanup();
401
+ return;
401
402
  }
403
+ const socket = this.socket;
404
+ const generation = this.runGeneration;
405
+ let settled = false;
406
+ const clear = () => {
407
+ if (settled) return;
408
+ settled = true;
409
+ clearTimeout(fallback);
410
+ if (this.runGeneration === generation) {
411
+ this.detachActiveRun();
412
+ this.cleanup();
413
+ } else this.cleanupOwned(channel, socket, runId);
414
+ };
415
+ const fallback = setTimeout(clear, 5e3);
416
+ channel.push(STOP_RUN_EVENT, { run_id: runId }).receive("ok", clear).receive("error", clear).receive("timeout", clear);
402
417
  }
403
418
  /**
404
419
  * Trigger the run via REST, then join the realtime thread channel and relay
@@ -406,6 +421,7 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
406
421
  */
407
422
  run(input) {
408
423
  if (!isMcpResourceRead(input)) {
424
+ this.runGeneration += 1;
409
425
  this.threadId = input.threadId;
410
426
  this.canonicalRunId = input.runId;
411
427
  }
@@ -446,6 +462,7 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
446
462
  * entire history every time the chat re-opens a socket.
447
463
  */
448
464
  connect(input, lifecycle) {
465
+ this.runGeneration += 1;
449
466
  this.threadId = input.threadId;
450
467
  this.canonicalRunId = null;
451
468
  const replayCursor = this.getReconnectCursor(input);
@@ -467,9 +484,10 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
467
484
  /**
468
485
  * Tear down a specific channel + socket pair that belongs to one pipeline.
469
486
  * Only nulls instance references when they still point to the owned resource,
470
- * so a concurrent pipeline's resources are never clobbered.
487
+ * and the run ID only while it is still the owner's, so a concurrent
488
+ * pipeline's resources are never clobbered.
471
489
  */
472
- cleanupOwned(ownChannel, ownSocket) {
490
+ cleanupOwned(ownChannel, ownSocket, ownRunId) {
473
491
  if (ownChannel) {
474
492
  ownChannel.leave();
475
493
  if (this.activeChannel === ownChannel) this.activeChannel = null;
@@ -478,10 +496,10 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
478
496
  ownSocket.disconnect();
479
497
  if (this.socket === ownSocket) this.socket = null;
480
498
  }
481
- this.canonicalRunId = null;
499
+ if (this.canonicalRunId === ownRunId) this.canonicalRunId = null;
482
500
  }
483
501
  cleanup() {
484
- this.cleanupOwned(this.activeChannel, this.socket);
502
+ this.cleanupOwned(this.activeChannel, this.socket, this.canonicalRunId);
485
503
  }
486
504
  requestJoinCredentials$(mode, input, replayCursor) {
487
505
  return (0, rxjs.defer)(async () => {
@@ -574,6 +592,7 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
574
592
  options.lifecycle?.onReplayStarted?.();
575
593
  let ownSocket = null;
576
594
  let ownChannel = null;
595
+ const ownRunId = this.canonicalRunId;
577
596
  let replayFinished = false;
578
597
  let warnedAboutIdle = false;
579
598
  let idleWarning;
@@ -656,7 +675,7 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
656
675
  const terminal$ = (0, rxjs.merge)(threadCompleted$, streamIdleCompletion$);
657
676
  return (0, rxjs.merge)(replayFailed$.pipe((0, rxjs_operators.ignoreElements)(), (0, rxjs_operators.takeUntil)(terminal$)), replayComplete$.pipe((0, rxjs_operators.ignoreElements)(), (0, rxjs_operators.takeUntil)(terminal$)), this.joinThreadChannel$(channel$), this.observeSocketHealth$(socket$, options.onSocketOpen).pipe((0, rxjs_operators.takeUntil)(terminal$)), threadEvents$.pipe((0, rxjs_operators.takeUntil)(streamIdleCompletion$)), streamIdleCompletion$.pipe((0, rxjs_operators.ignoreElements)(), (0, rxjs_operators.takeUntil)(threadCompleted$))).pipe((0, rxjs_operators.finalize)(() => {
658
677
  clearIdleWarning();
659
- this.cleanupOwned(ownChannel, ownSocket);
678
+ this.cleanupOwned(ownChannel, ownSocket, ownRunId);
660
679
  }));
661
680
  });
662
681
  }
@@ -12053,1361 +12072,6 @@ var ɵInspectorThreadOverride = class {
12053
12072
  }
12054
12073
  };
12055
12074
 
12056
- //#endregion
12057
- //#region src/a2ui-markdown/fence-parser.ts
12058
- /** Language of a fenced code block that carries A2UI operations. */
12059
- const A2UI_FENCE_LANGUAGE = "a2ui";
12060
- /** Column-0 fence opener: a run of 3+ backticks or tildes, then the info string. */
12061
- const FENCE_OPEN = /^(`{3,}|~{3,})(.*)$/;
12062
- /** Info-string token that names the placement target of an a2ui fence. */
12063
- const TARGET_TOKEN = /^target=(.+)$/;
12064
- function isCloser(line, fence) {
12065
- const trimmed = line.trim();
12066
- if (trimmed.length < fence.length) return false;
12067
- for (const ch of trimmed) if (ch !== fence.char) return false;
12068
- return true;
12069
- }
12070
- /** The id of the first `target=<id>` token. Other tokens are ignored. */
12071
- function readTarget(tokens) {
12072
- for (const token of tokens) {
12073
- const match = TARGET_TOKEN.exec(token);
12074
- if (match) return match[1];
12075
- }
12076
- }
12077
- function a2uiSegment(fence, text, closed) {
12078
- const segment = {
12079
- type: "a2ui",
12080
- index: fence.index,
12081
- text,
12082
- closed
12083
- };
12084
- if (fence.target !== void 0) segment.target = fence.target;
12085
- return segment;
12086
- }
12087
- /**
12088
- * Split a (possibly still streaming) markdown string into prose segments and
12089
- * top-level ```a2ui fences. Fences of other languages stay inside prose
12090
- * segments byte-for-byte, and a2ui markers inside them are ignored. Only
12091
- * column-0 fences are recognised, so a fence indented inside a list item is
12092
- * left to the markdown renderer.
12093
- *
12094
- * The first info-string token must be exactly `a2ui`. A later
12095
- * `target=<id>` token sets `target` on the segment (for example
12096
- * ```` ```a2ui target=recommendations ````). Other tokens are ignored.
12097
- *
12098
- * An a2ui segment's `text` is the fence body. For a closed fence it ends with
12099
- * "\n" when non-empty. For an open (still streaming or aborted) fence it is
12100
- * everything after the opener line, minus a half-streamed closing marker.
12101
- *
12102
- * @param markdown - The assistant message text, complete or still streaming.
12103
- * @returns The segments in source order.
12104
- *
12105
- * @example
12106
- * ```ts
12107
- * for (const segment of splitA2UIMarkdown(message.content)) {
12108
- * if (segment.type === "a2ui") renderSurface(segment.text, segment.target);
12109
- * else renderMarkdown(segment.text);
12110
- * }
12111
- * ```
12112
- */
12113
- function splitA2UIMarkdown(markdown) {
12114
- const segments = [];
12115
- let proseStart = 0;
12116
- let fence = null;
12117
- let a2uiIndex = 0;
12118
- const pushProse = (end) => {
12119
- if (end > proseStart) segments.push({
12120
- type: "markdown",
12121
- text: markdown.slice(proseStart, end)
12122
- });
12123
- };
12124
- let lineStart = 0;
12125
- while (lineStart <= markdown.length) {
12126
- const newline = markdown.indexOf("\n", lineStart);
12127
- const lineEnd = newline < 0 ? markdown.length : newline;
12128
- const hasCR = lineEnd > lineStart && markdown[lineEnd - 1] === "\r";
12129
- const line = markdown.slice(lineStart, hasCR ? lineEnd - 1 : lineEnd);
12130
- if (fence) {
12131
- if (isCloser(line, fence)) {
12132
- if (fence.index >= 0) {
12133
- const body = markdown.slice(fence.bodyStart, Math.max(fence.bodyStart, lineStart));
12134
- segments.push(a2uiSegment(fence, body, true));
12135
- proseStart = hasCR ? lineEnd - 1 : lineEnd;
12136
- }
12137
- fence = null;
12138
- }
12139
- } else {
12140
- const open = FENCE_OPEN.exec(line);
12141
- if (open) {
12142
- const marker = open[1] ?? "";
12143
- const info = open[2] ?? "";
12144
- const char = marker.charAt(0);
12145
- if (!(char === "`" && info.includes("`"))) {
12146
- const [lang = "", ...tokens] = info.trim().split(/\s+/);
12147
- const isA2UI = lang === A2UI_FENCE_LANGUAGE;
12148
- if (isA2UI) pushProse(lineStart);
12149
- fence = {
12150
- char,
12151
- length: marker.length,
12152
- bodyStart: newline < 0 ? markdown.length : lineEnd + 1,
12153
- index: isA2UI ? a2uiIndex++ : -1,
12154
- target: isA2UI ? readTarget(tokens) : void 0
12155
- };
12156
- }
12157
- }
12158
- }
12159
- if (newline < 0) break;
12160
- lineStart = newline + 1;
12161
- }
12162
- if (fence && fence.index >= 0) {
12163
- const { char } = fence;
12164
- let body = markdown.slice(fence.bodyStart);
12165
- const lastNewline = body.lastIndexOf("\n");
12166
- const lastLine = body.slice(lastNewline + 1).replace(/\r$/, "");
12167
- if (lastLine.length > 0 && [...lastLine].every((ch) => ch === char)) body = body.slice(0, lastNewline + 1);
12168
- segments.push(a2uiSegment(fence, body, false));
12169
- } else pushProse(markdown.length);
12170
- return segments;
12171
- }
12172
-
12173
- //#endregion
12174
- //#region src/a2ui-markdown/operations.ts
12175
- /** The operation keys that change a surface. */
12176
- const SURFACE_OP_KEYS = [
12177
- "createSurface",
12178
- "updateComponents",
12179
- "updateDataModel",
12180
- "deleteSurface"
12181
- ];
12182
- /** The operation key of an agent-called function. It has no surface. */
12183
- const FUNCTION_CALL_KEY = "callRendererFunction";
12184
- const OP_KEYS = [...SURFACE_OP_KEYS, FUNCTION_CALL_KEY];
12185
- function isRecord$2(value) {
12186
- return typeof value === "object" && value !== null && !Array.isArray(value);
12187
- }
12188
- function isWhitespace(ch) {
12189
- return ch === " " || ch === "\n" || ch === "\r" || ch === " ";
12190
- }
12191
- function skipWhitespace(s, i) {
12192
- while (i < s.length && isWhitespace(s[i])) i++;
12193
- return i;
12194
- }
12195
- /** Index of the closing quote of the JSON string opening at `start`, or -1. */
12196
- function findStringEnd(s, start) {
12197
- for (let i = start + 1; i < s.length; i++) {
12198
- if (s[i] === "\\") {
12199
- i++;
12200
- continue;
12201
- }
12202
- if (s[i] === "\"") return i;
12203
- }
12204
- return -1;
12205
- }
12206
- /**
12207
- * Find the first `"key":` whose value starts with `opener` and return the index
12208
- * of that opener, or -1.
12209
- */
12210
- function findKeyValue(s, key, opener) {
12211
- const needle = `"${key}"`;
12212
- let from = 0;
12213
- while (true) {
12214
- const k = s.indexOf(needle, from);
12215
- if (k < 0) return -1;
12216
- let i = skipWhitespace(s, k + needle.length);
12217
- if (s[i] === ":") {
12218
- i = skipWhitespace(s, i + 1);
12219
- if (s[i] === opener) return i;
12220
- }
12221
- from = k + 1;
12222
- }
12223
- }
12224
- /**
12225
- * Read `"key":"value"` from partial JSON. The first match anywhere in the
12226
- * text wins, at any depth.
12227
- *
12228
- * @param partialJson - JSON text that can still be streaming.
12229
- * @param key - The field name.
12230
- * @returns The string value, or null until its closing quote has arrived.
12231
- *
12232
- * @example
12233
- * ```ts
12234
- * extractStringField('{"createSurface":{"surfaceId":"plan","cat', "surfaceId"); // "plan"
12235
- * ```
12236
- */
12237
- function extractStringField(partialJson, key) {
12238
- const start = findKeyValue(partialJson, key, "\"");
12239
- if (start < 0) return null;
12240
- const end = findStringEnd(partialJson, start);
12241
- if (end < 0) return null;
12242
- try {
12243
- const value = JSON.parse(partialJson.slice(start, end + 1));
12244
- return typeof value === "string" ? value : null;
12245
- } catch {
12246
- return null;
12247
- }
12248
- }
12249
- function pushItem(raw, items) {
12250
- const trimmed = raw.trim();
12251
- if (!trimmed) return;
12252
- try {
12253
- items.push(JSON.parse(trimmed));
12254
- } catch {}
12255
- }
12256
- /**
12257
- * Find `"key":[` in partial JSON and return every complete item of that array
12258
- * so far, plus whether the array has closed. Items of a `components` array get
12259
- * structural-key depth repair: a component that lost closing braces is fixed
12260
- * when its `id`, `component`, `child` or `children` key shows where it ends.
12261
- *
12262
- * @param partialJson - JSON text that can still be streaming.
12263
- * @param key - The name of the array field.
12264
- * @returns `{ items, closed }`, or null when the key (with an array value)
12265
- * has not appeared yet.
12266
- *
12267
- * @example
12268
- * ```ts
12269
- * const result = extractCompleteArrayItems(streamedText, "components");
12270
- * if (result) render(result.items);
12271
- * ```
12272
- */
12273
- function extractCompleteArrayItems(partialJson, key) {
12274
- const open = findKeyValue(partialJson, key, "[");
12275
- if (open < 0) return null;
12276
- return completeArrayItemsAt(partialJson, open, { repairComponents: key === "components" });
12277
- }
12278
- /** Index of the last non-whitespace character before `i`, or -1. */
12279
- function prevNonWhitespace(s, i) {
12280
- let j = i - 1;
12281
- while (j >= 0 && isWhitespace(s[j])) j--;
12282
- return j;
12283
- }
12284
- /**
12285
- * Keys that only ever belong at a component's top level. Seen nested inside
12286
- * the component's objects, they mean the model forgot closing braces.
12287
- */
12288
- const STRUCTURAL_KEYS = new Set([
12289
- "id",
12290
- "component",
12291
- "child",
12292
- "children"
12293
- ]);
12294
- /** Whether a value starting with `ch` has the shape `key` takes on a component. */
12295
- function structuralValueFits(key, ch) {
12296
- if (key === "children") return ch === "[" || ch === "{";
12297
- return ch === "\"";
12298
- }
12299
- /** `{"id":` — a new component object starting at `i`. */
12300
- const COMPONENT_START = /^\{\s*"id"\s*:/;
12301
- /**
12302
- * Structural-key depth repair for one component item. While scanning, a
12303
- * structural key (`id`, `component`, `child`, `children`) found as an object
12304
- * key below the item's top level, with only objects (no arrays) between it
12305
- * and the item root, a value of the expected shape, and not already present
12306
- * at the top level, means closing braces were dropped: the missing `}` are
12307
- * synthesized right before it so it lands at the top level. Containers still
12308
- * open at the end are closed. Returns null when a string never terminates.
12309
- */
12310
- function repairComponentItem(item) {
12311
- const stack = [];
12312
- const topKeys = /* @__PURE__ */ new Set();
12313
- let out = "";
12314
- let copied = 0;
12315
- for (let i = 0; i < item.length; i++) {
12316
- const c = item[i];
12317
- if (c === "\"") {
12318
- const end = findStringEnd(item, i);
12319
- if (end < 0) return null;
12320
- const prev = prevNonWhitespace(item, i);
12321
- const prevCh = item[prev];
12322
- const colon = skipWhitespace(item, end + 1);
12323
- if (stack[stack.length - 1] === "{" && (prevCh === "," || prevCh === "{") && item[colon] === ":") {
12324
- let key;
12325
- try {
12326
- key = JSON.parse(item.slice(i, end + 1));
12327
- } catch {
12328
- return null;
12329
- }
12330
- if (typeof key === "string") {
12331
- if (stack.length === 1) topKeys.add(key);
12332
- else if (STRUCTURAL_KEYS.has(key) && !topKeys.has(key) && stack.every((x) => x === "{") && structuralValueFits(key, item[skipWhitespace(item, colon + 1)])) {
12333
- const closers = "}".repeat(stack.length - 1);
12334
- if (prevCh === ",") {
12335
- out += item.slice(copied, prev) + closers;
12336
- copied = prev;
12337
- } else {
12338
- out += item.slice(copied, i) + closers + ",";
12339
- copied = i;
12340
- }
12341
- stack.length = 1;
12342
- topKeys.add(key);
12343
- }
12344
- }
12345
- }
12346
- i = end;
12347
- continue;
12348
- }
12349
- if (c === "{" || c === "[") stack.push(c);
12350
- else if (c === "}" || c === "]") {
12351
- stack.pop();
12352
- if (stack.length === 0) return out + item.slice(copied, i + 1);
12353
- }
12354
- }
12355
- const closers = stack.reduceRight((text, opener) => text + (opener === "{" ? "}" : "]"), "");
12356
- return out + item.slice(copied) + closers;
12357
- }
12358
- function parseRecord(text) {
12359
- if (text === null) return void 0;
12360
- try {
12361
- const value = JSON.parse(text);
12362
- return isRecord$2(value) ? value : void 0;
12363
- } catch {
12364
- return;
12365
- }
12366
- }
12367
- /**
12368
- * Complete items of the (possibly unterminated) array whose "[" is at `open`.
12369
- * With `repairComponents`, an item that balanced but does not parse is retried
12370
- * with structural-key repair, and a `,{"id":` where an item expects a key
12371
- * ends that (unbalanced) item there, so one malformed component cannot
12372
- * swallow the rest of the array; the cut item is kept only if repair makes
12373
- * it parse.
12374
- */
12375
- function completeArrayItemsAt(partialJson, open, options) {
12376
- const { repairComponents } = options;
12377
- const s = partialJson;
12378
- const items = [];
12379
- const stack = [];
12380
- let inString = false;
12381
- let itemStart = -1;
12382
- const finishItem = (end, balanced) => {
12383
- const raw = s.slice(itemStart, end);
12384
- if (!repairComponents) {
12385
- pushItem(raw, items);
12386
- return;
12387
- }
12388
- if (balanced) try {
12389
- items.push(JSON.parse(raw));
12390
- return;
12391
- } catch {}
12392
- const repaired = parseRecord(repairComponentItem(raw.trim()));
12393
- if (repaired !== void 0) items.push(repaired);
12394
- };
12395
- for (let i = open + 1; i < s.length; i++) {
12396
- const c = s[i];
12397
- if (inString) {
12398
- if (c === "\\") i++;
12399
- else if (c === "\"") inString = false;
12400
- continue;
12401
- }
12402
- if (c === "\"") {
12403
- inString = true;
12404
- if (stack.length === 0 && itemStart < 0) itemStart = i;
12405
- continue;
12406
- }
12407
- if (c === "{" || c === "[") {
12408
- if (repairComponents && c === "{" && stack[stack.length - 1] === "{" && COMPONENT_START.test(s.slice(i, i + 24))) {
12409
- const prev = prevNonWhitespace(s, i);
12410
- if (s[prev] === ",") {
12411
- finishItem(prev, false);
12412
- stack.length = 0;
12413
- itemStart = i;
12414
- stack.push(c);
12415
- continue;
12416
- }
12417
- }
12418
- if (stack.length === 0) itemStart = i;
12419
- stack.push(c);
12420
- continue;
12421
- }
12422
- if (c === "}" || c === "]") {
12423
- if (stack.length === 0) {
12424
- if (c === "]") {
12425
- if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
12426
- return {
12427
- items,
12428
- closed: true
12429
- };
12430
- }
12431
- return {
12432
- items,
12433
- closed: false
12434
- };
12435
- }
12436
- stack.pop();
12437
- if (stack.length === 0) {
12438
- finishItem(i + 1, true);
12439
- itemStart = -1;
12440
- }
12441
- continue;
12442
- }
12443
- if (stack.length === 0) {
12444
- if (c === ",") {
12445
- if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
12446
- itemStart = -1;
12447
- } else if (itemStart < 0 && !isWhitespace(c)) itemStart = i;
12448
- }
12449
- }
12450
- return {
12451
- items,
12452
- closed: false
12453
- };
12454
- }
12455
- /** The first operation key whose value is an object, with that value. */
12456
- function getOperationEntry(op) {
12457
- for (const key of OP_KEYS) {
12458
- const inner = op[key];
12459
- if (isRecord$2(inner)) return {
12460
- key,
12461
- inner
12462
- };
12463
- }
12464
- return null;
12465
- }
12466
- /**
12467
- * The surfaceId an operation targets: the one nested under its operation key,
12468
- * else a top-level `surfaceId`. A `callRendererFunction` operation targets no
12469
- * surface, so it gets undefined.
12470
- *
12471
- * It is named `getMarkdownOperationSurfaceId` because `@copilotkit/shared`
12472
- * already exports a strict `getOperationSurfaceId`. This one also reads a
12473
- * top-level `surfaceId`, which models sometimes write.
12474
- *
12475
- * @param op - An operation from an a2ui fence.
12476
- * @returns The surfaceId, or undefined when the operation names none or is a
12477
- * function call.
12478
- *
12479
- * @example
12480
- * ```ts
12481
- * getMarkdownOperationSurfaceId({ updateDataModel: { surfaceId: "plan" } }); // "plan"
12482
- * ```
12483
- */
12484
- function getMarkdownOperationSurfaceId(op) {
12485
- if (getOperationEntry(op)?.key === FUNCTION_CALL_KEY) return void 0;
12486
- for (const key of SURFACE_OP_KEYS) {
12487
- const inner = op[key];
12488
- if (isRecord$2(inner) && typeof inner.surfaceId === "string") return inner.surfaceId;
12489
- }
12490
- return typeof op.surfaceId === "string" ? op.surfaceId : void 0;
12491
- }
12492
- /**
12493
- * Index just past the JSON value starting at `start`, or -1 when the value is
12494
- * still incomplete. A primitive at the very end of the input counts as
12495
- * incomplete, since more digits or letters may still stream in.
12496
- */
12497
- function findValueEnd(s, start) {
12498
- const c = s[start];
12499
- if (c === "\"") {
12500
- const end = findStringEnd(s, start);
12501
- return end < 0 ? -1 : end + 1;
12502
- }
12503
- if (c === "{" || c === "[") {
12504
- let depth = 0;
12505
- for (let i = start; i < s.length; i++) {
12506
- const ch = s[i];
12507
- if (ch === "\"") {
12508
- const end = findStringEnd(s, i);
12509
- if (end < 0) return -1;
12510
- i = end;
12511
- } else if (ch === "{" || ch === "[") depth++;
12512
- else if (ch === "}" || ch === "]") {
12513
- depth--;
12514
- if (depth === 0) return i + 1;
12515
- }
12516
- }
12517
- return -1;
12518
- }
12519
- let i = start;
12520
- while (i < s.length && !isWhitespace(s[i]) && !",}]".includes(s[i])) i++;
12521
- return i >= s.length ? -1 : i;
12522
- }
12523
- /**
12524
- * Walk the direct entries of the (possibly unterminated) JSON object whose "{"
12525
- * is at `objStart`, calling `visit` with each key and the index where its value
12526
- * starts. Nested objects and arrays are skipped whole, so keys inside them are
12527
- * never visited. Stops when `visit` returns true, at the object's end, or where
12528
- * the input runs out.
12529
- */
12530
- function visitDirectEntries(s, objStart, visit) {
12531
- let i = objStart + 1;
12532
- while (i < s.length) {
12533
- i = skipWhitespace(s, i);
12534
- const c = s[i];
12535
- if (c === ",") {
12536
- i++;
12537
- continue;
12538
- }
12539
- if (c !== "\"") return;
12540
- const keyEnd = findStringEnd(s, i);
12541
- if (keyEnd < 0) return;
12542
- let key;
12543
- try {
12544
- key = JSON.parse(s.slice(i, keyEnd + 1));
12545
- } catch {
12546
- return;
12547
- }
12548
- i = skipWhitespace(s, keyEnd + 1);
12549
- if (s[i] !== ":") return;
12550
- i = skipWhitespace(s, i + 1);
12551
- if (i >= s.length) return;
12552
- if (typeof key === "string" && visit(key, i)) return;
12553
- const valueEnd = findValueEnd(s, i);
12554
- if (valueEnd < 0) return;
12555
- i = valueEnd;
12556
- }
12557
- }
12558
- /**
12559
- * Value start of a direct `key` of the object at `objStart` whose value begins
12560
- * with `opener` (any value when omitted), or -1.
12561
- */
12562
- function findDirectKeyValue(s, objStart, key, opener) {
12563
- let found = -1;
12564
- visitDirectEntries(s, objStart, (k, valueStart) => {
12565
- if (k !== key) return false;
12566
- if (opener === void 0 || s[valueStart] === opener) found = valueStart;
12567
- return true;
12568
- });
12569
- return found;
12570
- }
12571
- /** A direct string field of the object at `objStart`, once its closing quote has arrived. */
12572
- function readDirectString(s, objStart, key) {
12573
- if (objStart < 0) return null;
12574
- const start = findDirectKeyValue(s, objStart, key, "\"");
12575
- if (start < 0) return null;
12576
- const end = findValueEnd(s, start);
12577
- if (end < 0) return null;
12578
- try {
12579
- const value = JSON.parse(s.slice(start, end));
12580
- return typeof value === "string" ? value : null;
12581
- } catch {
12582
- return null;
12583
- }
12584
- }
12585
- /** A direct object field of the object at `objStart`, once the whole object has arrived. */
12586
- function readDirectRecord(s, objStart, key) {
12587
- const start = findDirectKeyValue(s, objStart, key, "{");
12588
- if (start < 0) return void 0;
12589
- const end = findValueEnd(s, start);
12590
- if (end < 0) return void 0;
12591
- return parseRecord(s.slice(start, end));
12592
- }
12593
- /**
12594
- * The complete part of a (possibly unterminated) JSON value: the parsed value
12595
- * when it is complete; for an open object, its complete entries plus the
12596
- * complete items of any streaming array entry; otherwise undefined.
12597
- */
12598
- function completePartOfValue(s, start) {
12599
- const end = findValueEnd(s, start);
12600
- if (end >= 0) try {
12601
- return JSON.parse(s.slice(start, end));
12602
- } catch {
12603
- return;
12604
- }
12605
- if (s[start] !== "{") return void 0;
12606
- const out = {};
12607
- visitDirectEntries(s, start, (key, valueStart) => {
12608
- const valueEnd = findValueEnd(s, valueStart);
12609
- if (valueEnd >= 0) try {
12610
- out[key] = JSON.parse(s.slice(valueStart, valueEnd));
12611
- } catch {}
12612
- else if (s[valueStart] === "[") {
12613
- const { items } = completeArrayItemsAt(s, valueStart, { repairComponents: false });
12614
- if (items.length > 0) out[key] = items;
12615
- }
12616
- return false;
12617
- });
12618
- return Object.keys(out).length > 0 ? out : void 0;
12619
- }
12620
- /**
12621
- * Best-effort operation from an unfinished or malformed top-level object.
12622
- * Fields are read only from the operation's own keys (`version` at the top
12623
- * level, `surfaceId`, `catalogId`, `path`, `dataModel` and `components` inside
12624
- * the operation object), never from component props or data-model values that
12625
- * happen to share a name.
12626
- *
12627
- * A `createSurface` keeps its complete components and a `dataModel` that has
12628
- * fully arrived, so a surface created in one line renders while it streams.
12629
- * A `callRendererFunction` gives nothing: a function must not run with half
12630
- * of its args.
12631
- */
12632
- function partialOperation(line) {
12633
- const root = skipWhitespace(line, 0);
12634
- if (line[root] !== "{") return null;
12635
- const version = readDirectString(line, root, "version") ?? _copilotkit_shared.A2UI_VERSION;
12636
- const components = findDirectKeyValue(line, root, "updateComponents", "{");
12637
- if (components >= 0) {
12638
- const arrayStart = findDirectKeyValue(line, components, "components", "[");
12639
- if (arrayStart < 0) return null;
12640
- const { items } = completeArrayItemsAt(line, arrayStart, { repairComponents: true });
12641
- if (items.length === 0) return null;
12642
- const surfaceId = readDirectString(line, components, "surfaceId");
12643
- return {
12644
- version,
12645
- updateComponents: {
12646
- ...surfaceId ? { surfaceId } : {},
12647
- components: items
12648
- }
12649
- };
12650
- }
12651
- const data = findDirectKeyValue(line, root, "updateDataModel", "{");
12652
- if (data >= 0) {
12653
- const valueStart = findDirectKeyValue(line, data, "value");
12654
- if (valueStart < 0) return null;
12655
- const value = completePartOfValue(line, valueStart);
12656
- if (value === void 0) return null;
12657
- const surfaceId = readDirectString(line, data, "surfaceId");
12658
- const path = readDirectString(line, data, "path");
12659
- return {
12660
- version,
12661
- updateDataModel: {
12662
- ...surfaceId ? { surfaceId } : {},
12663
- ...path ? { path } : {},
12664
- value
12665
- }
12666
- };
12667
- }
12668
- const create = findDirectKeyValue(line, root, "createSurface", "{");
12669
- if (create >= 0) {
12670
- const surfaceId = readDirectString(line, create, "surfaceId");
12671
- if (!surfaceId) return null;
12672
- const catalogId = readDirectString(line, create, "catalogId");
12673
- const dataModel = readDirectRecord(line, create, "dataModel");
12674
- const componentsStart = findDirectKeyValue(line, create, "components", "[");
12675
- const components = componentsStart < 0 ? [] : completeArrayItemsAt(line, componentsStart, { repairComponents: true }).items;
12676
- return {
12677
- version,
12678
- createSurface: {
12679
- surfaceId,
12680
- ...catalogId ? { catalogId } : {},
12681
- ...dataModel ? { dataModel } : {},
12682
- ...components.length > 0 ? { components } : {}
12683
- }
12684
- };
12685
- }
12686
- return null;
12687
- }
12688
- /**
12689
- * A line that opens a new top-level operation: `{"version":"1…` or
12690
- * `{"<operation>":{`. Seen at the start of a line while an earlier object is
12691
- * still unbalanced, it means that object is malformed and has ended.
12692
- */
12693
- const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
12694
- /**
12695
- * Scan the top-level object whose "{" is at `start`. Returns the index just
12696
- * past it and whether it balanced. An unbalanced object ends early (at the
12697
- * start of the line) when a line opens a new operation; otherwise it runs to
12698
- * the end of the input. JSON strings cannot contain raw newlines, so a newline
12699
- * inside a string ends it: a stray quote then breaks one line, not the rest of
12700
- * the fence.
12701
- */
12702
- function scanTopLevelObject(s, start) {
12703
- let depth = 0;
12704
- let inString = false;
12705
- for (let i = start; i < s.length; i++) {
12706
- const c = s[i];
12707
- if (inString) {
12708
- if (c === "\\" && s[i + 1] !== "\n") i++;
12709
- else if (c === "\"" || c === "\n") inString = false;
12710
- if (c !== "\n") continue;
12711
- }
12712
- if (c === "\n") {
12713
- const next = skipWhitespace(s, i + 1);
12714
- if (OPERATION_START.test(s.slice(next, next + 40))) return {
12715
- end: i + 1,
12716
- balanced: false
12717
- };
12718
- continue;
12719
- }
12720
- if (c === "\"") inString = true;
12721
- else if (c === "{" || c === "[") depth++;
12722
- else if (c === "}" || c === "]") {
12723
- depth--;
12724
- if (depth === 0) return {
12725
- end: i + 1,
12726
- balanced: true
12727
- };
12728
- }
12729
- }
12730
- return {
12731
- end: s.length,
12732
- balanced: false
12733
- };
12734
- }
12735
- const OPERATION_NAMES = [
12736
- "createSurface",
12737
- "updateComponents",
12738
- "updateDataModel",
12739
- "deleteSurface",
12740
- "callRendererFunction"
12741
- ];
12742
- /** Whether a value is shaped like one A2UI operation, with named components. */
12743
- function isOperationShape(value) {
12744
- if (!isRecord$2(value) || value.version !== _copilotkit_shared.A2UI_VERSION) return false;
12745
- const names = OPERATION_NAMES.filter((name) => name in value);
12746
- if (names.length !== 1 || Object.keys(value).length !== 2) return false;
12747
- const body = value[names[0]];
12748
- if (!isRecord$2(body)) return false;
12749
- if (names[0] === "callRendererFunction") return true;
12750
- if (typeof body.surfaceId !== "string") return false;
12751
- const components = body.components;
12752
- return components === void 0 || Array.isArray(components) && components.every((c) => isRecord$2(c) && typeof c.id === "string" && typeof c.component === "string");
12753
- }
12754
- /** Openers minus closers ({ and [ against } and ]) outside strings. */
12755
- function closerImbalance(line) {
12756
- let depth = 0;
12757
- let inString = false;
12758
- for (let i = 0; i < line.length; i++) {
12759
- const c = line[i];
12760
- if (inString) {
12761
- if (c === "\\") i++;
12762
- else if (c === "\"") inString = false;
12763
- } else if (c === "\"") inString = true;
12764
- else if (c === "{" || c === "[") depth++;
12765
- else if (c === "}" || c === "]") depth--;
12766
- }
12767
- return depth;
12768
- }
12769
- /** The text with closers and whitespace removed, to compare a repair. */
12770
- function withoutClosers(text) {
12771
- return text.replace(/[\]}\s]/g, "");
12772
- }
12773
- /**
12774
- * Whether a component of the operation holds a structural key (`id`,
12775
- * `component`, `child`, `children`) in a nested object: a closer added at
12776
- * the end instead of where it was dropped. The scan below repairs those.
12777
- */
12778
- function nestsStructuralKey(value) {
12779
- const nests = (v) => isRecord$2(v) && Object.entries(v).some(([k, x]) => STRUCTURAL_KEYS.has(k) || nests(x));
12780
- const components = (isRecord$2(value) ? Object.values(value).find(isRecord$2) : void 0)?.components;
12781
- return Array.isArray(components) && components.some((c) => isRecord$2(c) && Object.values(c).some((prop) => nests(prop)));
12782
- }
12783
- /**
12784
- * Repairs the complete lines of a fence that are not valid JSON (a missing
12785
- * or extra brace) with jsonrepair, when the repair only adds or removes
12786
- * closers and the result is shaped like an operation. A line still streaming in (no newline yet) is left alone.
12787
- */
12788
- function repairFenceLines(fenceText) {
12789
- const repaired = [];
12790
- const lines = fenceText.split("\n");
12791
- if (fenceText.trimStart().startsWith("[")) return {
12792
- text: fenceText,
12793
- repaired
12794
- };
12795
- for (let n = 0; n < lines.length - 1; n++) {
12796
- const line = lines[n];
12797
- if (!line.trim().startsWith("{")) continue;
12798
- try {
12799
- JSON.parse(line);
12800
- continue;
12801
- } catch {}
12802
- const imbalance = closerImbalance(line);
12803
- if (Math.abs(imbalance) !== 1) continue;
12804
- const next = lines.slice(n + 1).find((l) => l.trim() !== "");
12805
- if (imbalance > 0 && next !== void 0 && !next.trim().startsWith("{")) continue;
12806
- try {
12807
- const fixed = (0, jsonrepair.jsonrepair)(line);
12808
- const value = JSON.parse(fixed);
12809
- if (withoutClosers(fixed) === withoutClosers(line) && isOperationShape(value) && !nestsStructuralKey(value) && !(isRecord$2(value) && "callRendererFunction" in value)) {
12810
- repaired.push(line.trim());
12811
- lines[n] = JSON.stringify(value);
12812
- }
12813
- } catch {}
12814
- }
12815
- return {
12816
- text: lines.join("\n"),
12817
- repaired
12818
- };
12819
- }
12820
- /**
12821
- * Parse the body of an a2ui fence as a stream of top-level JSON values, so
12822
- * operations may be one per line (the documented format), several per line,
12823
- * pretty-printed over many lines, or wrapped in a top-level array (which is
12824
- * flattened). Whitespace and commas between objects are ignored.
12825
- *
12826
- * - A balanced object is `JSON.parse`d. When that fails (e.g. a stray quote),
12827
- * its raw text goes to `invalidLines` and whatever `partialOperation` can
12828
- * salvage (complete components, data-model entries, createSurface fields)
12829
- * is kept.
12830
- * - An unbalanced object followed by a line that opens a new operation is
12831
- * treated the same way.
12832
- * - The trailing unbalanced object (still streaming, or never closed) is
12833
- * `partialObject` and yields a partial operation when it has usable data.
12834
- * - Other text between objects is skipped and reported in `recovered` (and in
12835
- * `invalidLines`, which predates it).
12836
- *
12837
- * `partialLine` is a deprecated alias of `partialObject`.
12838
- *
12839
- * @param fenceText - The body of an a2ui fence (`text` of an a2ui
12840
- * `MarkdownSegment`), complete or still streaming.
12841
- * @returns `{ operations, partialObject, partialLine, invalidLines, recovered }`.
12842
- *
12843
- * @example
12844
- * ```ts
12845
- * const { operations } = extractFenceOperations(segment.text);
12846
- * ```
12847
- */
12848
- function extractFenceOperations(fenceText) {
12849
- const { text: s, repaired: repairedLines } = repairFenceLines(fenceText);
12850
- const operations = [];
12851
- const invalidLines = [];
12852
- const recovered = [];
12853
- let partialObject = null;
12854
- const salvage = (raw) => {
12855
- invalidLines.push(raw.trim());
12856
- const partial = partialOperation(raw);
12857
- if (partial) operations.push(partial);
12858
- };
12859
- let junkStart = -1;
12860
- const flushJunk = (end) => {
12861
- if (junkStart < 0) return;
12862
- const junk = s.slice(junkStart, end).trim();
12863
- junkStart = -1;
12864
- if (!junk) return;
12865
- recovered.push(junk);
12866
- invalidLines.push(junk);
12867
- };
12868
- let i = 0;
12869
- while (i < s.length) {
12870
- const c = s[i];
12871
- if (c === "{") {
12872
- flushJunk(i);
12873
- const { end, balanced } = scanTopLevelObject(s, i);
12874
- const raw = s.slice(i, end);
12875
- if (balanced) {
12876
- let parsed;
12877
- try {
12878
- parsed = JSON.parse(raw);
12879
- } catch {
12880
- parsed = void 0;
12881
- }
12882
- if (isRecord$2(parsed)) operations.push(parsed);
12883
- else salvage(raw);
12884
- } else if (end < s.length) salvage(raw);
12885
- else {
12886
- partialObject = raw;
12887
- const partial = partialOperation(raw);
12888
- if (partial) operations.push(partial);
12889
- }
12890
- i = end;
12891
- continue;
12892
- }
12893
- if (c === "\n" || c === "[" || c === "]") flushJunk(i);
12894
- else if (junkStart < 0 && !isWhitespace(c) && c !== ",") junkStart = i;
12895
- i++;
12896
- }
12897
- flushJunk(s.length);
12898
- return {
12899
- operations,
12900
- partialObject,
12901
- partialLine: partialObject,
12902
- invalidLines,
12903
- recovered,
12904
- repairedLines
12905
- };
12906
- }
12907
- /**
12908
- * Normalise a fence's operations for the renderer: drop unknown messages, fill
12909
- * in `version` and missing `surfaceId`s, keep only the first `createSurface`,
12910
- * keep its `catalogId` when `catalogIds` lists it (else use `catalogId`), synthesize
12911
- * `createSurface` when the model omitted it, and report the
12912
- * surfaceId (the first one found, else `fallbackSurfaceId`).
12913
- *
12914
- * `callRendererFunction` operations target no surface. They get no surfaceId,
12915
- * do not cause a synthesized `createSurface`, and come back in
12916
- * `functionCalls` (in fence order), never in `operations`.
12917
- *
12918
- * @param input.operations - Operations from `extractFenceOperations`.
12919
- * @param input.fallbackSurfaceId - The surfaceId to use when no operation
12920
- * names one.
12921
- * @param input.catalogId - The client catalog. It replaces a catalogId of the
12922
- * model that `catalogIds` does not list.
12923
- * @param input.catalogIds - The catalogs that the model can name. Left out,
12924
- * only `catalogId`.
12925
- * @returns `{ surfaceId, operations, functionCalls }`.
12926
- *
12927
- * @example
12928
- * ```ts
12929
- * const { surfaceId, operations, functionCalls } = prepareSurfaceOperations({
12930
- * operations: extractFenceOperations(segment.text).operations,
12931
- * fallbackSurfaceId: `${messageId}-${segment.index}`,
12932
- * catalogId,
12933
- * });
12934
- * ```
12935
- */
12936
- function prepareSurfaceOperations(input) {
12937
- const { operations, fallbackSurfaceId, catalogId } = input;
12938
- const catalogIds = input.catalogIds ?? [catalogId];
12939
- const surfaceId = operations.map(getMarkdownOperationSurfaceId).find((id) => !!id) ?? fallbackSurfaceId;
12940
- const out = [];
12941
- const functionCalls = [];
12942
- let hasCreate = false;
12943
- for (const op of operations) {
12944
- const entry = getOperationEntry(op);
12945
- if (!entry) continue;
12946
- const { key } = entry;
12947
- const inner = { ...entry.inner };
12948
- const version = typeof op.version === "string" ? op.version : _copilotkit_shared.A2UI_VERSION;
12949
- if (key === FUNCTION_CALL_KEY) {
12950
- functionCalls.push({
12951
- version,
12952
- [key]: inner
12953
- });
12954
- continue;
12955
- }
12956
- if (typeof inner.surfaceId !== "string") inner.surfaceId = surfaceId;
12957
- if (key === "createSurface") {
12958
- if (hasCreate) {
12959
- const { surfaceId: id, dataModel, components } = inner;
12960
- if (dataModel !== void 0) out.push({
12961
- version,
12962
- updateDataModel: {
12963
- surfaceId: id,
12964
- path: "/",
12965
- value: dataModel
12966
- }
12967
- });
12968
- if (Array.isArray(components) && components.length > 0) out.push({
12969
- version,
12970
- updateComponents: {
12971
- surfaceId: id,
12972
- components
12973
- }
12974
- });
12975
- continue;
12976
- }
12977
- hasCreate = true;
12978
- if (!catalogIds.includes(inner.catalogId)) inner.catalogId = catalogId;
12979
- }
12980
- out.push({
12981
- version,
12982
- [key]: inner
12983
- });
12984
- }
12985
- if (!hasCreate && out.length > 0) out.unshift({
12986
- version: _copilotkit_shared.A2UI_VERSION,
12987
- createSurface: {
12988
- surfaceId,
12989
- catalogId
12990
- }
12991
- });
12992
- return {
12993
- surfaceId,
12994
- operations: out,
12995
- functionCalls
12996
- };
12997
- }
12998
- /**
12999
- * Components a user operates. A Card containing one of these is an
13000
- * interactive panel and keeps its box; every other Card is informational.
13001
- */
13002
- const INTERACTIVE_COMPONENTS = new Set([
13003
- "Button",
13004
- "Pressable",
13005
- "Form",
13006
- "TextField",
13007
- "TextArea",
13008
- "Select",
13009
- "CheckBox",
13010
- "Radio",
13011
- "RadioGroup",
13012
- "Slider",
13013
- "SegmentedControl",
13014
- "ChoicePicker",
13015
- "DateTimeInput"
13016
- ]);
13017
- /** A component id referenced by a `child`/`children` entry or a table cell. */
13018
- function referencedId(value) {
13019
- if (typeof value === "string") return value;
13020
- if (isRecord$2(value)) {
13021
- if (typeof value.componentId === "string") return value.componentId;
13022
- if (typeof value.id === "string") return value.id;
13023
- }
13024
- }
13025
- /** Ids of a table cell / column that renders a component (`{componentId}` or `{id}`). */
13026
- function cellComponentId(value) {
13027
- return isRecord$2(value) ? referencedId(value) : void 0;
13028
- }
13029
- /**
13030
- * Ids a component renders directly: `child`, `children` (string ids, an
13031
- * array, or a `{componentId}` template), component cells of a Table's
13032
- * `rows`/`columns`, and the ids that `extra` finds in its typed references.
13033
- */
13034
- function directChildIds(component, extra) {
13035
- const ids = [];
13036
- const add = (id) => {
13037
- if (id) ids.push(id);
13038
- };
13039
- const extraIds = extra?.(component);
13040
- if (Array.isArray(extraIds)) extraIds.forEach(add);
13041
- add(referencedId(component.child));
13042
- const children = component.children;
13043
- if (Array.isArray(children)) children.forEach((c) => add(referencedId(c)));
13044
- else add(referencedId(children));
13045
- if (Array.isArray(component.columns)) component.columns.forEach((c) => add(cellComponentId(c)));
13046
- if (Array.isArray(component.rows)) {
13047
- for (const row of component.rows) if (Array.isArray(row)) row.forEach((c) => add(cellComponentId(c)));
13048
- }
13049
- return ids;
13050
- }
13051
- /** Components of every updateComponents operation, by id (last definition wins). */
13052
- function componentsById(operations) {
13053
- const byId = /* @__PURE__ */ new Map();
13054
- for (const op of operations) {
13055
- const update = op.updateComponents;
13056
- const list = isRecord$2(update) ? update.components : void 0;
13057
- if (!Array.isArray(list)) continue;
13058
- for (const c of list) if (isRecord$2(c) && typeof c.id === "string") byId.set(c.id, c);
13059
- }
13060
- return byId;
13061
- }
13062
- function descendantIds(rootId, byId, extra) {
13063
- const seen = /* @__PURE__ */ new Set();
13064
- const stack = [...directChildIds(byId.get(rootId) ?? {}, extra)];
13065
- while (stack.length > 0) {
13066
- const id = stack.pop();
13067
- if (seen.has(id) || id === rootId) continue;
13068
- seen.add(id);
13069
- const c = byId.get(id);
13070
- if (c) stack.push(...directChildIds(c, extra));
13071
- }
13072
- return seen;
13073
- }
13074
- /**
13075
- * Ids of the `Card` components that are interactive panels: at least one
13076
- * descendant (via `child`, `children` or table component cells) is a control
13077
- * (Button, Pressable, Form, TextField, TextArea, Select, CheckBox, Radio,
13078
- * RadioGroup, Slider, SegmentedControl, DateTimeInput).
13079
- *
13080
- * @param components - The components of one surface.
13081
- * @returns The ids of the interactive cards.
13082
- *
13083
- * @example
13084
- * ```ts
13085
- * const interactive = classifySurfaceCards(components);
13086
- * const keepsBox = interactive.has("quote-form");
13087
- * ```
13088
- */
13089
- function classifySurfaceCards(components, options = {}) {
13090
- const byId = /* @__PURE__ */ new Map();
13091
- for (const c of components) if (isRecord$2(c) && typeof c.id === "string") byId.set(c.id, c);
13092
- const interactive = /* @__PURE__ */ new Set();
13093
- for (const [id, c] of byId) {
13094
- if (c.component !== "Card") continue;
13095
- for (const d of descendantIds(id, byId, options.childIds)) {
13096
- const type = byId.get(d)?.component;
13097
- if (typeof type === "string" && INTERACTIVE_COMPONENTS.has(type)) {
13098
- interactive.add(id);
13099
- break;
13100
- }
13101
- }
13102
- }
13103
- return interactive;
13104
- }
13105
- /**
13106
- * Markdown mode: only interactive panels keep a box. Every `Card` that is not
13107
- * an interactive panel (see `classifySurfaceCards`), sets no `variant` or
13108
- * `border` of its own and is not nested inside an interactive panel becomes
13109
- * `variant: "section"` (a heading plus content without a box). Operations
13110
- * other than updateComponents pass through unchanged.
13111
- *
13112
- * @param operations - The operations of one surface.
13113
- * @returns The operations with informational cards set to `variant: "section"`.
13114
- * When no card changes, it returns the same array.
13115
- *
13116
- * @example
13117
- * ```ts
13118
- * const operations = flattenInformationalCards(prepared.operations);
13119
- * ```
13120
- */
13121
- function flattenInformationalCards(operations, options = {}) {
13122
- const byId = componentsById(operations);
13123
- if (![...byId.values()].some((c) => c.component === "Card")) return operations;
13124
- const interactive = classifySurfaceCards([...byId.values()], options);
13125
- const insideInteractive = /* @__PURE__ */ new Set();
13126
- for (const id of interactive) for (const d of descendantIds(id, byId, options.childIds)) insideInteractive.add(d);
13127
- const flatten = (c) => c.component === "Card" && typeof c.id === "string" && !interactive.has(c.id) && !insideInteractive.has(c.id) && c.variant == null && c.border == null;
13128
- return operations.map((op) => {
13129
- const update = op.updateComponents;
13130
- if (!isRecord$2(update) || !Array.isArray(update.components)) return op;
13131
- if (!update.components.some((c) => isRecord$2(c) && flatten(c))) return op;
13132
- return {
13133
- ...op,
13134
- updateComponents: {
13135
- ...update,
13136
- components: update.components.map((c) => isRecord$2(c) && flatten(c) ? {
13137
- ...c,
13138
- variant: "section"
13139
- } : c)
13140
- }
13141
- };
13142
- });
13143
- }
13144
- /** Text-bearing components that belong in the chat's markdown, not a surface. */
13145
- const PROSE_TEXT_COMPONENTS = new Set([
13146
- "Title",
13147
- "Text",
13148
- "Caption",
13149
- "Markdown"
13150
- ]);
13151
- /** One line of text: list items and headings cannot span lines in markdown. */
13152
- function oneLine(text) {
13153
- return text.trim().replace(/\s*\n\s*/g, " ");
13154
- }
13155
- /**
13156
- * A literal List entry as list-item markdown: a non-empty string, or
13157
- * `{ label, description? }` with literal strings only. Anything carrying
13158
- * behaviour or decoration (`icon`, `action`, other keys, bound values) is null.
13159
- */
13160
- function listEntryMarkdown(entry) {
13161
- if (typeof entry === "string") return entry.trim() ? oneLine(entry) : null;
13162
- if (!isRecord$2(entry)) return null;
13163
- for (const key of Object.keys(entry)) if (key !== "label" && key !== "description") return null;
13164
- if (typeof entry.label !== "string" || !entry.label.trim()) return null;
13165
- const label = oneLine(entry.label);
13166
- if (entry.description === void 0) return label;
13167
- if (typeof entry.description !== "string") return null;
13168
- return entry.description.trim() ? `**${label}** — ${oneLine(entry.description)}` : label;
13169
- }
13170
- /**
13171
- * A List of literal text items as a markdown list (`marker: "number"` →
13172
- * `1. …`, otherwise `- …`), or null when it binds its items, renders
13173
- * `children`, or any item is not plain text.
13174
- */
13175
- function listToMarkdown(c) {
13176
- const children = c.children;
13177
- if (children != null && !(Array.isArray(children) && children.length === 0)) return null;
13178
- if (!Array.isArray(c.items) || c.items.length === 0) return null;
13179
- const lines = [];
13180
- for (const entry of c.items) {
13181
- const line = listEntryMarkdown(entry);
13182
- if (line === null) return null;
13183
- lines.push(line);
13184
- }
13185
- if (c.marker === "number") {
13186
- const start = typeof c.start === "number" && Number.isInteger(c.start) ? c.start : 1;
13187
- return lines.map((line, i) => `${start + i}. ${line}`).join("\n");
13188
- }
13189
- return lines.map((line) => `- ${line}`).join("\n");
13190
- }
13191
- /** The prose item a component converts to, or null when it is not prose. */
13192
- function toProseItem(c) {
13193
- if (!c) return null;
13194
- if (c.accessibility !== void 0) return null;
13195
- if (c.component === "Divider") return { kind: "divider" };
13196
- if (c.component === "Spacer") return { kind: "spacer" };
13197
- if (c.component === "List") {
13198
- if (c.direction !== void 0 && c.direction !== "vertical") return null;
13199
- const markdown = listToMarkdown(c);
13200
- return markdown === null ? null : {
13201
- kind: "text",
13202
- markdown
13203
- };
13204
- }
13205
- if (typeof c.component !== "string") return null;
13206
- if (!PROSE_TEXT_COMPONENTS.has(c.component)) return null;
13207
- if (typeof c.text !== "string" || c.text.trim() === "") return null;
13208
- const text = c.text.trim();
13209
- switch (c.component) {
13210
- case "Title": {
13211
- const size = typeof c.size === "string" ? c.size : "md";
13212
- return {
13213
- kind: "text",
13214
- markdown: `${size === "sm" ? "####" : size === "md" || size === "lg" ? "###" : "##"} ${text}`
13215
- };
13216
- }
13217
- case "Text":
13218
- if (directChildIds(c).length > 0) return null;
13219
- return {
13220
- kind: "text",
13221
- markdown: c.strong === true ? `**${text}**` : text
13222
- };
13223
- default: return {
13224
- kind: "text",
13225
- markdown: text
13226
- };
13227
- }
13228
- }
13229
- /** Prose items as markdown: separators only survive between two text items. */
13230
- function proseItemsToMarkdown(items) {
13231
- const blocks = [];
13232
- let pendingDivider = false;
13233
- for (const item of items) if (item?.kind === "text") {
13234
- if (pendingDivider && blocks.length > 0) blocks.push("---");
13235
- pendingDivider = false;
13236
- blocks.push(item.markdown);
13237
- } else if (item?.kind === "divider") pendingDivider = true;
13238
- return blocks.join("\n\n");
13239
- }
13240
- /** Column, column-direction Box, or an informational Card (section/unset variant). */
13241
- function isVerticalStack(c, interactiveCards) {
13242
- if (c.accessibility !== void 0) return false;
13243
- if (c.component === "Column") return true;
13244
- if (c.component === "Box") return c.direction == null || c.direction === "col";
13245
- if (c.component === "Card") return (c.variant == null || c.variant === "section") && typeof c.id === "string" && !interactiveCards.has(c.id);
13246
- return false;
13247
- }
13248
- /** The child-id list of a stack (`children`, or a lone `child`), else null. */
13249
- /**
13250
- * The children of a stack in render order: `child` first (a Card renders
13251
- * its `child` before its `children`), then `children`.
13252
- */
13253
- function stackChildren(c) {
13254
- const first = typeof c.child === "string" ? [c.child] : [];
13255
- if (Array.isArray(c.children)) return [...first, ...c.children];
13256
- if (first.length > 0 && c.children === void 0) return first;
13257
- return null;
13258
- }
13259
- /**
13260
- * Partitions the stack's children into alternating prose and surface runs.
13261
- * A run of consecutive prose items is prose only when it holds text: a run of
13262
- * separators alone (Divider/Spacer between two UI components, or at the very
13263
- * start/end of the stack) stays with the surface it sits in.
13264
- */
13265
- function partitionChildren(items) {
13266
- const runs = [];
13267
- let i = 0;
13268
- while (i < items.length) {
13269
- const candidate = items[i] !== null;
13270
- let hasText = false;
13271
- let j = i;
13272
- while (j < items.length && items[j] !== null === candidate) {
13273
- if (items[j]?.kind === "text") hasText = true;
13274
- j++;
13275
- }
13276
- const prose = candidate && hasText;
13277
- const last = runs[runs.length - 1];
13278
- if (!prose && last && !last.prose) last.end = j;
13279
- else runs.push({
13280
- prose,
13281
- start: i,
13282
- end: j
13283
- });
13284
- i = j;
13285
- }
13286
- return runs;
13287
- }
13288
- /**
13289
- * Markdown mode: split a surface into markdown and surface segments so that
13290
- * only real UI renders as A2UI and everything else is the chat's markdown.
13291
- *
13292
- * From `root`, descend through single-child vertical containers (Column,
13293
- * column Box, informational Card) to the first one with several children:
13294
- * the stack. Its children are partitioned, in order, into runs of prose and
13295
- * runs of UI. Prose is `Title`, `Text`, `Caption`, `Markdown` with literal
13296
- * text, a `List` of literal text items, plus `Divider`/`Spacer` next to them:
13297
- * `Title` → heading by size (sm `####`, md/lg `###`, larger `##`), `Text` →
13298
- * paragraph (`strong` → `**…**`), `Caption`/`Markdown` → paragraph, `List` →
13299
- * `- …` (or `1. …` for `marker: "number"`, `**label** — description` for
13300
- * described items), and a `Divider` between two prose blocks → `---`.
13301
- *
13302
- * Not prose: `{path}`-bound text or items, a Text with inline children, a
13303
- * List with `children`/icons/actions, a template entry, a component with an
13304
- * `accessibility` envelope, and a child whose component has not streamed
13305
- * yet. Separators with no text beside them stay in
13306
- * the surface. An interactive Card (see `classifySurfaceCards`) is never
13307
- * entered.
13308
- *
13309
- * Each prose run becomes a markdown segment; each UI run becomes a surface
13310
- * segment whose `root` is a copy of the stack (its other props kept, `child`
13311
- * dropped) with only that run's `children`, followed by every component
13312
- * reachable from them. When nothing is prose the input comes back as the one
13313
- * surface segment (same array); when everything is (or `root` itself is),
13314
- * there are only markdown segments.
13315
- *
13316
- * Pure and linear in the number of components, so it runs on every stream
13317
- * update.
13318
- *
13319
- * @param components - The components of one surface, root included.
13320
- * @returns The segments in render order.
13321
- *
13322
- * @example
13323
- * ```ts
13324
- * for (const segment of segmentSurfaceProse(components)) {
13325
- * if (segment.kind === "markdown") renderMarkdown(segment.markdown);
13326
- * else renderSurface(segment.components);
13327
- * }
13328
- * ```
13329
- */
13330
- function segmentSurfaceProse(components, options = {}) {
13331
- const unchanged = [{
13332
- kind: "surface",
13333
- components
13334
- }];
13335
- const byId = /* @__PURE__ */ new Map();
13336
- for (const c of components) if (isRecord$2(c) && typeof c.id === "string") byId.set(c.id, c);
13337
- const root = byId.get(_copilotkit_shared.GENERATIVE_UI_ROOT_ID);
13338
- if (!root) return unchanged;
13339
- if (components.some((c) => isRecord$2(c) && options.childIds?.(c) === "unknown")) return unchanged;
13340
- const rootItem = toProseItem(root);
13341
- if (rootItem?.kind === "text") return [{
13342
- kind: "markdown",
13343
- markdown: rootItem.markdown
13344
- }];
13345
- const interactiveCards = classifySurfaceCards(components, options);
13346
- let stack = root;
13347
- let stackId = _copilotkit_shared.GENERATIVE_UI_ROOT_ID;
13348
- let children;
13349
- const visited = /* @__PURE__ */ new Set();
13350
- while (true) {
13351
- if (!isVerticalStack(stack, interactiveCards)) return unchanged;
13352
- visited.add(stackId);
13353
- const list = stackChildren(stack);
13354
- if (!list) return unchanged;
13355
- children = list;
13356
- const nextId = list.length === 1 ? list[0] : void 0;
13357
- if (typeof nextId !== "string") break;
13358
- const next = byId.get(nextId);
13359
- if (!next || visited.has(nextId) || toProseItem(next)) break;
13360
- stack = next;
13361
- stackId = nextId;
13362
- }
13363
- const stackChildIds = children;
13364
- const items = stackChildIds.map((id) => typeof id === "string" ? toProseItem(byId.get(id)) : null);
13365
- const runs = partitionChildren(items);
13366
- if (!runs.some((run) => run.prose)) return unchanged;
13367
- const surfaceRuns = runs.filter((run) => !run.prose);
13368
- const owners = /* @__PURE__ */ new Map();
13369
- surfaceRuns.forEach((run, index) => {
13370
- const pending = stackChildIds.slice(run.start, run.end).map(referencedId).filter((id) => id !== void 0);
13371
- const seen = /* @__PURE__ */ new Set();
13372
- while (pending.length > 0) {
13373
- const id = pending.pop();
13374
- if (id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID || id === stackId || seen.has(id)) continue;
13375
- seen.add(id);
13376
- const list = owners.get(id);
13377
- if (list) list.push(index);
13378
- else owners.set(id, [index]);
13379
- const c = byId.get(id);
13380
- if (c) pending.push(...directChildIds(c, options.childIds));
13381
- }
13382
- });
13383
- const surfaceComponents = surfaceRuns.map((run) => {
13384
- const { child: _child, ...stackRest } = stack;
13385
- const nextRoot = {
13386
- ...stackRest,
13387
- id: _copilotkit_shared.GENERATIVE_UI_ROOT_ID,
13388
- children: stackChildIds.slice(run.start, run.end)
13389
- };
13390
- delete nextRoot.child;
13391
- return [nextRoot];
13392
- });
13393
- for (const c of components) {
13394
- if (!isRecord$2(c) || typeof c.id !== "string" || byId.get(c.id) !== c) continue;
13395
- const ownerIndexes = owners.get(c.id) ?? [];
13396
- for (const index of ownerIndexes) surfaceComponents[index].push(c);
13397
- }
13398
- let surfaceIndex = 0;
13399
- return runs.map((run) => {
13400
- if (run.prose) return {
13401
- kind: "markdown",
13402
- markdown: proseItemsToMarkdown(items.slice(run.start, run.end))
13403
- };
13404
- return {
13405
- kind: "surface",
13406
- components: surfaceComponents[surfaceIndex++]
13407
- };
13408
- });
13409
- }
13410
-
13411
12075
  //#endregion
13412
12076
  //#region src/a2ui/constants.ts
13413
12077
  /**
@@ -20496,7 +19160,7 @@ function cn(...inputs) {
20496
19160
  }
20497
19161
 
20498
19162
  //#endregion
20499
- exports.A2UI_FENCE_LANGUAGE = A2UI_FENCE_LANGUAGE;
19163
+ exports.A2UI_FENCE_LANGUAGE = require_a2ui_markdown.A2UI_FENCE_LANGUAGE;
20500
19164
  exports.AgentRegistry = AgentRegistry;
20501
19165
  exports.AgentThreadLockedError = AgentThreadLockedError;
20502
19166
  exports.ContextStore = ContextStore;
@@ -20521,7 +19185,7 @@ exports.ToolCallStatus = ToolCallStatus;
20521
19185
  exports.TranscriptionError = TranscriptionError;
20522
19186
  exports.TranscriptionErrorCode = _copilotkit_shared.TranscriptionErrorCode;
20523
19187
  exports.WebMCPRegistry = WebMCPRegistry;
20524
- exports.classifySurfaceCards = classifySurfaceCards;
19188
+ exports.classifySurfaceCards = require_a2ui_markdown.classifySurfaceCards;
20525
19189
  exports.completePartialMarkdown = completePartialMarkdown;
20526
19190
  exports.createActionGroup = createActionGroup;
20527
19191
  exports.createEffect = createEffect;
@@ -20535,11 +19199,11 @@ exports.emitInspectorViewThread = emitInspectorViewThread;
20535
19199
  exports.emitInspectorViewThreadResult = emitInspectorViewThreadResult;
20536
19200
  exports.empty = empty;
20537
19201
  exports.ensureObjectArgs = ensureObjectArgs;
20538
- exports.extractCompleteArrayItems = extractCompleteArrayItems;
20539
- exports.extractFenceOperations = extractFenceOperations;
20540
- exports.extractStringField = extractStringField;
20541
- exports.flattenInformationalCards = flattenInformationalCards;
20542
- exports.getMarkdownOperationSurfaceId = getMarkdownOperationSurfaceId;
19202
+ exports.extractCompleteArrayItems = require_a2ui_markdown.extractCompleteArrayItems;
19203
+ exports.extractFenceOperations = require_a2ui_markdown.extractFenceOperations;
19204
+ exports.extractStringField = require_a2ui_markdown.extractStringField;
19205
+ exports.flattenInformationalCards = require_a2ui_markdown.flattenInformationalCards;
19206
+ exports.getMarkdownOperationSurfaceId = require_a2ui_markdown.getMarkdownOperationSurfaceId;
20543
19207
  exports.getWebMCPModelContext = getWebMCPModelContext;
20544
19208
  exports.isAbortError = isAbortError;
20545
19209
  exports.isInspectorThreadBridgeEnabled = isInspectorThreadBridgeEnabled;
@@ -20551,11 +19215,11 @@ exports.onInspectorStopViewing = onInspectorStopViewing;
20551
19215
  exports.onInspectorViewThread = onInspectorViewThread;
20552
19216
  exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
20553
19217
  exports.parseToolArguments = parseToolArguments;
20554
- exports.prepareSurfaceOperations = prepareSurfaceOperations;
19218
+ exports.prepareSurfaceOperations = require_a2ui_markdown.prepareSurfaceOperations;
20555
19219
  exports.props = props;
20556
- exports.segmentSurfaceProse = segmentSurfaceProse;
19220
+ exports.segmentSurfaceProse = require_a2ui_markdown.segmentSurfaceProse;
20557
19221
  exports.select = select;
20558
- exports.splitA2UIMarkdown = splitA2UIMarkdown;
19222
+ exports.splitA2UIMarkdown = require_a2ui_markdown.splitA2UIMarkdown;
20559
19223
  exports.ɵA2UIActivityController = A2UIActivityController;
20560
19224
  exports.ɵA2UI_DEFAULT_SURFACE_ID = A2UI_DEFAULT_SURFACE_ID;
20561
19225
  exports.ɵA2UI_LIFECYCLE_TEXT = A2UI_LIFECYCLE_TEXT;