@copilotkit/shared 1.80.0 → 1.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/dist/a2ui-envelope.cjs +154 -0
  2. package/dist/a2ui-envelope.cjs.map +1 -0
  3. package/dist/a2ui-envelope.d.cts +101 -0
  4. package/dist/a2ui-envelope.d.cts.map +1 -0
  5. package/dist/a2ui-envelope.d.mts +101 -0
  6. package/dist/a2ui-envelope.d.mts.map +1 -0
  7. package/dist/a2ui-envelope.mjs +151 -0
  8. package/dist/a2ui-envelope.mjs.map +1 -0
  9. package/dist/a2ui-prompts.cjs +139 -0
  10. package/dist/a2ui-prompts.cjs.map +1 -1
  11. package/dist/a2ui-prompts.d.cts +60 -1
  12. package/dist/a2ui-prompts.d.cts.map +1 -1
  13. package/dist/a2ui-prompts.d.mts +60 -1
  14. package/dist/a2ui-prompts.d.mts.map +1 -1
  15. package/dist/a2ui-prompts.mjs +134 -1
  16. package/dist/a2ui-prompts.mjs.map +1 -1
  17. package/dist/generative-ui/basic-functions.cjs +177 -0
  18. package/dist/generative-ui/basic-functions.cjs.map +1 -0
  19. package/dist/generative-ui/basic-functions.d.cts +108 -0
  20. package/dist/generative-ui/basic-functions.d.cts.map +1 -0
  21. package/dist/generative-ui/basic-functions.d.mts +108 -0
  22. package/dist/generative-ui/basic-functions.d.mts.map +1 -0
  23. package/dist/generative-ui/basic-functions.mjs +167 -0
  24. package/dist/generative-ui/basic-functions.mjs.map +1 -0
  25. package/dist/generative-ui/child-refs.cjs +161 -0
  26. package/dist/generative-ui/child-refs.cjs.map +1 -0
  27. package/dist/generative-ui/child-refs.d.cts +68 -0
  28. package/dist/generative-ui/child-refs.d.cts.map +1 -0
  29. package/dist/generative-ui/child-refs.d.mts +68 -0
  30. package/dist/generative-ui/child-refs.d.mts.map +1 -0
  31. package/dist/generative-ui/child-refs.mjs +152 -0
  32. package/dist/generative-ui/child-refs.mjs.map +1 -0
  33. package/dist/generative-ui/is-record.cjs +10 -0
  34. package/dist/generative-ui/is-record.cjs.map +1 -0
  35. package/dist/generative-ui/is-record.mjs +9 -0
  36. package/dist/generative-ui/is-record.mjs.map +1 -0
  37. package/dist/generative-ui/prompt.cjs +91 -0
  38. package/dist/generative-ui/prompt.cjs.map +1 -0
  39. package/dist/generative-ui/prompt.d.cts +13 -0
  40. package/dist/generative-ui/prompt.d.cts.map +1 -0
  41. package/dist/generative-ui/prompt.d.mts +13 -0
  42. package/dist/generative-ui/prompt.d.mts.map +1 -0
  43. package/dist/generative-ui/prompt.mjs +90 -0
  44. package/dist/generative-ui/prompt.mjs.map +1 -0
  45. package/dist/generative-ui/render-ui-args.cjs +160 -0
  46. package/dist/generative-ui/render-ui-args.cjs.map +1 -0
  47. package/dist/generative-ui/render-ui-args.d.cts +40 -0
  48. package/dist/generative-ui/render-ui-args.d.cts.map +1 -0
  49. package/dist/generative-ui/render-ui-args.d.mts +40 -0
  50. package/dist/generative-ui/render-ui-args.d.mts.map +1 -0
  51. package/dist/generative-ui/render-ui-args.mjs +159 -0
  52. package/dist/generative-ui/render-ui-args.mjs.map +1 -0
  53. package/dist/generative-ui/types.cjs +101 -0
  54. package/dist/generative-ui/types.cjs.map +1 -0
  55. package/dist/generative-ui/types.d.cts +270 -0
  56. package/dist/generative-ui/types.d.cts.map +1 -0
  57. package/dist/generative-ui/types.d.mts +270 -0
  58. package/dist/generative-ui/types.d.mts.map +1 -0
  59. package/dist/generative-ui/types.mjs +86 -0
  60. package/dist/generative-ui/types.mjs.map +1 -0
  61. package/dist/generative-ui/validate-operation.cjs +405 -0
  62. package/dist/generative-ui/validate-operation.cjs.map +1 -0
  63. package/dist/generative-ui/validate-operation.d.cts +86 -0
  64. package/dist/generative-ui/validate-operation.d.cts.map +1 -0
  65. package/dist/generative-ui/validate-operation.d.mts +86 -0
  66. package/dist/generative-ui/validate-operation.d.mts.map +1 -0
  67. package/dist/generative-ui/validate-operation.mjs +399 -0
  68. package/dist/generative-ui/validate-operation.mjs.map +1 -0
  69. package/dist/index.cjs +63 -0
  70. package/dist/index.cjs.map +1 -1
  71. package/dist/index.d.cts +9 -2
  72. package/dist/index.d.cts.map +1 -1
  73. package/dist/index.d.mts +9 -2
  74. package/dist/index.d.mts.map +1 -1
  75. package/dist/index.mjs +9 -2
  76. package/dist/index.mjs.map +1 -1
  77. package/dist/index.umd.js +1421 -20
  78. package/dist/index.umd.js.map +1 -1
  79. package/dist/package.cjs +1 -1
  80. package/dist/package.mjs +1 -1
  81. package/dist/utils/dashboard-url.cjs +19 -0
  82. package/dist/utils/dashboard-url.cjs.map +1 -0
  83. package/dist/utils/dashboard-url.mjs +18 -0
  84. package/dist/utils/dashboard-url.mjs.map +1 -0
  85. package/dist/utils/index.cjs +2 -1
  86. package/dist/utils/index.cjs.map +1 -1
  87. package/dist/utils/index.d.cts.map +1 -1
  88. package/dist/utils/index.d.mts.map +1 -1
  89. package/dist/utils/index.mjs +2 -1
  90. package/dist/utils/index.mjs.map +1 -1
  91. package/dist/utils/inspector-learning.cjs +10 -7
  92. package/dist/utils/inspector-learning.cjs.map +1 -1
  93. package/dist/utils/inspector-learning.d.cts.map +1 -1
  94. package/dist/utils/inspector-learning.d.mts.map +1 -1
  95. package/dist/utils/inspector-learning.mjs +11 -7
  96. package/dist/utils/inspector-learning.mjs.map +1 -1
  97. package/dist/utils/inspector-metadata.cjs +2 -3
  98. package/dist/utils/inspector-metadata.cjs.map +1 -1
  99. package/dist/utils/inspector-metadata.d.cts.map +1 -1
  100. package/dist/utils/inspector-metadata.d.mts.map +1 -1
  101. package/dist/utils/inspector-metadata.mjs +3 -3
  102. package/dist/utils/inspector-metadata.mjs.map +1 -1
  103. package/package.json +1 -1
  104. package/src/__tests__/a2ui-envelope.test.ts +434 -0
  105. package/src/__tests__/a2ui-prompts.test.ts +362 -0
  106. package/src/a2ui-envelope.ts +309 -0
  107. package/src/a2ui-prompts.ts +207 -0
  108. package/src/generative-ui/__tests__/render-ui-args.test.ts +175 -0
  109. package/src/generative-ui/__tests__/validate-operation.test.ts +977 -0
  110. package/src/generative-ui/basic-functions.ts +282 -0
  111. package/src/generative-ui/child-refs.ts +210 -0
  112. package/src/generative-ui/index.ts +6 -0
  113. package/src/generative-ui/is-record.ts +4 -0
  114. package/src/generative-ui/prompt.ts +174 -0
  115. package/src/generative-ui/render-ui-args.ts +199 -0
  116. package/src/generative-ui/types.ts +314 -0
  117. package/src/generative-ui/validate-operation.ts +723 -0
  118. package/src/index.ts +15 -0
  119. package/src/utils/dashboard-url.ts +17 -0
  120. package/src/utils/index.ts +7 -1
  121. package/src/utils/inspector-learning.test.ts +58 -0
  122. package/src/utils/inspector-learning.ts +26 -5
  123. package/src/utils/inspector-metadata.test.ts +2 -1
  124. package/src/utils/inspector-metadata.ts +3 -13
  125. package/src/utils.test.ts +71 -0
