@copilotkit/core 2.0.0-rc.4 → 2.0.0-rc.40

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 (47) 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 +269 -0
  6. package/dist/chat-configuration.cjs.map +1 -0
  7. package/dist/chat-configuration.d.cts +123 -0
  8. package/dist/chat-configuration.d.cts.map +1 -0
  9. package/dist/chat-configuration.d.mts +123 -0
  10. package/dist/chat-configuration.d.mts.map +1 -0
  11. package/dist/chat-configuration.mjs +268 -0
  12. package/dist/chat-configuration.mjs.map +1 -0
  13. package/dist/generative-ui/index.cjs +3474 -0
  14. package/dist/generative-ui/index.cjs.map +1 -0
  15. package/dist/generative-ui/index.d.cts +1041 -0
  16. package/dist/generative-ui/index.d.cts.map +1 -0
  17. package/dist/generative-ui/index.d.mts +1041 -0
  18. package/dist/generative-ui/index.d.mts.map +1 -0
  19. package/dist/generative-ui/index.mjs +3425 -0
  20. package/dist/generative-ui/index.mjs.map +1 -0
  21. package/dist/index.cjs +10892 -2231
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +3 -3908
  24. package/dist/index.d.mts +3 -3908
  25. package/dist/index.mjs +10613 -2222
  26. package/dist/index.mjs.map +1 -1
  27. package/dist/index.umd.js +14459 -2201
  28. package/dist/index.umd.js.map +1 -1
  29. package/dist/learning-bridge-Cqc7VJuV.d.cts +10919 -0
  30. package/dist/learning-bridge-Cqc7VJuV.d.cts.map +1 -0
  31. package/dist/learning-bridge-y2bnVsjp.d.mts +10919 -0
  32. package/dist/learning-bridge-y2bnVsjp.d.mts.map +1 -0
  33. package/dist/styles.cjs +1 -1
  34. package/dist/styles.cjs.map +1 -1
  35. package/dist/styles.css +1 -1
  36. package/dist/styles.mjs +1 -1
  37. package/dist/styles.mjs.map +1 -1
  38. package/dist/viewport-CksL5y8p.mjs +954 -0
  39. package/dist/viewport-CksL5y8p.mjs.map +1 -0
  40. package/dist/viewport-D-tuKCeb.cjs +1182 -0
  41. package/dist/viewport-D-tuKCeb.cjs.map +1 -0
  42. package/package.json +36 -8
  43. package/stryker.config.mjs +6 -0
  44. package/tsdown.config.ts +16 -2
  45. package/vitest.mutation.config.mjs +6 -0
  46. package/dist/index.d.cts.map +0 -1
  47. package/dist/index.d.mts.map +0 -1
