ain-ui 0.2.3 → 1.0.4
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/NOTICE +37 -0
- package/README.md +179 -77
- package/dist/agent.d.ts +131 -0
- package/dist/agent.js +822 -0
- package/dist/ainui.d.ts +15 -1
- package/dist/ainui.js +53 -10
- package/dist/basic.d.ts +5 -47
- package/dist/basic.js +22 -29
- package/dist/catalog/standard.gen.d.ts +5 -0
- package/dist/catalog/standard.gen.js +6 -0
- package/dist/catalog-v1.json +2560 -0
- package/dist/catalog.json +19917 -2061
- package/dist/chat.js +6 -7
- package/dist/expression.d.ts +23 -0
- package/dist/expression.js +222 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/macros.d.ts +12 -0
- package/dist/macros.js +57 -0
- package/dist/payment.js +6 -7
- package/dist/pickers.d.ts +158 -0
- package/dist/pickers.js +110 -0
- package/dist/protocol.d.ts +100 -0
- package/dist/protocol.js +232 -0
- package/dist/react/ain.d.ts +1 -0
- package/dist/react/ain.js +225 -0
- package/dist/react/catalog.d.ts +9 -0
- package/dist/react/catalog.js +23 -0
- package/dist/react/core.d.ts +91 -0
- package/dist/react/core.js +173 -0
- package/dist/react/functions.d.ts +2 -0
- package/dist/react/functions.js +29 -0
- package/dist/react/standard/composites.d.ts +1 -0
- package/dist/react/standard/composites.js +110 -0
- package/dist/react/standard/data.d.ts +1 -0
- package/dist/react/standard/data.js +481 -0
- package/dist/react/standard/feedback.d.ts +11 -0
- package/dist/react/standard/feedback.js +111 -0
- package/dist/react/standard/inputs.d.ts +5 -0
- package/dist/react/standard/inputs.js +467 -0
- package/dist/react/standard/layout.d.ts +5 -0
- package/dist/react/standard/layout.js +104 -0
- package/dist/react/standard/media.d.ts +33 -0
- package/dist/react/standard/media.js +208 -0
- package/dist/react/standard/rich.d.ts +1 -0
- package/dist/react/standard/rich.js +146 -0
- package/dist/react/standard/text.d.ts +9 -0
- package/dist/react/standard/text.js +209 -0
- package/dist/react/surface.d.ts +46 -0
- package/dist/react/surface.js +134 -0
- package/dist/react.d.ts +3 -35
- package/dist/react.js +3 -272
- package/dist/renderer.d.ts +1 -1
- package/dist/renderer.js +299 -4
- package/dist/styles.css +805 -20
- package/package.json +28 -11
package/dist/agent.js
ADDED
|
@@ -0,0 +1,822 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agent side of AIN-UI: what a model is told, the `render_ui` tool it calls, and the check and compilation of
|
|
3
|
+
* what it writes — built on Google's `@a2ui/agent`.
|
|
4
|
+
*
|
|
5
|
+
* Two formats. "express" is one line per component (`root = Column([Title("Hi"), Button("Go", onClick=Event("go"))])`),
|
|
6
|
+
* compiled here into A2UI 1.0 messages; "json" is the messages themselves. Either way nothing reaches a renderer
|
|
7
|
+
* before it has been validated against the catalog the renderer said it draws.
|
|
8
|
+
*
|
|
9
|
+
* Node or any server runtime; no DOM, no React.
|
|
10
|
+
*/
|
|
11
|
+
import { A2uiGenerator, Catalog, CatalogConfig, DirectJsonFormatFactory, ExpressFormatFactory, SkillGenerator, readRendererCapabilities, validatePayload, } from "@a2ui/agent";
|
|
12
|
+
import { AINUI_CATALOG_DOCUMENT } from "./catalog/standard.gen.js";
|
|
13
|
+
import { A2UI_VERSION, AINUI_CATALOG } from "./protocol.js";
|
|
14
|
+
export const RENDER_UI_TOOL = "render_ui";
|
|
15
|
+
/** Where a renderer's capabilities travel in request metadata (A2A `metadata`, AG-UI `forwardedProps`, MCP `_meta`). */
|
|
16
|
+
export const RENDERER_CAPABILITIES_KEY = "a2uiRendererCapabilities";
|
|
17
|
+
const clone = (v) => JSON.parse(JSON.stringify(v));
|
|
18
|
+
export const defineMacro = (macro) => macro;
|
|
19
|
+
const MACRO_DEPTH = 16;
|
|
20
|
+
/** Replaces every macro in a component list with its expansion, repeatedly, so a macro may use another. */
|
|
21
|
+
export function expandMacros(components, macros) {
|
|
22
|
+
if (!macros.length)
|
|
23
|
+
return components;
|
|
24
|
+
const byName = new Map(macros.map((m) => [m.name, m]));
|
|
25
|
+
let list = components;
|
|
26
|
+
for (let depth = 0; depth < MACRO_DEPTH; depth++) {
|
|
27
|
+
if (!list.some((c) => byName.has(c.component)))
|
|
28
|
+
return list;
|
|
29
|
+
list = list.flatMap((c) => {
|
|
30
|
+
const macro = byName.get(c.component);
|
|
31
|
+
if (!macro)
|
|
32
|
+
return [c];
|
|
33
|
+
const { id, component: _component, ...props } = c;
|
|
34
|
+
let n = 0;
|
|
35
|
+
const made = macro.expand(props, (key) => `${id}__${key}`);
|
|
36
|
+
if (!made.length)
|
|
37
|
+
return [];
|
|
38
|
+
return made.map((part, i) => ({ ...part, id: i === 0 ? id : part.id ?? `${id}__${part.component}_${++n}` }));
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
throw new Error(`macros nest deeper than ${MACRO_DEPTH} levels`);
|
|
42
|
+
}
|
|
43
|
+
function withMacros(doc, macros) {
|
|
44
|
+
if (!macros.length)
|
|
45
|
+
return doc;
|
|
46
|
+
const next = clone(doc);
|
|
47
|
+
for (const m of macros) {
|
|
48
|
+
next.components[m.name] = { type: "object", description: m.description, properties: { component: { const: m.name }, ...m.props }, required: ["component", ...(m.required ?? [])] };
|
|
49
|
+
}
|
|
50
|
+
next.$defs = { ...next.$defs, anyComponent: { oneOf: Object.keys(next.components).map((name) => ({ $ref: `#/components/${name}` })) } };
|
|
51
|
+
return next;
|
|
52
|
+
}
|
|
53
|
+
// ── catalogs ───────────────────────────────────────────────────────────────
|
|
54
|
+
/** The AINUI catalog document, optionally narrowed to some components (a smaller prompt, a stricter check). */
|
|
55
|
+
export function ainuiCatalogDocument(options = {}) {
|
|
56
|
+
const doc = clone(AINUI_CATALOG_DOCUMENT);
|
|
57
|
+
if (options.components) {
|
|
58
|
+
const keep = new Set(options.components);
|
|
59
|
+
doc.components = Object.fromEntries(Object.entries(doc.components).filter(([name]) => keep.has(name)));
|
|
60
|
+
doc.$defs.anyComponent = { oneOf: Object.keys(doc.components).map((name) => ({ $ref: `#/components/${name}` })) };
|
|
61
|
+
}
|
|
62
|
+
return doc;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* What the renderer on the other end said it can draw, read from request metadata. `undefined` means it did not
|
|
66
|
+
* ask for A2UI: answer in text.
|
|
67
|
+
*/
|
|
68
|
+
export function rendererCapabilities(metadata) {
|
|
69
|
+
return readRendererCapabilities(metadata);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The catalog documents to write for, given a renderer's capabilities: the catalogs it sent inline (a browser that
|
|
73
|
+
* brings its own design system), else AIN-UI's own when the renderer lists its id.
|
|
74
|
+
*/
|
|
75
|
+
export function catalogsFor(capabilities) {
|
|
76
|
+
const v1 = capabilities?.[A2UI_VERSION] ?? capabilities;
|
|
77
|
+
const inline = Array.isArray(v1?.inlineCatalogs) ? v1.inlineCatalogs.filter((c) => c && typeof c === "object" && c.components) : [];
|
|
78
|
+
if (inline.length)
|
|
79
|
+
return inline;
|
|
80
|
+
const ids = Array.isArray(v1?.supportedCatalogIds) ? v1.supportedCatalogIds : [];
|
|
81
|
+
return ids.includes(AINUI_CATALOG) ? [ainuiCatalogDocument()] : [];
|
|
82
|
+
}
|
|
83
|
+
// ── what the model is shown, and what it is forgiven ───────────────────────
|
|
84
|
+
const BOX_RARE = ["onVisible", "wrap", "rowGap", "columnGap", "borderColor", "minWidth", "maxWidth", "minHeight", "maxHeight", "weight", "aspectRatio",
|
|
85
|
+
"scrollable", "clip", "shadow", "inline", "role", "flush", "minSize", "maxSize", "disableAutoSpacing"];
|
|
86
|
+
/**
|
|
87
|
+
* The catalog as the model is told it: container components lose the twenty layout props almost no surface
|
|
88
|
+
* needs (the same list on fourteen components is a third of the prompt). The renderer's catalog is unchanged, so
|
|
89
|
+
* a surface that does use one of them is still valid.
|
|
90
|
+
*/
|
|
91
|
+
export function compactCatalogDocument(doc) {
|
|
92
|
+
const next = clone(doc);
|
|
93
|
+
for (const c of Object.values(next.components ?? {})) {
|
|
94
|
+
const props = c.properties ?? {};
|
|
95
|
+
if (BOX_RARE.filter((k) => k in props).length < 15)
|
|
96
|
+
continue;
|
|
97
|
+
for (const k of BOX_RARE)
|
|
98
|
+
delete props[k];
|
|
99
|
+
}
|
|
100
|
+
return next;
|
|
101
|
+
}
|
|
102
|
+
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
103
|
+
const isDynamic = (v) => isObj(v) && (typeof v["@path"] === "string" || typeof v["@call"] === "string" || typeof v.event === "object" || typeof v.componentId === "string");
|
|
104
|
+
const alternatives = (schema) => (!schema ? [] : schema.anyOf || schema.oneOf ? (schema.anyOf ?? schema.oneOf).flatMap(alternatives) : [schema]);
|
|
105
|
+
const typesOf = (schema) => (Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : []);
|
|
106
|
+
/**
|
|
107
|
+
* Forgives the two mistakes models make most and a renderer would reject outright: a key the schema does not
|
|
108
|
+
* have (dropped) and a number written as a string (converted). Everything else is left for validation to refuse.
|
|
109
|
+
*/
|
|
110
|
+
function tidy(value, schema, notes, where) {
|
|
111
|
+
const alts = alternatives(schema);
|
|
112
|
+
if (!alts.length || isDynamic(value))
|
|
113
|
+
return value;
|
|
114
|
+
if (Array.isArray(value)) {
|
|
115
|
+
const list = alts.find((a) => typesOf(a).includes("array") && a.items);
|
|
116
|
+
return list ? value.map((item, i) => tidy(item, list.items, notes, `${where}[${i}]`)) : value;
|
|
117
|
+
}
|
|
118
|
+
if (typeof value === "string" && !alts.some((a) => typesOf(a).includes("string") || "const" in a || a.enum)) {
|
|
119
|
+
const shape = alts.find((a) => typesOf(a).includes("object") && a.properties && (a.required ?? []).length === 1);
|
|
120
|
+
const only = shape?.required?.[0];
|
|
121
|
+
if (shape && only && alternatives(shape.properties[only]).some((a) => typesOf(a).includes("string"))) {
|
|
122
|
+
notes.push(`${where} was text; read as {${only}}`);
|
|
123
|
+
return { [only]: value };
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (isObj(value)) {
|
|
127
|
+
const shapes = alts.filter((a) => typesOf(a).includes("object") && a.properties);
|
|
128
|
+
const shape = shapes.find((a) => (a.required ?? []).every((k) => k in value)) ?? shapes[0];
|
|
129
|
+
if (!shape)
|
|
130
|
+
return value;
|
|
131
|
+
const out = {};
|
|
132
|
+
for (const [k, v] of Object.entries(value)) {
|
|
133
|
+
if (!(k in shape.properties)) {
|
|
134
|
+
if (shape.additionalProperties === false) {
|
|
135
|
+
notes.push(`${where}.${k} is not a property; ignored`);
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
out[k] = v;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
out[k] = tidy(v, shape.properties[k], notes, `${where}.${k}`);
|
|
142
|
+
}
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
if (typeof value === "string" && value.trim() !== "" && !Number.isNaN(Number(value))) {
|
|
146
|
+
const types = alts.flatMap(typesOf);
|
|
147
|
+
if (!types.includes("string") && (types.includes("number") || types.includes("integer")) && !alts.some((a) => a.enum || "const" in a))
|
|
148
|
+
return Number(value);
|
|
149
|
+
}
|
|
150
|
+
return value;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Reads JSON a model wrote as a string, repairing the one mistake it makes most: a closing bracket that does
|
|
154
|
+
* not match (`…"/x"}}}}, {"id": …` inside an array, or `…}]}]` at the end). Such a closer is dropped and
|
|
155
|
+
* counted; closers missing at the end are added. Strings are never touched, and anything else that does not
|
|
156
|
+
* parse still fails.
|
|
157
|
+
*/
|
|
158
|
+
export function leadingJson(text) {
|
|
159
|
+
const src = text.trim();
|
|
160
|
+
try {
|
|
161
|
+
return { value: JSON.parse(src), trailing: 0 };
|
|
162
|
+
}
|
|
163
|
+
catch { /* repair below */ }
|
|
164
|
+
if (src[0] !== "[" && src[0] !== "{")
|
|
165
|
+
return undefined;
|
|
166
|
+
const stack = [];
|
|
167
|
+
let out = "", dropped = 0, inString = false;
|
|
168
|
+
for (let i = 0; i < src.length; i++) {
|
|
169
|
+
const ch = src[i];
|
|
170
|
+
if (inString) {
|
|
171
|
+
out += ch;
|
|
172
|
+
if (ch === "\\" && i + 1 < src.length)
|
|
173
|
+
out += src[++i];
|
|
174
|
+
else if (ch === '"')
|
|
175
|
+
inString = false;
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (ch === '"') {
|
|
179
|
+
inString = true;
|
|
180
|
+
out += ch;
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
if (ch === "[" || ch === "{") {
|
|
184
|
+
if (!stack.length && out.trim()) {
|
|
185
|
+
dropped += src.length - i;
|
|
186
|
+
break;
|
|
187
|
+
}
|
|
188
|
+
// `{` where an object expects a key (`…}}}, {"id": …`): the object before it was never closed. Close
|
|
189
|
+
// objects up to the array the new item belongs in.
|
|
190
|
+
if (ch === "{" && stack[stack.length - 1] === "}" && /,\s*$/.test(out) && stack.includes("]")) {
|
|
191
|
+
while (stack[stack.length - 1] === "}") {
|
|
192
|
+
out = out.replace(/,\s*$/, "") + stack.pop();
|
|
193
|
+
dropped++;
|
|
194
|
+
}
|
|
195
|
+
out += ",";
|
|
196
|
+
}
|
|
197
|
+
stack.push(ch === "[" ? "]" : "}");
|
|
198
|
+
out += ch;
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
if (ch === "]" || ch === "}") {
|
|
202
|
+
if (stack[stack.length - 1] === ch) {
|
|
203
|
+
stack.pop();
|
|
204
|
+
out += ch;
|
|
205
|
+
}
|
|
206
|
+
else
|
|
207
|
+
dropped++;
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (!stack.length && out.trim() && ch.trim()) {
|
|
211
|
+
if (/^[\s,]*$/.test(src.slice(i)))
|
|
212
|
+
break;
|
|
213
|
+
return undefined;
|
|
214
|
+
}
|
|
215
|
+
out += ch;
|
|
216
|
+
}
|
|
217
|
+
while (stack.length)
|
|
218
|
+
out += stack.pop();
|
|
219
|
+
try {
|
|
220
|
+
return { value: JSON.parse(out.replace(/,(\s*[\]}])/g, "$1")), trailing: dropped || 1 };
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
return undefined;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Messages that replace a surface the renderer already shows with a whole new one under the same id: delete it,
|
|
228
|
+
* then create it again (1.0 allows the id again once it was deleted).
|
|
229
|
+
*/
|
|
230
|
+
export function replaceSurface(surfaceId, catalogId, components, dataModel) {
|
|
231
|
+
return [
|
|
232
|
+
{ version: A2UI_VERSION, deleteSurface: { surfaceId } },
|
|
233
|
+
{ version: A2UI_VERSION, createSurface: { surfaceId, catalogId, components, ...(dataModel ? { dataModel } : {}) } },
|
|
234
|
+
];
|
|
235
|
+
}
|
|
236
|
+
/** Names models use for a prop the catalog calls something else. Only applied when the component has the target. */
|
|
237
|
+
const PROP_ALIASES = { title: ["text", "label"], text: ["label", "title"], label: ["text", "title"], content: ["text"], name: ["label", "title"] };
|
|
238
|
+
/**
|
|
239
|
+
* One keyword argument `name=` in the call of component `component`, removed or renamed. Calls are found by
|
|
240
|
+
* `Component(`; arguments are split at top-level commas, so nested lists, maps and calls are skipped whole.
|
|
241
|
+
*/
|
|
242
|
+
function editExpressArgument(source, component, name, rename) {
|
|
243
|
+
const edits = [];
|
|
244
|
+
const call = new RegExp(`\\b${component}\\(`, "g");
|
|
245
|
+
const key = new RegExp(`^(\\s*)${name}(\\s*=)`);
|
|
246
|
+
let match;
|
|
247
|
+
while ((match = call.exec(source))) {
|
|
248
|
+
const args = [];
|
|
249
|
+
let depth = 0, quote = null, from = match.index + match[0].length;
|
|
250
|
+
for (let i = from; i < source.length; i++) {
|
|
251
|
+
const ch = source[i];
|
|
252
|
+
if (quote) {
|
|
253
|
+
if (ch === "\\")
|
|
254
|
+
i++;
|
|
255
|
+
else if (ch === quote)
|
|
256
|
+
quote = null;
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
if (ch === '"' || ch === "'") {
|
|
260
|
+
quote = ch;
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
if (ch === "(" || ch === "[" || ch === "{") {
|
|
264
|
+
depth++;
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
if ((ch === ")" || ch === "]" || ch === "}") && depth > 0) {
|
|
268
|
+
depth--;
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
if (depth === 0 && (ch === "," || ch === ")")) {
|
|
272
|
+
args.push([from, i]);
|
|
273
|
+
from = i + 1;
|
|
274
|
+
if (ch === ")")
|
|
275
|
+
break;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
args.forEach(([a, b], n) => {
|
|
279
|
+
const arg = source.slice(a, b);
|
|
280
|
+
if (!key.test(arg))
|
|
281
|
+
return;
|
|
282
|
+
if (rename)
|
|
283
|
+
edits.push({ from: a, to: b, text: arg.replace(key, `$1${rename}$2`) });
|
|
284
|
+
// drop the argument with the comma before it, or after it when it is the first one
|
|
285
|
+
else if (n > 0)
|
|
286
|
+
edits.push({ from: args[n - 1][1], to: b, text: "" });
|
|
287
|
+
else
|
|
288
|
+
edits.push({ from: a, to: args.length > 1 ? args[1][0] : b, text: "" });
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
if (!edits.length)
|
|
292
|
+
return null;
|
|
293
|
+
let out = source;
|
|
294
|
+
for (const e of edits.sort((x, y) => y.from - x.from))
|
|
295
|
+
out = out.slice(0, e.from) + e.text + out.slice(e.to);
|
|
296
|
+
return out;
|
|
297
|
+
}
|
|
298
|
+
/** A compiler complaint the source can be edited past, and the edited source. */
|
|
299
|
+
function repairExpress(source, error, docs) {
|
|
300
|
+
const props = (component) => Object.keys(docs.map((d) => d.components?.[component]).find(Boolean)?.properties ?? {});
|
|
301
|
+
let m = /Property '(\w+)' is not a valid property of component '(\w+)'/.exec(error);
|
|
302
|
+
if (m) {
|
|
303
|
+
const [, prop, component] = m;
|
|
304
|
+
const known = props(component);
|
|
305
|
+
const target = (PROP_ALIASES[prop] ?? []).find((t) => known.includes(t));
|
|
306
|
+
const next = editExpressArgument(source, component, prop, target);
|
|
307
|
+
return next ? { source: next, note: target ? `${component}: ${prop}= read as ${target}=` : `${component}: ${prop}= is not a property; left out` } : null;
|
|
308
|
+
}
|
|
309
|
+
m = /Value '[^']*' is not a valid enum choice for property '(\w+)' of component '(\w+)'/.exec(error);
|
|
310
|
+
if (m) {
|
|
311
|
+
const next = editExpressArgument(source, m[2], m[1]);
|
|
312
|
+
return next ? { source: next, note: `${m[2]}: ${m[1]}= had a value it does not take; left unset` } : null;
|
|
313
|
+
}
|
|
314
|
+
m = /Component '(\w+)' does not accept checks/.exec(error);
|
|
315
|
+
if (m) {
|
|
316
|
+
const next = editExpressArgument(source, m[1], "checks");
|
|
317
|
+
return next ? { source: next, note: `${m[1]}: checks are not taken there; left out` } : null;
|
|
318
|
+
}
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* A component written where the schema wants a list of plain objects: `actions=[Button("Buy", onClick=…)]`,
|
|
323
|
+
* `StatGroup([Stat(…), Stat(…)])`. Express makes each a component of its own and leaves its id in the list,
|
|
324
|
+
* which the renderer refuses. The component's own props become the list item, and the component goes.
|
|
325
|
+
*/
|
|
326
|
+
function inlineItemComponents(list, docs, notes) {
|
|
327
|
+
const byId = new Map(list.map((c) => [c.id, c]));
|
|
328
|
+
const inlined = new Set();
|
|
329
|
+
const next = list.map((c) => {
|
|
330
|
+
const schema = docs.map((d) => d.components?.[c.component]).find(Boolean);
|
|
331
|
+
if (!schema?.properties)
|
|
332
|
+
return c;
|
|
333
|
+
let changed = null;
|
|
334
|
+
for (const [key, value] of Object.entries(c)) {
|
|
335
|
+
if (!Array.isArray(value) || !value.some((v) => typeof v === "string" && byId.has(v)))
|
|
336
|
+
continue;
|
|
337
|
+
const prop = schema.properties[key];
|
|
338
|
+
if (!prop || /ChildList$|ComponentId$/.test(String(prop.$ref ?? "")))
|
|
339
|
+
continue;
|
|
340
|
+
const list = alternatives(prop).find((a) => typesOf(a).includes("array") && a.items);
|
|
341
|
+
const wantsObjects = list && alternatives(list.items).some((a) => typesOf(a).includes("object") && a.properties);
|
|
342
|
+
if (!wantsObjects)
|
|
343
|
+
continue;
|
|
344
|
+
const item = alternatives(list.items).find((a) => typesOf(a).includes("object") && a.properties);
|
|
345
|
+
changed ??= { ...c };
|
|
346
|
+
changed[key] = value.map((v) => {
|
|
347
|
+
const ref = typeof v === "string" ? byId.get(v) : undefined;
|
|
348
|
+
if (!ref)
|
|
349
|
+
return v;
|
|
350
|
+
inlined.add(ref.id);
|
|
351
|
+
const { id: _id, component: _component, ...props } = ref;
|
|
352
|
+
// what the component called its words, the item may call label/title/text
|
|
353
|
+
const own = Object.keys(item.properties);
|
|
354
|
+
const out = {};
|
|
355
|
+
for (const [k, x] of Object.entries(props)) {
|
|
356
|
+
const target = own.includes(k) ? k : (PROP_ALIASES[k] ?? []).find((t) => own.includes(t));
|
|
357
|
+
if (target && !(target in out))
|
|
358
|
+
out[target] = x;
|
|
359
|
+
else if (k === "onClick" || k === "action")
|
|
360
|
+
out[k] = x;
|
|
361
|
+
}
|
|
362
|
+
return out;
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
return changed ?? c;
|
|
366
|
+
});
|
|
367
|
+
if (inlined.size)
|
|
368
|
+
notes.push(`components used as list items became the items: ${[...inlined].slice(0, 6).join(", ")}`);
|
|
369
|
+
return next.filter((c) => !inlined.has(c.id));
|
|
370
|
+
}
|
|
371
|
+
/** Where one component names another. */
|
|
372
|
+
const REF_KEYS = new Set(["children", "child", "trigger", "content", "componentId", "cellComponents"]);
|
|
373
|
+
const IDENT = /^[\p{ID_Start}_][\p{ID_Continue}]*$/u;
|
|
374
|
+
function mapRefs(value, key, fn) {
|
|
375
|
+
if (typeof value === "string")
|
|
376
|
+
return key && REF_KEYS.has(key) ? fn(value) : value;
|
|
377
|
+
if (Array.isArray(value))
|
|
378
|
+
return value.map((v) => mapRefs(v, key, fn));
|
|
379
|
+
if (isObj(value))
|
|
380
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, mapRefs(v, k, fn)]));
|
|
381
|
+
return value;
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Ids must be identifiers in 1.0 (`rec-title` is not); a model that writes one otherwise means the obvious thing.
|
|
385
|
+
* Then components nothing refers to are left out — a renderer refuses a surface with an orphan in it.
|
|
386
|
+
*/
|
|
387
|
+
function tidyTree(list, notes, whole) {
|
|
388
|
+
const renamed = new Map();
|
|
389
|
+
const taken = new Set(list.map((c) => c.id));
|
|
390
|
+
for (const c of list) {
|
|
391
|
+
if (typeof c.id !== "string" || IDENT.test(c.id))
|
|
392
|
+
continue;
|
|
393
|
+
let next = c.id.replace(/[^\p{ID_Continue}]/gu, "_").replace(/^(?![\p{ID_Start}_])/u, "_") || "_";
|
|
394
|
+
while (taken.has(next))
|
|
395
|
+
next += "_";
|
|
396
|
+
taken.add(next);
|
|
397
|
+
renamed.set(c.id, next);
|
|
398
|
+
}
|
|
399
|
+
let out = list;
|
|
400
|
+
if (renamed.size) {
|
|
401
|
+
notes.push(`ids renamed to identifiers: ${[...renamed].slice(0, 4).map(([a, b]) => `${a} → ${b}`).join(", ")}${renamed.size > 4 ? ", …" : ""}`);
|
|
402
|
+
out = list.map((c) => ({ ...mapRefs(c, undefined, (id) => renamed.get(id) ?? id), id: renamed.get(c.id) ?? c.id }));
|
|
403
|
+
}
|
|
404
|
+
if (!whole || !out.some((c) => c.id === "root"))
|
|
405
|
+
return out;
|
|
406
|
+
// A child named in a list that was never written is left out of the list, not fatal.
|
|
407
|
+
const ids = new Set(out.map((c) => c.id));
|
|
408
|
+
const missing = new Set();
|
|
409
|
+
out = out.map((c) => Array.isArray(c.children) && c.children.some((x) => typeof x === "string" && !ids.has(x))
|
|
410
|
+
? { ...c, children: c.children.filter((x) => typeof x !== "string" || ids.has(x) || (missing.add(x), false)) } : c);
|
|
411
|
+
if (missing.size)
|
|
412
|
+
notes.push(`children never written, left out: ${[...missing].slice(0, 6).join(", ")}`);
|
|
413
|
+
const byId = new Map(out.map((c) => [c.id, c]));
|
|
414
|
+
const reached = new Set();
|
|
415
|
+
const visit = (id) => {
|
|
416
|
+
const c = byId.get(id);
|
|
417
|
+
if (!c || reached.has(id))
|
|
418
|
+
return;
|
|
419
|
+
reached.add(id);
|
|
420
|
+
mapRefs(c, undefined, (ref) => { visit(ref); return ref; });
|
|
421
|
+
};
|
|
422
|
+
visit("root");
|
|
423
|
+
const orphans = out.filter((c) => !reached.has(c.id));
|
|
424
|
+
if (orphans.length)
|
|
425
|
+
notes.push(`not used by any parent, left out: ${orphans.map((c) => c.id).slice(0, 6).join(", ")}`);
|
|
426
|
+
return orphans.length ? out.filter((c) => reached.has(c.id)) : out;
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Buttons inside a list prop (an EntityCard's `actions`) have no event of their own: the component sends one
|
|
430
|
+
* `onAction` with the item that was pressed. Models write `onClick` on each item anyway; dropped, the buttons
|
|
431
|
+
* would do nothing when clicked. So the first such event becomes the component's `onAction`.
|
|
432
|
+
*/
|
|
433
|
+
function hoistItemEvents(c, schema, notes) {
|
|
434
|
+
if (!("onAction" in (schema.properties ?? {})) || c.onAction)
|
|
435
|
+
return c;
|
|
436
|
+
for (const [key, value] of Object.entries(c)) {
|
|
437
|
+
if (!Array.isArray(value))
|
|
438
|
+
continue;
|
|
439
|
+
const item = value.find((v) => isObj(v) && ["onClick", "action", "onAction"].some((k) => isObj(v[k]) && isObj(v[k].event)));
|
|
440
|
+
if (!item)
|
|
441
|
+
continue;
|
|
442
|
+
const event = (["onClick", "action", "onAction"].map((k) => item[k]).find((v) => isObj(v) && isObj(v.event)));
|
|
443
|
+
notes.push(`${c.component} "${c.id}": the ${key} buttons' event became its onAction (the pressed one is in the context)`);
|
|
444
|
+
return { ...c, onAction: { event: { name: event.event.name, ...(isObj(event.event.context) ? { context: event.event.context } : {}) } } };
|
|
445
|
+
}
|
|
446
|
+
return c;
|
|
447
|
+
}
|
|
448
|
+
const CHECK_MESSAGES = { required: "Required", email: "Enter a valid email address", regex: "Check the format", length: "Check the length", numeric: "Enter a number in range" };
|
|
449
|
+
/** The name a function call is written with: `@call`, or `call` as models also write it. */
|
|
450
|
+
const callName = (x) => (isObj(x) && typeof (x["@call"] ?? x.call) === "string" ? String(x["@call"] ?? x.call) : null);
|
|
451
|
+
/** One `checks` entry as the catalog wants it: `{ condition, message }`, the condition a bare call or a path. */
|
|
452
|
+
function checkRule(x, where, notes) {
|
|
453
|
+
if (!isObj(x))
|
|
454
|
+
return x;
|
|
455
|
+
const name = callName(x);
|
|
456
|
+
if (name && !("condition" in x)) {
|
|
457
|
+
const { message, ...call } = x;
|
|
458
|
+
notes.push(`${where}: a check was written as the call itself; it became the check's condition`);
|
|
459
|
+
return { condition: call, message: typeof message === "string" && message.trim() ? message : CHECK_MESSAGES[name] ?? "Check this value" };
|
|
460
|
+
}
|
|
461
|
+
if (isObj(x.condition) && callName(x.condition) && "message" in x.condition) {
|
|
462
|
+
const { message, ...call } = x.condition;
|
|
463
|
+
return { ...x, condition: call, message: typeof x.message === "string" && x.message.trim() ? x.message : typeof message === "string" ? message : CHECK_MESSAGES[callName(call)] ?? "Check this value" };
|
|
464
|
+
}
|
|
465
|
+
return x;
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* A Table's cells may hold components (`{"componentId": "b"}` in rows or columns), and the renderer counts them as
|
|
469
|
+
* the table's only when they are also listed in `cellComponents`. Models list them in the rows and forget the list.
|
|
470
|
+
*/
|
|
471
|
+
function listTableCells(c, notes) {
|
|
472
|
+
if (c.component !== "Table")
|
|
473
|
+
return c;
|
|
474
|
+
const used = [];
|
|
475
|
+
const walk = (v) => {
|
|
476
|
+
if (Array.isArray(v))
|
|
477
|
+
v.forEach(walk);
|
|
478
|
+
else if (isObj(v)) {
|
|
479
|
+
if (typeof v.componentId === "string" && Object.keys(v).length <= 2)
|
|
480
|
+
used.push(v.componentId);
|
|
481
|
+
else
|
|
482
|
+
Object.values(v).forEach(walk);
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
walk(c.rows);
|
|
486
|
+
walk(c.columns);
|
|
487
|
+
const listed = Array.isArray(c.cellComponents) ? c.cellComponents.filter((x) => typeof x === "string") : [];
|
|
488
|
+
const missing = [...new Set(used)].filter((id) => !listed.includes(id));
|
|
489
|
+
if (!missing.length)
|
|
490
|
+
return c;
|
|
491
|
+
notes.push(`Table "${c.id}": cell components added to cellComponents: ${missing.slice(0, 6).join(", ")}`);
|
|
492
|
+
return { ...c, cellComponents: [...listed, ...missing] };
|
|
493
|
+
}
|
|
494
|
+
function tidyComponent(c, docs, notes) {
|
|
495
|
+
const schema = docs.map((d) => d.components?.[c.component]).find(Boolean);
|
|
496
|
+
if (!schema?.properties)
|
|
497
|
+
return c;
|
|
498
|
+
c = listTableCells(c, notes);
|
|
499
|
+
c = hoistItemEvents(c, schema, notes);
|
|
500
|
+
const out = {};
|
|
501
|
+
for (const [k, v] of Object.entries(c)) {
|
|
502
|
+
if (k === "id" || k === "component" || k.startsWith("@")) {
|
|
503
|
+
out[k] = v;
|
|
504
|
+
continue;
|
|
505
|
+
}
|
|
506
|
+
if (!(k in schema.properties)) {
|
|
507
|
+
notes.push(`${c.component} "${c.id}": ${k} is not a property; ignored`);
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
const prop = schema.properties[k];
|
|
511
|
+
// null for a prop that is optional and cannot be null means "not set"
|
|
512
|
+
if (v === null && !(schema.required ?? []).includes(k) && !alternatives(prop).some((a) => typesOf(a).includes("null"))) {
|
|
513
|
+
notes.push(`${c.component} "${c.id}": ${k} was null; left unset`);
|
|
514
|
+
continue;
|
|
515
|
+
}
|
|
516
|
+
// children named as {componentId: "x"} or {id: "x"} instead of "x"
|
|
517
|
+
if (Array.isArray(v) && /ChildList$/.test(String(prop.$ref ?? ""))) {
|
|
518
|
+
out[k] = v.map((x) => (isObj(x) && typeof (x.componentId ?? x.id) === "string" && Object.keys(x).length === 1 ? (x.componentId ?? x.id) : x));
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
// A validation check written as the bare function call — often with its message beside the call
|
|
522
|
+
// ({"@call": "email", args, message}) — is the condition; the message belongs to the check, not to the call,
|
|
523
|
+
// whose arguments the catalog checks strictly. A condition that itself carries the message is moved the same way.
|
|
524
|
+
if (k === "checks" && Array.isArray(v)) {
|
|
525
|
+
out[k] = v.map((x) => checkRule(x, `${c.component} "${c.id}"`, notes));
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
out[k] = tidy(v, prop, notes, `${c.component} "${c.id}".${k}`);
|
|
529
|
+
}
|
|
530
|
+
return out;
|
|
531
|
+
}
|
|
532
|
+
// ── a compact catalog guide for the JSON format ────────────────────────────
|
|
533
|
+
function brief(schema, depth = 0) {
|
|
534
|
+
if (!schema || typeof schema !== "object")
|
|
535
|
+
return "any";
|
|
536
|
+
if (schema.$ref)
|
|
537
|
+
return String(schema.$ref).split("/").pop();
|
|
538
|
+
if ("const" in schema)
|
|
539
|
+
return JSON.stringify(schema.const);
|
|
540
|
+
if (schema.enum)
|
|
541
|
+
return schema.enum.map((v) => JSON.stringify(v)).join("|");
|
|
542
|
+
const alts = schema.anyOf ?? schema.oneOf;
|
|
543
|
+
if (alts) {
|
|
544
|
+
const parts = [...new Set(alts.map((a) => brief(a, depth + 1)).filter((p) => p !== "DataBinding" && p !== "FunctionCall"))];
|
|
545
|
+
return parts.length > 1 ? parts.join(" | ") : parts[0] ?? "any";
|
|
546
|
+
}
|
|
547
|
+
if (schema.type === "array") {
|
|
548
|
+
const item = brief(schema.items, depth + 1);
|
|
549
|
+
return item.includes(" | ") ? `(${item})[]` : `${item}[]`;
|
|
550
|
+
}
|
|
551
|
+
if (schema.type === "object") {
|
|
552
|
+
const props = Object.entries(schema.properties ?? {});
|
|
553
|
+
if (!props.length || depth > 6)
|
|
554
|
+
return "object";
|
|
555
|
+
const required = new Set(schema.required ?? []);
|
|
556
|
+
return `{ ${props.map(([k, v]) => `${k}${required.has(k) ? "" : "?"}: ${brief(v, depth + 1)}`).join(", ")} }`;
|
|
557
|
+
}
|
|
558
|
+
return Array.isArray(schema.type) ? schema.type.join("|") : String(schema.type ?? "any");
|
|
559
|
+
}
|
|
560
|
+
/** One line per component: name, what it is for, and its props with types. A fraction of the full JSON Schema. */
|
|
561
|
+
export function catalogGuide(doc) {
|
|
562
|
+
const lines = [];
|
|
563
|
+
for (const [name, c] of Object.entries(doc.components ?? {})) {
|
|
564
|
+
const required = new Set(c.required ?? []);
|
|
565
|
+
const props = Object.entries(c.properties ?? {}).filter(([k]) => k !== "component")
|
|
566
|
+
.map(([k, v]) => `${k}${required.has(k) ? "" : "?"}: ${brief(v)}`).join("; ");
|
|
567
|
+
lines.push(`- ${name} — ${String(c.description ?? "").replace(/\s+/g, " ").trim()}\n props: ${props || "(none)"}`);
|
|
568
|
+
}
|
|
569
|
+
const functions = Object.entries(doc.functions ?? {}).map(([name, f]) => `- ${name} — ${String(f.description ?? "").replace(/\s+/g, " ").trim()}`);
|
|
570
|
+
return `### Components\n${lines.join("\n")}${functions.length ? `\n\n### Functions ({"@call": name, "args": {...}})\n${functions.join("\n")}` : ""}`;
|
|
571
|
+
}
|
|
572
|
+
const JSON_RULES = `## How to show UI
|
|
573
|
+
|
|
574
|
+
Call the \`${RENDER_UI_TOOL}\` tool with \`components\` (and \`data\` when values are bound). It shows one surface.
|
|
575
|
+
|
|
576
|
+
- \`components\` is a FLAT JSON array, never a string. Each item is {"id": "...", "component": "<Name>", ...props}. Exactly one has id "root". A parent names its children by id: "children": ["a","b"] or "child": "a". Never nest a component inside another.
|
|
577
|
+
- A value that comes from \`data\` is {"@path": "/pointer"} (inside a template, a relative name like {"@path": "name"}). To repeat a component for each item of a list in data: "children": {"componentId": "<id of the template>", "path": "/items"}.
|
|
578
|
+
- An input writes what the user types to the path its value is bound to. A button's event is "onClick": {"event": {"name": "<name>", "context": {"key": {"@path": "/x"}}}}; you receive it as the user's next message.
|
|
579
|
+
- Use only the components and props listed below, spelled exactly. Do not invent props; leave a prop out rather than guess its value.
|
|
580
|
+
- To change a surface you showed earlier instead of showing a new one, pass its \`surfaceId\` with the new \`components\` and/or \`data\`.`;
|
|
581
|
+
const EXPRESS_EXAMPLE = `title = Title("Team capacity")
|
|
582
|
+
note = Caption("Illustrative numbers")
|
|
583
|
+
tbl = Table(columns=["Person", "Role", "Load"], rows=[["Mina", "Design", "80%"], ["Jun", "Backend", "95%"]])
|
|
584
|
+
name = TextField(label="Add a person", value=$/draft/name)
|
|
585
|
+
add = Button("Add", variant="primary", onClick=Event("add_person", {name: $/draft/name}))
|
|
586
|
+
form = Row([name, add])
|
|
587
|
+
next = FollowUp(items=["Who is overloaded?", "Show it as a chart"])
|
|
588
|
+
root = Column([title, tbl, form, note, next])`;
|
|
589
|
+
const JSON_EXAMPLE = `{"components": [
|
|
590
|
+
{"id": "root", "component": "Column", "children": ["title", "tbl", "form", "note", "next"]},
|
|
591
|
+
{"id": "title", "component": "Title", "text": "Team capacity"},
|
|
592
|
+
{"id": "tbl", "component": "Table", "columns": ["Person", "Role", "Load"], "rows": [["Mina", "Design", "80%"], ["Jun", "Backend", "95%"]]},
|
|
593
|
+
{"id": "form", "component": "Row", "children": ["name", "add"]},
|
|
594
|
+
{"id": "name", "component": "TextField", "label": "Add a person", "value": {"@path": "/draft/name"}},
|
|
595
|
+
{"id": "add", "component": "Button", "label": "Add", "variant": "primary", "onClick": {"event": {"name": "add_person", "context": {"name": {"@path": "/draft/name"}}}}},
|
|
596
|
+
{"id": "note", "component": "Caption", "text": "Illustrative numbers"},
|
|
597
|
+
{"id": "next", "component": "FollowUp", "items": ["Who is overloaded?", "Show it as a chart"]}
|
|
598
|
+
], "data": {"draft": {"name": ""}}}`;
|
|
599
|
+
export class UiError extends Error {
|
|
600
|
+
cause;
|
|
601
|
+
/** Written for the model: what was wrong and how to say it again. */
|
|
602
|
+
constructor(message, cause) {
|
|
603
|
+
super(message);
|
|
604
|
+
this.cause = cause;
|
|
605
|
+
this.name = "UiError";
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
const surfaceIds = () => `ui-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
609
|
+
function describe(error) {
|
|
610
|
+
const e = error;
|
|
611
|
+
const detail = Array.isArray(e?.errors) ? e.errors.map((x) => x?.message ?? String(x)).slice(0, 6).join("; ") : "";
|
|
612
|
+
return [e?.message ?? String(error), detail].filter(Boolean).join(" — ").slice(0, 1600);
|
|
613
|
+
}
|
|
614
|
+
/** Everything one agent turn needs to let a model show UI in the given catalogs and format. */
|
|
615
|
+
export function createUiAuthor(options = {}) {
|
|
616
|
+
const format = options.format ?? "express";
|
|
617
|
+
const macros = options.macros ?? [];
|
|
618
|
+
const full = options.catalogs?.length ? options.catalogs : [ainuiCatalogDocument()];
|
|
619
|
+
/** What the model is told and what Express is parsed against: compact, with the macros. */
|
|
620
|
+
const docs = full.map((d) => withMacros(options.compact === false ? d : compactCatalogDocument(d), macros));
|
|
621
|
+
const catalogs = docs.map((d) => Catalog.fromJson(d, A2UI_VERSION));
|
|
622
|
+
/** What the renderer will check against: the full catalogs, without the macros. */
|
|
623
|
+
const wire = full.map((d) => Catalog.fromJson(d, A2UI_VERSION));
|
|
624
|
+
const lenient = full.map((d) => withMacros(d, macros));
|
|
625
|
+
const capabilities = { [A2UI_VERSION]: { supportedCatalogIds: catalogs.map((c) => c.id) } };
|
|
626
|
+
const configs = catalogs.map((c) => new CatalogConfig(c));
|
|
627
|
+
const express = new A2uiGenerator(configs, undefined, new ExpressFormatFactory({ version: A2UI_VERSION })).createProcessor(capabilities);
|
|
628
|
+
const json = new A2uiGenerator(configs, undefined, new DirectJsonFormatFactory()).createProcessor(capabilities);
|
|
629
|
+
const examples = Object.entries({ "a small surface": format === "express" ? EXPRESS_EXAMPLE : JSON_EXAMPLE, ...options.examples }).map(([name, body]) => `### Example: ${name}\n${body}`).join("\n\n");
|
|
630
|
+
const finish = (messages, notes = []) => {
|
|
631
|
+
const settle = (list, whole) => expandMacros(tidyTree(inlineItemComponents(list, lenient, notes).map((c) => tidyComponent(c, lenient, notes)), notes, whole), macros);
|
|
632
|
+
const expanded = messages.map((m) => {
|
|
633
|
+
const anyM = m;
|
|
634
|
+
if (anyM.createSurface?.components)
|
|
635
|
+
return { ...anyM, createSurface: { ...anyM.createSurface, components: settle(anyM.createSurface.components, true) } };
|
|
636
|
+
if (anyM.updateComponents?.components)
|
|
637
|
+
return { ...anyM, updateComponents: { ...anyM.updateComponents, components: settle(anyM.updateComponents.components, false) } };
|
|
638
|
+
return anyM;
|
|
639
|
+
});
|
|
640
|
+
try {
|
|
641
|
+
validatePayload(wire, expanded);
|
|
642
|
+
}
|
|
643
|
+
catch (e) {
|
|
644
|
+
throw new UiError(`The UI was not valid for the catalog: ${describe(e)}. Fix it and call ${RENDER_UI_TOOL} again.`, e);
|
|
645
|
+
}
|
|
646
|
+
return expanded;
|
|
647
|
+
};
|
|
648
|
+
const compileExpress = (source, notes = []) => {
|
|
649
|
+
let body = source.replace(/^\s*<a2ui>\s*/, "").replace(/\s*<\/a2ui>\s*$/, "").replace(/^```[a-z0-9]*\n?/i, "").replace(/\n?```\s*$/, "");
|
|
650
|
+
// The compiler is stricter than the renderer: an unknown or wrongly valued keyword argument stops the whole
|
|
651
|
+
// surface. Such an argument is renamed when the meaning is plain (Heading title= → text=) or left out, and
|
|
652
|
+
// the source compiled again; anything else is the model's to fix.
|
|
653
|
+
for (let round = 0;; round++) {
|
|
654
|
+
try {
|
|
655
|
+
return express.parser.compile(body, true);
|
|
656
|
+
}
|
|
657
|
+
catch (e) {
|
|
658
|
+
const fixed = round < 12 ? repairExpress(body, describe(e), docs) : null;
|
|
659
|
+
if (!fixed)
|
|
660
|
+
throw new UiError(`The A2UI Express did not compile: ${describe(e)}. Correct the syntax and call ${RENDER_UI_TOOL} again.`, e);
|
|
661
|
+
notes.push(fixed.note);
|
|
662
|
+
body = fixed.source;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
const readJson = (value) => {
|
|
667
|
+
let parsed = value;
|
|
668
|
+
if (typeof parsed === "string") {
|
|
669
|
+
try {
|
|
670
|
+
parsed = JSON.parse(parsed.replace(/^\s*<a2ui-json>\s*/, "").replace(/\s*<\/a2ui-json>\s*$/, "").replace(/^```[a-z]*\n?/i, "").replace(/\n?```\s*$/, ""));
|
|
671
|
+
}
|
|
672
|
+
catch (e) {
|
|
673
|
+
throw new UiError(`messages was not valid JSON: ${describe(e)}. Send a JSON array of A2UI messages.`, e);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
const list = Array.isArray(parsed) ? parsed : parsed && typeof parsed === "object" ? [parsed] : null;
|
|
677
|
+
if (!list?.length)
|
|
678
|
+
throw new UiError("messages must be a non-empty JSON array of A2UI messages.");
|
|
679
|
+
return list.map((m) => {
|
|
680
|
+
const withVersion = { version: A2UI_VERSION, ...m };
|
|
681
|
+
// A model that forgets the catalog still means the one it was told to use.
|
|
682
|
+
if (withVersion.createSurface && !withVersion.createSurface.catalogId)
|
|
683
|
+
withVersion.createSurface = { ...withVersion.createSurface, catalogId: catalogs[0].id };
|
|
684
|
+
if (withVersion.createSurface && !withVersion.createSurface.surfaceId)
|
|
685
|
+
withVersion.createSurface = { ...withVersion.createSurface, surfaceId: surfaceIds() };
|
|
686
|
+
return withVersion;
|
|
687
|
+
});
|
|
688
|
+
};
|
|
689
|
+
/** `{components, data, surfaceId?}` → one new surface, or an update of the surface named. */
|
|
690
|
+
const fromParts = (args, notes = []) => {
|
|
691
|
+
const parse = (v, what) => {
|
|
692
|
+
if (typeof v !== "string")
|
|
693
|
+
return v;
|
|
694
|
+
const lenient = leadingJson(v);
|
|
695
|
+
if (lenient !== undefined) {
|
|
696
|
+
if (lenient.trailing)
|
|
697
|
+
notes.push(`${what} was sent as text with ${lenient.trailing} unmatched bracket(s); repaired`);
|
|
698
|
+
return lenient.value;
|
|
699
|
+
}
|
|
700
|
+
try {
|
|
701
|
+
return JSON.parse(v);
|
|
702
|
+
}
|
|
703
|
+
catch (e) {
|
|
704
|
+
throw new UiError(`${what} was a string that is not valid JSON (${describe(e)}). Pass ${what} as a JSON ${what === "data" ? "object" : "array"}, not as text.`, e);
|
|
705
|
+
}
|
|
706
|
+
};
|
|
707
|
+
const components = parse(args.components, "components"), data = parse(args.data, "data");
|
|
708
|
+
if (components !== undefined && !Array.isArray(components))
|
|
709
|
+
throw new UiError("components must be a JSON array of {id, component, ...props}.");
|
|
710
|
+
if (data !== undefined && data !== null && !isObj(data))
|
|
711
|
+
throw new UiError("data must be a JSON object.");
|
|
712
|
+
const list = components?.map((c) => (isObj(c) ? c : {}));
|
|
713
|
+
if (typeof args.surfaceId === "string" && args.surfaceId) {
|
|
714
|
+
const surfaceId = args.surfaceId;
|
|
715
|
+
// A whole new screen for that surface (it has a root): the old one is replaced, not patched — what the
|
|
716
|
+
// new root no longer reaches would be left behind as orphans, which a renderer refuses.
|
|
717
|
+
if (list?.some((c) => c.id === "root"))
|
|
718
|
+
return replaceSurface(surfaceId, catalogs[0].id, list, data);
|
|
719
|
+
return [
|
|
720
|
+
...(list?.length ? [{ version: A2UI_VERSION, updateComponents: { surfaceId, components: list } }] : []),
|
|
721
|
+
...(data ? [{ version: A2UI_VERSION, updateDataModel: { surfaceId, path: "/", value: data } }] : []),
|
|
722
|
+
];
|
|
723
|
+
}
|
|
724
|
+
if (!list?.length)
|
|
725
|
+
throw new UiError("components must have at least the root component.");
|
|
726
|
+
if (!list.some((c) => c.id === "root"))
|
|
727
|
+
throw new UiError(`One component must have the id "root" (the top of the surface). Yours are: ${list.map((c) => c.id).slice(0, 12).join(", ")}.`);
|
|
728
|
+
return [{ version: A2UI_VERSION, createSurface: { surfaceId: surfaceIds(), catalogId: catalogs[0].id, components: list, ...(data ? { dataModel: data } : {}) } }];
|
|
729
|
+
};
|
|
730
|
+
const unique = (messages) => {
|
|
731
|
+
// Express compiles every block to the same default surface id, and a renderer rejects a second createSurface
|
|
732
|
+
// with an id it already has: each call gets its own.
|
|
733
|
+
const renamed = new Map();
|
|
734
|
+
return messages.map((m) => {
|
|
735
|
+
const anyM = m;
|
|
736
|
+
const key = ["createSurface", "updateComponents", "updateDataModel", "deleteSurface"].find((k) => anyM[k]);
|
|
737
|
+
if (!key)
|
|
738
|
+
return m;
|
|
739
|
+
const id = anyM[key].surfaceId;
|
|
740
|
+
if (key === "createSurface" && format === "express")
|
|
741
|
+
renamed.set(id, surfaceIds());
|
|
742
|
+
return renamed.has(id) ? { ...anyM, [key]: { ...anyM[key], surfaceId: renamed.get(id) } } : m;
|
|
743
|
+
});
|
|
744
|
+
};
|
|
745
|
+
const prompt = format === "express"
|
|
746
|
+
? `${express.promptSnippet}\n\nShow UI by calling the \`${RENDER_UI_TOOL}\` tool with \`express\`: the A2UI Express source, without the <a2ui> tags.${examples ? `\n\n${examples}` : ""}`
|
|
747
|
+
: `${JSON_RULES}\n\n${docs.map((d) => `## Catalog ${d.catalogId}\n\n${d.instructions ? `${d.instructions}\n\n` : ""}${catalogGuide(d)}`).join("\n\n")}${examples ? `\n\n${examples}` : ""}`;
|
|
748
|
+
const tool = {
|
|
749
|
+
type: "function",
|
|
750
|
+
function: {
|
|
751
|
+
name: RENDER_UI_TOOL,
|
|
752
|
+
description: "Show the user an interactive UI surface (cards, tables, charts, forms, files, payment) instead of describing it in text. Call it once per surface; say a sentence of text before or after, not instead.",
|
|
753
|
+
parameters: format === "express"
|
|
754
|
+
? { type: "object", properties: { express: { type: "string", description: "A2UI Express source. One statement per line; the entry point is assigned to `root`." } }, required: ["express"], additionalProperties: false }
|
|
755
|
+
: { type: "object", properties: {
|
|
756
|
+
// `items` is left open on purpose: a model held to a schema writes only the properties the schema names.
|
|
757
|
+
components: { type: "array", items: { type: "object", additionalProperties: true }, description: "The flat list of components: {\"id\": ..., \"component\": ..., ...props}. One has id \"root\"." },
|
|
758
|
+
data: { type: "object", description: "The data model that {\"@path\": ...} bindings read and inputs write." },
|
|
759
|
+
surfaceId: { type: "string", description: "Only to change a surface you showed earlier: its id." },
|
|
760
|
+
}, required: ["components"] },
|
|
761
|
+
},
|
|
762
|
+
};
|
|
763
|
+
return {
|
|
764
|
+
format, prompt, tool, catalogIds: catalogs.map((c) => c.id),
|
|
765
|
+
fromToolCall(raw, notes) {
|
|
766
|
+
let args;
|
|
767
|
+
if (typeof raw === "string") {
|
|
768
|
+
try {
|
|
769
|
+
args = JSON.parse(raw);
|
|
770
|
+
}
|
|
771
|
+
catch {
|
|
772
|
+
args = format === "express" ? { express: raw } : { messages: raw };
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
else
|
|
776
|
+
args = raw ?? {};
|
|
777
|
+
const source = args.express ?? args.ui;
|
|
778
|
+
if (typeof source === "string" && source.trim() && !/^\s*[[{]/.test(source))
|
|
779
|
+
return finish(unique(compileExpress(source, notes)), notes);
|
|
780
|
+
if (args.components !== undefined || args.data !== undefined)
|
|
781
|
+
return finish(fromParts(args, notes), notes);
|
|
782
|
+
const payload = args.messages ?? args.ui ?? args.express;
|
|
783
|
+
if (payload === undefined || payload === null || payload === "")
|
|
784
|
+
throw new UiError(`${RENDER_UI_TOOL} needs ${format === "express" ? "`express`" : "`components`"}.`);
|
|
785
|
+
return finish(readJson(payload), notes);
|
|
786
|
+
},
|
|
787
|
+
fromText(text) {
|
|
788
|
+
const parts = [];
|
|
789
|
+
const pattern = /<a2ui>([\s\S]*?)<\/a2ui>|<a2ui-json>([\s\S]*?)<\/a2ui-json>/g;
|
|
790
|
+
let last = 0, m;
|
|
791
|
+
while ((m = pattern.exec(text))) {
|
|
792
|
+
const before = text.slice(last, m.index).trim();
|
|
793
|
+
if (before)
|
|
794
|
+
parts.push({ type: "text", text: before });
|
|
795
|
+
parts.push({ type: "a2ui", messages: m[1] !== undefined ? finish(unique(compileExpress(m[1], []))) : finish(readJson(m[2])) });
|
|
796
|
+
last = m.index + m[0].length;
|
|
797
|
+
}
|
|
798
|
+
const rest = text.slice(last).trim();
|
|
799
|
+
if (rest)
|
|
800
|
+
parts.push({ type: "text", text: rest });
|
|
801
|
+
return parts;
|
|
802
|
+
},
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
/** The Express source that compiles to these messages — for showing both forms side by side. */
|
|
806
|
+
export function toExpress(messages, catalogs = [ainuiCatalogDocument()]) {
|
|
807
|
+
const list = catalogs.map((d) => new CatalogConfig(Catalog.fromJson(d, A2UI_VERSION)));
|
|
808
|
+
const processor = new A2uiGenerator(list, undefined, new ExpressFormatFactory({ version: A2UI_VERSION }))
|
|
809
|
+
.createProcessor({ [A2UI_VERSION]: { supportedCatalogIds: list.map((c) => c.catalog.id) } });
|
|
810
|
+
return processor.parser.decompile(messages);
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Agent skill files (Markdown) that teach a coding agent or another model to write for these catalogs:
|
|
814
|
+
* `{ filename: content }`.
|
|
815
|
+
*/
|
|
816
|
+
export function exportSkills(options = {}) {
|
|
817
|
+
const docs = (options.catalogs?.length ? options.catalogs : [ainuiCatalogDocument()]).map((d) => withMacros(d, options.macros ?? []));
|
|
818
|
+
const catalogs = docs.map((d) => Catalog.fromJson(d, A2UI_VERSION));
|
|
819
|
+
const factory = options.format === "json" ? new DirectJsonFormatFactory() : new ExpressFormatFactory({ version: A2UI_VERSION });
|
|
820
|
+
const generator = new SkillGenerator(factory.createFormat(catalogs));
|
|
821
|
+
return generator.generateSkillSet({ catalogs: catalogs }).toDict();
|
|
822
|
+
}
|