@copilotkit/core 1.84.2-canary.1793809041 → 1.84.2-canary.openbot-intel-fixes

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.
@@ -0,0 +1,3075 @@
1
+ import { a as flattenInformationalCards, c as segmentSurfaceProse, o as getMarkdownOperationSurfaceId, r as extractFenceOperations, s as prepareSurfaceOperations, u as splitA2UIMarkdown } from "../a2ui-markdown-BxZr1mEU.mjs";
2
+ import { A2UI_COMPONENT_ENVELOPE_KEYS, A2UI_INDEX_FUNCTION, A2UI_VERSION, COPILOTKIT_UI_ENVELOPE_FORMAT, GENERATIVE_UI_AGENT_FUNCTION_CALLS, GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON, GENERATIVE_UI_CHAT_TARGET, GENERATIVE_UI_FUNCTIONS, GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE, GENERATIVE_UI_MAX_REJECTION_LENGTH, GENERATIVE_UI_MAX_SUMMARY_REJECTIONS, GENERATIVE_UI_MAX_TARGET_COMPONENTS, GENERATIVE_UI_ROOT_ID, applyDescriptionOverrides, buildGenerativeUIMarkdownGuidelines, buildGenerativeUIPrompt, callerProblem, childIdsAtRefs, collectChildRefs, defaultGenerativeUIPromptSpec, envelopeToManifest, functionCallers, generativeUIGuideFeatures, getOperationKind, getOperationSurfaceId, hasBoundChildRef, isActionBinding, isCallBinding, isPathBinding, isValidationResult, randomUUID, renderGenerativeUISchema, validateOperation } from "@copilotkit/shared";
3
+ import { GenerativeUIError, catalogIdsOf, componentCatalogIds, formatIssues, isAsyncIssue, isRecord, issueKey, toJsonSchema, validateSchema, validateSchemaSync, withoutRejectedNulls } from "@copilotkit/shared/generative-ui";
4
+ import { Catalog, ComponentModel, DataModel, SurfaceModel } from "@a2ui/web_core/v0_9";
5
+ import { z } from "zod";
6
+
7
+ //#region src/generative-ui/runtime.ts
8
+ /**
9
+ * Reports an error without ever throwing: `reportError` reaches host code
10
+ * (`onError`), and a throwing host callback must not break rendering or an
11
+ * event handler.
12
+ */
13
+ function reportErrorSafely(engine, info) {
14
+ try {
15
+ engine.reportError(info);
16
+ } catch {}
17
+ }
18
+
19
+ //#endregion
20
+ //#region src/generative-ui/functions.ts
21
+ /**
22
+ * The renderer-side functions of the A2UI 1.0 basic catalog. Each one takes
23
+ * resolved args (no bindings left in them) and gives a plain value. They
24
+ * run synchronously, so a prop bound to one updates in the same render as
25
+ * the data it reads. The signatures the model sees are in
26
+ * `@copilotkit/shared` (`A2UI_BASIC_FUNCTIONS`).
27
+ */
28
+ /** Thrown for a bad call: an unknown function, bad args, or a bad value. */
29
+ var ExpressionError = class extends Error {
30
+ constructor(message) {
31
+ super(message);
32
+ this.name = "ExpressionError";
33
+ }
34
+ };
35
+ /** The boolean of a DynamicBoolean: a ValidationResult counts as `valid`. */
36
+ function truthOf(value) {
37
+ if (isValidationResult(value)) return value.valid;
38
+ return Boolean(value);
39
+ }
40
+ const valid = () => ({ valid: true });
41
+ /** A failed result. `code` names the failure, the same for every locale. */
42
+ const invalid = (message, code) => ({
43
+ valid: false,
44
+ message,
45
+ code
46
+ });
47
+ function text(value) {
48
+ if (value === void 0 || value === null) return "";
49
+ return typeof value === "string" ? value : String(value);
50
+ }
51
+ function numberOf$1(value) {
52
+ if (typeof value === "number") return value;
53
+ if (typeof value === "string" && value.trim() !== "") return Number(value);
54
+ return NaN;
55
+ }
56
+ function optionalNumber(value, name) {
57
+ if (value === void 0 || value === null) return void 0;
58
+ const parsed = numberOf$1(value);
59
+ if (Number.isNaN(parsed)) throw new ExpressionError(`${name} must be a number`);
60
+ return parsed;
61
+ }
62
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
63
+ /** The locale of the user. `undefined` lets Intl pick the default. */
64
+ function locale() {
65
+ return typeof navigator !== "undefined" ? navigator.language : void 0;
66
+ }
67
+ function numberFormat(args, options) {
68
+ const decimals = optionalNumber(args.decimals, "decimals");
69
+ return new Intl.NumberFormat(locale(), {
70
+ ...options,
71
+ useGrouping: args.grouping !== false,
72
+ ...decimals === void 0 ? {} : {
73
+ minimumFractionDigits: decimals,
74
+ maximumFractionDigits: decimals
75
+ }
76
+ });
77
+ }
78
+ /** A date from an ISO string, a timestamp, or a Date. */
79
+ function dateOf(value) {
80
+ const date = value instanceof Date ? value : typeof value === "number" ? new Date(value) : typeof value === "string" ? new Date(/^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00` : value) : void 0;
81
+ if (date === void 0 || Number.isNaN(date.getTime())) throw new ExpressionError("value must be a date");
82
+ return date;
83
+ }
84
+ const pad = (value, width) => String(value).padStart(width, "0");
85
+ /**
86
+ * A TR35 field is a run of one letter ("EEE" is one abbreviated weekday,
87
+ * not three), and text in single quotes is literal. Letters that are not
88
+ * fields stay as they are.
89
+ */
90
+ const DATE_FIELD = /([A-Za-z])\1*|'(?:[^']|'')*'/g;
91
+ function formatDatePattern(date, pattern) {
92
+ const parts = (options) => new Intl.DateTimeFormat(locale(), options).format(date);
93
+ const hours12 = date.getHours() % 12 || 12;
94
+ const numeric = (value, width) => width >= 2 ? pad(value, 2) : String(value);
95
+ return pattern.replace(DATE_FIELD, (token) => {
96
+ if (token.startsWith("'")) return token.slice(1, -1).replace(/''/g, "'");
97
+ const width = token.length;
98
+ switch (token[0]) {
99
+ case "y": return width === 2 ? pad(date.getFullYear() % 100, 2) : String(date.getFullYear());
100
+ case "M":
101
+ if (width >= 4) return parts({ month: "long" });
102
+ if (width === 3) return parts({ month: "short" });
103
+ return numeric(date.getMonth() + 1, width);
104
+ case "d": return numeric(date.getDate(), width);
105
+ case "E": return parts({ weekday: width >= 4 ? "long" : "short" });
106
+ case "H": return numeric(date.getHours(), width);
107
+ case "h": return numeric(hours12, width);
108
+ case "m": return pad(date.getMinutes(), 2);
109
+ case "s": return pad(date.getSeconds(), 2);
110
+ case "a": return date.getHours() < 12 ? "AM" : "PM";
111
+ default: return token;
112
+ }
113
+ });
114
+ }
115
+ /** Opens an http(s) URL in a new tab. Any other scheme is refused. */
116
+ function openUrlSafely(url) {
117
+ if (typeof url !== "string" || url === "") throw new ExpressionError("url must be a string");
118
+ if (typeof window === "undefined") return;
119
+ let parsed;
120
+ try {
121
+ parsed = new URL(url, window.location.href);
122
+ } catch {
123
+ throw new ExpressionError(`"${url}" is not a URL`);
124
+ }
125
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new ExpressionError(`openUrl takes only http(s) URLs, not ${parsed.protocol}`);
126
+ window.open(parsed.href, "_blank", "noopener,noreferrer");
127
+ }
128
+ /**
129
+ * The basic functions, except `formatString`, which needs the resolver.
130
+ * `calc` and `series` are added by `resolve.ts`, which imports both.
131
+ */
132
+ const BASIC_FUNCTIONS = {
133
+ required: ({ value }) => {
134
+ return value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0 ? invalid("Required", "required") : valid();
135
+ },
136
+ regex: ({ value, pattern }) => {
137
+ if (typeof pattern !== "string") throw new ExpressionError("pattern must be a string");
138
+ let expression;
139
+ try {
140
+ expression = new RegExp(pattern, "u");
141
+ } catch {
142
+ throw new ExpressionError(`"${pattern}" is not a regular expression`);
143
+ }
144
+ return expression.test(text(value)) ? valid() : invalid("Invalid format", "pattern");
145
+ },
146
+ length: ({ value, min, max }) => {
147
+ const size = text(value).length;
148
+ const low = optionalNumber(min, "min");
149
+ const high = optionalNumber(max, "max");
150
+ if (low !== void 0 && size < low) return invalid(`At least ${low} characters`, "tooShort");
151
+ if (high !== void 0 && size > high) return invalid(`At most ${high} characters`, "tooLong");
152
+ return valid();
153
+ },
154
+ numeric: ({ value, min, max }) => {
155
+ const parsed = numberOf$1(value);
156
+ if (Number.isNaN(parsed)) return invalid("Must be a number", "notANumber");
157
+ const low = optionalNumber(min, "min");
158
+ const high = optionalNumber(max, "max");
159
+ if (low !== void 0 && parsed < low) return invalid(`At least ${low}`, "tooSmall");
160
+ if (high !== void 0 && parsed > high) return invalid(`At most ${high}`, "tooLarge");
161
+ return valid();
162
+ },
163
+ email: ({ value }) => EMAIL.test(text(value)) ? valid() : invalid("Invalid email address", "email"),
164
+ formatNumber: (args) => {
165
+ const parsed = numberOf$1(args.value);
166
+ if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
167
+ return numberFormat(args, {}).format(parsed);
168
+ },
169
+ formatCurrency: (args) => {
170
+ const parsed = numberOf$1(args.value);
171
+ if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
172
+ if (typeof args.currency !== "string" || args.currency === "") throw new ExpressionError("currency must be an ISO 4217 code");
173
+ try {
174
+ return numberFormat(args, {
175
+ style: "currency",
176
+ currency: args.currency
177
+ }).format(parsed);
178
+ } catch {
179
+ throw new ExpressionError(`"${args.currency}" is not a currency code`);
180
+ }
181
+ },
182
+ formatDate: ({ value, format }) => {
183
+ if (typeof format !== "string") throw new ExpressionError("format must be a string");
184
+ return formatDatePattern(dateOf(value), format);
185
+ },
186
+ pluralize: (args) => {
187
+ const parsed = numberOf$1(args.value);
188
+ if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
189
+ const category = new Intl.PluralRules(locale()).select(parsed);
190
+ return text((parsed === 0 ? args.zero : void 0) ?? args[category] ?? args.other);
191
+ },
192
+ and: ({ values }) => {
193
+ if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
194
+ return values.every(truthOf);
195
+ },
196
+ or: ({ values }) => {
197
+ if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
198
+ return values.some(truthOf);
199
+ },
200
+ not: ({ value }) => !truthOf(value),
201
+ openUrl: ({ url }) => {
202
+ openUrlSafely(url);
203
+ }
204
+ };
205
+ /** True when the basic function `name` must run from a user gesture. */
206
+ function requiresUserActivation(name) {
207
+ return GENERATIVE_UI_FUNCTIONS[name]?.requiresUserActivation === true;
208
+ }
209
+ /** True when a basic function gives a ValidationResult. */
210
+ function givesValidationResult(name) {
211
+ return GENERATIVE_UI_FUNCTIONS[name]?.returnType === "validationResult";
212
+ }
213
+
214
+ //#endregion
215
+ //#region src/generative-ui/function-calls.ts
216
+ /** At most this many function follow-up runs for each user turn. */
217
+ const MAX_FUNCTION_FOLLOW_UPS = 5;
218
+ /** True when `value` names a `functionCallId`. */
219
+ function hasFunctionCallId(value) {
220
+ return typeof value === "object" && value !== null && "functionCallId" in value && typeof value.functionCallId === "string" && value.functionCallId !== "";
221
+ }
222
+ /** The `functionCallId` that a developer message answers, if any. */
223
+ function answeredCallId(content) {
224
+ if (!content.includes("rendererFunctionResponse")) return void 0;
225
+ try {
226
+ const parsed = JSON.parse(content);
227
+ const response = typeof parsed === "object" && parsed !== null && "rendererFunctionResponse" in parsed ? parsed.rendererFunctionResponse : void 0;
228
+ return hasFunctionCallId(response) ? response.functionCallId : void 0;
229
+ } catch {
230
+ return;
231
+ }
232
+ }
233
+ /** The function calls that a developer message in `messages` answers. */
234
+ function answeredCallIds(messages) {
235
+ const ids = /* @__PURE__ */ new Set();
236
+ for (const message of messages) {
237
+ if (message.role !== "developer") continue;
238
+ const id = answeredCallId(message.content);
239
+ if (id !== void 0) ids.add(id);
240
+ }
241
+ return ids;
242
+ }
243
+ /** The id of the last user message. A user turn starts with it. */
244
+ function lastUserMessageId(messages) {
245
+ for (let index = messages.length - 1; index >= 0; index--) {
246
+ const message = messages[index];
247
+ if (message?.role === "user") return message.id;
248
+ }
249
+ }
250
+ /** The function calls of the tool transport: its function-call activities. */
251
+ function activityFunctionCalls(messages) {
252
+ const requests = [];
253
+ for (const message of messages) {
254
+ if (!(message.role === "activity" && message.activityType === GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE) || !hasFunctionCallId(message.content)) continue;
255
+ requests.push({
256
+ functionCallId: message.content.functionCallId,
257
+ operation: {
258
+ version: A2UI_VERSION,
259
+ callRendererFunction: message.content
260
+ }
261
+ });
262
+ }
263
+ return requests;
264
+ }
265
+ /** The function calls of the markdown transport: its fence lines. */
266
+ function markdownFunctionCalls(calls) {
267
+ const requests = [];
268
+ for (const { operation } of calls) {
269
+ const payload = operation.callRendererFunction;
270
+ if (!hasFunctionCallId(payload)) continue;
271
+ requests.push({
272
+ functionCallId: payload.functionCallId,
273
+ operation
274
+ });
275
+ }
276
+ return requests;
277
+ }
278
+ /** The text of a `rendererFunctionResponse` developer message. */
279
+ function responseContent(response) {
280
+ return JSON.stringify({
281
+ version: A2UI_VERSION,
282
+ rendererFunctionResponse: response
283
+ });
284
+ }
285
+ function errorAnswer(functionCallId, code, message) {
286
+ return {
287
+ content: responseContent({
288
+ functionCallId,
289
+ error: {
290
+ code,
291
+ message
292
+ }
293
+ }),
294
+ followUp: true
295
+ };
296
+ }
297
+ const overCapAnswer = (functionCallId) => ({
298
+ content: responseContent({
299
+ functionCallId,
300
+ error: {
301
+ code: "follow_up_limit",
302
+ message: `The function did not run. A user turn can have at most ${MAX_FUNCTION_FOLLOW_UPS} function follow-up runs. Wait for the next user message.`
303
+ }
304
+ }),
305
+ followUp: false
306
+ });
307
+ /**
308
+ * Runs the functions that the agent calls with `callRendererFunction`, for
309
+ * both transports, and answers each call.
310
+ *
311
+ * - Each `functionCallId` runs once for each thread. A replay, a sync of
312
+ * the same messages again, or a call that already has an answer message
313
+ * does not run it again.
314
+ * - The answer is a hidden developer message with a `rendererFunctionResponse`.
315
+ * The answers go to the agent only when it is not running. Then one
316
+ * follow-up run starts for all of them.
317
+ * - A user turn has at most {@link MAX_FUNCTION_FOLLOW_UPS} follow-up runs.
318
+ * A call after that does not run. It gets a `follow_up_limit` error and
319
+ * starts no follow-up run.
320
+ */
321
+ function createFunctionCallRunner(options) {
322
+ const { core, dispatcher, manifest, settle, warn } = options;
323
+ const threads = /* @__PURE__ */ new Map();
324
+ const threadState = (threadId) => {
325
+ let state = threads.get(threadId);
326
+ if (!state) {
327
+ state = {
328
+ done: /* @__PURE__ */ new Set(),
329
+ pending: [],
330
+ turn: void 0,
331
+ followUps: 0,
332
+ flushing: false
333
+ };
334
+ threads.set(threadId, state);
335
+ }
336
+ return state;
337
+ };
338
+ const answer = async (request) => {
339
+ const { functionCallId } = request;
340
+ const validation = validateOperation(request.operation, {
341
+ manifest,
342
+ knownSurfaces: /* @__PURE__ */ new Set()
343
+ });
344
+ if (!validation.ok) return errorAnswer(functionCallId, "invalid_arguments", validation.reason);
345
+ const operation = request.operation;
346
+ if (!("callRendererFunction" in operation)) return errorAnswer(functionCallId, "invalid_arguments", "the operation is not a callRendererFunction");
347
+ const { callFunction } = operation.callRendererFunction;
348
+ const name = callFunction["@call"];
349
+ const result = await dispatcher.invoke(name, callFunction.args ?? {}, { functionCallId });
350
+ if (!result.ok) return errorAnswer(functionCallId, result.error.code, result.error.message);
351
+ try {
352
+ return {
353
+ content: responseContent({
354
+ functionCallId,
355
+ value: result.result ?? null
356
+ }),
357
+ followUp: true
358
+ };
359
+ } catch (cause) {
360
+ return errorAnswer(functionCallId, "handler_failed", `The result of "${name}" is not JSON: ${cause instanceof Error ? cause.message : String(cause)}`);
361
+ }
362
+ };
363
+ /**
364
+ * Adds the pending answers of a thread to the agent, then starts one
365
+ * follow-up run. It waits while the agent runs: the next read of the
366
+ * thread, at the end of the run, flushes again.
367
+ */
368
+ const flush = async (agent, threadId, state) => {
369
+ if (state.flushing) return;
370
+ state.flushing = true;
371
+ try {
372
+ while (state.pending.length > 0) {
373
+ const batch = [...state.pending];
374
+ const answers = await Promise.all(batch);
375
+ await settle();
376
+ if (agent.isRunning || agent.threadId !== threadId) return;
377
+ if (state.pending.length > batch.length) continue;
378
+ state.pending = [];
379
+ for (const { content } of answers) agent.addMessage({
380
+ id: randomUUID(),
381
+ role: "developer",
382
+ content
383
+ });
384
+ if (!answers.some((item) => item.followUp)) continue;
385
+ state.followUps++;
386
+ await core.runAgent({ agent });
387
+ }
388
+ } catch (error) {
389
+ warn("[generativeUI] function follow-up run failed:", error);
390
+ } finally {
391
+ state.flushing = false;
392
+ }
393
+ };
394
+ return { run(agent, requests, messages, running) {
395
+ const { threadId } = agent;
396
+ if (!threadId) return;
397
+ const state = threadState(threadId);
398
+ const turn = lastUserMessageId(messages);
399
+ if (turn !== state.turn) {
400
+ state.turn = turn;
401
+ state.followUps = 0;
402
+ }
403
+ const fresh = requests.filter((request) => !state.done.has(request.functionCallId));
404
+ const answered = fresh.length > 0 ? answeredCallIds(messages) : /* @__PURE__ */ new Set();
405
+ for (const request of fresh) {
406
+ const { functionCallId } = request;
407
+ if (state.done.has(functionCallId)) continue;
408
+ state.done.add(functionCallId);
409
+ if (answered.has(functionCallId)) continue;
410
+ const isOverCap = state.followUps >= MAX_FUNCTION_FOLLOW_UPS;
411
+ state.pending.push(isOverCap ? Promise.resolve(overCapAnswer(functionCallId)) : answer(request));
412
+ }
413
+ if (!running) flush(agent, threadId, state);
414
+ } };
415
+ }
416
+
417
+ //#endregion
418
+ //#region src/generative-ui/calc.ts
419
+ const MAX_SERIES = 1e3;
420
+ const OPERATORS = [
421
+ "&&",
422
+ "||",
423
+ "==",
424
+ "!=",
425
+ "<=",
426
+ ">=",
427
+ "<",
428
+ ">",
429
+ "+",
430
+ "-",
431
+ "*",
432
+ "/",
433
+ "%",
434
+ "^",
435
+ "(",
436
+ ")",
437
+ ",",
438
+ "?",
439
+ ":",
440
+ "!"
441
+ ];
442
+ function tokenize(source) {
443
+ const tokens = [];
444
+ let i = 0;
445
+ while (i < source.length) {
446
+ const char = source.charAt(i);
447
+ if (/\s/.test(char)) {
448
+ i++;
449
+ continue;
450
+ }
451
+ if (/[0-9.]/.test(char)) {
452
+ const match = /^\d*\.?\d+(?:[eE][-+]?\d+)?|^\d+\.?/.exec(source.slice(i));
453
+ if (!match) throw new ExpressionError(`calc: bad number at "${source.slice(i, i + 8)}"`);
454
+ tokens.push({
455
+ kind: "number",
456
+ value: Number(match[0])
457
+ });
458
+ i += match[0].length;
459
+ continue;
460
+ }
461
+ if (char === "'" || char === "\"") {
462
+ let value = "";
463
+ i++;
464
+ while (i < source.length && source[i] !== char) {
465
+ if (source[i] === "\\" && i + 1 < source.length) i++;
466
+ value += source.charAt(i++);
467
+ }
468
+ if (i >= source.length) throw new ExpressionError("calc: unclosed string");
469
+ i++;
470
+ tokens.push({
471
+ kind: "string",
472
+ value
473
+ });
474
+ continue;
475
+ }
476
+ if (/[A-Za-z_]/.test(char)) {
477
+ const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i));
478
+ tokens.push({
479
+ kind: "name",
480
+ value: match[0]
481
+ });
482
+ i += match[0].length;
483
+ continue;
484
+ }
485
+ const op = OPERATORS.find((candidate) => source.startsWith(candidate, i));
486
+ if (!op) throw new ExpressionError(`calc: unexpected "${char}"`);
487
+ tokens.push({
488
+ kind: "op",
489
+ value: op
490
+ });
491
+ i += op.length;
492
+ }
493
+ tokens.push({ kind: "end" });
494
+ return tokens;
495
+ }
496
+ function numberOf(value, what) {
497
+ if (typeof value === "number") {
498
+ if (!Number.isFinite(value)) throw new ExpressionError(`calc: ${what} is not finite`);
499
+ return value;
500
+ }
501
+ if (typeof value === "boolean") return value ? 1 : 0;
502
+ if (typeof value === "string" && value.trim() !== "") {
503
+ const parsed = Number(value);
504
+ if (Number.isFinite(parsed)) return parsed;
505
+ }
506
+ if (value === null || value === void 0) throw new ExpressionError(`calc: ${what} has no value`);
507
+ throw new ExpressionError(`calc: ${what} is not a number`);
508
+ }
509
+ function describe(value) {
510
+ return typeof value === "string" ? `"${value}"` : String(value);
511
+ }
512
+ const MATH = {
513
+ min: (args) => Math.min(...args),
514
+ max: (args) => Math.max(...args),
515
+ abs: ([x = NaN]) => Math.abs(x),
516
+ floor: ([x = NaN]) => Math.floor(x),
517
+ ceil: ([x = NaN]) => Math.ceil(x),
518
+ round: ([x = NaN, decimals = 0]) => {
519
+ const factor = 10 ** Math.trunc(decimals);
520
+ return Math.round(x * factor) / factor;
521
+ },
522
+ pow: ([x = NaN, y = NaN]) => x ** y,
523
+ sqrt: ([x = NaN]) => Math.sqrt(x),
524
+ exp: ([x = NaN]) => Math.exp(x),
525
+ ln: ([x = NaN]) => Math.log(x),
526
+ log10: ([x = NaN]) => Math.log10(x)
527
+ };
528
+ /** How many args a function takes, at least and at most; min and max take any. */
529
+ const ARITY = {
530
+ abs: [1, 1],
531
+ floor: [1, 1],
532
+ ceil: [1, 1],
533
+ round: [1, 2],
534
+ pow: [2, 2],
535
+ sqrt: [1, 1],
536
+ exp: [1, 1],
537
+ ln: [1, 1],
538
+ log10: [1, 1]
539
+ };
540
+ /** Named constants, when no arg of the same name is passed. */
541
+ const CONSTANTS = {
542
+ pi: Math.PI,
543
+ e: Math.E
544
+ };
545
+ const END = { kind: "end" };
546
+ var CalcParser = class {
547
+ pos = 0;
548
+ constructor(tokens, scope, source) {
549
+ this.tokens = tokens;
550
+ this.scope = scope;
551
+ this.source = source;
552
+ }
553
+ /** The current token. The list always ends with an "end" token. */
554
+ peek() {
555
+ return this.tokens[this.pos] ?? END;
556
+ }
557
+ parse() {
558
+ const value = this.ternary();
559
+ if (this.peek().kind !== "end") this.fail(`unexpected "${this.text(this.peek())}"`);
560
+ return value;
561
+ }
562
+ fail(what) {
563
+ throw new ExpressionError(`calc: ${what} in "${this.source}"`);
564
+ }
565
+ text(token) {
566
+ return token.kind === "end" ? "end" : String(token.value);
567
+ }
568
+ peekOp(...ops) {
569
+ const token = this.peek();
570
+ return token.kind === "op" && ops.includes(token.value) ? token.value : void 0;
571
+ }
572
+ expectOp(op) {
573
+ if (this.peekOp(op) === void 0) this.fail(`expected "${op}" but found "${this.text(this.peek())}"`);
574
+ this.pos++;
575
+ }
576
+ /**
577
+ * Parses a part of the expression that the result does not need (the
578
+ * other branch of `?:`, the right side of a decided `&&` or `||`). It
579
+ * still has to be parsed to find where it ends, so syntax errors are
580
+ * reported, but no value is checked or computed: `n == 0 ? 0 : 10 / n`
581
+ * is a valid guard.
582
+ */
583
+ skipped(parse) {
584
+ this.skipDepth++;
585
+ try {
586
+ parse();
587
+ } finally {
588
+ this.skipDepth--;
589
+ }
590
+ return null;
591
+ }
592
+ /** Above 0 while parsing a part whose value is not needed. */
593
+ skipDepth = 0;
594
+ /** The number of a value, or 0 while skipping. */
595
+ num(value, what) {
596
+ return this.skipDepth > 0 ? 0 : numberOf(value, what);
597
+ }
598
+ ternary() {
599
+ const condition = this.or();
600
+ if (this.peekOp("?") === void 0) return condition;
601
+ this.pos++;
602
+ const takesFirst = truthOf(condition);
603
+ const whenTrue = takesFirst ? this.ternary() : this.skipped(() => this.ternary());
604
+ this.expectOp(":");
605
+ const whenFalse = takesFirst ? this.skipped(() => this.ternary()) : this.ternary();
606
+ return takesFirst ? whenTrue : whenFalse;
607
+ }
608
+ or() {
609
+ let left = this.and();
610
+ while (this.peekOp("||")) {
611
+ this.pos++;
612
+ if (truthOf(left)) {
613
+ this.skipped(() => this.and());
614
+ left = true;
615
+ } else left = truthOf(this.and());
616
+ }
617
+ return left;
618
+ }
619
+ and() {
620
+ let left = this.equality();
621
+ while (this.peekOp("&&")) {
622
+ this.pos++;
623
+ if (!truthOf(left)) {
624
+ this.skipped(() => this.equality());
625
+ left = false;
626
+ } else left = truthOf(this.equality());
627
+ }
628
+ return left;
629
+ }
630
+ equality() {
631
+ let left = this.comparison();
632
+ for (let op = this.peekOp("==", "!="); op; op = this.peekOp("==", "!=")) {
633
+ this.pos++;
634
+ const right = this.comparison();
635
+ const isEqual = typeof left === "number" || typeof right === "number" ? this.num(left, "the left side of ==") === this.num(right, "the right side of ==") : left === right;
636
+ left = op === "==" ? isEqual : !isEqual;
637
+ }
638
+ return left;
639
+ }
640
+ comparison() {
641
+ let left = this.additive();
642
+ for (let op = this.peekOp("<", "<=", ">", ">="); op; op = this.peekOp("<", "<=", ">", ">=")) {
643
+ this.pos++;
644
+ const a = this.num(left, `the left side of ${op}`);
645
+ const b = this.num(this.additive(), `the right side of ${op}`);
646
+ left = op === "<" ? a < b : op === "<=" ? a <= b : op === ">" ? a > b : a >= b;
647
+ }
648
+ return left;
649
+ }
650
+ additive() {
651
+ let left = this.multiplicative();
652
+ for (let op = this.peekOp("+", "-"); op; op = this.peekOp("+", "-")) {
653
+ this.pos++;
654
+ const right = this.multiplicative();
655
+ if (op === "+" && (typeof left === "string" || typeof right === "string")) left = `${left ?? ""}${right ?? ""}`;
656
+ else {
657
+ const a = this.num(left, `the left side of ${op}`);
658
+ const b = this.num(right, `the right side of ${op}`);
659
+ left = op === "+" ? a + b : a - b;
660
+ }
661
+ }
662
+ return left;
663
+ }
664
+ multiplicative() {
665
+ let left = this.unary();
666
+ for (let op = this.peekOp("*", "/", "%"); op; op = this.peekOp("*", "/", "%")) {
667
+ this.pos++;
668
+ const a = this.num(left, `the left side of ${op}`);
669
+ const b = this.num(this.unary(), `the right side of ${op}`);
670
+ if (op !== "*" && b === 0 && this.skipDepth === 0) this.fail("division by zero");
671
+ left = op === "*" ? a * b : op === "/" ? a / b : a % b;
672
+ }
673
+ return left;
674
+ }
675
+ unary() {
676
+ if (this.peekOp("-")) {
677
+ this.pos++;
678
+ return -this.num(this.unary(), "the operand of -");
679
+ }
680
+ if (this.peekOp("!")) {
681
+ this.pos++;
682
+ return !truthOf(this.unary());
683
+ }
684
+ return this.power();
685
+ }
686
+ /** `a ^ b`: binds tighter than `*` and unary minus, right to left. */
687
+ power() {
688
+ const base = this.primary();
689
+ if (!this.peekOp("^")) return base;
690
+ this.pos++;
691
+ const exponent = this.unary();
692
+ if (this.skipDepth > 0) return null;
693
+ return this.finite(this.num(base, "the left side of ^") ** this.num(exponent, "the right side of ^"), "^");
694
+ }
695
+ finite(value, what) {
696
+ if (!Number.isFinite(value)) this.fail(`${what} has no finite result`);
697
+ return value;
698
+ }
699
+ primary() {
700
+ const token = this.peek();
701
+ this.pos++;
702
+ switch (token.kind) {
703
+ case "number": return token.value;
704
+ case "string": return token.value;
705
+ case "name": return this.name(token.value);
706
+ case "op":
707
+ if (token.value === "(") {
708
+ const value = this.ternary();
709
+ this.expectOp(")");
710
+ return value;
711
+ }
712
+ return this.fail(`unexpected "${token.value}"`);
713
+ case "end": return this.fail("missing value");
714
+ }
715
+ }
716
+ name(name) {
717
+ if (name === "true") return true;
718
+ if (name === "false") return false;
719
+ if (name === "null") return null;
720
+ if (this.peekOp("(")) {
721
+ this.pos++;
722
+ const args = [];
723
+ if (this.peekOp(")") === void 0) for (;;) {
724
+ args.push(this.num(this.ternary(), `an argument of ${name}`));
725
+ if (this.peekOp(",") === void 0) break;
726
+ this.pos++;
727
+ }
728
+ this.expectOp(")");
729
+ if (this.skipDepth > 0) return null;
730
+ const fn = Object.prototype.hasOwnProperty.call(MATH, name) ? MATH[name] : void 0;
731
+ if (!fn) this.fail(`unknown function ${name}`);
732
+ if (args.length === 0) this.fail(`${name} needs an argument`);
733
+ const [least, most] = ARITY[name] ?? [1, Infinity];
734
+ if (args.length < least || args.length > most) this.fail(`${name} takes ${least === most ? least : `${least} or ${most}`} argument${most === 1 ? "" : "s"}`);
735
+ return this.finite(fn(args), name);
736
+ }
737
+ if (this.skipDepth > 0) return null;
738
+ if (!Object.prototype.hasOwnProperty.call(this.scope, name)) {
739
+ const constant = Object.prototype.hasOwnProperty.call(CONSTANTS, name) ? CONSTANTS[name] : void 0;
740
+ if (constant !== void 0) return constant;
741
+ this.fail(`unknown name ${name}; pass it as an arg`);
742
+ }
743
+ const value = this.scope[name];
744
+ if (value !== null && typeof value !== "number" && typeof value !== "string" && typeof value !== "boolean") this.fail(`${name} is not a number, text or boolean (${describe(value)})`);
745
+ return value;
746
+ }
747
+ };
748
+ /**
749
+ * Evaluates `expression` with the names in `scope`. Gives a number, a
750
+ * string, a boolean or null. Throws an {@link ExpressionError} for a bad
751
+ * expression or a missing name.
752
+ */
753
+ function evaluateCalc(expression, scope) {
754
+ if (typeof expression !== "string" || expression.trim() === "") throw new ExpressionError("calc: expression must be a string");
755
+ return new CalcParser(tokenize(expression), scope, expression).parse();
756
+ }
757
+ /** The `calc` function: the expression is `args.expression`, the rest is the scope. */
758
+ function calc(args) {
759
+ const { expression, ...scope } = args;
760
+ return evaluateCalc(expression, scope);
761
+ }
762
+ const WHOLE_EXPRESSION = /^\$\{([^}]*)\}$/;
763
+ /**
764
+ * Fills `item` for one iteration: a string that is one `${...}` gives the
765
+ * typed value of the expression, a string with `${...}` inside it is
766
+ * interpolated as text, and objects and arrays are walked.
767
+ */
768
+ function fillItem(item, scope) {
769
+ if (typeof item === "string") {
770
+ const whole = WHOLE_EXPRESSION.exec(item);
771
+ if (whole) return evaluateCalc(whole[1], scope);
772
+ return item.replace(/\$\{([^}]*)\}/g, (_, expression) => {
773
+ const value = evaluateCalc(expression, scope);
774
+ return value === null ? "" : String(value);
775
+ });
776
+ }
777
+ if (Array.isArray(item)) return item.map((entry) => fillItem(entry, scope));
778
+ if (typeof item === "object" && item !== null) return Object.fromEntries(Object.entries(item).map(([key, value]) => [key, fillItem(value, scope)]));
779
+ return item;
780
+ }
781
+ /**
782
+ * The `series` function: `count` copies of `item`, with the loop variable
783
+ * (`variable`, default "i") counting from `start` (default 1) and the other
784
+ * args in scope of the `${...}` expressions of the item.
785
+ */
786
+ function series(args) {
787
+ const { count, item, variable, start, ...scope } = args;
788
+ const length = numberOf(count, "count");
789
+ if (!Number.isInteger(length) || length < 0) throw new ExpressionError("series: count must be a whole number");
790
+ if (length > MAX_SERIES) throw new ExpressionError(`series: count is at most ${MAX_SERIES}`);
791
+ if (item === void 0) throw new ExpressionError("series: item is required");
792
+ const name = variable === void 0 ? "i" : variable;
793
+ if (typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new ExpressionError("series: variable must be a name");
794
+ const first = start === void 0 ? 1 : numberOf(start, "start");
795
+ return Array.from({ length }, (_, index) => fillItem(item, {
796
+ ...scope,
797
+ [name]: first + index
798
+ }));
799
+ }
800
+
801
+ //#endregion
802
+ //#region src/generative-ui/resolve.ts
803
+ BASIC_FUNCTIONS.calc = calc;
804
+ BASIC_FUNCTIONS.series = series;
805
+ const NO_DATA = { get: () => void 0 };
806
+ BASIC_FUNCTIONS.formatString = (args) => resolveDynamicValue({
807
+ "@call": "formatString",
808
+ args
809
+ }, {
810
+ data: NO_DATA,
811
+ basePath: void 0
812
+ }).value;
813
+ /** Adds one segment to a JSON pointer: ("/items", "0") gives "/items/0". */
814
+ function joinPath(base, segment) {
815
+ return base === "/" ? `/${segment}` : `${base}/${segment}`;
816
+ }
817
+ /**
818
+ * The absolute data model path of a binding. A path without a leading "/"
819
+ * is relative to the current template item, or to the root outside of one.
820
+ */
821
+ function resolvePath(path, basePath) {
822
+ if (path.startsWith("/")) return path;
823
+ return joinPath(basePath ?? "/", path);
824
+ }
825
+ /**
826
+ * The index of the template item at `basePath`: its last segment.
827
+ * `undefined` outside of a template.
828
+ */
829
+ function templateIndex(basePath) {
830
+ if (basePath === void 0) return void 0;
831
+ const index = Number(basePath.slice(basePath.lastIndexOf("/") + 1));
832
+ return Number.isInteger(index) ? index : void 0;
833
+ }
834
+ /** The value of a ValidationResult where a boolean is expected. */
835
+ function coerce(value, keep) {
836
+ return !keep && isValidationResult(value) ? value.valid : value;
837
+ }
838
+ /**
839
+ * Resolves `value`. `keepValidation` keeps a ValidationResult as it is; by
840
+ * default it becomes its `valid` boolean, which is what every prop except
841
+ * a check condition wants.
842
+ */
843
+ function walk(value, state, keepValidation, scope = "outside") {
844
+ if (Array.isArray(value)) {
845
+ let changed = false;
846
+ const itemScope = scope === "list" ? "check" : "outside";
847
+ const items = value.map((item) => {
848
+ const next = walk(item, state, keepValidation, itemScope);
849
+ if (next !== item) changed = true;
850
+ return next;
851
+ });
852
+ return changed ? items : value;
853
+ }
854
+ if (!isRecord(value)) return value;
855
+ if (isPathBinding(value)) {
856
+ const path = resolvePath(value["@path"], state.context.basePath);
857
+ state.paths.add(path);
858
+ return state.context.data.get(path);
859
+ }
860
+ if (isCallBinding(value)) return call(value, state, keepValidation);
861
+ if (isActionBinding(value)) return value;
862
+ let changed = false;
863
+ const entries = Object.entries(value).map(([key, item]) => {
864
+ const next = walk(item, state, keepValidation || scope === "check" && key === "condition", key === "checks" ? "list" : "outside");
865
+ if (next !== item) changed = true;
866
+ return [key, next];
867
+ });
868
+ return changed ? Object.fromEntries(entries) : value;
869
+ }
870
+ function call(binding, state, keepValidation) {
871
+ const name = binding["@call"];
872
+ const rawArgs = binding.args ?? {};
873
+ if (!isRecord(rawArgs)) throw new ExpressionError(`the args of "${name}" must be an object`);
874
+ if (name === A2UI_INDEX_FUNCTION) {
875
+ const index = templateIndex(state.context.basePath);
876
+ if (index === void 0) return void 0;
877
+ const offset = walk(rawArgs.offset, state, false);
878
+ return index + (typeof offset === "number" ? offset : 0);
879
+ }
880
+ if (name === "formatString") {
881
+ const template = walk(rawArgs.value, state, false);
882
+ if (typeof template !== "string") throw new ExpressionError("formatString takes a string value");
883
+ return formatString(template, state);
884
+ }
885
+ const fn = Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name) ? BASIC_FUNCTIONS[name] : void 0;
886
+ if (!fn) throw new ExpressionError(`"${name}" is not a basic function`);
887
+ if (requiresUserActivation(name)) throw new ExpressionError(`"${name}" is not a value; bind it as the functionCall of an event`);
888
+ const result = fn(walk(rawArgs, state, false));
889
+ return givesValidationResult(name) ? coerce(result, keepValidation) : result;
890
+ }
891
+ function resolveDynamicValue(value, context, options = {}) {
892
+ const result = tryResolveDynamicValue(value, context, options);
893
+ if (!result.ok) throw result.error;
894
+ return result;
895
+ }
896
+ /**
897
+ * Like {@link resolveDynamicValue}, but a failure comes back as a result
898
+ * with the paths read so far, so the caller can keep watching them: a
899
+ * function that fails on an empty field works once the user fills it.
900
+ */
901
+ function tryResolveDynamicValue(value, context, options = {}) {
902
+ const state = {
903
+ context,
904
+ paths: /* @__PURE__ */ new Set()
905
+ };
906
+ try {
907
+ return {
908
+ ok: true,
909
+ value: walk(value, state, options.keepValidation ?? false, options.isChecks ? "list" : "outside"),
910
+ paths: state.paths
911
+ };
912
+ } catch (error) {
913
+ return {
914
+ ok: false,
915
+ error: error instanceof Error ? error : new Error(String(error)),
916
+ paths: state.paths
917
+ };
918
+ }
919
+ }
920
+ /** True when `value` holds a `{"@path"}` or `{"@call"}` at any depth. */
921
+ function containsDynamicValue(value) {
922
+ if (Array.isArray(value)) return value.some(containsDynamicValue);
923
+ if (!isRecord(value)) return false;
924
+ if (isPathBinding(value) || isCallBinding(value)) return true;
925
+ if (isActionBinding(value)) return false;
926
+ return Object.values(value).some(containsDynamicValue);
927
+ }
928
+ /**
929
+ * The `${...}` grammar of `formatString`:
930
+ *
931
+ * expression := path | literal | call
932
+ * path := "/" segments | identifier ("/" segments)*
933
+ * literal := 'text' | "text" | number | true | false | null
934
+ * call := identifier "(" [ name ":" expression ("," name ":" expression)* ] ")"
935
+ *
936
+ * A `\${` in the template is a literal `${`.
937
+ */
938
+ function formatString(template, state) {
939
+ let out = "";
940
+ let index = 0;
941
+ while (index < template.length) {
942
+ const start = template.indexOf("${", index);
943
+ if (start === -1) {
944
+ out += template.slice(index);
945
+ break;
946
+ }
947
+ if (start > 0 && template[start - 1] === "\\") {
948
+ out += `${template.slice(index, start - 1)}\${`;
949
+ index = start + 2;
950
+ continue;
951
+ }
952
+ out += template.slice(index, start);
953
+ const end = matchingBrace(template, start + 2);
954
+ if (end === -1) throw new ExpressionError("formatString: unclosed ${");
955
+ const value = new ExpressionParser(template.slice(start + 2, end).trim(), state).parse();
956
+ out += value === void 0 || value === null ? "" : String(value);
957
+ index = end + 1;
958
+ }
959
+ return out;
960
+ }
961
+ /** The index of the `}` that closes the block opened at `from`, or -1. */
962
+ function matchingBrace(template, from) {
963
+ let depth = 1;
964
+ let quote;
965
+ for (let i = from; i < template.length; i++) {
966
+ const char = template[i];
967
+ if (quote) {
968
+ if (char === "\\") i++;
969
+ else if (char === quote) quote = void 0;
970
+ continue;
971
+ }
972
+ if (char === "'" || char === "\"") quote = char;
973
+ else if (char === "{") depth++;
974
+ else if (char === "}" && --depth === 0) return i;
975
+ }
976
+ return -1;
977
+ }
978
+ const IDENTIFIER = /@?[A-Za-z_][A-Za-z0-9_-]*/y;
979
+ const NUMBER = /-?\d+(?:\.\d+)?/y;
980
+ const PATH_SEGMENT = /[^\s,():'"]+/y;
981
+ var ExpressionParser = class {
982
+ pos = 0;
983
+ constructor(source, state) {
984
+ this.source = source;
985
+ this.state = state;
986
+ }
987
+ parse() {
988
+ const value = this.expression();
989
+ this.skipSpace();
990
+ if (this.pos < this.source.length) throw new ExpressionError(`formatString: unexpected "${this.source.slice(this.pos)}" in \${${this.source}}`);
991
+ return value;
992
+ }
993
+ fail(what) {
994
+ throw new ExpressionError(`formatString: ${what} in \${${this.source}}`);
995
+ }
996
+ skipSpace() {
997
+ while (this.pos < this.source.length && /\s/.test(this.source.charAt(this.pos))) this.pos++;
998
+ }
999
+ match(pattern) {
1000
+ pattern.lastIndex = this.pos;
1001
+ const found = pattern.exec(this.source);
1002
+ if (!found) return void 0;
1003
+ this.pos = pattern.lastIndex;
1004
+ return found[0];
1005
+ }
1006
+ expression() {
1007
+ this.skipSpace();
1008
+ const char = this.source[this.pos];
1009
+ if (char === void 0) this.fail("missing expression");
1010
+ if (char === "'" || char === "\"") return this.quoted(char);
1011
+ if (char === "/") return this.path(this.match(PATH_SEGMENT) ?? "/");
1012
+ const number = this.match(NUMBER);
1013
+ if (number !== void 0) return Number(number);
1014
+ const name = this.match(IDENTIFIER);
1015
+ if (name === void 0) this.fail(`unexpected "${char}"`);
1016
+ if (name === "true") return true;
1017
+ if (name === "false") return false;
1018
+ if (name === "null") return null;
1019
+ this.skipSpace();
1020
+ if (this.source[this.pos] === "(") return this.call(name);
1021
+ if (name.startsWith("@")) return call({ "@call": name }, this.state, false);
1022
+ const rest = this.source[this.pos] === "/" ? this.match(PATH_SEGMENT) : "";
1023
+ return this.path(`${name}${rest ?? ""}`);
1024
+ }
1025
+ quoted(quote) {
1026
+ let value = "";
1027
+ this.pos++;
1028
+ while (this.pos < this.source.length) {
1029
+ const char = this.source[this.pos++];
1030
+ if (char === "\\" && this.pos < this.source.length) value += this.source[this.pos++];
1031
+ else if (char === quote) return value;
1032
+ else value += char;
1033
+ }
1034
+ return this.fail("unclosed string");
1035
+ }
1036
+ path(path) {
1037
+ const absolute = resolvePath(path, this.state.context.basePath);
1038
+ this.state.paths.add(absolute);
1039
+ return this.state.context.data.get(absolute);
1040
+ }
1041
+ call(name) {
1042
+ this.pos++;
1043
+ const args = {};
1044
+ this.skipSpace();
1045
+ if (this.source[this.pos] === ")") {
1046
+ this.pos++;
1047
+ return call({
1048
+ "@call": name,
1049
+ args
1050
+ }, this.state, false);
1051
+ }
1052
+ for (;;) {
1053
+ this.skipSpace();
1054
+ const key = this.match(IDENTIFIER);
1055
+ if (key === void 0) this.fail("expected an argument name");
1056
+ this.skipSpace();
1057
+ if (this.source[this.pos] !== ":") this.fail(`expected ":" after ${key}`);
1058
+ this.pos++;
1059
+ args[key] = this.expression();
1060
+ this.skipSpace();
1061
+ const next = this.source[this.pos++];
1062
+ if (next === ")") break;
1063
+ if (next !== ",") this.fail(`expected "," or ")" after ${key}`);
1064
+ }
1065
+ return call({
1066
+ "@call": name,
1067
+ args
1068
+ }, this.state, false);
1069
+ }
1070
+ };
1071
+
1072
+ //#endregion
1073
+ //#region src/generative-ui/surface-manager.ts
1074
+ function surfaceKey(threadId, surfaceId) {
1075
+ return `${threadId}::${surfaceId}`;
1076
+ }
1077
+ let creationCounter = 0;
1078
+ const FORBIDDEN_SEGMENTS = new Set([
1079
+ "__proto__",
1080
+ "constructor",
1081
+ "prototype"
1082
+ ]);
1083
+ /** "/a/b/" to "/a/b". The root stays "/". */
1084
+ function normalizePath(path) {
1085
+ return (path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path) || "/";
1086
+ }
1087
+ /** True when `path` is `ancestor` or below it. */
1088
+ function isAtOrBelow(path, ancestor) {
1089
+ if (ancestor === "/") return true;
1090
+ return path === ancestor || path.startsWith(`${ancestor}/`);
1091
+ }
1092
+ /**
1093
+ * Rejections as `"operation <index>: <reason>"` lines, cut to the size that
1094
+ * the envelope reader accepts.
1095
+ */
1096
+ function summarizeRejections(rejections) {
1097
+ return rejections.slice(0, GENERATIVE_UI_MAX_SUMMARY_REJECTIONS).map(({ index, reason }) => `operation ${index}: ${reason}`.slice(0, GENERATIVE_UI_MAX_REJECTION_LENGTH));
1098
+ }
1099
+ /**
1100
+ * Framework-agnostic store of generated surfaces. One web_core SurfaceModel per
1101
+ * (threadId, surfaceId), shared by every mount. Applies only newly committed
1102
+ * operations, validates each before applying it, and owns app state and the
1103
+ * data model paths that the user wrote, so agent updates cannot overwrite
1104
+ * them. App state never goes into a surface's data model. Selectors read it
1105
+ * with `getState()`.
1106
+ */
1107
+ var GenerativeUISurfaceManager = class {
1108
+ surfaces = /* @__PURE__ */ new Map();
1109
+ bookkeeping = /* @__PURE__ */ new Map();
1110
+ listeners = /* @__PURE__ */ new Set();
1111
+ /** Mounts of each target id, in mount order. */
1112
+ targets = /* @__PURE__ */ new Map();
1113
+ state = {};
1114
+ /**
1115
+ * User-owned data model values, by surface key, then by path. Kept when a
1116
+ * surface is rebuilt. Cleared when the surface is deleted.
1117
+ */
1118
+ owned = /* @__PURE__ */ new Map();
1119
+ /**
1120
+ * Keys of the surfaces that a `deleteSurface` removed. A surface id is
1121
+ * unique for the life of the page, so a key stays here when its surface is
1122
+ * built again.
1123
+ */
1124
+ deletedKeys = /* @__PURE__ */ new Set();
1125
+ /**
1126
+ * Surfaces that share their data model, by surface key: the parts of a
1127
+ * chat surface that the prose lift split. A user write to one part goes
1128
+ * to every part, so an input in one part drives a binding in another.
1129
+ */
1130
+ linked = /* @__PURE__ */ new Map();
1131
+ webCoreCatalog;
1132
+ activeThreadId;
1133
+ version = 0;
1134
+ constructor(ui, options = {}) {
1135
+ this.ui = ui;
1136
+ this.options = options;
1137
+ this.webCoreCatalog = new Catalog(ui.id, [...ui.components.keys()].map((name) => ({
1138
+ name,
1139
+ schema: z.any()
1140
+ })), []);
1141
+ }
1142
+ subscribe = (listener) => {
1143
+ this.listeners.add(listener);
1144
+ return () => {
1145
+ this.listeners.delete(listener);
1146
+ };
1147
+ };
1148
+ getVersion = () => this.version;
1149
+ notify() {
1150
+ this.version++;
1151
+ for (const listener of [...this.listeners]) listener();
1152
+ }
1153
+ setActiveThread(threadId) {
1154
+ if (threadId === this.activeThreadId) return;
1155
+ this.activeThreadId = threadId;
1156
+ this.notify();
1157
+ }
1158
+ getActiveThread() {
1159
+ return this.activeThreadId;
1160
+ }
1161
+ ingest(threadId, agentId, content) {
1162
+ const key = surfaceKey(threadId, content.surfaceId);
1163
+ const operations = content.operations ?? [];
1164
+ let surface = this.surfaces.get(key);
1165
+ let book = this.bookkeeping.get(key);
1166
+ let changed = false;
1167
+ if (surface && book && !this.extendsApplied(book, operations)) {
1168
+ this.disposeSurface(key);
1169
+ surface = void 0;
1170
+ book = void 0;
1171
+ }
1172
+ if (!surface || !book) {
1173
+ surface = this.createSurface(key, threadId, agentId, content);
1174
+ this.restoreOwnedValues(surface);
1175
+ book = {
1176
+ appliedCount: 0,
1177
+ lastFingerprint: void 0
1178
+ };
1179
+ this.surfaces.set(key, surface);
1180
+ this.bookkeeping.set(key, book);
1181
+ changed = true;
1182
+ }
1183
+ const serverRejected = content.rejected ?? [];
1184
+ if (surface.clientRejected.length > 0 && (surface.status !== "streaming" && content.status === "streaming" || serverRejected.length < surface.serverRejected.length)) {
1185
+ surface.clientRejected = [];
1186
+ changed = true;
1187
+ }
1188
+ if (operations.length > 0) {
1189
+ const lastFingerprint = JSON.stringify(operations[operations.length - 1]);
1190
+ const isReplay = operations.some((op) => getOperationKind(op) === "deleteSurface");
1191
+ for (let index = book.appliedCount; index < operations.length; index++) {
1192
+ this.applyOperation(surface, operations[index], {
1193
+ index,
1194
+ isReplay
1195
+ });
1196
+ changed = true;
1197
+ }
1198
+ book.appliedCount = operations.length;
1199
+ surface.operations = operations;
1200
+ book.lastFingerprint = lastFingerprint;
1201
+ }
1202
+ if (surface.status !== content.status || surface.target !== content.target || surface.serverRejected.length !== serverRejected.length) {
1203
+ surface.status = content.status;
1204
+ surface.target = content.target;
1205
+ surface.serverRejected = serverRejected;
1206
+ changed = true;
1207
+ }
1208
+ if (changed) this.notify();
1209
+ }
1210
+ /** The surface of a `key` (see `surfaceKey`), unless it is deleted. */
1211
+ getSurfaceByKey(key) {
1212
+ const surface = this.surfaces.get(key);
1213
+ return surface && !surface.deleted ? surface : void 0;
1214
+ }
1215
+ getSurface(threadId, surfaceId) {
1216
+ const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
1217
+ return surface && !surface.deleted ? surface : void 0;
1218
+ }
1219
+ getSurfaceForTarget(target, threadId = this.activeThreadId) {
1220
+ if (!threadId) return void 0;
1221
+ let latest;
1222
+ for (const surface of this.surfaces.values()) {
1223
+ if (surface.threadId !== threadId || surface.target !== target || surface.deleted) continue;
1224
+ if (!latest || surface.createdAt > latest.createdAt) latest = surface;
1225
+ }
1226
+ return latest;
1227
+ }
1228
+ /**
1229
+ * A surface whose first createSurface was rejected, so the chat can show
1230
+ * the error where the surface would be. `undefined` for any other surface.
1231
+ */
1232
+ getFailedSurface(threadId, surfaceId) {
1233
+ const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
1234
+ return surface?.failed ? surface : void 0;
1235
+ }
1236
+ /**
1237
+ * The surfaces of a thread, for the model. A surface with user-owned
1238
+ * values lists them in `dataModel`, so the model can read what the user
1239
+ * entered. A surface with dropped operations lists them in `rejected`, so
1240
+ * the model can fix them on the next run. A deleted surface, or one that
1241
+ * was never created, has a `status`, so the model knows that the id is
1242
+ * not a live surface.
1243
+ */
1244
+ describeSurfaces(threadId) {
1245
+ const described = {};
1246
+ for (const surface of this.surfaces.values()) {
1247
+ if (surface.threadId !== threadId) continue;
1248
+ const owned = this.owned.get(surface.key);
1249
+ const rejections = [...surface.serverRejected, ...surface.clientRejected];
1250
+ const status = this.deletedKeys.has(surface.key) ? "deleted" : surface.failed ? "failed" : void 0;
1251
+ described[surface.surfaceId] = {
1252
+ target: surface.target,
1253
+ ...owned && owned.size > 0 ? { dataModel: Object.fromEntries(owned) } : {},
1254
+ ...rejections.length > 0 && status !== "deleted" ? { rejected: summarizeRejections(rejections) } : {},
1255
+ ...status ? { status } : {}
1256
+ };
1257
+ }
1258
+ return described;
1259
+ }
1260
+ /** Every surface that is not deleted, oldest first, for the inspector. */
1261
+ debugSurfaces() {
1262
+ return [...this.surfaces.values()].filter((surface) => !surface.deleted).sort((a, b) => a.createdAt - b.createdAt).map((surface) => ({
1263
+ surfaceId: surface.surfaceId,
1264
+ threadId: surface.threadId,
1265
+ agentId: surface.agentId,
1266
+ target: surface.target,
1267
+ status: surface.status,
1268
+ operations: surface.operations,
1269
+ dataModel: surface.model.dataModel.get("/"),
1270
+ userValues: Object.fromEntries(this.owned.get(surface.key) ?? []),
1271
+ rejected: [...surface.serverRejected.map((r) => ({
1272
+ ...r,
1273
+ source: "runtime"
1274
+ })), ...surface.clientRejected.map((r) => ({
1275
+ ...r,
1276
+ source: "browser"
1277
+ }))]
1278
+ }));
1279
+ }
1280
+ /**
1281
+ * Marks a target as mounted. Returns the function that unmounts it. Calling
1282
+ * that function more than once has no effect.
1283
+ *
1284
+ * @param id - The target id.
1285
+ * @param options - The description and the allowed components of this mount.
1286
+ */
1287
+ registerTarget(id, options = {}) {
1288
+ const registration = { ...options };
1289
+ const registrations = this.targets.get(id) ?? /* @__PURE__ */ new Set();
1290
+ registrations.add(registration);
1291
+ this.targets.set(id, registrations);
1292
+ this.notify();
1293
+ let released = false;
1294
+ return () => {
1295
+ if (released) return;
1296
+ released = true;
1297
+ registrations.delete(registration);
1298
+ if (registrations.size === 0) this.targets.delete(id);
1299
+ this.notify();
1300
+ };
1301
+ }
1302
+ /**
1303
+ * The mounted targets. Each has the description and the component list of
1304
+ * its earliest mount that has one.
1305
+ */
1306
+ getMountedTargets() {
1307
+ const mounted = [];
1308
+ for (const [id, registrations] of this.targets) {
1309
+ const description = [...registrations].find((registration) => registration.description !== void 0)?.description;
1310
+ const components = this.targetComponents(id);
1311
+ mounted.push({
1312
+ id,
1313
+ ...description === void 0 ? {} : { description },
1314
+ ...components === void 0 ? {} : { components: [...components] }
1315
+ });
1316
+ }
1317
+ return mounted;
1318
+ }
1319
+ /**
1320
+ * The component list of the earliest mount of `id` that has one.
1321
+ * `undefined` when no mount of `id` limits its components.
1322
+ */
1323
+ targetComponents(id) {
1324
+ return [...this.targets.get(id) ?? /* @__PURE__ */ new Set()].find((registration) => registration.components !== void 0)?.components;
1325
+ }
1326
+ /** The components that `validateOperation` allows on a surface. */
1327
+ allowedComponentsFor(surface) {
1328
+ const components = this.targetComponents(surface.target);
1329
+ return components === void 0 ? void 0 : {
1330
+ target: surface.target,
1331
+ names: new Set(components)
1332
+ };
1333
+ }
1334
+ /**
1335
+ * The app state object. It is the same object until a key changes, so it
1336
+ * can be a `useSyncExternalStore` snapshot.
1337
+ */
1338
+ getState = () => this.state;
1339
+ /** Sets one state key. Notifies only when the value changed. */
1340
+ setState(key, value) {
1341
+ if (Object.hasOwn(this.state, key) && Object.is(this.state[key], value)) return;
1342
+ this.state = {
1343
+ ...this.state,
1344
+ [key]: value
1345
+ };
1346
+ this.notify();
1347
+ }
1348
+ /** Removes one state key. Notifies only when the key was set. */
1349
+ removeState(key) {
1350
+ if (!Object.hasOwn(this.state, key)) return;
1351
+ const { [key]: _removed, ...rest } = this.state;
1352
+ this.state = rest;
1353
+ this.notify();
1354
+ }
1355
+ /**
1356
+ * Makes the surfaces of `surfaceIds` share their data model: a user write
1357
+ * to one of them goes to all of them (see `setOwnedValue`). The markdown
1358
+ * transport links the parts of a chat surface that the prose lift split.
1359
+ * A later call for one of the surfaces replaces its group.
1360
+ *
1361
+ * @param threadId - The thread of the surfaces.
1362
+ * @param surfaceIds - The surface ids of the group. One id clears a link.
1363
+ */
1364
+ linkSurfaces(threadId, surfaceIds) {
1365
+ const keys = new Set(surfaceIds.map((id) => surfaceKey(threadId, id)));
1366
+ for (const key of keys) if (keys.size > 1) this.linked.set(key, keys);
1367
+ else this.linked.delete(key);
1368
+ }
1369
+ /**
1370
+ * Writes a user value into the data model of a surface, and marks `path`
1371
+ * as user-owned. Then agent writes to that path, or below it, are ignored.
1372
+ * An agent write above it keeps the user value. Ownership ends when the
1373
+ * surface is deleted. Does nothing for an unknown or deleted surface. The
1374
+ * surfaces linked to it (see `linkSurfaces`) get the same write.
1375
+ *
1376
+ * @param key - The `key` of the surface.
1377
+ * @param path - An absolute JSON pointer, for example "/form/email".
1378
+ * @param value - The new value. It is copied.
1379
+ * @throws Error when a path segment is "__proto__", "constructor" or
1380
+ * "prototype", or when the path does not fit the data (for example, a
1381
+ * segment above it holds a string).
1382
+ */
1383
+ setOwnedValue(key, path, value) {
1384
+ const normalized = normalizePath(path);
1385
+ const forbidden = normalized.split("/").find((segment) => FORBIDDEN_SEGMENTS.has(segment));
1386
+ if (forbidden !== void 0) throw new Error(`[generativeUI] path segment "${forbidden}" is not allowed in "${path}".`);
1387
+ for (const target of this.linked.get(key) ?? [key]) this.writeOwnedValue(target, normalized, value);
1388
+ }
1389
+ writeOwnedValue(key, path, value) {
1390
+ const surface = this.surfaces.get(key);
1391
+ if (!surface || surface.deleted) return;
1392
+ surface.model.dataModel.set(path, structuredClone(value));
1393
+ const owned = this.owned.get(key) ?? /* @__PURE__ */ new Map();
1394
+ owned.set(path, structuredClone(value));
1395
+ this.owned.set(key, owned);
1396
+ }
1397
+ /**
1398
+ * Writes the user-owned values into the new, empty data model of a rebuilt
1399
+ * surface. The agent operations are applied after it.
1400
+ */
1401
+ restoreOwnedValues(surface) {
1402
+ const owned = this.owned.get(surface.key) ?? /* @__PURE__ */ new Map();
1403
+ for (const [path, value] of owned) surface.model.dataModel.set(path, structuredClone(value));
1404
+ }
1405
+ /**
1406
+ * The value that an agent write puts at `path`, with the user-owned values
1407
+ * below `path` written back into it. `undefined` when `path` is user-owned
1408
+ * or below a user-owned path, so the agent cannot write it. Throws when a
1409
+ * user value does not fit the new value.
1410
+ */
1411
+ mergeOwnedValues(key, path, value) {
1412
+ const merged = { value: structuredClone(value) };
1413
+ const owned = this.owned.get(key);
1414
+ if (!owned) return merged;
1415
+ const ownedPaths = [...owned.keys()];
1416
+ if (ownedPaths.some((ownedPath) => isAtOrBelow(path, ownedPath))) return void 0;
1417
+ const below = ownedPaths.filter((ownedPath) => isAtOrBelow(ownedPath, path));
1418
+ if (below.length === 0) return merged;
1419
+ const scratch = new DataModel({ value: merged.value });
1420
+ const prefix = path === "/" ? "" : path;
1421
+ for (const ownedPath of below) {
1422
+ const relative = ownedPath.slice(prefix.length);
1423
+ scratch.set(`/value${relative}`, structuredClone(owned.get(ownedPath)));
1424
+ }
1425
+ return { value: scratch.get("/value") };
1426
+ }
1427
+ extendsApplied(book, operations) {
1428
+ if (operations.length < book.appliedCount) return false;
1429
+ if (book.appliedCount === 0) return true;
1430
+ return JSON.stringify(operations[book.appliedCount - 1]) === book.lastFingerprint;
1431
+ }
1432
+ createSurface(key, threadId, agentId, content) {
1433
+ return {
1434
+ key,
1435
+ threadId,
1436
+ surfaceId: content.surfaceId,
1437
+ agentId,
1438
+ model: new SurfaceModel(content.surfaceId, this.webCoreCatalog),
1439
+ createdAt: ++creationCounter,
1440
+ target: content.target,
1441
+ status: content.status,
1442
+ deleted: false,
1443
+ failed: false,
1444
+ serverRejected: content.rejected ?? [],
1445
+ clientRejected: [],
1446
+ operations: []
1447
+ };
1448
+ }
1449
+ disposeSurface(key) {
1450
+ this.surfaces.get(key)?.model.dispose();
1451
+ this.surfaces.delete(key);
1452
+ this.bookkeeping.delete(key);
1453
+ }
1454
+ /**
1455
+ * Marks a surface deleted and frees its components and data. The record
1456
+ * stays, so the model is still told about the id and the bookkeeping does
1457
+ * not rebuild the surface for content that was already applied.
1458
+ */
1459
+ closeSurface(surface) {
1460
+ surface.deleted = true;
1461
+ surface.model.dispose();
1462
+ surface.model = new SurfaceModel(surface.surfaceId, this.webCoreCatalog);
1463
+ this.owned.delete(surface.key);
1464
+ this.linked.delete(surface.key);
1465
+ }
1466
+ /** The surfaces of a thread that a part of `surfaceId` reads, for tests. */
1467
+ getLinkedSurfaceIds(threadId, surfaceId) {
1468
+ const keys = this.linked.get(surfaceKey(threadId, surfaceId));
1469
+ if (!keys) return [surfaceId];
1470
+ const prefix = `${threadId}::`;
1471
+ return [...keys].map((key) => key.slice(prefix.length));
1472
+ }
1473
+ /**
1474
+ * Drops the node keys that the app sets: bound props and matched events.
1475
+ * The model does not see them, so a model value for one is ignored, not
1476
+ * rejected. This runs before validation, because validation rejects keys
1477
+ * that are not in the manifest. It never changes the given operation.
1478
+ */
1479
+ dropAppSetKeys(op) {
1480
+ const kind = getOperationKind(op);
1481
+ if (kind !== "updateComponents" && kind !== "createSurface") return op;
1482
+ const record = op;
1483
+ const payload = record[kind];
1484
+ const nodes = payload?.components;
1485
+ if (!Array.isArray(nodes)) return op;
1486
+ return {
1487
+ ...record,
1488
+ [kind]: {
1489
+ ...payload,
1490
+ components: nodes.map((node) => this.dropAppSetNodeKeys(node))
1491
+ }
1492
+ };
1493
+ }
1494
+ dropAppSetNodeKeys(node) {
1495
+ if (typeof node !== "object" || node === null || !("component" in node)) return node;
1496
+ const { component } = node;
1497
+ if (typeof component !== "string") return node;
1498
+ const definition = this.ui.components.get(component);
1499
+ if (!definition) return node;
1500
+ return Object.fromEntries(Object.entries(node).filter(([key]) => !Object.hasOwn(definition.selectors, key) && !Object.hasOwn(definition.eventFunctions, key)));
1501
+ }
1502
+ /**
1503
+ * The surfaces that `validateOperation` gets for one operation of the
1504
+ * content of `surface`.
1505
+ *
1506
+ * - `knownSurfaces`: the surface, when it exists before the operation. It
1507
+ * does not exist before its first createSurface, or after a delete.
1508
+ * - `createdSurfaces`: the surface, when a createSurface at this position
1509
+ * uses its id again. That is the case after the first operation, and for
1510
+ * a surface that was deleted before, unless the content replays that
1511
+ * delete.
1512
+ */
1513
+ surfacesFor(surface, kind, position) {
1514
+ const isFirstCreate = kind === "createSurface" && position.index === 0;
1515
+ const exists = !surface.deleted && !isFirstCreate;
1516
+ const isRecreate = this.deletedKeys.has(surface.key) && !position.isReplay;
1517
+ const isUsedAgain = position.index > 0 || isRecreate;
1518
+ return {
1519
+ knownSurfaces: new Set(exists ? [surface.surfaceId] : []),
1520
+ createdSurfaces: new Set(isUsedAgain ? [surface.surfaceId] : [])
1521
+ };
1522
+ }
1523
+ applyOperation(surface, received, position) {
1524
+ const { index } = position;
1525
+ const kind = getOperationKind(received);
1526
+ if (kind === "callRendererFunction") return;
1527
+ const reject = (reason) => {
1528
+ if (kind === "createSurface" && index === 0) {
1529
+ this.closeSurface(surface);
1530
+ surface.failed = true;
1531
+ }
1532
+ surface.clientRejected.push({
1533
+ index,
1534
+ reason
1535
+ });
1536
+ this.options.onOperationRejected?.({
1537
+ surfaceId: surface.surfaceId,
1538
+ index,
1539
+ reason
1540
+ });
1541
+ };
1542
+ const targetId = getOperationSurfaceId(received);
1543
+ if (targetId !== void 0 && targetId !== surface.surfaceId) return reject(`operation is for surface "${targetId}", not "${surface.surfaceId}"`);
1544
+ const op = this.dropAppSetKeys(received);
1545
+ const validation = validateOperation(op, {
1546
+ manifest: {
1547
+ catalogId: this.ui.id,
1548
+ catalogIds: catalogIdsOf(this.ui),
1549
+ components: this.ui.manifestComponents
1550
+ },
1551
+ ...this.surfacesFor(surface, kind, position),
1552
+ allowedComponents: this.allowedComponentsFor(surface)
1553
+ });
1554
+ if (!validation.ok) return reject(validation.reason);
1555
+ const typed = op;
1556
+ if ("createSurface" in typed) {
1557
+ const { dataModel, components = [] } = typed.createSurface;
1558
+ const problem = this.nodesProblem(components);
1559
+ if (problem) return reject(problem);
1560
+ if (dataModel) {
1561
+ const failure = this.writeAgentData(surface, "/", dataModel);
1562
+ if (failure) return reject(failure);
1563
+ }
1564
+ for (const node of components) this.upsertNode(surface.model, node);
1565
+ return;
1566
+ }
1567
+ if ("updateComponents" in typed) {
1568
+ const nodes = typed.updateComponents.components;
1569
+ const problem = this.nodesProblem(nodes);
1570
+ if (problem) return reject(problem);
1571
+ for (const node of nodes) this.upsertNode(surface.model, node);
1572
+ return;
1573
+ }
1574
+ if ("updateDataModel" in typed) {
1575
+ const { path = "/", value } = typed.updateDataModel;
1576
+ const written = value === null ? void 0 : value;
1577
+ const failure = this.writeAgentData(surface, normalizePath(path), written);
1578
+ if (failure) return reject(failure);
1579
+ return;
1580
+ }
1581
+ if ("deleteSurface" in typed) {
1582
+ this.closeSurface(surface);
1583
+ this.deletedKeys.add(surface.key);
1584
+ }
1585
+ }
1586
+ /** The first node with props of the wrong type, as a reason. */
1587
+ nodesProblem(nodes) {
1588
+ for (const node of nodes) {
1589
+ const problem = this.checkNodeProps(node);
1590
+ if (problem) return `component "${node.id}": ${problem}`;
1591
+ }
1592
+ }
1593
+ /**
1594
+ * Writes an agent value at `path` and keeps the user-owned values. A write
1595
+ * to a user-owned path is ignored, not rejected. Gives the reason when the
1596
+ * value does not fit the data, else `undefined`.
1597
+ */
1598
+ writeAgentData(surface, path, value) {
1599
+ try {
1600
+ const merged = this.mergeOwnedValues(surface.key, path, value);
1601
+ if (merged) surface.model.dataModel.set(path, merged.value);
1602
+ return;
1603
+ } catch (error) {
1604
+ return error instanceof Error ? error.message : String(error);
1605
+ }
1606
+ }
1607
+ checkNodeProps(node) {
1608
+ const definition = this.ui.components.get(node.component);
1609
+ if (!definition) return `unknown component "${node.component}"`;
1610
+ const { id: _id, component: _component, ...rest } = node;
1611
+ const dataProps = Object.fromEntries(Object.entries(rest).filter(([key]) => !definition.events?.[key] && !definition.slots?.[key] && !A2UI_COMPONENT_ENVELOPE_KEYS.has(key)));
1612
+ if (!definition.props) return void 0;
1613
+ const unknownNow = new Set(Object.keys(definition.selectors));
1614
+ const literals = {};
1615
+ for (const [key, value] of Object.entries(dataProps)) if (containsDynamicValue(value)) unknownNow.add(key);
1616
+ else literals[key] = value;
1617
+ let result = validateSchemaSync(definition.props, literals);
1618
+ if (!result.success) {
1619
+ const unset = withoutRejectedNulls(literals, result.issues);
1620
+ if (unset) result = validateSchemaSync(definition.props, unset);
1621
+ }
1622
+ if (result.success) return void 0;
1623
+ const issues = result.issues.filter((issue) => {
1624
+ const key = issueKey(issue);
1625
+ return key === void 0 ? isAsyncIssue(issue) : !unknownNow.has(key);
1626
+ });
1627
+ return issues.length > 0 ? formatIssues(issues) : void 0;
1628
+ }
1629
+ upsertNode(model, node) {
1630
+ const { id, component, ...rest } = node;
1631
+ const properties = structuredClone(rest);
1632
+ const existing = model.componentsModel.get(id);
1633
+ if (existing && existing.type === component) {
1634
+ existing.properties = properties;
1635
+ return;
1636
+ }
1637
+ if (existing) model.componentsModel.removeComponent(id);
1638
+ model.componentsModel.addComponent(new ComponentModel(id, component, properties));
1639
+ }
1640
+ };
1641
+
1642
+ //#endregion
1643
+ //#region src/generative-ui/dispatcher.ts
1644
+ const messageOf = (error) => error instanceof Error ? error.message : String(error);
1645
+ /**
1646
+ * Creates the registry of functions that generated UI may call.
1647
+ *
1648
+ * A function is callable when it is declared in `getDeclared()` and exactly
1649
+ * one handler is mounted for it with `register`. Names are resolved at call
1650
+ * time and fail closed. Nothing is sent to the agent.
1651
+ * Neither `invoke` nor `listExposed` throws.
1652
+ *
1653
+ * @param options.getDeclared - Returns the declared functions.
1654
+ * @param options.onError - Gets each failed call.
1655
+ *
1656
+ * @example
1657
+ * ```ts
1658
+ * const dispatcher = createGenerativeUIDispatcher({
1659
+ * getDeclared: () => new Map(Object.entries(ui.functions)),
1660
+ * });
1661
+ * const unregister = dispatcher.register("addToCart", handlerRef);
1662
+ * await dispatcher.invoke("addToCart", { productId: "p1" }, origin);
1663
+ * unregister();
1664
+ * ```
1665
+ */
1666
+ /**
1667
+ * True while the browser counts the current task as user-activated (a
1668
+ * click, a key press). Where the API is missing (older browsers, test
1669
+ * environments), the gesture is assumed.
1670
+ */
1671
+ function hasUserActivation() {
1672
+ if (typeof navigator === "undefined") return true;
1673
+ const activation = navigator.userActivation;
1674
+ return activation === void 0 || activation.isActive;
1675
+ }
1676
+ /**
1677
+ * The permissions of a declared function as the manifest states them: the
1678
+ * callers always written out, so a reader needs no default.
1679
+ */
1680
+ function permissionsOf(fn) {
1681
+ const callers = functionCallers(fn);
1682
+ return {
1683
+ allowedCallers: callers.renderer && callers.agent ? "rendererOrAgent" : callers.agent ? "agentOnly" : "rendererOnly",
1684
+ ...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
1685
+ };
1686
+ }
1687
+ function createGenerativeUIDispatcher(options) {
1688
+ const handlers = /* @__PURE__ */ new Map();
1689
+ const resolveUnchecked = (name) => {
1690
+ const declared = options.getDeclared().get(name);
1691
+ if (!declared) return {
1692
+ ok: false,
1693
+ error: new GenerativeUIError("function_not_found", `No generative UI function named "${name}" is declared in createGenerativeUI({ functions })`)
1694
+ };
1695
+ const mounted = [...handlers.get(name) ?? []];
1696
+ const [ref] = mounted;
1697
+ if (!ref) return {
1698
+ ok: false,
1699
+ error: new GenerativeUIError("function_not_found", `"${name}" is declared, but no useGenerativeUIFunction handler is mounted for it`)
1700
+ };
1701
+ if (mounted.length > 1) return {
1702
+ ok: false,
1703
+ error: new GenerativeUIError("function_conflict", `"${name}" has ${mounted.length} useGenerativeUIFunction handlers mounted. Mount exactly one.`)
1704
+ };
1705
+ return {
1706
+ ok: true,
1707
+ declared,
1708
+ ref
1709
+ };
1710
+ };
1711
+ const isDeclared = (name) => {
1712
+ try {
1713
+ return options.getDeclared().has(name);
1714
+ } catch {
1715
+ return false;
1716
+ }
1717
+ };
1718
+ const resolve = (name) => {
1719
+ try {
1720
+ return resolveUnchecked(name);
1721
+ } catch (error) {
1722
+ return {
1723
+ ok: false,
1724
+ error: new GenerativeUIError("handler_failed", `"${name}" could not be resolved: ${messageOf(error)}`)
1725
+ };
1726
+ }
1727
+ };
1728
+ const validateArgs = async (name, schema, args) => {
1729
+ try {
1730
+ const validation = await schema["~standard"].validate(args);
1731
+ if (!validation.issues) return {
1732
+ ok: true,
1733
+ value: validation.value
1734
+ };
1735
+ return {
1736
+ ok: false,
1737
+ error: new GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": ${validation.issues.map((i) => `${(i.path ?? []).map((p) => typeof p === "object" ? p.key : p).join(".") || "args"}: ${i.message}`).join("; ")}`)
1738
+ };
1739
+ } catch (error) {
1740
+ return {
1741
+ ok: false,
1742
+ error: new GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": ${messageOf(error)}`)
1743
+ };
1744
+ }
1745
+ };
1746
+ const failWith = (name, origin, error) => {
1747
+ try {
1748
+ options.onError?.({
1749
+ name,
1750
+ origin,
1751
+ error
1752
+ });
1753
+ } catch {}
1754
+ return {
1755
+ ok: false,
1756
+ error
1757
+ };
1758
+ };
1759
+ /**
1760
+ * Why `origin` may not call a function with these permissions now, as an
1761
+ * error, or `undefined` when it may. The agent is refused what is for the
1762
+ * renderer; a component is refused what is for the agent, and a gesture
1763
+ * function when the browser counts no user activation.
1764
+ */
1765
+ const callerError = (name, fn, origin) => {
1766
+ const isComponent = "componentId" in origin;
1767
+ if (!isComponent && !GENERATIVE_UI_AGENT_FUNCTION_CALLS) return new GenerativeUIError("invalid_function_call", GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON);
1768
+ const problem = callerProblem(name, fn, isComponent ? "renderer" : "agent");
1769
+ if (problem !== void 0) return new GenerativeUIError("invalid_function_call", problem);
1770
+ if (isComponent && fn.requiresUserActivation && !hasUserActivation()) return new GenerativeUIError("invalid_function_call", `function "${name}" runs only from a user gesture; this event was not one`);
1771
+ };
1772
+ /**
1773
+ * Runs a basic function of the A2UI catalog. They are value functions of
1774
+ * the renderer: the agent cannot call them, and one that needs a user
1775
+ * gesture runs only from an event binding.
1776
+ */
1777
+ const invokeBasic = (name, args, origin) => {
1778
+ const info = GENERATIVE_UI_FUNCTIONS[name];
1779
+ const run = BASIC_FUNCTIONS[name];
1780
+ if (!info || !run) return failWith(name, origin, new GenerativeUIError("function_not_found", `"${name}" is not a basic function`));
1781
+ const refused = callerError(name, info, origin);
1782
+ if (refused) return failWith(name, origin, refused);
1783
+ if (args !== void 0 && !(typeof args === "object" && args !== null && !Array.isArray(args))) return failWith(name, origin, new GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": args must be an object`));
1784
+ try {
1785
+ return {
1786
+ ok: true,
1787
+ result: run(args ?? {})
1788
+ };
1789
+ } catch (error) {
1790
+ return failWith(name, origin, new GenerativeUIError(error instanceof ExpressionError ? "invalid_arguments" : "handler_failed", `"${name}" failed: ${messageOf(error)}`));
1791
+ }
1792
+ };
1793
+ return {
1794
+ async invoke(name, args, origin) {
1795
+ const resolved = resolve(name);
1796
+ if (!resolved.ok && resolved.error.code === "function_not_found" && !isDeclared(name) && Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name)) return invokeBasic(name, args, origin);
1797
+ if (!resolved.ok) return failWith(name, origin, resolved.error);
1798
+ const refused = callerError(name, resolved.declared, origin);
1799
+ if (refused) return failWith(name, origin, refused);
1800
+ const validated = await validateArgs(name, resolved.declared.parameters, args ?? {});
1801
+ if (!validated.ok) return failWith(name, origin, validated.error);
1802
+ try {
1803
+ return {
1804
+ ok: true,
1805
+ result: await resolved.ref.current(validated.value)
1806
+ };
1807
+ } catch (error) {
1808
+ return failWith(name, origin, new GenerativeUIError("handler_failed", `"${name}" failed: ${messageOf(error)}`));
1809
+ }
1810
+ },
1811
+ listExposed() {
1812
+ let names;
1813
+ try {
1814
+ names = [...options.getDeclared().keys()];
1815
+ } catch {
1816
+ return {};
1817
+ }
1818
+ const listed = {};
1819
+ for (const name of names) {
1820
+ const resolved = resolve(name);
1821
+ if (!resolved.ok) continue;
1822
+ if (!functionCallers(resolved.declared).renderer && !GENERATIVE_UI_AGENT_FUNCTION_CALLS) continue;
1823
+ const { description, parameters, returnType } = resolved.declared;
1824
+ try {
1825
+ listed[name] = {
1826
+ ...description ? { description } : {},
1827
+ parameters: toJsonSchema(parameters),
1828
+ ...returnType ? { returnType } : {},
1829
+ ...permissionsOf(resolved.declared)
1830
+ };
1831
+ } catch {}
1832
+ }
1833
+ return listed;
1834
+ },
1835
+ register(name, ref) {
1836
+ const mounted = handlers.get(name) ?? /* @__PURE__ */ new Set();
1837
+ mounted.add(ref);
1838
+ handlers.set(name, mounted);
1839
+ return () => {
1840
+ mounted.delete(ref);
1841
+ };
1842
+ },
1843
+ handlerCount: (name) => handlers.get(name)?.size ?? 0
1844
+ };
1845
+ }
1846
+
1847
+ //#endregion
1848
+ //#region src/generative-ui/events.ts
1849
+ /**
1850
+ * The context of a running event binding: it reads the surface data model
1851
+ * and resolves relative paths against the template item of the component.
1852
+ * A function that needs a user gesture (openUrl) is not a value here
1853
+ * either; it runs through the dispatcher as the binding's functionCall.
1854
+ */
1855
+ function eventContext(surface, basePath) {
1856
+ return {
1857
+ data: surface.model.dataModel,
1858
+ basePath
1859
+ };
1860
+ }
1861
+ /**
1862
+ * A value of an event binding with its dynamic values resolved: `{"@path"}`
1863
+ * bindings and function values, at any depth.
1864
+ */
1865
+ function resolveValue(surface, basePath, value) {
1866
+ return resolveDynamicValue(value, eventContext(surface, basePath)).value;
1867
+ }
1868
+ /**
1869
+ * The entries of an args or context record, each resolved on its own. The
1870
+ * record is not resolved as a whole, because a record with one `event` or
1871
+ * `functionCall` key would look like an action binding and stay as it is.
1872
+ */
1873
+ function resolveValues(surface, basePath, values) {
1874
+ return Object.fromEntries(Object.entries(values ?? {}).map(([key, value]) => [key, resolveValue(surface, basePath, value)]));
1875
+ }
1876
+ /**
1877
+ * The `userMessage` of an event binding, as text. A `{"@path"}` or a
1878
+ * function value is resolved. `undefined` when there is no message, or
1879
+ * the value is not a string.
1880
+ */
1881
+ function resolveUserMessage(surface, basePath, userMessage) {
1882
+ const value = resolveValue(surface, basePath, userMessage);
1883
+ return typeof value === "string" ? value : void 0;
1884
+ }
1885
+ /**
1886
+ * Validates the component's args with the event `parameters`, then runs
1887
+ * `send` with them. Never throws: every failure is reported and becomes
1888
+ * `{ ok: false, error }`.
1889
+ */
1890
+ async function runEvent(call, send) {
1891
+ const { runtime, surface, componentId, name, parameters, args } = call;
1892
+ const origin = {
1893
+ surfaceId: surface.surfaceId,
1894
+ componentId
1895
+ };
1896
+ try {
1897
+ if (!parameters) return await send(args ?? {}, origin);
1898
+ const result = validateSchema(parameters, args ?? {});
1899
+ const parsed = result instanceof Promise ? await result : result;
1900
+ if (!parsed.success) {
1901
+ const error = new GenerativeUIError("invalid_event_args", `${name}: ${formatIssues(parsed.issues, "args")}`);
1902
+ reportErrorSafely(runtime, {
1903
+ kind: "event",
1904
+ ...origin,
1905
+ error
1906
+ });
1907
+ return {
1908
+ ok: false,
1909
+ error
1910
+ };
1911
+ }
1912
+ return await send(parsed.data ?? {}, origin);
1913
+ } catch (cause) {
1914
+ const error = new GenerativeUIError("event_forward_failed", `${name}: ${cause instanceof Error ? cause.message : String(cause)}`);
1915
+ reportErrorSafely(runtime, {
1916
+ kind: "event",
1917
+ ...origin,
1918
+ error
1919
+ });
1920
+ return {
1921
+ ok: false,
1922
+ error
1923
+ };
1924
+ }
1925
+ }
1926
+ /**
1927
+ * Runs one call of an event that the model bound: validates the component's
1928
+ * args, merges them with the args from the binding (binding literals win),
1929
+ * then calls a declared function or forwards an agent event. Never throws.
1930
+ */
1931
+ function invokeBoundEvent(params) {
1932
+ const { runtime, surface, binding, basePath } = params;
1933
+ return runEvent(params, (args, origin) => {
1934
+ const componentArgs = args;
1935
+ if ("functionCall" in binding) return runtime.dispatcher.invoke(binding.functionCall["@call"], {
1936
+ ...componentArgs,
1937
+ ...resolveValues(surface, basePath, binding.functionCall.args)
1938
+ }, origin);
1939
+ const { event } = binding;
1940
+ const forwarded = {
1941
+ name: event.name,
1942
+ ...origin,
1943
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1944
+ userMessage: resolveUserMessage(surface, basePath, event.userMessage),
1945
+ context: {
1946
+ ...componentArgs,
1947
+ ...resolveValues(surface, basePath, event.context)
1948
+ }
1949
+ };
1950
+ return runtime.forwardEvent(forwarded, surface.agentId);
1951
+ });
1952
+ }
1953
+ /**
1954
+ * Runs one call of an event that matches a declared function: validates the
1955
+ * component's args with the event `parameters` (if any), then calls the
1956
+ * function, which validates them with its own schema. Never throws.
1957
+ */
1958
+ function invokeMatchedEvent(params) {
1959
+ const { runtime, functionName } = params;
1960
+ return runEvent(params, (componentArgs, origin) => runtime.dispatcher.invoke(functionName, componentArgs, origin));
1961
+ }
1962
+
1963
+ //#endregion
1964
+ //#region src/generative-ui/manifest.ts
1965
+ /**
1966
+ * The built-in functions (the A2UI basic catalog plus calc and series) as
1967
+ * manifest entries. Their args are described by the short signature, not
1968
+ * by a full JSON Schema: the renderer checks them when they run. An app
1969
+ * function of the same name replaces the entry.
1970
+ */
1971
+ function builtInFunctionManifests() {
1972
+ return Object.fromEntries(Object.entries(GENERATIVE_UI_FUNCTIONS).map(([name, fn]) => [name, {
1973
+ description: fn.description,
1974
+ parameters: {
1975
+ type: "object",
1976
+ description: fn.parameters
1977
+ },
1978
+ returnType: fn.returnType,
1979
+ allowedCallers: fn.allowedCallers,
1980
+ ...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
1981
+ }]));
1982
+ }
1983
+ /**
1984
+ * The manifest of a catalog, with no React runtime: the components of `ui`,
1985
+ * the built-in functions (minus the names the app declares) and
1986
+ * `options.functions`, the chat target and `options.targets`, and
1987
+ * `options.surfaces`. `buildGenerativeUIManifest` builds the per-run
1988
+ * manifest with it; tools that run outside React use it directly.
1989
+ *
1990
+ * @example
1991
+ * ```ts
1992
+ * const manifest = buildCatalogManifest(standardUI);
1993
+ * manifest.targets; // [{ id: "chat", kind: "chat" }]
1994
+ * ```
1995
+ */
1996
+ function buildCatalogManifest(ui, options = {}) {
1997
+ return {
1998
+ catalogId: ui.id,
1999
+ catalogIds: catalogIdsOf(ui),
2000
+ components: applyDescriptionOverrides({ components: ui.manifestComponents }, defaultGenerativeUIPromptSpec().descriptions).manifest.components,
2001
+ functions: {
2002
+ ...Object.fromEntries(Object.entries(builtInFunctionManifests()).filter(([name]) => !ui.functions.has(name))),
2003
+ ...options.functions
2004
+ },
2005
+ targets: [{
2006
+ id: GENERATIVE_UI_CHAT_TARGET,
2007
+ kind: "chat"
2008
+ }, ...options.targets ?? []],
2009
+ surfaces: options.surfaces ?? {}
2010
+ };
2011
+ }
2012
+ /**
2013
+ * Builds the per-run manifest. Never contains handlers or renderers.
2014
+ *
2015
+ * - `functions`: the built-in functions, then the declared functions with
2016
+ * exactly one mounted handler.
2017
+ * - `targets`: the chat first, then each mounted `<GenerativeUISurface>`,
2018
+ * with its `description` and its `components` when it has them.
2019
+ */
2020
+ function buildGenerativeUIManifest(runtime, threadId) {
2021
+ const { ui, manager, dispatcher } = runtime;
2022
+ const inlineTargets = manager.getMountedTargets().filter((target) => target.id !== GENERATIVE_UI_CHAT_TARGET).map(({ id, ...rest }) => ({
2023
+ id,
2024
+ kind: "inline",
2025
+ ...rest
2026
+ }));
2027
+ return buildCatalogManifest(ui, {
2028
+ functions: dispatcher.listExposed(),
2029
+ targets: inlineTargets,
2030
+ surfaces: threadId ? manager.describeSurfaces(threadId) : {}
2031
+ });
2032
+ }
2033
+ /** What the envelope of a run says, from the provider config. */
2034
+ function envelopeOptionsFor(config) {
2035
+ if (config.transport === "markdown") return {
2036
+ transport: "markdown",
2037
+ includeCatalog: config.includeCatalog !== false,
2038
+ contextSent: config.sendContext !== false
2039
+ };
2040
+ return {
2041
+ transport: "tool",
2042
+ includeCatalog: true,
2043
+ contextSent: false
2044
+ };
2045
+ }
2046
+ /**
2047
+ * Builds the envelope that a run sends as `forwardedProps.copilotkit.ui`,
2048
+ * from the per-run manifest. It has the A2UI v1.0 renderer capabilities
2049
+ * shape: one inline catalog with the id of the UI, and the CopilotKit data
2050
+ * in `metadata.extensions`.
2051
+ *
2052
+ * The inline catalog has no `components` only for the markdown transport
2053
+ * with `includeCatalog: false`. It has `instructions` for the markdown
2054
+ * transport, or when given.
2055
+ *
2056
+ * @param runtime - The generative UI runtime of the provider.
2057
+ * @param threadId - The thread of the run. Its surfaces go in `copilotkit_surfaces`.
2058
+ * @param options - The transport and what to send.
2059
+ *
2060
+ * @example
2061
+ * ```ts
2062
+ * const envelope = buildGenerativeUIEnvelope(runtime, agent.threadId, {
2063
+ * transport: "tool",
2064
+ * includeCatalog: true,
2065
+ * contextSent: false,
2066
+ * });
2067
+ * envelope["1.0"].supportedCatalogIds; // [runtime.ui.id]
2068
+ * ```
2069
+ */
2070
+ function buildGenerativeUIEnvelope(runtime, threadId, options) {
2071
+ const { transport, includeCatalog, contextSent, action } = options;
2072
+ const manifest = buildGenerativeUIManifest(runtime, threadId);
2073
+ const instructions = options.instructions ?? (transport === "markdown" ? buildGenerativeUIMarkdownGuidelines(generativeUIGuideFeatures(manifest)) : void 0);
2074
+ const omitComponents = transport === "markdown" && !includeCatalog;
2075
+ return {
2076
+ "1.0": {
2077
+ supportedCatalogIds: manifest.catalogIds ?? [manifest.catalogId],
2078
+ inlineCatalogs: [{
2079
+ catalogId: manifest.catalogId,
2080
+ protocolVersion: "1.0",
2081
+ ...omitComponents ? {} : { components: manifest.components },
2082
+ functions: manifest.functions,
2083
+ ...instructions === void 0 ? {} : { instructions }
2084
+ }]
2085
+ },
2086
+ metadata: { extensions: {
2087
+ copilotkit_format: COPILOTKIT_UI_ENVELOPE_FORMAT,
2088
+ copilotkit_transport: transport,
2089
+ copilotkit_targets: manifest.targets,
2090
+ copilotkit_surfaces: manifest.surfaces,
2091
+ copilotkit_contextSent: contextSent,
2092
+ ...action === void 0 ? {} : { copilotkit_action: action }
2093
+ } }
2094
+ };
2095
+ }
2096
+
2097
+ //#endregion
2098
+ //#region src/generative-ui/markdown-source.ts
2099
+ /**
2100
+ * Values by key, from the latest build. A value that a build does not use
2101
+ * is dropped at the end of that build, so the cache does not grow.
2102
+ */
2103
+ var BuildMemo = class {
2104
+ previous = /* @__PURE__ */ new Map();
2105
+ current = /* @__PURE__ */ new Map();
2106
+ /**
2107
+ * The value of `key`. It is computed when no earlier value is there, or
2108
+ * when `isFresh` says that the earlier value is out of date.
2109
+ */
2110
+ get(key, compute, isFresh = () => true) {
2111
+ let value = this.current.get(key) ?? this.previous.get(key);
2112
+ if (value === void 0 || !isFresh(value)) value = compute();
2113
+ this.current.set(key, value);
2114
+ return value;
2115
+ }
2116
+ endBuild() {
2117
+ this.previous = this.current;
2118
+ this.current = /* @__PURE__ */ new Map();
2119
+ }
2120
+ };
2121
+ /** The results of the builds of one thread. See `BuildMarkdownSurfacesOptions.cache`. */
2122
+ var MarkdownBuildCache = class {
2123
+ segments = new BuildMemo();
2124
+ fences = new BuildMemo();
2125
+ drafts = new BuildMemo();
2126
+ /** The copies of an operation for other surface ids, by operation. */
2127
+ readdressed = /* @__PURE__ */ new WeakMap();
2128
+ endBuild() {
2129
+ this.segments.endBuild();
2130
+ this.fences.endBuild();
2131
+ this.drafts.endBuild();
2132
+ }
2133
+ };
2134
+ /** True when both lists hold the same objects in the same order. */
2135
+ function sameItems(a, b) {
2136
+ return a.length === b.length && a.every((item, index) => item === b[index]);
2137
+ }
2138
+ function isString(value) {
2139
+ return typeof value === "string";
2140
+ }
2141
+ /** The key of one fence of one message. */
2142
+ function fenceKey(messageId, fenceIndex) {
2143
+ return `${messageId}:${fenceIndex}`;
2144
+ }
2145
+ /**
2146
+ * The operations of a fence body. While the fence streams, the last object
2147
+ * can be unfinished. Of an unfinished updateComponents or createSurface, the
2148
+ * components that are complete render at once (a createSurface also keeps
2149
+ * its data model when all of it arrived). Any other unfinished object is
2150
+ * left out, because a part of a data model value can still change. A final
2151
+ * fence keeps what can be saved from an unfinished object.
2152
+ */
2153
+ function fenceOperations(text, isStreaming) {
2154
+ const parsed = extractFenceOperations(text);
2155
+ if (!isStreaming || parsed.partialObject === null) return parsed.operations;
2156
+ const complete = extractFenceOperations(text.slice(0, text.length - parsed.partialObject.length)).operations;
2157
+ const partial = parsed.operations.length > complete.length ? parsed.operations[parsed.operations.length - 1] : void 0;
2158
+ return partial !== void 0 && (isRecord(partial.updateComponents) || isRecord(partial.createSurface)) ? [...complete, partial] : complete;
2159
+ }
2160
+ /**
2161
+ * An inline createSurface becomes a createSurface with only its surfaceId
2162
+ * and catalog, then an updateDataModel for its data model, then an
2163
+ * updateComponents for its components. The prose lift and the split per
2164
+ * component read only updateComponents, so they then work for an inline
2165
+ * surface too. A createSurface with a data model or components of a wrong
2166
+ * shape does not change, so that validation rejects it with the reason.
2167
+ */
2168
+ function expandInlineCreate(operations) {
2169
+ return operations.flatMap((op) => {
2170
+ const create = op.createSurface;
2171
+ if (!isRecord(create)) return [op];
2172
+ const { dataModel, components, ...rest } = create;
2173
+ const hasData = isRecord(dataModel);
2174
+ const hasComponents = Array.isArray(components) && components.length > 0;
2175
+ if (!((dataModel === void 0 || hasData) && (components === void 0 || hasComponents)) || !hasData && !hasComponents) return [op];
2176
+ const { surfaceId } = create;
2177
+ const expanded = [{
2178
+ ...op,
2179
+ createSurface: rest
2180
+ }];
2181
+ if (hasData) expanded.push({
2182
+ version: op.version,
2183
+ updateDataModel: {
2184
+ surfaceId,
2185
+ path: "/",
2186
+ value: dataModel
2187
+ }
2188
+ });
2189
+ if (hasComponents) expanded.push({
2190
+ version: op.version,
2191
+ updateComponents: {
2192
+ surfaceId,
2193
+ components
2194
+ }
2195
+ });
2196
+ return expanded;
2197
+ });
2198
+ }
2199
+ /**
2200
+ * Each updateComponents becomes one operation per component, in order. The
2201
+ * complete components of a streaming line then give the same first
2202
+ * operations as the finished line, so the operation list only grows and the
2203
+ * manager never has to start the surface again.
2204
+ */
2205
+ function splitComponentUpdates(operations) {
2206
+ return operations.flatMap((op) => {
2207
+ const update = op.updateComponents;
2208
+ if (!isRecord(update) || !Array.isArray(update.components)) return [op];
2209
+ if (update.components.length <= 1) return [op];
2210
+ return update.components.map((component) => ({
2211
+ ...op,
2212
+ updateComponents: {
2213
+ ...update,
2214
+ components: [component]
2215
+ }
2216
+ }));
2217
+ });
2218
+ }
2219
+ /** createSurface first, the other operations after it in their order. */
2220
+ function createSurfaceFirst(operations) {
2221
+ const creates = operations.filter((op) => isRecord(op.createSurface));
2222
+ const others = operations.filter((op) => !isRecord(op.createSurface));
2223
+ return [...creates, ...others];
2224
+ }
2225
+ /** True when the component of `name` has the prop `prop`. */
2226
+ function hasProp(ui, name, prop) {
2227
+ const properties = ui.manifestComponents[name]?.props.properties;
2228
+ return isRecord(properties) && Object.hasOwn(properties, prop);
2229
+ }
2230
+ const childRefCache = /* @__PURE__ */ new WeakMap();
2231
+ /** The ids in a slot value: an id, a list of ids, or a template. */
2232
+ function slotIds(value) {
2233
+ if (typeof value === "string") return [value];
2234
+ if (Array.isArray(value)) return value.filter(isString);
2235
+ return isRecord(value) && isString(value.componentId) ? [value.componentId] : [];
2236
+ }
2237
+ /**
2238
+ * A reader of the ids a component renders beyond `child` and `children`:
2239
+ * its declared slots (the `trigger` and `content` of a Modal) and its typed
2240
+ * child references (the `child` of each entry of `tabs`), from its catalog
2241
+ * entry. The prose lift follows these ids like `children`, so a panel is
2242
+ * never cut off from its Tabs. A reference that is bound to the data
2243
+ * model is "unknown": its ids exist only at render time.
2244
+ */
2245
+ function childIdsReader(ui) {
2246
+ return (component) => {
2247
+ const name = component.component;
2248
+ const entry = typeof name === "string" && Object.hasOwn(ui.manifestComponents, name) ? ui.manifestComponents[name] : void 0;
2249
+ if (!entry) return [];
2250
+ const ids = [];
2251
+ for (const slot of Object.keys(entry.slots ?? {})) if (slot !== "child" && slot !== "children") ids.push(...slotIds(component[slot]));
2252
+ let refs = childRefCache.get(entry.props);
2253
+ if (!refs) {
2254
+ refs = collectChildRefs(entry.props);
2255
+ childRefCache.set(entry.props, refs);
2256
+ }
2257
+ if (refs.length === 0) return ids;
2258
+ if (hasBoundChildRef(component, refs)) return "unknown";
2259
+ return [...ids, ...childIdsAtRefs(component, refs)];
2260
+ };
2261
+ }
2262
+ /** Every component of the operations by id, last definition wins. */
2263
+ function collectComponents(operations) {
2264
+ const byId = /* @__PURE__ */ new Map();
2265
+ for (const op of operations) {
2266
+ const update = op.updateComponents;
2267
+ const list = isRecord(update) ? update.components : void 0;
2268
+ if (!Array.isArray(list)) continue;
2269
+ for (const component of list) if (isRecord(component) && isString(component.id)) byId.set(component.id, component);
2270
+ }
2271
+ return [...byId.values()];
2272
+ }
2273
+ /**
2274
+ * The data model must not be shared between two surfaces. A data model
2275
+ * keeps the object it gets, so an input in one surface would change the
2276
+ * data of the other one.
2277
+ */
2278
+ function cloneData(value) {
2279
+ return value === void 0 ? void 0 : structuredClone(value);
2280
+ }
2281
+ /** The operation sent to `surfaceId`, with a copy of its data model value. */
2282
+ function readdress(op, surfaceId) {
2283
+ const kind = getOperationKind(op);
2284
+ const payload = kind ? op[kind] : void 0;
2285
+ if (!kind || !isRecord(payload)) return op;
2286
+ const next = {
2287
+ ...payload,
2288
+ surfaceId
2289
+ };
2290
+ if (kind === "updateDataModel" && "value" in payload) next.value = cloneData(payload.value);
2291
+ return {
2292
+ ...op,
2293
+ [kind]: next
2294
+ };
2295
+ }
2296
+ /**
2297
+ * The operations of one sub-surface. Each updateComponents keeps only the
2298
+ * components of the sub-surface, with its own root. The other operations
2299
+ * are sent to the sub-surface. The order stays the same, so a new operation
2300
+ * of the fence only adds operations at the end.
2301
+ */
2302
+ function subSurfaceOperations(operations, components, surfaceId) {
2303
+ const root = components.find((c) => c.id === GENERATIVE_UI_ROOT_ID);
2304
+ const ids = new Set(components.map((c) => c.id));
2305
+ const out = [];
2306
+ for (const op of operations) {
2307
+ const update = op.updateComponents;
2308
+ if (!isRecord(update) || !Array.isArray(update.components)) {
2309
+ out.push(readdress(op, surfaceId));
2310
+ continue;
2311
+ }
2312
+ const kept = update.components.filter((c) => isRecord(c) && ids.has(c.id)).map((c) => isRecord(c) && c.id === GENERATIVE_UI_ROOT_ID ? root : c);
2313
+ if (kept.length === 0) continue;
2314
+ out.push({
2315
+ ...op,
2316
+ updateComponents: {
2317
+ ...update,
2318
+ surfaceId,
2319
+ components: kept
2320
+ }
2321
+ });
2322
+ }
2323
+ return out;
2324
+ }
2325
+ /**
2326
+ * Prose lift. Text components in the main stack of the surface (titles,
2327
+ * paragraphs, text lists and the dividers between them) become chat
2328
+ * markdown. The surface splits around them: the first surface keeps
2329
+ * `surfaceId`, the next ones are `<surfaceId>#1`, `<surfaceId>#2`, and so
2330
+ * on. A surface with no prose comes back as one part with the same
2331
+ * operations.
2332
+ */
2333
+ function liftProse(operations, surfaceId, childIds) {
2334
+ const components = collectComponents(operations);
2335
+ const segments = segmentSurfaceProse(components, { childIds });
2336
+ const [first] = segments;
2337
+ if (segments.length === 1 && first?.kind === "surface" && first.components === components) return [{
2338
+ kind: "surface",
2339
+ surfaceId,
2340
+ operations
2341
+ }];
2342
+ let surfaceIndex = 0;
2343
+ return segments.map((segment) => {
2344
+ if (segment.kind === "markdown") return segment;
2345
+ const id = surfaceIndex === 0 ? surfaceId : `${surfaceId}#${surfaceIndex}`;
2346
+ surfaceIndex++;
2347
+ return {
2348
+ kind: "surface",
2349
+ surfaceId: id,
2350
+ operations: subSurfaceOperations(operations, segment.components, id)
2351
+ };
2352
+ });
2353
+ }
2354
+ /** `validateOperation`, with the operation typed when it is valid. */
2355
+ function checkOperation(op, options) {
2356
+ const validation = validateOperation(op, options);
2357
+ if (!validation.ok) return validation;
2358
+ return {
2359
+ ok: true,
2360
+ operation: op
2361
+ };
2362
+ }
2363
+ /**
2364
+ * The content of one surface. Each operation is validated against the
2365
+ * manifest. A valid operation goes in `operations`. A rejected one goes in
2366
+ * `rejected`, with its position and the reason.
2367
+ */
2368
+ function surfaceContent(surfaceId, draft, operations, options) {
2369
+ const { ui, functions } = options;
2370
+ const knownSurfaces = /* @__PURE__ */ new Set();
2371
+ const manifest = {
2372
+ catalogId: ui.id,
2373
+ catalogIds: catalogIdsOf(ui),
2374
+ components: ui.manifestComponents
2375
+ };
2376
+ const valid = [];
2377
+ const rejected = [];
2378
+ operations.forEach((op, index) => {
2379
+ const result = checkOperation(op, {
2380
+ manifest,
2381
+ knownSurfaces,
2382
+ functions
2383
+ });
2384
+ if (!result.ok) {
2385
+ rejected.push({
2386
+ index,
2387
+ reason: result.reason
2388
+ });
2389
+ return;
2390
+ }
2391
+ valid.push(result.operation);
2392
+ const kind = getOperationKind(result.operation);
2393
+ if (kind === "createSurface") knownSurfaces.add(surfaceId);
2394
+ if (kind === "deleteSurface") knownSurfaces.delete(surfaceId);
2395
+ });
2396
+ const create = valid.find((op) => "createSurface" in op);
2397
+ return {
2398
+ surfaceId,
2399
+ target: draft.target,
2400
+ catalogId: create?.createSurface.catalogId ?? ui.id,
2401
+ operations: valid,
2402
+ status: draft.streaming ? "streaming" : "ready",
2403
+ rejected
2404
+ };
2405
+ }
2406
+ /**
2407
+ * Builds the surfaces of a thread from the ```a2ui fences of its assistant
2408
+ * messages, in message order.
2409
+ *
2410
+ * - Operations are grouped by surfaceId across all messages. An operation
2411
+ * with no surfaceId goes to the first surface of its fence, else to
2412
+ * `<messageId>-<fenceIndex>`.
2413
+ * - The fence that first writes a surface creates it. The `target=<id>` of
2414
+ * that fence sets the target. With no target, the surface goes to the
2415
+ * chat.
2416
+ * - A later fence of the same reply for the same surfaceId updates it. A
2417
+ * later reply that reuses the id of a chat surface gets a surface of its
2418
+ * own, `<id>@<messageId>`. A page target is updated from any reply.
2419
+ * - The status is "streaming" while the creating fence streams, else
2420
+ * "ready".
2421
+ * - Each operation is validated with `validateOperation`. Rejected ones are
2422
+ * left out and listed in `rejected`.
2423
+ * - Chat surfaces get the prose lift: informational cards lose their box,
2424
+ * and prose becomes markdown that renders between sub-surfaces
2425
+ * (`<surfaceId>#<n>`). An inline createSurface is split into its
2426
+ * createSurface, updateDataModel and updateComponents first.
2427
+ * - A `callRendererFunction` line is not part of a surface. It goes to
2428
+ * `functionCalls`. A streaming line gives nothing, so a function never
2429
+ * runs with a part of its args.
2430
+ *
2431
+ * The function is pure. Call it again on each stream update. The manager
2432
+ * applies only the new operations, so unchanged surfaces do not render
2433
+ * again.
2434
+ *
2435
+ * @param messages - The messages of one thread.
2436
+ * @param options - The generative UI, its declared functions, and whether
2437
+ * the last message can still grow.
2438
+ * @returns `surfaces`, one content for each surface and sub-surface;
2439
+ * `fences`, the blocks that each fence renders, by `fenceKey` (a fence
2440
+ * that is not in `fences` renders nothing); `functionCalls`, the function
2441
+ * calls of the fences in order; and `parts`, the surface ids of the parts
2442
+ * of each surface, by surface id.
2443
+ *
2444
+ * @example
2445
+ * ```ts
2446
+ * const { surfaces } = buildMarkdownSurfaces(agent.messages, {
2447
+ * ui,
2448
+ * functions: {},
2449
+ * running: agent.isRunning,
2450
+ * });
2451
+ * for (const content of surfaces) manager.ingest(threadId, agentId, content);
2452
+ * ```
2453
+ */
2454
+ function buildMarkdownSurfaces(messages, options) {
2455
+ const { ui, cache } = options;
2456
+ const drafts = /* @__PURE__ */ new Map();
2457
+ const readdressOnce = (op, surfaceId) => {
2458
+ if (!cache) return readdress(op, surfaceId);
2459
+ let copies = cache.readdressed.get(op);
2460
+ if (!copies) {
2461
+ copies = /* @__PURE__ */ new Map();
2462
+ cache.readdressed.set(op, copies);
2463
+ }
2464
+ let copy = copies.get(surfaceId);
2465
+ if (!copy) {
2466
+ copy = readdress(op, surfaceId);
2467
+ copies.set(surfaceId, copy);
2468
+ }
2469
+ return copy;
2470
+ };
2471
+ /** The surfaces that each fence created, in order. */
2472
+ const created = /* @__PURE__ */ new Map();
2473
+ const functionCalls = [];
2474
+ /** The message that owns each chat surface id, by the id the model wrote. */
2475
+ const chatOwners = /* @__PURE__ */ new Map();
2476
+ const lastMessage = messages[messages.length - 1];
2477
+ /**
2478
+ * A chat surface belongs to the reply that wrote it: the chat is a
2479
+ * transcript, so a later reply that reuses an id gets a surface of its
2480
+ * own (`<id>@<messageId>`) instead of changing the earlier reply. A fence
2481
+ * for a page target keeps its id, because a target is a place on the
2482
+ * page that a later reply updates on purpose.
2483
+ */
2484
+ const scopedSurfaceId = (requested, messageId, target) => {
2485
+ if (target !== void 0) return requested;
2486
+ const owner = chatOwners.get(requested);
2487
+ if (owner === void 0) {
2488
+ chatOwners.set(requested, messageId);
2489
+ return requested;
2490
+ }
2491
+ return owner === messageId ? requested : `${requested}@${messageId}`;
2492
+ };
2493
+ for (const message of messages) {
2494
+ if (message.role !== "assistant" || !isString(message.content)) continue;
2495
+ const isLastMessage = message === lastMessage;
2496
+ const content = message.content;
2497
+ const segments = cache ? cache.segments.get(content, () => splitA2UIMarkdown(content)) : splitA2UIMarkdown(content);
2498
+ for (const segment of segments) {
2499
+ if (segment.type !== "a2ui") continue;
2500
+ const isStreaming = !segment.closed && isLastMessage && options.running;
2501
+ const parseFence = () => {
2502
+ const parsed = fenceOperations(segment.text, isStreaming);
2503
+ const { functionCalls } = prepareSurfaceOperations({
2504
+ operations: parsed,
2505
+ fallbackSurfaceId: "",
2506
+ catalogId: ui.id
2507
+ });
2508
+ return {
2509
+ operations: parsed,
2510
+ functionCalls
2511
+ };
2512
+ };
2513
+ const fence = cache ? cache.fences.get(`${isStreaming}:${segment.text}`, parseFence) : parseFence();
2514
+ const { operations } = fence;
2515
+ const key = fenceKey(message.id, segment.index);
2516
+ const fenceSurfaceId = operations.map(getMarkdownOperationSurfaceId).find(isString) ?? `${message.id}-${segment.index}`;
2517
+ for (const operation of fence.functionCalls) functionCalls.push({
2518
+ messageId: message.id,
2519
+ fenceIndex: segment.index,
2520
+ operation
2521
+ });
2522
+ const surfaceOperations = operations.filter((op) => getOperationKind(op) !== "callRendererFunction");
2523
+ for (const op of surfaceOperations) {
2524
+ const requested = getMarkdownOperationSurfaceId(op) ?? fenceSurfaceId;
2525
+ const surfaceId = scopedSurfaceId(requested, message.id, segment.target);
2526
+ let draft = drafts.get(surfaceId);
2527
+ if (!draft) {
2528
+ draft = {
2529
+ surfaceId,
2530
+ target: segment.target ?? GENERATIVE_UI_CHAT_TARGET,
2531
+ operations: [],
2532
+ streaming: isStreaming
2533
+ };
2534
+ drafts.set(surfaceId, draft);
2535
+ created.set(key, [...created.get(key) ?? [], surfaceId]);
2536
+ }
2537
+ draft.operations.push(surfaceId === requested ? op : readdressOnce(op, surfaceId));
2538
+ }
2539
+ }
2540
+ }
2541
+ const canFlattenCards = hasProp(ui, "Card", "variant");
2542
+ const surfaces = [];
2543
+ const partsBySurface = /* @__PURE__ */ new Map();
2544
+ const childIds = childIdsReader(ui);
2545
+ const buildDraft = (draft) => {
2546
+ const operations = splitComponentUpdates(expandInlineCreate(createSurfaceFirst(prepareSurfaceOperations({
2547
+ operations: draft.operations,
2548
+ fallbackSurfaceId: draft.surfaceId,
2549
+ catalogId: ui.id,
2550
+ catalogIds: catalogIdsOf(ui)
2551
+ }).operations)));
2552
+ const parts = draft.target === GENERATIVE_UI_CHAT_TARGET ? liftProse(canFlattenCards ? flattenInformationalCards(operations, { childIds }) : operations, draft.surfaceId, childIds) : [{
2553
+ kind: "surface",
2554
+ surfaceId: draft.surfaceId,
2555
+ operations
2556
+ }];
2557
+ const contents = parts.flatMap((part) => part.kind === "surface" ? [surfaceContent(part.surfaceId, draft, part.operations, options)] : []);
2558
+ return {
2559
+ ...draft,
2560
+ parts,
2561
+ contents
2562
+ };
2563
+ };
2564
+ for (const draft of drafts.values()) {
2565
+ const built = cache ? cache.drafts.get(draft.surfaceId, () => buildDraft(draft), (last) => last.target === draft.target && last.streaming === draft.streaming && sameItems(last.operations, draft.operations)) : buildDraft(draft);
2566
+ partsBySurface.set(draft.surfaceId, built.parts);
2567
+ surfaces.push(...built.contents);
2568
+ }
2569
+ cache?.endBuild();
2570
+ /** The surface ids of the parts of each split surface, by surface id. */
2571
+ const parts = /* @__PURE__ */ new Map();
2572
+ for (const [surfaceId, surfaceParts] of partsBySurface) {
2573
+ const ids = surfaceParts.flatMap((part) => part.kind === "surface" ? [part.surfaceId] : []);
2574
+ parts.set(surfaceId, ids);
2575
+ }
2576
+ const fences = /* @__PURE__ */ new Map();
2577
+ for (const [key, surfaceIds] of created) {
2578
+ const blocks = [];
2579
+ for (const surfaceId of surfaceIds) {
2580
+ if (drafts.get(surfaceId)?.target !== GENERATIVE_UI_CHAT_TARGET) continue;
2581
+ for (const part of partsBySurface.get(surfaceId) ?? []) blocks.push(part.kind === "markdown" ? part : {
2582
+ kind: "surface",
2583
+ surfaceId: part.surfaceId
2584
+ });
2585
+ }
2586
+ if (blocks.length > 0) fences.set(key, blocks);
2587
+ }
2588
+ return {
2589
+ surfaces,
2590
+ fences,
2591
+ functionCalls,
2592
+ parts
2593
+ };
2594
+ }
2595
+ /** The declared functions, as `validateOperation` takes them. */
2596
+ function declaredFunctions(ui) {
2597
+ const functions = {};
2598
+ for (const [name, fn] of ui.functions) try {
2599
+ functions[name] = {
2600
+ ...fn.description ? { description: fn.description } : {},
2601
+ parameters: toJsonSchema(fn.parameters)
2602
+ };
2603
+ } catch {
2604
+ functions[name] = { parameters: {} };
2605
+ }
2606
+ return functions;
2607
+ }
2608
+ /** True when `list` starts with all the items of `prefix`. */
2609
+ function startsWith(list, prefix) {
2610
+ return list.length >= prefix.length && prefix.every((item, index) => item === list[index]);
2611
+ }
2612
+ /** A content that deletes a surface that the fences no longer write. */
2613
+ function removalContent(surfaceId, catalogId) {
2614
+ return {
2615
+ surfaceId,
2616
+ target: GENERATIVE_UI_CHAT_TARGET,
2617
+ catalogId,
2618
+ status: "ready",
2619
+ rejected: [],
2620
+ operations: [{
2621
+ version: A2UI_VERSION,
2622
+ createSurface: {
2623
+ surfaceId,
2624
+ catalogId
2625
+ }
2626
+ }, {
2627
+ version: A2UI_VERSION,
2628
+ deleteSurface: { surfaceId }
2629
+ }]
2630
+ };
2631
+ }
2632
+ /**
2633
+ * The markdown transport source of one surface manager. It turns the
2634
+ * messages of a thread into surfaces in the manager, and keeps the blocks
2635
+ * that each fence renders.
2636
+ */
2637
+ var MarkdownSurfaceSource = class {
2638
+ functions;
2639
+ /** By thread: the blocks of each fence, from the latest sync. */
2640
+ fences = /* @__PURE__ */ new Map();
2641
+ /** By thread, then surface: the operations last ingested, as JSON. */
2642
+ ingested = /* @__PURE__ */ new Map();
2643
+ /** By thread, then surface: the content last ingested. */
2644
+ contents = /* @__PURE__ */ new Map();
2645
+ /** By thread: the results of the earlier builds. */
2646
+ caches = /* @__PURE__ */ new Map();
2647
+ constructor(manager, ui) {
2648
+ this.manager = manager;
2649
+ this.ui = ui;
2650
+ this.functions = declaredFunctions(ui);
2651
+ }
2652
+ /**
2653
+ * Builds the surfaces of `threadId` from `messages` and gives them to the
2654
+ * manager. A surface that an earlier sync of the thread made, and that the
2655
+ * messages no longer write, is deleted. Other threads do not change.
2656
+ *
2657
+ * @param threadId - The thread of the messages.
2658
+ * @param agentId - The agent that owns the thread.
2659
+ * @param messages - All messages of the thread.
2660
+ * @param options - `running`: the last message can still grow.
2661
+ * @returns The function calls of the fences, in order. The source does
2662
+ * not run them.
2663
+ */
2664
+ sync(threadId, agentId, messages, options) {
2665
+ let cache = this.caches.get(threadId);
2666
+ if (!cache) {
2667
+ cache = new MarkdownBuildCache();
2668
+ this.caches.set(threadId, cache);
2669
+ }
2670
+ const result = buildMarkdownSurfaces(messages, {
2671
+ ui: this.ui,
2672
+ functions: this.functions,
2673
+ running: options.running,
2674
+ cache
2675
+ });
2676
+ this.fences.set(threadId, result.fences);
2677
+ for (const parts of result.parts.values()) this.manager.linkSurfaces(threadId, parts);
2678
+ const previous = this.ingested.get(threadId) ?? /* @__PURE__ */ new Map();
2679
+ const previousContents = this.contents.get(threadId) ?? /* @__PURE__ */ new Map();
2680
+ const next = /* @__PURE__ */ new Map();
2681
+ const nextContents = /* @__PURE__ */ new Map();
2682
+ for (const content of result.surfaces) {
2683
+ nextContents.set(content.surfaceId, content);
2684
+ const before = previous.get(content.surfaceId);
2685
+ if (before && previousContents.get(content.surfaceId) === content) {
2686
+ next.set(content.surfaceId, before);
2687
+ continue;
2688
+ }
2689
+ const fingerprints = content.operations.map((op) => JSON.stringify(op));
2690
+ if (before && !startsWith(fingerprints, before)) this.manager.ingest(threadId, agentId, {
2691
+ ...content,
2692
+ operations: []
2693
+ });
2694
+ this.manager.ingest(threadId, agentId, content);
2695
+ next.set(content.surfaceId, fingerprints);
2696
+ }
2697
+ for (const surfaceId of previous.keys()) {
2698
+ if (next.has(surfaceId)) continue;
2699
+ this.manager.ingest(threadId, agentId, removalContent(surfaceId, this.ui.id));
2700
+ }
2701
+ this.ingested.set(threadId, next);
2702
+ this.contents.set(threadId, nextContents);
2703
+ return result.functionCalls;
2704
+ }
2705
+ /**
2706
+ * The blocks that a fence renders in the chat, from the latest sync of the
2707
+ * thread. `undefined` when the fence renders nothing: it updates a surface
2708
+ * of an earlier fence, its surface is for a named target, or it has no
2709
+ * complete operation yet.
2710
+ */
2711
+ getFenceBlocks(threadId, messageId, fenceIndex) {
2712
+ return this.fences.get(threadId)?.get(fenceKey(messageId, fenceIndex));
2713
+ }
2714
+ };
2715
+ const sources = /* @__PURE__ */ new WeakMap();
2716
+ /**
2717
+ * The markdown source of a generative UI runtime. There is one source for
2718
+ * each surface manager. The root syncs it, and the chat messages read the
2719
+ * fence blocks from it.
2720
+ */
2721
+ function getMarkdownSurfaceSource(runtime) {
2722
+ let source = sources.get(runtime.manager);
2723
+ if (!source) {
2724
+ source = new MarkdownSurfaceSource(runtime.manager, runtime.ui);
2725
+ sources.set(runtime.manager, source);
2726
+ }
2727
+ return source;
2728
+ }
2729
+
2730
+ //#endregion
2731
+ //#region src/generative-ui/action-message.ts
2732
+ /** Context keys that supply the message's first line, in priority order. */
2733
+ const TEXT_KEYS = ["message", "label"];
2734
+ function isNonEmptyString(value) {
2735
+ return typeof value === "string" && value.trim().length > 0;
2736
+ }
2737
+ /** `choose_plan`, `choose-plan` and `choosePlan` all become "Choose plan". */
2738
+ function humanize(name) {
2739
+ const spaced = name.replace(/[_-]+/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").trim();
2740
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();
2741
+ }
2742
+ function formatContextValue(value) {
2743
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
2744
+ }
2745
+ /**
2746
+ * Turns a user event that no function handles into the text of a visible
2747
+ * user message.
2748
+ *
2749
+ * The first line is, in order: `userMessage`, `context.message`,
2750
+ * `context.label`, the label of the source component (from `resolveLabel`),
2751
+ * or the event name made readable (`choose_plan` becomes "Choose plan").
2752
+ * Each other context field follows as one `key: value` line. Objects are
2753
+ * written as JSON. `null` and `undefined` fields are skipped.
2754
+ *
2755
+ * @param event - The user event, as sent by a surface.
2756
+ * @param resolveLabel - Finds the visible label of a component by id. Build
2757
+ * one with {@link createComponentLabelResolver}.
2758
+ *
2759
+ * @example
2760
+ * ```ts
2761
+ * buildActionMessageText({
2762
+ * name: "choose_plan",
2763
+ * surfaceId: "plans",
2764
+ * componentId: "team-button",
2765
+ * userMessage: "I pick the Team plan",
2766
+ * context: { seats: 12 },
2767
+ * });
2768
+ * // "I pick the Team plan\n\nseats: 12"
2769
+ * ```
2770
+ */
2771
+ function buildActionMessageText(event, resolveLabel) {
2772
+ const { context, userMessage } = event;
2773
+ const explicit = [userMessage, ...TEXT_KEYS.map((key) => context[key])].find(isNonEmptyString);
2774
+ const resolved = explicit ? void 0 : resolveLabel?.(event.componentId);
2775
+ const head = explicit ?? (isNonEmptyString(resolved) ? resolved.trim() : humanize(event.name));
2776
+ const lines = Object.entries(context).filter(([key, value]) => !TEXT_KEYS.includes(key) && value !== void 0 && value !== null).map(([key, value]) => `${key}: ${formatContextValue(value)}`);
2777
+ return lines.length > 0 ? `${head}\n\n${lines.join("\n")}` : head;
2778
+ }
2779
+ function ownText(component) {
2780
+ if (!component) return void 0;
2781
+ if (isNonEmptyString(component.label)) return component.label;
2782
+ if (isNonEmptyString(component.text)) return component.text;
2783
+ }
2784
+ function childIds(component) {
2785
+ const { child, children } = component;
2786
+ const single = typeof child === "string" ? [child] : [];
2787
+ const multiple = Array.isArray(children) ? children.filter((id) => typeof id === "string") : [];
2788
+ return [...single, ...multiple];
2789
+ }
2790
+ /** The components that an operation adds, inline or in an update. */
2791
+ function componentsOf(operation) {
2792
+ if ("createSurface" in operation) return operation.createSurface.components ?? [];
2793
+ if ("updateComponents" in operation) return operation.updateComponents.components;
2794
+ return [];
2795
+ }
2796
+ /**
2797
+ * Builds a function that finds the visible label of a component on a surface.
2798
+ *
2799
+ * The label is the component's own string `label`, else its string `text`,
2800
+ * else the first `child` or `children` component that has a string `label`
2801
+ * or `text`. When a component id is defined more than once, the last
2802
+ * definition wins, as in the renderer.
2803
+ *
2804
+ * @param operations - The committed operations of the surface.
2805
+ *
2806
+ * @example
2807
+ * ```ts
2808
+ * const resolveLabel = createComponentLabelResolver(surface.operations);
2809
+ * buildActionMessageText(event, resolveLabel);
2810
+ * ```
2811
+ */
2812
+ function createComponentLabelResolver(operations) {
2813
+ const byId = /* @__PURE__ */ new Map();
2814
+ for (const operation of operations) {
2815
+ const components = componentsOf(operation);
2816
+ for (const component of components) byId.set(component.id, component);
2817
+ }
2818
+ return (componentId) => {
2819
+ const component = byId.get(componentId);
2820
+ if (!component) return void 0;
2821
+ const own = ownText(component);
2822
+ if (own) return own;
2823
+ const ids = childIds(component);
2824
+ for (const id of ids) {
2825
+ const text = ownText(byId.get(id));
2826
+ if (text) return text;
2827
+ }
2828
+ };
2829
+ }
2830
+ /**
2831
+ * The label resolver of a rendered surface: the components the surface has
2832
+ * now, as one `updateComponents` operation, so that the label of the
2833
+ * component that sent an event can be found.
2834
+ */
2835
+ function surfaceLabelResolver(surface) {
2836
+ const components = [...surface.model.componentsModel.entries].map(([id, model]) => ({
2837
+ ...model.properties,
2838
+ id,
2839
+ component: model.type
2840
+ }));
2841
+ return createComponentLabelResolver([{
2842
+ version: A2UI_VERSION,
2843
+ updateComponents: {
2844
+ surfaceId: surface.surfaceId,
2845
+ components
2846
+ }
2847
+ }]);
2848
+ }
2849
+
2850
+ //#endregion
2851
+ //#region src/generative-ui/debug-source.ts
2852
+ /**
2853
+ * What a run of `threadId` sends: its envelope, and the text that goes into
2854
+ * the prompt of the model because of it.
2855
+ *
2856
+ * - Tool transport: the runtime adds the `render_ui` guide. It builds it
2857
+ * from the envelope with `buildGenerativeUIPrompt`, as done here.
2858
+ * - Markdown transport: the provider sends the guideline and the compact
2859
+ * schema as context entries. With `sendContext: false`, the backend builds
2860
+ * its own prompt, usually from the `instructions` of the envelope.
2861
+ */
2862
+ function describeGenerativeUIRun(runtime, threadId, options) {
2863
+ const envelope = buildGenerativeUIEnvelope(runtime, threadId, options);
2864
+ if (options.transport === "tool") return {
2865
+ envelope,
2866
+ prompt: [{
2867
+ title: "render_ui guide",
2868
+ source: "runtime",
2869
+ text: buildGenerativeUIPrompt(envelopeToManifest(envelope))
2870
+ }]
2871
+ };
2872
+ const manifest = buildGenerativeUIManifest(runtime, threadId);
2873
+ if (!options.contextSent) return {
2874
+ envelope,
2875
+ prompt: [{
2876
+ title: "Envelope instructions",
2877
+ source: "backend",
2878
+ text: envelopeToManifest(envelope).instructions ?? ""
2879
+ }]
2880
+ };
2881
+ const guideline = buildGenerativeUIMarkdownGuidelines(generativeUIGuideFeatures(manifest));
2882
+ const schema = renderGenerativeUISchema(manifest, defaultGenerativeUIPromptSpec().schema.markdown);
2883
+ return {
2884
+ envelope,
2885
+ prompt: [{
2886
+ title: "Markdown guideline",
2887
+ source: "context",
2888
+ text: guideline
2889
+ }, {
2890
+ title: "Component schema",
2891
+ source: "context",
2892
+ text: schema
2893
+ }]
2894
+ };
2895
+ }
2896
+ /** The declared functions, with the JSON Schema of their parameters. */
2897
+ function debugFunctions(runtime) {
2898
+ const functions = {};
2899
+ for (const [name, declared] of runtime.ui.functions) {
2900
+ let parameters = {};
2901
+ try {
2902
+ parameters = toJsonSchema(declared.parameters);
2903
+ } catch {}
2904
+ functions[name] = {
2905
+ ...declared.description ? { description: declared.description } : {},
2906
+ parameters,
2907
+ handlers: runtime.dispatcher.handlerCount(name)
2908
+ };
2909
+ }
2910
+ return functions;
2911
+ }
2912
+ /**
2913
+ * The debug source that the provider gives core for the inspector. It builds
2914
+ * a snapshot only when the inspector reads one.
2915
+ *
2916
+ * @param runtime - The generative UI parts of the provider.
2917
+ * @param getOptions - The envelope options and agent ids of the current config.
2918
+ * @returns The source, and `recordRun` for each run start.
2919
+ */
2920
+ function createGenerativeUIDebugSource(runtime, getOptions) {
2921
+ const listeners = /* @__PURE__ */ new Set();
2922
+ let lastRun;
2923
+ const notify = () => {
2924
+ for (const listener of [...listeners]) listener();
2925
+ };
2926
+ return {
2927
+ source: {
2928
+ getSnapshot() {
2929
+ const { options, agentIds } = getOptions();
2930
+ const threadId = runtime.manager.getActiveThread();
2931
+ const manifest = buildGenerativeUIManifest(runtime, threadId);
2932
+ return {
2933
+ catalogId: runtime.ui.id,
2934
+ transport: options.transport,
2935
+ ...agentIds ? { agentIds } : {},
2936
+ components: runtime.ui.manifestComponents,
2937
+ componentCatalogs: Object.fromEntries(componentCatalogIds(runtime.ui)),
2938
+ functions: debugFunctions(runtime),
2939
+ state: { ...runtime.manager.getState() },
2940
+ targets: manifest.targets,
2941
+ activeThreadId: threadId,
2942
+ surfaces: runtime.manager.debugSurfaces(),
2943
+ lastRun,
2944
+ nextRun: {
2945
+ agentId: void 0,
2946
+ threadId,
2947
+ ...describeGenerativeUIRun(runtime, threadId, options)
2948
+ }
2949
+ };
2950
+ },
2951
+ subscribe(listener) {
2952
+ listeners.add(listener);
2953
+ const unsubscribe = runtime.manager.subscribe(listener);
2954
+ return () => {
2955
+ listeners.delete(listener);
2956
+ unsubscribe();
2957
+ };
2958
+ }
2959
+ },
2960
+ recordRun(run) {
2961
+ lastRun = run;
2962
+ notify();
2963
+ }
2964
+ };
2965
+ }
2966
+
2967
+ //#endregion
2968
+ //#region src/generative-ui/accessibility.ts
2969
+ const LIVE = new Set([
2970
+ "off",
2971
+ "polite",
2972
+ "assertive"
2973
+ ]);
2974
+ /**
2975
+ * The accessibility of a component from its resolved `accessibility`
2976
+ * value. Fields of the wrong type are left out: a label that is still a
2977
+ * binding, or a list, names nothing.
2978
+ */
2979
+ function readAccessibility(value) {
2980
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return;
2981
+ const { label, description, live, hidden } = value;
2982
+ const result = {};
2983
+ if (typeof label === "string" && label !== "") result.label = label;
2984
+ if (typeof description === "string" && description !== "") result.description = description;
2985
+ if (typeof live === "string" && LIVE.has(live)) result.live = live;
2986
+ if (typeof hidden === "boolean") result.hidden = hidden;
2987
+ return Object.keys(result).length > 0 ? result : void 0;
2988
+ }
2989
+ /**
2990
+ * The ARIA attributes for an `accessibility`. `live: "off"` is written out:
2991
+ * a region inherits the live setting of its ancestors, and a `status` role
2992
+ * is live on its own, so only the explicit value silences it.
2993
+ *
2994
+ * @example
2995
+ * ```ts
2996
+ * accessibilityAttributes({ label: "Totals", live: "polite" });
2997
+ * // { "aria-label": "Totals", "aria-live": "polite" }
2998
+ * ```
2999
+ */
3000
+ function accessibilityAttributes(accessibility) {
3001
+ if (!accessibility) return {};
3002
+ const { label, description, live, hidden } = accessibility;
3003
+ return {
3004
+ ...label === void 0 ? {} : { "aria-label": label },
3005
+ ...description === void 0 ? {} : { "aria-description": description },
3006
+ ...live === void 0 ? {} : { "aria-live": live },
3007
+ ...hidden ? { "aria-hidden": true } : {}
3008
+ };
3009
+ }
3010
+ /**
3011
+ * The role of a container that the envelope names. A generic element
3012
+ * cannot carry a name, so a label or a description makes it a `group`,
3013
+ * unless the component has a role of its own.
3014
+ */
3015
+ function namedRole(aria, explicit) {
3016
+ if (explicit !== void 0) return explicit;
3017
+ return aria["aria-label"] !== void 0 || aria["aria-description"] !== void 0 ? "group" : void 0;
3018
+ }
3019
+ /**
3020
+ * The part of the attributes for the focusable control of a labelled pair:
3021
+ * its name and its description. ARIA names are not inherited, so the
3022
+ * wrapper of a control cannot name it.
3023
+ */
3024
+ function controlAria(aria) {
3025
+ const { "aria-label": label, "aria-description": description } = aria;
3026
+ return {
3027
+ ...label === void 0 ? {} : { "aria-label": label },
3028
+ ...description === void 0 ? {} : { "aria-description": description }
3029
+ };
3030
+ }
3031
+ /**
3032
+ * The part of the attributes for the wrapper around a control: hidden and
3033
+ * live cover the label and the control together.
3034
+ */
3035
+ function wrapperAria(aria) {
3036
+ const { "aria-hidden": hidden, "aria-live": live } = aria;
3037
+ return {
3038
+ ...hidden === void 0 ? {} : { "aria-hidden": hidden },
3039
+ ...live === void 0 ? {} : { "aria-live": live }
3040
+ };
3041
+ }
3042
+
3043
+ //#endregion
3044
+ //#region src/generative-ui/targets.ts
3045
+ /** Scrolls `element` into view, unless it is already fully on screen. */
3046
+ function scrollToSurface(element) {
3047
+ const { top, bottom } = element.getBoundingClientRect();
3048
+ if (top >= 0 && bottom <= window.innerHeight) return;
3049
+ const reduceMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
3050
+ element.scrollIntoView?.({
3051
+ behavior: reduceMotion ? "auto" : "smooth",
3052
+ block: "start"
3053
+ });
3054
+ }
3055
+ /**
3056
+ * The names of `requested` that `ui` has, without repeats, at most the
3057
+ * number that the envelope takes. `warning` tells what was dropped.
3058
+ */
3059
+ function allowedComponents(requested, ui) {
3060
+ const unique = [...new Set(requested)];
3061
+ const unknown = unique.filter((name) => !ui.components.has(name));
3062
+ const known = unique.filter((name) => ui.components.has(name));
3063
+ const names = known.slice(0, GENERATIVE_UI_MAX_TARGET_COMPONENTS);
3064
+ const problems = [];
3065
+ if (unknown.length > 0) problems.push(`these components are not in the UI and are ignored: ${unknown.join(", ")}`);
3066
+ if (known.length > names.length) problems.push(`only the first ${GENERATIVE_UI_MAX_TARGET_COMPONENTS} components are used`);
3067
+ return {
3068
+ names,
3069
+ warning: problems.join("; ")
3070
+ };
3071
+ }
3072
+
3073
+ //#endregion
3074
+ export { BASIC_FUNCTIONS, ExpressionError, GenerativeUISurfaceManager, MarkdownBuildCache, MarkdownSurfaceSource, accessibilityAttributes, activityFunctionCalls, allowedComponents, buildActionMessageText, buildCatalogManifest, buildGenerativeUIEnvelope, buildGenerativeUIManifest, buildMarkdownSurfaces, builtInFunctionManifests, calc, containsDynamicValue, controlAria, createComponentLabelResolver, createFunctionCallRunner, createGenerativeUIDebugSource, createGenerativeUIDispatcher, describeGenerativeUIRun, envelopeOptionsFor, evaluateCalc, fenceKey, getMarkdownSurfaceSource, givesValidationResult, invokeBoundEvent, invokeMatchedEvent, joinPath, markdownFunctionCalls, namedRole, openUrlSafely, readAccessibility, reportErrorSafely, requiresUserActivation, resolveDynamicValue, resolvePath, scrollToSurface, series, surfaceKey, surfaceLabelResolver, templateIndex, truthOf, tryResolveDynamicValue, wrapperAria };
3075
+ //# sourceMappingURL=index.mjs.map