@@ -0,0 +1,723 @@
1
+ import {
2
+ GENERATIVE_UI_FUNCTIONS,
3
+ functionCallers,
4
+ isA2UIBasicFunction,
5
+ isA2UIValueFunction,
6
+ isCallBinding,
7
+ } from "./basic-functions";
8
+ import type { A2UIFunctionPermissions } from "./basic-functions";
9
+ import { collectChildRefs } from "./child-refs";
10
+ import type { ChildRef } from "./child-refs";
11
+ import {
12
+ A2UI_VERSION,
13
+ GENERATIVE_UI_AGENT_FUNCTION_CALLS,
14
+ GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON,
15
+ } from "./types";
16
+ import type {
17
+ GenerativeUIActionBinding,
18
+ GenerativeUIJSONSchema,
19
+ GenerativeUIManifest,
20
+ } from "./types";
21
+ import { isRecord } from "./is-record";
22
+
23
+ export type OperationValidation = { ok: true } | { ok: false; reason: string };
24
+
25
+ const OPERATION_KINDS = [
26
+ "createSurface",
27
+ "updateComponents",
28
+ "updateDataModel",
29
+ "deleteSurface",
30
+ "callRendererFunction",
31
+ ] as const;
32
+ export type OperationKind = (typeof OPERATION_KINDS)[number];
33
+
34
+ export interface ValidateOperationOptions {
35
+ manifest: Pick<
36
+ GenerativeUIManifest,
37
+ "catalogId" | "catalogIds" | "components"
38
+ >;
39
+ /**
40
+ * Surfaces that exist before this operation is applied. `updateComponents`,
41
+ * `updateDataModel`, and `deleteSurface` need their surface in this set.
42
+ */
43
+ knownSurfaces: ReadonlySet<string>;
44
+ /**
45
+ * Surface ids that were created before, also the deleted ones. A surface id
46
+ * is unique for the life of the page, so `createSurface` rejects them.
47
+ */
48
+ createdSurfaces?: ReadonlySet<string>;
49
+ /**
50
+ * UI-callable functions. When provided, `functionCall` bindings and
51
+ * `callRendererFunction` must name one of them. The client omits it:
52
+ * availability is checked when the function runs.
53
+ */
54
+ functions?: GenerativeUIManifest["functions"];
55
+ /**
56
+ * The components that the target of the surface takes. When provided,
57
+ * `updateComponents` and the inline components of `createSurface` can use
58
+ * only these names. Left out, every catalog component is allowed.
59
+ */
60
+ allowedComponents?: AllowedComponents;
61
+ }
62
+
63
+ /** The component names that one target takes. */
64
+ export interface AllowedComponents {
65
+ /** The target id, for the reason of a rejection. */
66
+ target: string;
67
+ names: ReadonlySet<string>;
68
+ }
69
+
70
+ const OK: OperationValidation = { ok: true };
71
+ const fail = (reason: string): OperationValidation => ({ ok: false, reason });
72
+
73
+ /** Models write the v0.9 binding from habit. The reason names the v1.0 form. */
74
+ const V09_PATH_REASON = 'bind data with {"@path": "/x"}, not {"path": "/x"}';
75
+
76
+ function hasOwn(record: object, key: string) {
77
+ return Object.prototype.hasOwnProperty.call(record, key);
78
+ }
79
+
80
+ /**
81
+ * Reads an own property only. Model-controlled keys such as "constructor" or
82
+ * "toString" must not resolve to Object.prototype members.
83
+ */
84
+ function ownValue<T>(record: Record<string, T> | undefined, key: string) {
85
+ return record && hasOwn(record, key) ? record[key] : undefined;
86
+ }
87
+
88
+ export function getOperationKind(op: unknown) {
89
+ if (!isRecord(op)) return undefined;
90
+ const kinds = OPERATION_KINDS.filter((kind) => kind in op);
91
+ return kinds.length === 1 ? kinds[0] : undefined;
92
+ }
93
+
94
+ /** The `surfaceId` of a surface operation. `callRendererFunction` has none. */
95
+ export function getOperationSurfaceId(op: unknown) {
96
+ if (!isRecord(op)) return undefined;
97
+ const kind = getOperationKind(op);
98
+ if (!kind) return undefined;
99
+ const payload = op[kind];
100
+ return isRecord(payload) && typeof payload.surfaceId === "string"
101
+ ? payload.surfaceId
102
+ : undefined;
103
+ }
104
+
105
+ /** `{ "@path": "/x" }`: a data-model binding. */
106
+ export function isPathBinding(value: unknown): value is { "@path": string } {
107
+ return (
108
+ isRecord(value) &&
109
+ typeof value["@path"] === "string" &&
110
+ Object.keys(value).length === 1
111
+ );
112
+ }
113
+
114
+ /** `{ "path": "/x" }`: the v0.9 binding, which v1.0 does not accept. */
115
+ function isV09PathBinding(value: unknown) {
116
+ return (
117
+ isRecord(value) &&
118
+ typeof value.path === "string" &&
119
+ Object.keys(value).length === 1
120
+ );
121
+ }
122
+
123
+ /**
124
+ * `{ "@call": "@index" }` or `{ "@call": "@index", "args": { "offset": 1 } }`:
125
+ * the 0-based position of the item in a template, plus `offset`.
126
+ */
127
+ export function isIndexCall(
128
+ value: unknown,
129
+ ): value is { "@call": "@index"; args?: { offset?: number } } {
130
+ if (!isRecord(value) || value["@call"] !== "@index") return false;
131
+ const hasOnlyCallKeys = Object.keys(value).every(
132
+ (key) => key === "@call" || key === "args",
133
+ );
134
+ if (!hasOnlyCallKeys) return false;
135
+ const { args } = value;
136
+ if (args === undefined) return true;
137
+ return (
138
+ isRecord(args) &&
139
+ Object.keys(args).every((key) => key === "offset") &&
140
+ (args.offset === undefined || Number.isFinite(args.offset))
141
+ );
142
+ }
143
+
144
+ export function isActionBinding(
145
+ value: unknown,
146
+ ): value is GenerativeUIActionBinding {
147
+ return (
148
+ isRecord(value) &&
149
+ Object.keys(value).length === 1 &&
150
+ (isRecord(value.functionCall) || isRecord(value.event))
151
+ );
152
+ }
153
+
154
+ /**
155
+ * Checks one A2UI v1.0 operation against the catalog and the surfaces that
156
+ * exist. The operation comes from the model, so nothing in it is trusted.
157
+ *
158
+ * @param op - The operation, as parsed from JSON.
159
+ * @param options - The catalog, the known and created surfaces, the
160
+ * functions that the UI can call, and the components that the target of
161
+ * the surface takes.
162
+ *
163
+ * @example
164
+ * ```ts
165
+ * const result = validateOperation(op, { manifest, knownSurfaces });
166
+ * if (!result.ok) rejected.push({ index, reason: result.reason });
167
+ * ```
168
+ */
169
+ export function validateOperation(
170
+ op: unknown,
171
+ options: ValidateOperationOptions,
172
+ ) {
173
+ if (!isRecord(op)) return fail("operation must be a JSON object");
174
+ if (op.version !== A2UI_VERSION) return fail(versionProblem(op.version));
175
+ const kind = getOperationKind(op);
176
+ if (!kind) {
177
+ return fail(
178
+ `operation must contain exactly one of ${OPERATION_KINDS.join(", ")}`,
179
+ );
180
+ }
181
+ const payload = op[kind];
182
+ if (kind === "callRendererFunction") {
183
+ if (!GENERATIVE_UI_AGENT_FUNCTION_CALLS) {
184
+ return fail(GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON);
185
+ }
186
+ return validateRendererFunctionCall(payload, options);
187
+ }
188
+ if (
189
+ !isRecord(payload) ||
190
+ typeof payload.surfaceId !== "string" ||
191
+ !payload.surfaceId
192
+ ) {
193
+ return fail(`${kind}.surfaceId is required`);
194
+ }
195
+ const surfaceId = payload.surfaceId;
196
+ if (kind === "createSurface") {
197
+ return validateCreateSurface(payload, surfaceId, options);
198
+ }
199
+ if (!options.knownSurfaces.has(surfaceId)) {
200
+ return fail(
201
+ `surface "${surfaceId}" does not exist; send createSurface first`,
202
+ );
203
+ }
204
+ switch (kind) {
205
+ case "deleteSurface":
206
+ return OK;
207
+ case "updateDataModel":
208
+ return validateDataModelUpdate(payload);
209
+ case "updateComponents":
210
+ return validateComponents(
211
+ payload.components,
212
+ "updateComponents.components",
213
+ options,
214
+ );
215
+ }
216
+ }
217
+
218
+ function versionProblem(version: unknown) {
219
+ return typeof version === "string"
220
+ ? `unsupported version "${version}"; use "${A2UI_VERSION}"`
221
+ : `operation needs "version":"${A2UI_VERSION}"`;
222
+ }
223
+
224
+ /** A `catalogId` can name the catalog of the run or one of its bases. */
225
+ function catalogProblem(
226
+ catalogId: unknown,
227
+ manifest: ValidateOperationOptions["manifest"],
228
+ ) {
229
+ const ids = manifest.catalogIds ?? [manifest.catalogId];
230
+ if (catalogId === undefined || ids.includes(catalogId as string)) {
231
+ return undefined;
232
+ }
233
+ const names = ids.map((id) => `"${id}"`).join(", ");
234
+ const use = ids.length === 1 ? names : `one of: ${names}`;
235
+ return `unknown catalog "${String(catalogId)}"; leave out catalogId or use ${use}`;
236
+ }
237
+
238
+ function validateCreateSurface(
239
+ payload: Record<string, unknown>,
240
+ surfaceId: string,
241
+ options: ValidateOperationOptions,
242
+ ) {
243
+ if (options.knownSurfaces.has(surfaceId)) {
244
+ return fail(`surface "${surfaceId}" already exists`);
245
+ }
246
+ if (options.createdSurfaces?.has(surfaceId)) {
247
+ return fail(
248
+ `surface id "${surfaceId}" was used before; use a new surfaceId`,
249
+ );
250
+ }
251
+ const catalogReason = catalogProblem(payload.catalogId, options.manifest);
252
+ if (catalogReason) return fail(catalogReason);
253
+ const { dataModel, components } = payload;
254
+ if (dataModel !== undefined && !isRecord(dataModel)) {
255
+ return fail("createSurface.dataModel must be a JSON object");
256
+ }
257
+ if (components === undefined) return OK;
258
+ return validateComponents(components, "createSurface.components", options);
259
+ }
260
+
261
+ function validateRendererFunctionCall(
262
+ payload: unknown,
263
+ options: ValidateOperationOptions,
264
+ ) {
265
+ const hasCallId =
266
+ isRecord(payload) &&
267
+ typeof payload.functionCallId === "string" &&
268
+ payload.functionCallId !== "";
269
+ if (!hasCallId) {
270
+ return fail(
271
+ "callRendererFunction.functionCallId must be a non-empty string",
272
+ );
273
+ }
274
+ const reason = functionCallProblem(
275
+ payload.callFunction,
276
+ "callRendererFunction.callFunction",
277
+ options,
278
+ );
279
+ return reason ? fail(reason) : OK;
280
+ }
281
+
282
+ const FORBIDDEN_SEGMENTS = new Set(["__proto__", "constructor", "prototype"]);
283
+
284
+ function decodeSegment(segment: string) {
285
+ return segment.replace(/~([01])/g, (_, g) => (g === "1" ? "/" : "~"));
286
+ }
287
+
288
+ function validateDataModelUpdate(payload: Record<string, unknown>) {
289
+ if (payload.value === undefined) {
290
+ return fail(
291
+ 'updateDataModel.value is required; use "value":null to delete',
292
+ );
293
+ }
294
+ const path = payload.path ?? "/";
295
+ if (typeof path !== "string" || !path.startsWith("/")) {
296
+ return fail("updateDataModel.path must be an absolute JSON pointer");
297
+ }
298
+ if (path === "/") {
299
+ // Paths such as "/items" point into the root, so the root must be an object.
300
+ if (!isRecord(payload.value)) {
301
+ return fail("a root updateDataModel value must be a JSON object");
302
+ }
303
+ return OK;
304
+ }
305
+ const reason = pathProblem(path, "updateDataModel.path");
306
+ return reason ? fail(reason) : OK;
307
+ }
308
+
309
+ /**
310
+ * Checks the segments of an absolute JSON pointer ("/a/b") or of a path
311
+ * relative to a template item ("a/b"). `label` names the field in the reason.
312
+ */
313
+ function pathProblem(path: string, label: string) {
314
+ const relative = path.startsWith("/") ? path.slice(1) : path;
315
+ const segments = relative.split("/");
316
+ if (segments.some((segment) => segment === "")) {
317
+ return `${label} must not contain empty segments`;
318
+ }
319
+ const decoded = segments.map(decodeSegment);
320
+ const forbidden = decoded.find((segment) => FORBIDDEN_SEGMENTS.has(segment));
321
+ if (forbidden !== undefined) {
322
+ return `path segment "${forbidden}" is not allowed in ${label}`;
323
+ }
324
+ return undefined;
325
+ }
326
+
327
+ function validateComponents(
328
+ components: unknown,
329
+ label: string,
330
+ options: ValidateOperationOptions,
331
+ ) {
332
+ if (!Array.isArray(components) || components.length === 0) {
333
+ return fail(`${label} must be a non-empty array`);
334
+ }
335
+ const ids = new Set<string>();
336
+ for (const node of components) {
337
+ if (!isRecord(node)) return fail("component must be a JSON object");
338
+ const { id } = node;
339
+ if (typeof id !== "string" || !id) return fail("id is required");
340
+ const reason = nodeProblem(node, id, options);
341
+ if (reason) return fail(`component "${id}": ${reason}`);
342
+ if (ids.has(id)) {
343
+ return fail(`component "${id}" appears twice in one update`);
344
+ }
345
+ ids.add(id);
346
+ }
347
+ return OK;
348
+ }
349
+
350
+ function nodeProblem(
351
+ node: Record<string, unknown>,
352
+ id: string,
353
+ options: ValidateOperationOptions,
354
+ ) {
355
+ if (typeof node.component !== "string") return "component type is required";
356
+ const entry = ownValue(options.manifest.components, node.component);
357
+ if (!entry) return `unknown component "${node.component}"`;
358
+ const { allowedComponents } = options;
359
+ if (allowedComponents && !allowedComponents.names.has(node.component)) {
360
+ const names = [...allowedComponents.names].join(", ") || "none";
361
+ return `"${node.component}" is not allowed in target "${allowedComponents.target}"; use one of: ${names}`;
362
+ }
363
+ const { properties, required } = entry.props;
364
+ const propNames = isRecord(properties) ? Object.keys(properties) : [];
365
+ const props = Object.entries(node);
366
+ for (const [key, value] of props) {
367
+ if (key === "id" || key === "component") continue;
368
+ if (key === "catalogId") {
369
+ const reason = catalogProblem(value, options.manifest);
370
+ if (reason) return `${key}: ${reason}`;
371
+ continue;
372
+ }
373
+ if (key === "metadata") {
374
+ const isMetadata =
375
+ isRecord(value) &&
376
+ (value.extensions === undefined || isRecord(value.extensions));
377
+ if (!isMetadata) return 'metadata must be { "extensions": { ... } }';
378
+ continue;
379
+ }
380
+ if (key === "accessibility") {
381
+ const reason = accessibilityProblem(value);
382
+ if (reason) return `${key}: ${reason}`;
383
+ continue;
384
+ }
385
+ if (ownValue(entry.events, key)) {
386
+ const reason = actionBindingProblem(value, options);
387
+ if (reason) return `${key}: ${reason}`;
388
+ continue;
389
+ }
390
+ const slot = ownValue(entry.slots, key);
391
+ if (slot) {
392
+ const reason = slotProblem(value, slot, id);
393
+ if (reason) return `${key}: ${reason}`;
394
+ continue;
395
+ }
396
+ if (!propNames.includes(key)) return `unknown prop "${key}"`;
397
+ if (isV09PathBinding(value)) return `${key}: ${V09_PATH_REASON}`;
398
+ const call = findForbiddenCall(value, { allowValueFunctions: true });
399
+ if (call !== undefined) {
400
+ return `${key}: ${call}; a data prop can call only ${VALUE_FUNCTION_LIST}`;
401
+ }
402
+ }
403
+ for (const ref of childRefsOf(entry.props)) {
404
+ const reason = childRefProblem(node, ref, id);
405
+ if (reason) return reason;
406
+ }
407
+ const requiredNames = Array.isArray(required) ? required : [];
408
+ for (const name of requiredNames) {
409
+ if (typeof name === "string" && !(name in node)) {
410
+ return `missing required prop "${name}"`;
411
+ }
412
+ }
413
+ return undefined;
414
+ }
415
+
416
+ const ACCESSIBILITY_KEYS = ["label", "description", "live", "hidden"];
417
+ const LIVE_VALUES = ["off", "polite", "assertive"];
418
+
419
+ /**
420
+ * Checks the `accessibility` of a component envelope: `label` and
421
+ * `description` are strings or dynamic values, `live` is one of the ARIA
422
+ * values, `hidden` is a boolean or a dynamic value.
423
+ */
424
+ function accessibilityProblem(value: unknown) {
425
+ if (!isRecord(value)) {
426
+ return 'must be { "label": "...", "description": "...", "live": "polite", "hidden": false }';
427
+ }
428
+ const isDynamic = (field: unknown) =>
429
+ isPathBinding(field) || isCallBinding(field);
430
+ for (const [key, field] of Object.entries(value)) {
431
+ if (!ACCESSIBILITY_KEYS.includes(key)) return `unknown key "${key}"`;
432
+ if (isV09PathBinding(field)) return `${key}: ${V09_PATH_REASON}`;
433
+ if (isDynamic(field)) {
434
+ const call = findForbiddenCall(field, { allowValueFunctions: true });
435
+ if (call !== undefined) return `${key}: ${call}`;
436
+ continue;
437
+ }
438
+ if (key === "live") {
439
+ if (typeof field !== "string" || !LIVE_VALUES.includes(field)) {
440
+ return `live must be one of ${LIVE_VALUES.join(", ")}`;
441
+ }
442
+ } else if (key === "hidden") {
443
+ if (typeof field !== "boolean") return "hidden must be a boolean";
444
+ } else if (typeof field !== "string") {
445
+ return `${key} must be a string`;
446
+ }
447
+ }
448
+ return undefined;
449
+ }
450
+
451
+ function actionBindingProblem(
452
+ value: unknown,
453
+ options: ValidateOperationOptions,
454
+ ) {
455
+ if (!isRecord(value)) return "must be an action object";
456
+ const keys = Object.keys(value);
457
+ const isOneAction =
458
+ keys.length === 1 && (keys[0] === "functionCall" || keys[0] === "event");
459
+ if (!isOneAction) {
460
+ return 'must be { "event": ... } or { "functionCall": ... }';
461
+ }
462
+ if (keys[0] === "functionCall") {
463
+ return functionCallProblem(value.functionCall, "functionCall", options);
464
+ }
465
+ return eventProblem(value.event);
466
+ }
467
+
468
+ /**
469
+ * Checks `{ "@call": "<function>", "args": { ... } }`. `label` names the
470
+ * field in the reason.
471
+ */
472
+ function functionCallProblem(
473
+ call: unknown,
474
+ label: string,
475
+ options: ValidateOperationOptions,
476
+ ) {
477
+ if (!isRecord(call)) {
478
+ return `${label} must be { "@call": "<function>", "args": { ... } }`;
479
+ }
480
+ const name = call["@call"];
481
+ if (typeof name !== "string" || !name) {
482
+ return typeof call.call === "string"
483
+ ? `${label} names the function with "@call", not "call"`
484
+ : `${label}["@call"] must be a function name`;
485
+ }
486
+ const { args } = call;
487
+ if (args !== undefined && !isRecord(args)) {
488
+ return `${label}.args must be an object`;
489
+ }
490
+ const catalogReason = catalogProblem(call.catalogId, options.manifest);
491
+ if (catalogReason) return `${label}: ${catalogReason}`;
492
+ const argEntries = Object.entries(args ?? {});
493
+ for (const [key, arg] of argEntries) {
494
+ if (isV09PathBinding(arg))
495
+ return `${label}.args.${key}: ${V09_PATH_REASON}`;
496
+ }
497
+ // A function the app declares under a built-in name is the app's; the
498
+ // restrictions of the built-in do not apply to it.
499
+ const appFunctions = options.functions;
500
+ const declared =
501
+ appFunctions !== undefined && hasOwn(appFunctions, name)
502
+ ? appFunctions[name]
503
+ : undefined;
504
+ const builtIn =
505
+ declared === undefined && hasOwn(GENERATIVE_UI_FUNCTIONS, name)
506
+ ? GENERATIVE_UI_FUNCTIONS[name]
507
+ : undefined;
508
+ if (declared === undefined && builtIn === undefined) {
509
+ return appFunctions === undefined
510
+ ? undefined
511
+ : `function "${name}" is not exposed to generative UI`;
512
+ }
513
+ // Without the list of app functions, a built-in name may be the app's own
514
+ // function, so the dispatcher applies the restriction when the call runs.
515
+ if (declared === undefined && appFunctions === undefined) return undefined;
516
+ return callerProblem(
517
+ name,
518
+ declared ?? builtIn!,
519
+ label.startsWith("callRendererFunction") ? "agent" : "renderer",
520
+ );
521
+ }
522
+
523
+ /**
524
+ * Why `caller` may not call a function with these permissions, or
525
+ * `undefined` when it may. The dispatcher gives the same reasons at run
526
+ * time, for the calls that are not validated against a function list.
527
+ */
528
+ export function callerProblem(
529
+ name: string,
530
+ fn: A2UIFunctionPermissions,
531
+ caller: "agent" | "renderer",
532
+ ) {
533
+ const callers = functionCallers(fn);
534
+ if (caller === "agent" && !callers.agent) {
535
+ return fn.requiresUserActivation
536
+ ? `function "${name}" runs only from a user gesture; the agent cannot call it`
537
+ : `function "${name}" runs only in the UI (allowedCallers "rendererOnly"); the agent cannot call it`;
538
+ }
539
+ if (caller === "renderer" && !callers.renderer) {
540
+ return `function "${name}" runs only for the agent (allowedCallers "agentOnly"); the UI cannot call it`;
541
+ }
542
+ return undefined;
543
+ }
544
+
545
+ function eventProblem(event: unknown) {
546
+ if (!isRecord(event) || typeof event.name !== "string" || !event.name) {
547
+ return "event.name is required";
548
+ }
549
+ const { userMessage, context } = event;
550
+ const isUserMessage =
551
+ userMessage === undefined ||
552
+ typeof userMessage === "string" ||
553
+ isPathBinding(userMessage) ||
554
+ (isRecord(userMessage) &&
555
+ typeof userMessage["@call"] === "string" &&
556
+ findForbiddenCall(userMessage, { allowValueFunctions: true }) ===
557
+ undefined);
558
+ if (!isUserMessage) {
559
+ return isV09PathBinding(userMessage)
560
+ ? `event.userMessage: ${V09_PATH_REASON}`
561
+ : 'event.userMessage must be a string, {"@path": "/x"} or a function value';
562
+ }
563
+ if (context === undefined) return undefined;
564
+ if (!isRecord(context)) return "event.context must be an object";
565
+ const entries = Object.entries(context);
566
+ for (const [key, entry] of entries) {
567
+ if (isV09PathBinding(entry)) {
568
+ return `event.context.${key}: ${V09_PATH_REASON}`;
569
+ }
570
+ const call = findForbiddenCall(entry, { allowValueFunctions: true });
571
+ if (call !== undefined) {
572
+ return `event.context.${key}: ${call}; a context value can call only ${VALUE_FUNCTION_LIST}`;
573
+ }
574
+ }
575
+ return undefined;
576
+ }
577
+
578
+ function slotProblem(
579
+ value: unknown,
580
+ kind: "single" | "multiple",
581
+ ownId: string,
582
+ ) {
583
+ const isTemplate = isRecord(value) && "componentId" in value;
584
+ if (kind === "single" && isTemplate) {
585
+ return 'a template { "componentId", "path" } is only allowed in a "multiple" slot';
586
+ }
587
+ if (kind === "multiple" && isTemplate) {
588
+ return templateProblem(value, ownId);
589
+ }
590
+ if (kind === "multiple" && !Array.isArray(value)) {
591
+ return 'must be an array of component ids or a template { "componentId", "path" }';
592
+ }
593
+ const ids = kind === "multiple" && Array.isArray(value) ? value : [value];
594
+ for (const id of ids) {
595
+ if (typeof id !== "string" || !id)
596
+ return "must reference component ids (strings)";
597
+ if (id === ownId) return "a component cannot be its own child";
598
+ }
599
+ return undefined;
600
+ }
601
+
602
+ function templateProblem(template: Record<string, unknown>, ownId: string) {
603
+ const hasOnlyTemplateKeys = Object.keys(template).every(
604
+ (key) => key === "componentId" || key === "path",
605
+ );
606
+ if (!hasOnlyTemplateKeys) {
607
+ return 'a template takes only "componentId" and "path"';
608
+ }
609
+ const { componentId, path } = template;
610
+ if (typeof componentId !== "string" || !componentId) {
611
+ return "template componentId must be a component id";
612
+ }
613
+ if (componentId === ownId) return "a component cannot be its own child";
614
+ if (typeof path !== "string" || !path) {
615
+ return "template path must be a JSON pointer or a relative path";
616
+ }
617
+ return pathProblem(path, "template path");
618
+ }
619
+
620
+ const VALUE_FUNCTION_LIST = `@index and the built-in functions (${Object.keys(
621
+ GENERATIVE_UI_FUNCTIONS,
622
+ )
623
+ .filter(isA2UIValueFunction)
624
+ .join(", ")})`;
625
+
626
+ /**
627
+ * The reason for the first function call in `value` that a data value may
628
+ * not make, at any depth, or `undefined`. A data value may call `@index`
629
+ * and, with `allowValueFunctions`, the basic functions that need no user
630
+ * gesture; the renderer resolves those. An app function, `openUrl`, or an
631
+ * event binding is not a value.
632
+ */
633
+ // The annotation is needed: the function calls itself in its return.
634
+ function findForbiddenCall(
635
+ value: unknown,
636
+ options: { allowValueFunctions: boolean },
637
+ ): string | undefined {
638
+ if (Array.isArray(value)) {
639
+ for (const item of value) {
640
+ const reason = findForbiddenCall(item, options);
641
+ if (reason !== undefined) return reason;
642
+ }
643
+ return undefined;
644
+ }
645
+ if (!isRecord(value)) return undefined;
646
+ if (isIndexCall(value)) return undefined;
647
+ if (value["@call"] === "@index") return "@index takes only an offset";
648
+ if (typeof value.call === "string") {
649
+ return 'name the function with "@call", not "call"';
650
+ }
651
+ if ("functionCall" in value) {
652
+ return "an event binding is not a value";
653
+ }
654
+ const name = value["@call"];
655
+ if (typeof name === "string") {
656
+ if (!options.allowValueFunctions || !isA2UIValueFunction(name)) {
657
+ return isA2UIBasicFunction(name)
658
+ ? `"${name}" runs only from an event`
659
+ : `"${name}" is not a basic function`;
660
+ }
661
+ const args = value.args;
662
+ if (args !== undefined && !isRecord(args)) {
663
+ return `the args of "${name}" must be an object`;
664
+ }
665
+ return args === undefined ? undefined : findForbiddenCall(args, options);
666
+ }
667
+ for (const item of Object.values(value)) {
668
+ const reason = findForbiddenCall(item, options);
669
+ if (reason !== undefined) return reason;
670
+ }
671
+ return undefined;
672
+ }
673
+
674
+ const childRefCache = new WeakMap<GenerativeUIJSONSchema, ChildRef[]>();
675
+
676
+ /** The component references of a props schema, computed once per schema. */
677
+ function childRefsOf(props: GenerativeUIJSONSchema) {
678
+ let refs = childRefCache.get(props);
679
+ if (!refs) {
680
+ refs = collectChildRefs(props);
681
+ childRefCache.set(props, refs);
682
+ }
683
+ return refs;
684
+ }
685
+
686
+ /**
687
+ * Checks the component ids at one reference of a node: a typed `child()`
688
+ * or `childList()` prop, at any depth. A missing key is fine; the props
689
+ * schema reports a required one.
690
+ */
691
+ function childRefProblem(
692
+ node: Record<string, unknown>,
693
+ ref: ChildRef,
694
+ ownId: string,
695
+ ): string | undefined {
696
+ const label = ref.path.filter((step) => step !== "*").join(".");
697
+ const isDynamic = (value: unknown) =>
698
+ isPathBinding(value) || (isRecord(value) && "@call" in value);
699
+ const visit = (
700
+ value: unknown,
701
+ steps: readonly string[],
702
+ ): string | undefined => {
703
+ // A bound or computed value, at the reference or above it, is known
704
+ // only at render.
705
+ if (isDynamic(value)) return undefined;
706
+ if (steps.length === 0) {
707
+ const reason = slotProblem(value, ref.kind, ownId);
708
+ return reason ? `${label}: ${reason}` : undefined;
709
+ }
710
+ const [head, ...rest] = steps;
711
+ if (head === "*") {
712
+ if (!Array.isArray(value)) return undefined;
713
+ for (const item of value) {
714
+ const reason = visit(item, rest);
715
+ if (reason) return reason;
716
+ }
717
+ return undefined;
718
+ }
719
+ if (!isRecord(value) || !hasOwn(value, head)) return undefined;
720
+ return visit(value[head], rest);
721
+ };
722
+ return visit(node, ref.path);
723
+ }