@@ -0,0 +1,1419 @@
1
+ let _copilotkit_shared = require("@copilotkit/shared");
2
+ let jsonrepair = require("jsonrepair");
3
+
4
+ //#region src/a2ui-markdown/fence-parser.ts
5
+ /** Language of a fenced code block that carries A2UI operations. */
6
+ const A2UI_FENCE_LANGUAGE = "a2ui";
7
+ /** Column-0 fence opener: a run of 3+ backticks or tildes, then the info string. */
8
+ const FENCE_OPEN = /^(`{3,}|~{3,})(.*)$/;
9
+ /** Info-string token that names the placement target of an a2ui fence. */
10
+ const TARGET_TOKEN = /^target=(.+)$/;
11
+ function isCloser(line, fence) {
12
+ const trimmed = line.trim();
13
+ if (trimmed.length < fence.length) return false;
14
+ for (const ch of trimmed) if (ch !== fence.char) return false;
15
+ return true;
16
+ }
17
+ /** The id of the first `target=<id>` token. Other tokens are ignored. */
18
+ function readTarget(tokens) {
19
+ for (const token of tokens) {
20
+ const match = TARGET_TOKEN.exec(token);
21
+ if (match) return match[1];
22
+ }
23
+ }
24
+ function a2uiSegment(fence, text, closed) {
25
+ const segment = {
26
+ type: "a2ui",
27
+ index: fence.index,
28
+ text,
29
+ closed
30
+ };
31
+ if (fence.target !== void 0) segment.target = fence.target;
32
+ return segment;
33
+ }
34
+ /**
35
+ * Split a (possibly still streaming) markdown string into prose segments and
36
+ * top-level ```a2ui fences. Fences of other languages stay inside prose
37
+ * segments byte-for-byte, and a2ui markers inside them are ignored. Only
38
+ * column-0 fences are recognised, so a fence indented inside a list item is
39
+ * left to the markdown renderer.
40
+ *
41
+ * The first info-string token must be exactly `a2ui`. A later
42
+ * `target=<id>` token sets `target` on the segment (for example
43
+ * ```` ```a2ui target=recommendations ````). Other tokens are ignored.
44
+ *
45
+ * An a2ui segment's `text` is the fence body. For a closed fence it ends with
46
+ * "\n" when non-empty. For an open (still streaming or aborted) fence it is
47
+ * everything after the opener line, minus a half-streamed closing marker.
48
+ *
49
+ * @param markdown - The assistant message text, complete or still streaming.
50
+ * @returns The segments in source order.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * for (const segment of splitA2UIMarkdown(message.content)) {
55
+ * if (segment.type === "a2ui") renderSurface(segment.text, segment.target);
56
+ * else renderMarkdown(segment.text);
57
+ * }
58
+ * ```
59
+ */
60
+ function splitA2UIMarkdown(markdown) {
61
+ const segments = [];
62
+ let proseStart = 0;
63
+ let fence = null;
64
+ let a2uiIndex = 0;
65
+ const pushProse = (end) => {
66
+ if (end > proseStart) segments.push({
67
+ type: "markdown",
68
+ text: markdown.slice(proseStart, end)
69
+ });
70
+ };
71
+ let lineStart = 0;
72
+ while (lineStart <= markdown.length) {
73
+ const newline = markdown.indexOf("\n", lineStart);
74
+ const lineEnd = newline < 0 ? markdown.length : newline;
75
+ const hasCR = lineEnd > lineStart && markdown[lineEnd - 1] === "\r";
76
+ const line = markdown.slice(lineStart, hasCR ? lineEnd - 1 : lineEnd);
77
+ if (fence) {
78
+ if (isCloser(line, fence)) {
79
+ if (fence.index >= 0) {
80
+ const body = markdown.slice(fence.bodyStart, Math.max(fence.bodyStart, lineStart));
81
+ segments.push(a2uiSegment(fence, body, true));
82
+ proseStart = hasCR ? lineEnd - 1 : lineEnd;
83
+ }
84
+ fence = null;
85
+ }
86
+ } else {
87
+ const open = FENCE_OPEN.exec(line);
88
+ if (open) {
89
+ const marker = open[1] ?? "";
90
+ const info = open[2] ?? "";
91
+ const char = marker.charAt(0);
92
+ if (!(char === "`" && info.includes("`"))) {
93
+ const [lang = "", ...tokens] = info.trim().split(/\s+/);
94
+ const isA2UI = lang === A2UI_FENCE_LANGUAGE;
95
+ if (isA2UI) pushProse(lineStart);
96
+ fence = {
97
+ char,
98
+ length: marker.length,
99
+ bodyStart: newline < 0 ? markdown.length : lineEnd + 1,
100
+ index: isA2UI ? a2uiIndex++ : -1,
101
+ target: isA2UI ? readTarget(tokens) : void 0
102
+ };
103
+ }
104
+ }
105
+ }
106
+ if (newline < 0) break;
107
+ lineStart = newline + 1;
108
+ }
109
+ if (fence && fence.index >= 0) {
110
+ const { char } = fence;
111
+ let body = markdown.slice(fence.bodyStart);
112
+ const lastNewline = body.lastIndexOf("\n");
113
+ const lastLine = body.slice(lastNewline + 1).replace(/\r$/, "");
114
+ if (lastLine.length > 0 && [...lastLine].every((ch) => ch === char)) body = body.slice(0, lastNewline + 1);
115
+ segments.push(a2uiSegment(fence, body, false));
116
+ } else pushProse(markdown.length);
117
+ return segments;
118
+ }
119
+
120
+ //#endregion
121
+ //#region src/a2ui-markdown/operations.ts
122
+ /** The operation keys that change a surface. */
123
+ const SURFACE_OP_KEYS = [
124
+ "createSurface",
125
+ "updateComponents",
126
+ "updateDataModel",
127
+ "deleteSurface"
128
+ ];
129
+ /** The operation key of an agent-called function. It has no surface. */
130
+ const FUNCTION_CALL_KEY = "callRendererFunction";
131
+ const OP_KEYS = [...SURFACE_OP_KEYS, FUNCTION_CALL_KEY];
132
+ function isRecord(value) {
133
+ return typeof value === "object" && value !== null && !Array.isArray(value);
134
+ }
135
+ function isWhitespace(ch) {
136
+ return ch === " " || ch === "\n" || ch === "\r" || ch === " ";
137
+ }
138
+ function skipWhitespace(s, i) {
139
+ while (i < s.length && isWhitespace(s[i])) i++;
140
+ return i;
141
+ }
142
+ /** Index of the closing quote of the JSON string opening at `start`, or -1. */
143
+ function findStringEnd(s, start) {
144
+ for (let i = start + 1; i < s.length; i++) {
145
+ if (s[i] === "\\") {
146
+ i++;
147
+ continue;
148
+ }
149
+ if (s[i] === "\"") return i;
150
+ }
151
+ return -1;
152
+ }
153
+ /**
154
+ * Find the first `"key":` whose value starts with `opener` and return the index
155
+ * of that opener, or -1.
156
+ */
157
+ function findKeyValue(s, key, opener) {
158
+ const needle = `"${key}"`;
159
+ let from = 0;
160
+ while (true) {
161
+ const k = s.indexOf(needle, from);
162
+ if (k < 0) return -1;
163
+ let i = skipWhitespace(s, k + needle.length);
164
+ if (s[i] === ":") {
165
+ i = skipWhitespace(s, i + 1);
166
+ if (s[i] === opener) return i;
167
+ }
168
+ from = k + 1;
169
+ }
170
+ }
171
+ /**
172
+ * Read `"key":"value"` from partial JSON. The first match anywhere in the
173
+ * text wins, at any depth.
174
+ *
175
+ * @param partialJson - JSON text that can still be streaming.
176
+ * @param key - The field name.
177
+ * @returns The string value, or null until its closing quote has arrived.
178
+ *
179
+ * @example
180
+ * ```ts
181
+ * extractStringField('{"createSurface":{"surfaceId":"plan","cat', "surfaceId"); // "plan"
182
+ * ```
183
+ */
184
+ function extractStringField(partialJson, key) {
185
+ const start = findKeyValue(partialJson, key, "\"");
186
+ if (start < 0) return null;
187
+ const end = findStringEnd(partialJson, start);
188
+ if (end < 0) return null;
189
+ try {
190
+ const value = JSON.parse(partialJson.slice(start, end + 1));
191
+ return typeof value === "string" ? value : null;
192
+ } catch {
193
+ return null;
194
+ }
195
+ }
196
+ function pushItem(raw, items) {
197
+ const trimmed = raw.trim();
198
+ if (!trimmed) return;
199
+ try {
200
+ items.push(JSON.parse(trimmed));
201
+ } catch {}
202
+ }
203
+ /**
204
+ * Find `"key":[` in partial JSON and return every complete item of that array
205
+ * so far, plus whether the array has closed. Items of a `components` array get
206
+ * structural-key depth repair: a component that lost closing braces is fixed
207
+ * when its `id`, `component`, `child` or `children` key shows where it ends.
208
+ *
209
+ * @param partialJson - JSON text that can still be streaming.
210
+ * @param key - The name of the array field.
211
+ * @returns `{ items, closed }`, or null when the key (with an array value)
212
+ * has not appeared yet.
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * const result = extractCompleteArrayItems(streamedText, "components");
217
+ * if (result) render(result.items);
218
+ * ```
219
+ */
220
+ function extractCompleteArrayItems(partialJson, key) {
221
+ const open = findKeyValue(partialJson, key, "[");
222
+ if (open < 0) return null;
223
+ return completeArrayItemsAt(partialJson, open, { repairComponents: key === "components" });
224
+ }
225
+ /** Index of the last non-whitespace character before `i`, or -1. */
226
+ function prevNonWhitespace(s, i) {
227
+ let j = i - 1;
228
+ while (j >= 0 && isWhitespace(s[j])) j--;
229
+ return j;
230
+ }
231
+ /**
232
+ * Keys that only ever belong at a component's top level. Seen nested inside
233
+ * the component's objects, they mean the model forgot closing braces.
234
+ */
235
+ const STRUCTURAL_KEYS = new Set([
236
+ "id",
237
+ "component",
238
+ "child",
239
+ "children"
240
+ ]);
241
+ /** Whether a value starting with `ch` has the shape `key` takes on a component. */
242
+ function structuralValueFits(key, ch) {
243
+ if (key === "children") return ch === "[" || ch === "{";
244
+ return ch === "\"";
245
+ }
246
+ /** `{"id":` — a new component object starting at `i`. */
247
+ const COMPONENT_START = /^\{\s*"id"\s*:/;
248
+ /**
249
+ * Structural-key depth repair for one component item. While scanning, a
250
+ * structural key (`id`, `component`, `child`, `children`) found as an object
251
+ * key below the item's top level, with only objects (no arrays) between it
252
+ * and the item root, a value of the expected shape, and not already present
253
+ * at the top level, means closing braces were dropped: the missing `}` are
254
+ * synthesized right before it so it lands at the top level. Containers still
255
+ * open at the end are closed. Returns null when a string never terminates.
256
+ */
257
+ function repairComponentItem(item) {
258
+ const stack = [];
259
+ const topKeys = /* @__PURE__ */ new Set();
260
+ let out = "";
261
+ let copied = 0;
262
+ for (let i = 0; i < item.length; i++) {
263
+ const c = item[i];
264
+ if (c === "\"") {
265
+ const end = findStringEnd(item, i);
266
+ if (end < 0) return null;
267
+ const prev = prevNonWhitespace(item, i);
268
+ const prevCh = item[prev];
269
+ const colon = skipWhitespace(item, end + 1);
270
+ if (stack[stack.length - 1] === "{" && (prevCh === "," || prevCh === "{") && item[colon] === ":") {
271
+ let key;
272
+ try {
273
+ key = JSON.parse(item.slice(i, end + 1));
274
+ } catch {
275
+ return null;
276
+ }
277
+ if (typeof key === "string") {
278
+ if (stack.length === 1) topKeys.add(key);
279
+ else if (STRUCTURAL_KEYS.has(key) && !topKeys.has(key) && stack.every((x) => x === "{") && structuralValueFits(key, item[skipWhitespace(item, colon + 1)])) {
280
+ const closers = "}".repeat(stack.length - 1);
281
+ if (prevCh === ",") {
282
+ out += item.slice(copied, prev) + closers;
283
+ copied = prev;
284
+ } else {
285
+ out += item.slice(copied, i) + closers + ",";
286
+ copied = i;
287
+ }
288
+ stack.length = 1;
289
+ topKeys.add(key);
290
+ }
291
+ }
292
+ }
293
+ i = end;
294
+ continue;
295
+ }
296
+ if (c === "{" || c === "[") stack.push(c);
297
+ else if (c === "}" || c === "]") {
298
+ stack.pop();
299
+ if (stack.length === 0) return out + item.slice(copied, i + 1);
300
+ }
301
+ }
302
+ const closers = stack.reduceRight((text, opener) => text + (opener === "{" ? "}" : "]"), "");
303
+ return out + item.slice(copied) + closers;
304
+ }
305
+ function parseRecord(text) {
306
+ if (text === null) return void 0;
307
+ try {
308
+ const value = JSON.parse(text);
309
+ return isRecord(value) ? value : void 0;
310
+ } catch {
311
+ return;
312
+ }
313
+ }
314
+ /**
315
+ * Complete items of the (possibly unterminated) array whose "[" is at `open`.
316
+ * With `repairComponents`, an item that balanced but does not parse is retried
317
+ * with structural-key repair, and a `,{"id":` where an item expects a key
318
+ * ends that (unbalanced) item there, so one malformed component cannot
319
+ * swallow the rest of the array; the cut item is kept only if repair makes
320
+ * it parse.
321
+ */
322
+ function completeArrayItemsAt(partialJson, open, options) {
323
+ const { repairComponents } = options;
324
+ const s = partialJson;
325
+ const items = [];
326
+ const stack = [];
327
+ let inString = false;
328
+ let itemStart = -1;
329
+ const finishItem = (end, balanced) => {
330
+ const raw = s.slice(itemStart, end);
331
+ if (!repairComponents) {
332
+ pushItem(raw, items);
333
+ return;
334
+ }
335
+ if (balanced) try {
336
+ items.push(JSON.parse(raw));
337
+ return;
338
+ } catch {}
339
+ const repaired = parseRecord(repairComponentItem(raw.trim()));
340
+ if (repaired !== void 0) items.push(repaired);
341
+ };
342
+ for (let i = open + 1; i < s.length; i++) {
343
+ const c = s[i];
344
+ if (inString) {
345
+ if (c === "\\") i++;
346
+ else if (c === "\"") inString = false;
347
+ continue;
348
+ }
349
+ if (c === "\"") {
350
+ inString = true;
351
+ if (stack.length === 0 && itemStart < 0) itemStart = i;
352
+ continue;
353
+ }
354
+ if (c === "{" || c === "[") {
355
+ if (repairComponents && c === "{" && stack[stack.length - 1] === "{" && COMPONENT_START.test(s.slice(i, i + 24))) {
356
+ const prev = prevNonWhitespace(s, i);
357
+ if (s[prev] === ",") {
358
+ finishItem(prev, false);
359
+ stack.length = 0;
360
+ itemStart = i;
361
+ stack.push(c);
362
+ continue;
363
+ }
364
+ }
365
+ if (stack.length === 0) itemStart = i;
366
+ stack.push(c);
367
+ continue;
368
+ }
369
+ if (c === "}" || c === "]") {
370
+ if (stack.length === 0) {
371
+ if (c === "]") {
372
+ if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
373
+ return {
374
+ items,
375
+ closed: true
376
+ };
377
+ }
378
+ return {
379
+ items,
380
+ closed: false
381
+ };
382
+ }
383
+ stack.pop();
384
+ if (stack.length === 0) {
385
+ finishItem(i + 1, true);
386
+ itemStart = -1;
387
+ }
388
+ continue;
389
+ }
390
+ if (stack.length === 0) {
391
+ if (c === ",") {
392
+ if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);
393
+ itemStart = -1;
394
+ } else if (itemStart < 0 && !isWhitespace(c)) itemStart = i;
395
+ }
396
+ }
397
+ return {
398
+ items,
399
+ closed: false
400
+ };
401
+ }
402
+ /** The first operation key whose value is an object, with that value. */
403
+ function getOperationEntry(op) {
404
+ for (const key of OP_KEYS) {
405
+ const inner = op[key];
406
+ if (isRecord(inner)) return {
407
+ key,
408
+ inner
409
+ };
410
+ }
411
+ return null;
412
+ }
413
+ /**
414
+ * The surfaceId an operation targets: the one nested under its operation key,
415
+ * else a top-level `surfaceId`. A `callRendererFunction` operation targets no
416
+ * surface, so it gets undefined.
417
+ *
418
+ * It is named `getMarkdownOperationSurfaceId` because `@copilotkit/shared`
419
+ * already exports a strict `getOperationSurfaceId`. This one also reads a
420
+ * top-level `surfaceId`, which models sometimes write.
421
+ *
422
+ * @param op - An operation from an a2ui fence.
423
+ * @returns The surfaceId, or undefined when the operation names none or is a
424
+ * function call.
425
+ *
426
+ * @example
427
+ * ```ts
428
+ * getMarkdownOperationSurfaceId({ updateDataModel: { surfaceId: "plan" } }); // "plan"
429
+ * ```
430
+ */
431
+ function getMarkdownOperationSurfaceId(op) {
432
+ if (getOperationEntry(op)?.key === FUNCTION_CALL_KEY) return void 0;
433
+ for (const key of SURFACE_OP_KEYS) {
434
+ const inner = op[key];
435
+ if (isRecord(inner) && typeof inner.surfaceId === "string") return inner.surfaceId;
436
+ }
437
+ return typeof op.surfaceId === "string" ? op.surfaceId : void 0;
438
+ }
439
+ /**
440
+ * Index just past the JSON value starting at `start`, or -1 when the value is
441
+ * still incomplete. A primitive at the very end of the input counts as
442
+ * incomplete, since more digits or letters may still stream in.
443
+ */
444
+ function findValueEnd(s, start) {
445
+ const c = s[start];
446
+ if (c === "\"") {
447
+ const end = findStringEnd(s, start);
448
+ return end < 0 ? -1 : end + 1;
449
+ }
450
+ if (c === "{" || c === "[") {
451
+ let depth = 0;
452
+ for (let i = start; i < s.length; i++) {
453
+ const ch = s[i];
454
+ if (ch === "\"") {
455
+ const end = findStringEnd(s, i);
456
+ if (end < 0) return -1;
457
+ i = end;
458
+ } else if (ch === "{" || ch === "[") depth++;
459
+ else if (ch === "}" || ch === "]") {
460
+ depth--;
461
+ if (depth === 0) return i + 1;
462
+ }
463
+ }
464
+ return -1;
465
+ }
466
+ let i = start;
467
+ while (i < s.length && !isWhitespace(s[i]) && !",}]".includes(s[i])) i++;
468
+ return i >= s.length ? -1 : i;
469
+ }
470
+ /**
471
+ * Walk the direct entries of the (possibly unterminated) JSON object whose "{"
472
+ * is at `objStart`, calling `visit` with each key and the index where its value
473
+ * starts. Nested objects and arrays are skipped whole, so keys inside them are
474
+ * never visited. Stops when `visit` returns true, at the object's end, or where
475
+ * the input runs out.
476
+ */
477
+ function visitDirectEntries(s, objStart, visit) {
478
+ let i = objStart + 1;
479
+ while (i < s.length) {
480
+ i = skipWhitespace(s, i);
481
+ const c = s[i];
482
+ if (c === ",") {
483
+ i++;
484
+ continue;
485
+ }
486
+ if (c !== "\"") return;
487
+ const keyEnd = findStringEnd(s, i);
488
+ if (keyEnd < 0) return;
489
+ let key;
490
+ try {
491
+ key = JSON.parse(s.slice(i, keyEnd + 1));
492
+ } catch {
493
+ return;
494
+ }
495
+ i = skipWhitespace(s, keyEnd + 1);
496
+ if (s[i] !== ":") return;
497
+ i = skipWhitespace(s, i + 1);
498
+ if (i >= s.length) return;
499
+ if (typeof key === "string" && visit(key, i)) return;
500
+ const valueEnd = findValueEnd(s, i);
501
+ if (valueEnd < 0) return;
502
+ i = valueEnd;
503
+ }
504
+ }
505
+ /**
506
+ * Value start of a direct `key` of the object at `objStart` whose value begins
507
+ * with `opener` (any value when omitted), or -1.
508
+ */
509
+ function findDirectKeyValue(s, objStart, key, opener) {
510
+ let found = -1;
511
+ visitDirectEntries(s, objStart, (k, valueStart) => {
512
+ if (k !== key) return false;
513
+ if (opener === void 0 || s[valueStart] === opener) found = valueStart;
514
+ return true;
515
+ });
516
+ return found;
517
+ }
518
+ /** A direct string field of the object at `objStart`, once its closing quote has arrived. */
519
+ function readDirectString(s, objStart, key) {
520
+ if (objStart < 0) return null;
521
+ const start = findDirectKeyValue(s, objStart, key, "\"");
522
+ if (start < 0) return null;
523
+ const end = findValueEnd(s, start);
524
+ if (end < 0) return null;
525
+ try {
526
+ const value = JSON.parse(s.slice(start, end));
527
+ return typeof value === "string" ? value : null;
528
+ } catch {
529
+ return null;
530
+ }
531
+ }
532
+ /** A direct object field of the object at `objStart`, once the whole object has arrived. */
533
+ function readDirectRecord(s, objStart, key) {
534
+ const start = findDirectKeyValue(s, objStart, key, "{");
535
+ if (start < 0) return void 0;
536
+ const end = findValueEnd(s, start);
537
+ if (end < 0) return void 0;
538
+ return parseRecord(s.slice(start, end));
539
+ }
540
+ /**
541
+ * The complete part of a (possibly unterminated) JSON value: the parsed value
542
+ * when it is complete; for an open object, its complete entries plus the
543
+ * complete items of any streaming array entry; otherwise undefined.
544
+ */
545
+ function completePartOfValue(s, start) {
546
+ const end = findValueEnd(s, start);
547
+ if (end >= 0) try {
548
+ return JSON.parse(s.slice(start, end));
549
+ } catch {
550
+ return;
551
+ }
552
+ if (s[start] !== "{") return void 0;
553
+ const out = {};
554
+ visitDirectEntries(s, start, (key, valueStart) => {
555
+ const valueEnd = findValueEnd(s, valueStart);
556
+ if (valueEnd >= 0) try {
557
+ out[key] = JSON.parse(s.slice(valueStart, valueEnd));
558
+ } catch {}
559
+ else if (s[valueStart] === "[") {
560
+ const { items } = completeArrayItemsAt(s, valueStart, { repairComponents: false });
561
+ if (items.length > 0) out[key] = items;
562
+ }
563
+ return false;
564
+ });
565
+ return Object.keys(out).length > 0 ? out : void 0;
566
+ }
567
+ /**
568
+ * Best-effort operation from an unfinished or malformed top-level object.
569
+ * Fields are read only from the operation's own keys (`version` at the top
570
+ * level, `surfaceId`, `catalogId`, `path`, `dataModel` and `components` inside
571
+ * the operation object), never from component props or data-model values that
572
+ * happen to share a name.
573
+ *
574
+ * A `createSurface` keeps its complete components and a `dataModel` that has
575
+ * fully arrived, so a surface created in one line renders while it streams.
576
+ * A `callRendererFunction` gives nothing: a function must not run with half
577
+ * of its args.
578
+ */
579
+ function partialOperation(line) {
580
+ const root = skipWhitespace(line, 0);
581
+ if (line[root] !== "{") return null;
582
+ const version = readDirectString(line, root, "version") ?? _copilotkit_shared.A2UI_VERSION;
583
+ const components = findDirectKeyValue(line, root, "updateComponents", "{");
584
+ if (components >= 0) {
585
+ const arrayStart = findDirectKeyValue(line, components, "components", "[");
586
+ if (arrayStart < 0) return null;
587
+ const { items } = completeArrayItemsAt(line, arrayStart, { repairComponents: true });
588
+ if (items.length === 0) return null;
589
+ const surfaceId = readDirectString(line, components, "surfaceId");
590
+ return {
591
+ version,
592
+ updateComponents: {
593
+ ...surfaceId ? { surfaceId } : {},
594
+ components: items
595
+ }
596
+ };
597
+ }
598
+ const data = findDirectKeyValue(line, root, "updateDataModel", "{");
599
+ if (data >= 0) {
600
+ const valueStart = findDirectKeyValue(line, data, "value");
601
+ if (valueStart < 0) return null;
602
+ const value = completePartOfValue(line, valueStart);
603
+ if (value === void 0) return null;
604
+ const surfaceId = readDirectString(line, data, "surfaceId");
605
+ const path = readDirectString(line, data, "path");
606
+ return {
607
+ version,
608
+ updateDataModel: {
609
+ ...surfaceId ? { surfaceId } : {},
610
+ ...path ? { path } : {},
611
+ value
612
+ }
613
+ };
614
+ }
615
+ const create = findDirectKeyValue(line, root, "createSurface", "{");
616
+ if (create >= 0) {
617
+ const surfaceId = readDirectString(line, create, "surfaceId");
618
+ if (!surfaceId) return null;
619
+ const catalogId = readDirectString(line, create, "catalogId");
620
+ const dataModel = readDirectRecord(line, create, "dataModel");
621
+ const componentsStart = findDirectKeyValue(line, create, "components", "[");
622
+ const components = componentsStart < 0 ? [] : completeArrayItemsAt(line, componentsStart, { repairComponents: true }).items;
623
+ return {
624
+ version,
625
+ createSurface: {
626
+ surfaceId,
627
+ ...catalogId ? { catalogId } : {},
628
+ ...dataModel ? { dataModel } : {},
629
+ ...components.length > 0 ? { components } : {}
630
+ }
631
+ };
632
+ }
633
+ return null;
634
+ }
635
+ /**
636
+ * A line that opens a new top-level operation: `{"version":"1…` or
637
+ * `{"<operation>":{`. Seen at the start of a line while an earlier object is
638
+ * still unbalanced, it means that object is malformed and has ended.
639
+ */
640
+ const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
641
+ /**
642
+ * Scan the top-level object whose "{" is at `start`. Returns the index just
643
+ * past it and whether it balanced. An unbalanced object ends early (at the
644
+ * start of the line) when a line opens a new operation; otherwise it runs to
645
+ * the end of the input. JSON strings cannot contain raw newlines, so a newline
646
+ * inside a string ends it: a stray quote then breaks one line, not the rest of
647
+ * the fence.
648
+ */
649
+ function scanTopLevelObject(s, start) {
650
+ let depth = 0;
651
+ let inString = false;
652
+ for (let i = start; i < s.length; i++) {
653
+ const c = s[i];
654
+ if (inString) {
655
+ if (c === "\\" && s[i + 1] !== "\n") i++;
656
+ else if (c === "\"" || c === "\n") inString = false;
657
+ if (c !== "\n") continue;
658
+ }
659
+ if (c === "\n") {
660
+ const next = skipWhitespace(s, i + 1);
661
+ if (OPERATION_START.test(s.slice(next, next + 40))) return {
662
+ end: i + 1,
663
+ balanced: false
664
+ };
665
+ continue;
666
+ }
667
+ if (c === "\"") inString = true;
668
+ else if (c === "{" || c === "[") depth++;
669
+ else if (c === "}" || c === "]") {
670
+ depth--;
671
+ if (depth === 0) return {
672
+ end: i + 1,
673
+ balanced: true
674
+ };
675
+ }
676
+ }
677
+ return {
678
+ end: s.length,
679
+ balanced: false
680
+ };
681
+ }
682
+ const OPERATION_NAMES = [
683
+ "createSurface",
684
+ "updateComponents",
685
+ "updateDataModel",
686
+ "deleteSurface",
687
+ "callRendererFunction"
688
+ ];
689
+ /** Whether a value is shaped like one A2UI operation, with named components. */
690
+ function isOperationShape(value) {
691
+ if (!isRecord(value) || value.version !== _copilotkit_shared.A2UI_VERSION) return false;
692
+ const names = OPERATION_NAMES.filter((name) => name in value);
693
+ if (names.length !== 1 || Object.keys(value).length !== 2) return false;
694
+ const body = value[names[0]];
695
+ if (!isRecord(body)) return false;
696
+ if (names[0] === "callRendererFunction") return true;
697
+ if (typeof body.surfaceId !== "string") return false;
698
+ const components = body.components;
699
+ return components === void 0 || Array.isArray(components) && components.every((c) => isRecord(c) && typeof c.id === "string" && typeof c.component === "string");
700
+ }
701
+ /** Openers minus closers ({ and [ against } and ]) outside strings. */
702
+ function closerImbalance(line) {
703
+ let depth = 0;
704
+ let inString = false;
705
+ for (let i = 0; i < line.length; i++) {
706
+ const c = line[i];
707
+ if (inString) {
708
+ if (c === "\\") i++;
709
+ else if (c === "\"") inString = false;
710
+ } else if (c === "\"") inString = true;
711
+ else if (c === "{" || c === "[") depth++;
712
+ else if (c === "}" || c === "]") depth--;
713
+ }
714
+ return depth;
715
+ }
716
+ /** The text with closers and whitespace removed, to compare a repair. */
717
+ function withoutClosers(text) {
718
+ return text.replace(/[\]}\s]/g, "");
719
+ }
720
+ /**
721
+ * Whether a component of the operation holds a structural key (`id`,
722
+ * `component`, `child`, `children`) in a nested object: a closer added at
723
+ * the end instead of where it was dropped. The scan below repairs those.
724
+ */
725
+ function nestsStructuralKey(value) {
726
+ const nests = (v) => isRecord(v) && Object.entries(v).some(([k, x]) => STRUCTURAL_KEYS.has(k) || nests(x));
727
+ const components = (isRecord(value) ? Object.values(value).find(isRecord) : void 0)?.components;
728
+ return Array.isArray(components) && components.some((c) => isRecord(c) && Object.values(c).some((prop) => nests(prop)));
729
+ }
730
+ /**
731
+ * Repairs the complete lines of a fence that are not valid JSON (a missing
732
+ * or extra brace) with jsonrepair, when the repair only adds or removes
733
+ * closers and the result is shaped like an operation. A line still streaming in (no newline yet) is left alone.
734
+ */
735
+ function repairFenceLines(fenceText) {
736
+ const repaired = [];
737
+ const lines = fenceText.split("\n");
738
+ if (fenceText.trimStart().startsWith("[")) return {
739
+ text: fenceText,
740
+ repaired
741
+ };
742
+ for (let n = 0; n < lines.length - 1; n++) {
743
+ const line = lines[n];
744
+ if (!line.trim().startsWith("{")) continue;
745
+ try {
746
+ JSON.parse(line);
747
+ continue;
748
+ } catch {}
749
+ const imbalance = closerImbalance(line);
750
+ if (Math.abs(imbalance) !== 1) continue;
751
+ const next = lines.slice(n + 1).find((l) => l.trim() !== "");
752
+ if (imbalance > 0 && next !== void 0 && !next.trim().startsWith("{")) continue;
753
+ try {
754
+ const fixed = (0, jsonrepair.jsonrepair)(line);
755
+ const value = JSON.parse(fixed);
756
+ if (withoutClosers(fixed) === withoutClosers(line) && isOperationShape(value) && !nestsStructuralKey(value) && !(isRecord(value) && "callRendererFunction" in value)) {
757
+ repaired.push(line.trim());
758
+ lines[n] = JSON.stringify(value);
759
+ }
760
+ } catch {}
761
+ }
762
+ return {
763
+ text: lines.join("\n"),
764
+ repaired
765
+ };
766
+ }
767
+ /**
768
+ * Parse the body of an a2ui fence as a stream of top-level JSON values, so
769
+ * operations may be one per line (the documented format), several per line,
770
+ * pretty-printed over many lines, or wrapped in a top-level array (which is
771
+ * flattened). Whitespace and commas between objects are ignored.
772
+ *
773
+ * - A balanced object is `JSON.parse`d. When that fails (e.g. a stray quote),
774
+ * its raw text goes to `invalidLines` and whatever `partialOperation` can
775
+ * salvage (complete components, data-model entries, createSurface fields)
776
+ * is kept.
777
+ * - An unbalanced object followed by a line that opens a new operation is
778
+ * treated the same way.
779
+ * - The trailing unbalanced object (still streaming, or never closed) is
780
+ * `partialObject` and yields a partial operation when it has usable data.
781
+ * - Other text between objects is skipped and reported in `recovered` (and in
782
+ * `invalidLines`, which predates it).
783
+ *
784
+ * `partialLine` is a deprecated alias of `partialObject`.
785
+ *
786
+ * @param fenceText - The body of an a2ui fence (`text` of an a2ui
787
+ * `MarkdownSegment`), complete or still streaming.
788
+ * @returns `{ operations, partialObject, partialLine, invalidLines, recovered }`.
789
+ *
790
+ * @example
791
+ * ```ts
792
+ * const { operations } = extractFenceOperations(segment.text);
793
+ * ```
794
+ */
795
+ function extractFenceOperations(fenceText) {
796
+ const { text: s, repaired: repairedLines } = repairFenceLines(fenceText);
797
+ const operations = [];
798
+ const invalidLines = [];
799
+ const recovered = [];
800
+ let partialObject = null;
801
+ const salvage = (raw) => {
802
+ invalidLines.push(raw.trim());
803
+ const partial = partialOperation(raw);
804
+ if (partial) operations.push(partial);
805
+ };
806
+ let junkStart = -1;
807
+ const flushJunk = (end) => {
808
+ if (junkStart < 0) return;
809
+ const junk = s.slice(junkStart, end).trim();
810
+ junkStart = -1;
811
+ if (!junk) return;
812
+ recovered.push(junk);
813
+ invalidLines.push(junk);
814
+ };
815
+ let i = 0;
816
+ while (i < s.length) {
817
+ const c = s[i];
818
+ if (c === "{") {
819
+ flushJunk(i);
820
+ const { end, balanced } = scanTopLevelObject(s, i);
821
+ const raw = s.slice(i, end);
822
+ if (balanced) {
823
+ let parsed;
824
+ try {
825
+ parsed = JSON.parse(raw);
826
+ } catch {
827
+ parsed = void 0;
828
+ }
829
+ if (isRecord(parsed)) operations.push(parsed);
830
+ else salvage(raw);
831
+ } else if (end < s.length) salvage(raw);
832
+ else {
833
+ partialObject = raw;
834
+ const partial = partialOperation(raw);
835
+ if (partial) operations.push(partial);
836
+ }
837
+ i = end;
838
+ continue;
839
+ }
840
+ if (c === "\n" || c === "[" || c === "]") flushJunk(i);
841
+ else if (junkStart < 0 && !isWhitespace(c) && c !== ",") junkStart = i;
842
+ i++;
843
+ }
844
+ flushJunk(s.length);
845
+ return {
846
+ operations,
847
+ partialObject,
848
+ partialLine: partialObject,
849
+ invalidLines,
850
+ recovered,
851
+ repairedLines
852
+ };
853
+ }
854
+ /**
855
+ * Normalise a fence's operations for the renderer: drop unknown messages, fill
856
+ * in `version` and missing `surfaceId`s, keep only the first `createSurface`,
857
+ * keep its `catalogId` when `catalogIds` lists it (else use `catalogId`), synthesize
858
+ * `createSurface` when the model omitted it, and report the
859
+ * surfaceId (the first one found, else `fallbackSurfaceId`).
860
+ *
861
+ * `callRendererFunction` operations target no surface. They get no surfaceId,
862
+ * do not cause a synthesized `createSurface`, and come back in
863
+ * `functionCalls` (in fence order), never in `operations`.
864
+ *
865
+ * @param input.operations - Operations from `extractFenceOperations`.
866
+ * @param input.fallbackSurfaceId - The surfaceId to use when no operation
867
+ * names one.
868
+ * @param input.catalogId - The client catalog. It replaces a catalogId of the
869
+ * model that `catalogIds` does not list.
870
+ * @param input.catalogIds - The catalogs that the model can name. Left out,
871
+ * only `catalogId`.
872
+ * @returns `{ surfaceId, operations, functionCalls }`.
873
+ *
874
+ * @example
875
+ * ```ts
876
+ * const { surfaceId, operations, functionCalls } = prepareSurfaceOperations({
877
+ * operations: extractFenceOperations(segment.text).operations,
878
+ * fallbackSurfaceId: `${messageId}-${segment.index}`,
879
+ * catalogId,
880
+ * });
881
+ * ```
882
+ */
883
+ function prepareSurfaceOperations(input) {
884
+ const { operations, fallbackSurfaceId, catalogId } = input;
885
+ const catalogIds = input.catalogIds ?? [catalogId];
886
+ const surfaceId = operations.map(getMarkdownOperationSurfaceId).find((id) => !!id) ?? fallbackSurfaceId;
887
+ const out = [];
888
+ const functionCalls = [];
889
+ let hasCreate = false;
890
+ for (const op of operations) {
891
+ const entry = getOperationEntry(op);
892
+ if (!entry) continue;
893
+ const { key } = entry;
894
+ const inner = { ...entry.inner };
895
+ const version = typeof op.version === "string" ? op.version : _copilotkit_shared.A2UI_VERSION;
896
+ if (key === FUNCTION_CALL_KEY) {
897
+ functionCalls.push({
898
+ version,
899
+ [key]: inner
900
+ });
901
+ continue;
902
+ }
903
+ if (typeof inner.surfaceId !== "string") inner.surfaceId = surfaceId;
904
+ if (key === "createSurface") {
905
+ if (hasCreate) {
906
+ const { surfaceId: id, dataModel, components } = inner;
907
+ if (dataModel !== void 0) out.push({
908
+ version,
909
+ updateDataModel: {
910
+ surfaceId: id,
911
+ path: "/",
912
+ value: dataModel
913
+ }
914
+ });
915
+ if (Array.isArray(components) && components.length > 0) out.push({
916
+ version,
917
+ updateComponents: {
918
+ surfaceId: id,
919
+ components
920
+ }
921
+ });
922
+ continue;
923
+ }
924
+ hasCreate = true;
925
+ if (!catalogIds.includes(inner.catalogId)) inner.catalogId = catalogId;
926
+ }
927
+ out.push({
928
+ version,
929
+ [key]: inner
930
+ });
931
+ }
932
+ if (!hasCreate && out.length > 0) out.unshift({
933
+ version: _copilotkit_shared.A2UI_VERSION,
934
+ createSurface: {
935
+ surfaceId,
936
+ catalogId
937
+ }
938
+ });
939
+ return {
940
+ surfaceId,
941
+ operations: out,
942
+ functionCalls
943
+ };
944
+ }
945
+ /**
946
+ * Components a user operates. A Card containing one of these is an
947
+ * interactive panel and keeps its box; every other Card is informational.
948
+ */
949
+ const INTERACTIVE_COMPONENTS = new Set([
950
+ "Button",
951
+ "Pressable",
952
+ "Form",
953
+ "TextField",
954
+ "TextArea",
955
+ "Select",
956
+ "CheckBox",
957
+ "Radio",
958
+ "RadioGroup",
959
+ "Slider",
960
+ "SegmentedControl",
961
+ "ChoicePicker",
962
+ "DateTimeInput"
963
+ ]);
964
+ /** A component id referenced by a `child`/`children` entry or a table cell. */
965
+ function referencedId(value) {
966
+ if (typeof value === "string") return value;
967
+ if (isRecord(value)) {
968
+ if (typeof value.componentId === "string") return value.componentId;
969
+ if (typeof value.id === "string") return value.id;
970
+ }
971
+ }
972
+ /** Ids of a table cell / column that renders a component (`{componentId}` or `{id}`). */
973
+ function cellComponentId(value) {
974
+ return isRecord(value) ? referencedId(value) : void 0;
975
+ }
976
+ /**
977
+ * Ids a component renders directly: `child`, `children` (string ids, an
978
+ * array, or a `{componentId}` template), component cells of a Table's
979
+ * `rows`/`columns`, and the ids that `extra` finds in its typed references.
980
+ */
981
+ function directChildIds(component, extra) {
982
+ const ids = [];
983
+ const add = (id) => {
984
+ if (id) ids.push(id);
985
+ };
986
+ const extraIds = extra?.(component);
987
+ if (Array.isArray(extraIds)) extraIds.forEach(add);
988
+ add(referencedId(component.child));
989
+ const children = component.children;
990
+ if (Array.isArray(children)) children.forEach((c) => add(referencedId(c)));
991
+ else add(referencedId(children));
992
+ if (Array.isArray(component.columns)) component.columns.forEach((c) => add(cellComponentId(c)));
993
+ if (Array.isArray(component.rows)) {
994
+ for (const row of component.rows) if (Array.isArray(row)) row.forEach((c) => add(cellComponentId(c)));
995
+ }
996
+ return ids;
997
+ }
998
+ /** Components of every updateComponents operation, by id (last definition wins). */
999
+ function componentsById(operations) {
1000
+ const byId = /* @__PURE__ */ new Map();
1001
+ for (const op of operations) {
1002
+ const update = op.updateComponents;
1003
+ const list = isRecord(update) ? update.components : void 0;
1004
+ if (!Array.isArray(list)) continue;
1005
+ for (const c of list) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
1006
+ }
1007
+ return byId;
1008
+ }
1009
+ function descendantIds(rootId, byId, extra) {
1010
+ const seen = /* @__PURE__ */ new Set();
1011
+ const stack = [...directChildIds(byId.get(rootId) ?? {}, extra)];
1012
+ while (stack.length > 0) {
1013
+ const id = stack.pop();
1014
+ if (seen.has(id) || id === rootId) continue;
1015
+ seen.add(id);
1016
+ const c = byId.get(id);
1017
+ if (c) stack.push(...directChildIds(c, extra));
1018
+ }
1019
+ return seen;
1020
+ }
1021
+ /**
1022
+ * Ids of the `Card` components that are interactive panels: at least one
1023
+ * descendant (via `child`, `children` or table component cells) is a control
1024
+ * (Button, Pressable, Form, TextField, TextArea, Select, CheckBox, Radio,
1025
+ * RadioGroup, Slider, SegmentedControl, DateTimeInput).
1026
+ *
1027
+ * @param components - The components of one surface.
1028
+ * @returns The ids of the interactive cards.
1029
+ *
1030
+ * @example
1031
+ * ```ts
1032
+ * const interactive = classifySurfaceCards(components);
1033
+ * const keepsBox = interactive.has("quote-form");
1034
+ * ```
1035
+ */
1036
+ function classifySurfaceCards(components, options = {}) {
1037
+ const byId = /* @__PURE__ */ new Map();
1038
+ for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
1039
+ const interactive = /* @__PURE__ */ new Set();
1040
+ for (const [id, c] of byId) {
1041
+ if (c.component !== "Card") continue;
1042
+ for (const d of descendantIds(id, byId, options.childIds)) {
1043
+ const type = byId.get(d)?.component;
1044
+ if (typeof type === "string" && INTERACTIVE_COMPONENTS.has(type)) {
1045
+ interactive.add(id);
1046
+ break;
1047
+ }
1048
+ }
1049
+ }
1050
+ return interactive;
1051
+ }
1052
+ /**
1053
+ * Markdown mode: only interactive panels keep a box. Every `Card` that is not
1054
+ * an interactive panel (see `classifySurfaceCards`), sets no `variant` or
1055
+ * `border` of its own and is not nested inside an interactive panel becomes
1056
+ * `variant: "section"` (a heading plus content without a box). Operations
1057
+ * other than updateComponents pass through unchanged.
1058
+ *
1059
+ * @param operations - The operations of one surface.
1060
+ * @returns The operations with informational cards set to `variant: "section"`.
1061
+ * When no card changes, it returns the same array.
1062
+ *
1063
+ * @example
1064
+ * ```ts
1065
+ * const operations = flattenInformationalCards(prepared.operations);
1066
+ * ```
1067
+ */
1068
+ function flattenInformationalCards(operations, options = {}) {
1069
+ const byId = componentsById(operations);
1070
+ if (![...byId.values()].some((c) => c.component === "Card")) return operations;
1071
+ const interactive = classifySurfaceCards([...byId.values()], options);
1072
+ const insideInteractive = /* @__PURE__ */ new Set();
1073
+ for (const id of interactive) for (const d of descendantIds(id, byId, options.childIds)) insideInteractive.add(d);
1074
+ const flatten = (c) => c.component === "Card" && typeof c.id === "string" && !interactive.has(c.id) && !insideInteractive.has(c.id) && c.variant == null && c.border == null;
1075
+ return operations.map((op) => {
1076
+ const update = op.updateComponents;
1077
+ if (!isRecord(update) || !Array.isArray(update.components)) return op;
1078
+ if (!update.components.some((c) => isRecord(c) && flatten(c))) return op;
1079
+ return {
1080
+ ...op,
1081
+ updateComponents: {
1082
+ ...update,
1083
+ components: update.components.map((c) => isRecord(c) && flatten(c) ? {
1084
+ ...c,
1085
+ variant: "section"
1086
+ } : c)
1087
+ }
1088
+ };
1089
+ });
1090
+ }
1091
+ /** Text-bearing components that belong in the chat's markdown, not a surface. */
1092
+ const PROSE_TEXT_COMPONENTS = new Set([
1093
+ "Title",
1094
+ "Text",
1095
+ "Caption",
1096
+ "Markdown"
1097
+ ]);
1098
+ /** One line of text: list items and headings cannot span lines in markdown. */
1099
+ function oneLine(text) {
1100
+ return text.trim().replace(/\s*\n\s*/g, " ");
1101
+ }
1102
+ /**
1103
+ * A literal List entry as list-item markdown: a non-empty string, or
1104
+ * `{ label, description? }` with literal strings only. Anything carrying
1105
+ * behaviour or decoration (`icon`, `action`, other keys, bound values) is null.
1106
+ */
1107
+ function listEntryMarkdown(entry) {
1108
+ if (typeof entry === "string") return entry.trim() ? oneLine(entry) : null;
1109
+ if (!isRecord(entry)) return null;
1110
+ for (const key of Object.keys(entry)) if (key !== "label" && key !== "description") return null;
1111
+ if (typeof entry.label !== "string" || !entry.label.trim()) return null;
1112
+ const label = oneLine(entry.label);
1113
+ if (entry.description === void 0) return label;
1114
+ if (typeof entry.description !== "string") return null;
1115
+ return entry.description.trim() ? `**${label}** — ${oneLine(entry.description)}` : label;
1116
+ }
1117
+ /**
1118
+ * A List of literal text items as a markdown list (`marker: "number"` →
1119
+ * `1. …`, otherwise `- …`), or null when it binds its items, renders
1120
+ * `children`, or any item is not plain text.
1121
+ */
1122
+ function listToMarkdown(c) {
1123
+ const children = c.children;
1124
+ if (children != null && !(Array.isArray(children) && children.length === 0)) return null;
1125
+ if (!Array.isArray(c.items) || c.items.length === 0) return null;
1126
+ const lines = [];
1127
+ for (const entry of c.items) {
1128
+ const line = listEntryMarkdown(entry);
1129
+ if (line === null) return null;
1130
+ lines.push(line);
1131
+ }
1132
+ if (c.marker === "number") {
1133
+ const start = typeof c.start === "number" && Number.isInteger(c.start) ? c.start : 1;
1134
+ return lines.map((line, i) => `${start + i}. ${line}`).join("\n");
1135
+ }
1136
+ return lines.map((line) => `- ${line}`).join("\n");
1137
+ }
1138
+ /** The prose item a component converts to, or null when it is not prose. */
1139
+ function toProseItem(c) {
1140
+ if (!c) return null;
1141
+ if (c.accessibility !== void 0) return null;
1142
+ if (c.component === "Divider") return { kind: "divider" };
1143
+ if (c.component === "Spacer") return { kind: "spacer" };
1144
+ if (c.component === "List") {
1145
+ if (c.direction !== void 0 && c.direction !== "vertical") return null;
1146
+ const markdown = listToMarkdown(c);
1147
+ return markdown === null ? null : {
1148
+ kind: "text",
1149
+ markdown
1150
+ };
1151
+ }
1152
+ if (typeof c.component !== "string") return null;
1153
+ if (!PROSE_TEXT_COMPONENTS.has(c.component)) return null;
1154
+ if (typeof c.text !== "string" || c.text.trim() === "") return null;
1155
+ const text = c.text.trim();
1156
+ switch (c.component) {
1157
+ case "Title": {
1158
+ const size = typeof c.size === "string" ? c.size : "md";
1159
+ return {
1160
+ kind: "text",
1161
+ markdown: `${size === "sm" ? "####" : size === "md" || size === "lg" ? "###" : "##"} ${text}`
1162
+ };
1163
+ }
1164
+ case "Text":
1165
+ if (directChildIds(c).length > 0) return null;
1166
+ return {
1167
+ kind: "text",
1168
+ markdown: c.strong === true ? `**${text}**` : text
1169
+ };
1170
+ default: return {
1171
+ kind: "text",
1172
+ markdown: text
1173
+ };
1174
+ }
1175
+ }
1176
+ /** Prose items as markdown: separators only survive between two text items. */
1177
+ function proseItemsToMarkdown(items) {
1178
+ const blocks = [];
1179
+ let pendingDivider = false;
1180
+ for (const item of items) if (item?.kind === "text") {
1181
+ if (pendingDivider && blocks.length > 0) blocks.push("---");
1182
+ pendingDivider = false;
1183
+ blocks.push(item.markdown);
1184
+ } else if (item?.kind === "divider") pendingDivider = true;
1185
+ return blocks.join("\n\n");
1186
+ }
1187
+ /** Column, column-direction Box, or an informational Card (section/unset variant). */
1188
+ function isVerticalStack(c, interactiveCards) {
1189
+ if (c.accessibility !== void 0) return false;
1190
+ if (c.component === "Column") return true;
1191
+ if (c.component === "Box") return c.direction == null || c.direction === "col";
1192
+ if (c.component === "Card") return (c.variant == null || c.variant === "section") && typeof c.id === "string" && !interactiveCards.has(c.id);
1193
+ return false;
1194
+ }
1195
+ /** The child-id list of a stack (`children`, or a lone `child`), else null. */
1196
+ /**
1197
+ * The children of a stack in render order: `child` first (a Card renders
1198
+ * its `child` before its `children`), then `children`.
1199
+ */
1200
+ function stackChildren(c) {
1201
+ const first = typeof c.child === "string" ? [c.child] : [];
1202
+ if (Array.isArray(c.children)) return [...first, ...c.children];
1203
+ if (first.length > 0 && c.children === void 0) return first;
1204
+ return null;
1205
+ }
1206
+ /**
1207
+ * Partitions the stack's children into alternating prose and surface runs.
1208
+ * A run of consecutive prose items is prose only when it holds text: a run of
1209
+ * separators alone (Divider/Spacer between two UI components, or at the very
1210
+ * start/end of the stack) stays with the surface it sits in.
1211
+ */
1212
+ function partitionChildren(items) {
1213
+ const runs = [];
1214
+ let i = 0;
1215
+ while (i < items.length) {
1216
+ const candidate = items[i] !== null;
1217
+ let hasText = false;
1218
+ let j = i;
1219
+ while (j < items.length && items[j] !== null === candidate) {
1220
+ if (items[j]?.kind === "text") hasText = true;
1221
+ j++;
1222
+ }
1223
+ const prose = candidate && hasText;
1224
+ const last = runs[runs.length - 1];
1225
+ if (!prose && last && !last.prose) last.end = j;
1226
+ else runs.push({
1227
+ prose,
1228
+ start: i,
1229
+ end: j
1230
+ });
1231
+ i = j;
1232
+ }
1233
+ return runs;
1234
+ }
1235
+ /**
1236
+ * Markdown mode: split a surface into markdown and surface segments so that
1237
+ * only real UI renders as A2UI and everything else is the chat's markdown.
1238
+ *
1239
+ * From `root`, descend through single-child vertical containers (Column,
1240
+ * column Box, informational Card) to the first one with several children:
1241
+ * the stack. Its children are partitioned, in order, into runs of prose and
1242
+ * runs of UI. Prose is `Title`, `Text`, `Caption`, `Markdown` with literal
1243
+ * text, a `List` of literal text items, plus `Divider`/`Spacer` next to them:
1244
+ * `Title` → heading by size (sm `####`, md/lg `###`, larger `##`), `Text` →
1245
+ * paragraph (`strong` → `**…**`), `Caption`/`Markdown` → paragraph, `List` →
1246
+ * `- …` (or `1. …` for `marker: "number"`, `**label** — description` for
1247
+ * described items), and a `Divider` between two prose blocks → `---`.
1248
+ *
1249
+ * Not prose: `{path}`-bound text or items, a Text with inline children, a
1250
+ * List with `children`/icons/actions, a template entry, a component with an
1251
+ * `accessibility` envelope, and a child whose component has not streamed
1252
+ * yet. Separators with no text beside them stay in
1253
+ * the surface. An interactive Card (see `classifySurfaceCards`) is never
1254
+ * entered.
1255
+ *
1256
+ * Each prose run becomes a markdown segment; each UI run becomes a surface
1257
+ * segment whose `root` is a copy of the stack (its other props kept, `child`
1258
+ * dropped) with only that run's `children`, followed by every component
1259
+ * reachable from them. When nothing is prose the input comes back as the one
1260
+ * surface segment (same array); when everything is (or `root` itself is),
1261
+ * there are only markdown segments.
1262
+ *
1263
+ * Pure and linear in the number of components, so it runs on every stream
1264
+ * update.
1265
+ *
1266
+ * @param components - The components of one surface, root included.
1267
+ * @returns The segments in render order.
1268
+ *
1269
+ * @example
1270
+ * ```ts
1271
+ * for (const segment of segmentSurfaceProse(components)) {
1272
+ * if (segment.kind === "markdown") renderMarkdown(segment.markdown);
1273
+ * else renderSurface(segment.components);
1274
+ * }
1275
+ * ```
1276
+ */
1277
+ function segmentSurfaceProse(components, options = {}) {
1278
+ const unchanged = [{
1279
+ kind: "surface",
1280
+ components
1281
+ }];
1282
+ const byId = /* @__PURE__ */ new Map();
1283
+ for (const c of components) if (isRecord(c) && typeof c.id === "string") byId.set(c.id, c);
1284
+ const root = byId.get(_copilotkit_shared.GENERATIVE_UI_ROOT_ID);
1285
+ if (!root) return unchanged;
1286
+ if (components.some((c) => isRecord(c) && options.childIds?.(c) === "unknown")) return unchanged;
1287
+ const rootItem = toProseItem(root);
1288
+ if (rootItem?.kind === "text") return [{
1289
+ kind: "markdown",
1290
+ markdown: rootItem.markdown
1291
+ }];
1292
+ const interactiveCards = classifySurfaceCards(components, options);
1293
+ let stack = root;
1294
+ let stackId = _copilotkit_shared.GENERATIVE_UI_ROOT_ID;
1295
+ let children;
1296
+ const visited = /* @__PURE__ */ new Set();
1297
+ while (true) {
1298
+ if (!isVerticalStack(stack, interactiveCards)) return unchanged;
1299
+ visited.add(stackId);
1300
+ const list = stackChildren(stack);
1301
+ if (!list) return unchanged;
1302
+ children = list;
1303
+ const nextId = list.length === 1 ? list[0] : void 0;
1304
+ if (typeof nextId !== "string") break;
1305
+ const next = byId.get(nextId);
1306
+ if (!next || visited.has(nextId) || toProseItem(next)) break;
1307
+ stack = next;
1308
+ stackId = nextId;
1309
+ }
1310
+ const stackChildIds = children;
1311
+ const items = stackChildIds.map((id) => typeof id === "string" ? toProseItem(byId.get(id)) : null);
1312
+ const runs = partitionChildren(items);
1313
+ if (!runs.some((run) => run.prose)) return unchanged;
1314
+ const surfaceRuns = runs.filter((run) => !run.prose);
1315
+ const owners = /* @__PURE__ */ new Map();
1316
+ surfaceRuns.forEach((run, index) => {
1317
+ const pending = stackChildIds.slice(run.start, run.end).map(referencedId).filter((id) => id !== void 0);
1318
+ const seen = /* @__PURE__ */ new Set();
1319
+ while (pending.length > 0) {
1320
+ const id = pending.pop();
1321
+ if (id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID || id === stackId || seen.has(id)) continue;
1322
+ seen.add(id);
1323
+ const list = owners.get(id);
1324
+ if (list) list.push(index);
1325
+ else owners.set(id, [index]);
1326
+ const c = byId.get(id);
1327
+ if (c) pending.push(...directChildIds(c, options.childIds));
1328
+ }
1329
+ });
1330
+ const surfaceComponents = surfaceRuns.map((run) => {
1331
+ const { child: _child, ...stackRest } = stack;
1332
+ const nextRoot = {
1333
+ ...stackRest,
1334
+ id: _copilotkit_shared.GENERATIVE_UI_ROOT_ID,
1335
+ children: stackChildIds.slice(run.start, run.end)
1336
+ };
1337
+ delete nextRoot.child;
1338
+ return [nextRoot];
1339
+ });
1340
+ for (const c of components) {
1341
+ if (!isRecord(c) || typeof c.id !== "string" || byId.get(c.id) !== c) continue;
1342
+ const ownerIndexes = owners.get(c.id) ?? [];
1343
+ for (const index of ownerIndexes) surfaceComponents[index].push(c);
1344
+ }
1345
+ let surfaceIndex = 0;
1346
+ return runs.map((run) => {
1347
+ if (run.prose) return {
1348
+ kind: "markdown",
1349
+ markdown: proseItemsToMarkdown(items.slice(run.start, run.end))
1350
+ };
1351
+ return {
1352
+ kind: "surface",
1353
+ components: surfaceComponents[surfaceIndex++]
1354
+ };
1355
+ });
1356
+ }
1357
+
1358
+ //#endregion
1359
+ Object.defineProperty(exports, 'A2UI_FENCE_LANGUAGE', {
1360
+ enumerable: true,
1361
+ get: function () {
1362
+ return A2UI_FENCE_LANGUAGE;
1363
+ }
1364
+ });
1365
+ Object.defineProperty(exports, 'classifySurfaceCards', {
1366
+ enumerable: true,
1367
+ get: function () {
1368
+ return classifySurfaceCards;
1369
+ }
1370
+ });
1371
+ Object.defineProperty(exports, 'extractCompleteArrayItems', {
1372
+ enumerable: true,
1373
+ get: function () {
1374
+ return extractCompleteArrayItems;
1375
+ }
1376
+ });
1377
+ Object.defineProperty(exports, 'extractFenceOperations', {
1378
+ enumerable: true,
1379
+ get: function () {
1380
+ return extractFenceOperations;
1381
+ }
1382
+ });
1383
+ Object.defineProperty(exports, 'extractStringField', {
1384
+ enumerable: true,
1385
+ get: function () {
1386
+ return extractStringField;
1387
+ }
1388
+ });
1389
+ Object.defineProperty(exports, 'flattenInformationalCards', {
1390
+ enumerable: true,
1391
+ get: function () {
1392
+ return flattenInformationalCards;
1393
+ }
1394
+ });
1395
+ Object.defineProperty(exports, 'getMarkdownOperationSurfaceId', {
1396
+ enumerable: true,
1397
+ get: function () {
1398
+ return getMarkdownOperationSurfaceId;
1399
+ }
1400
+ });
1401
+ Object.defineProperty(exports, 'prepareSurfaceOperations', {
1402
+ enumerable: true,
1403
+ get: function () {
1404
+ return prepareSurfaceOperations;
1405
+ }
1406
+ });
1407
+ Object.defineProperty(exports, 'segmentSurfaceProse', {
1408
+ enumerable: true,
1409
+ get: function () {
1410
+ return segmentSurfaceProse;
1411
+ }
1412
+ });
1413
+ Object.defineProperty(exports, 'splitA2UIMarkdown', {
1414
+ enumerable: true,
1415
+ get: function () {
1416
+ return splitA2UIMarkdown;
1417
+ }
1418
+ });
1419
+ //# sourceMappingURL=a2ui-markdown-DkMXFQih.cjs.map