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

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