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