From b7a8c71bfbcb91c72a34e760b0f57c9351f4b352 Mon Sep 17 00:00:00 2001 From: Manfred Steyer Date: Wed, 25 Nov 2026 00:33:03 +0100 Subject: [PATCH 1/9] feat(ts_agent): add component tree flattener for macros Add a plain-object component tree and `flattenComponentTree`, which turns nested component objects into the flat component list of `updateComponents`. Slots take a nested node or the ID of a component on the surface. IDs are allocated as `___`, IDs the author set are namespaced and never handed out again, and descendants are listed before their parents, as in the Python SDK. Run `conformance/agent/builder/builder.yaml` against it. Case `01_primitive_components_v1_0` passes. The other v1.0 goldens hold catalog defaults that a typed builder fills in, so they stay skipped with that reason, and the v0.9 cases stay skipped. --- .../src/component-tree/component-node.ts | 45 +++++ .../a2ui_agent/src/component-tree/flatten.ts | 141 +++++++++++++++ .../src/component-tree/id-allocator.ts | 52 ++++++ typescript/agents/a2ui_agent/src/index.ts | 8 + .../conformance/builder-conformance.test.ts | 114 ++++++++++++ .../conformance/unsupported-suites.test.ts | 3 +- .../tests/unit/component-tree/flatten.test.ts | 170 ++++++++++++++++++ 7 files changed, 531 insertions(+), 2 deletions(-) create mode 100644 typescript/agents/a2ui_agent/src/component-tree/component-node.ts create mode 100644 typescript/agents/a2ui_agent/src/component-tree/flatten.ts create mode 100644 typescript/agents/a2ui_agent/src/component-tree/id-allocator.ts create mode 100644 typescript/agents/a2ui_agent/tests/conformance/builder-conformance.test.ts create mode 100644 typescript/agents/a2ui_agent/tests/unit/component-tree/flatten.test.ts diff --git a/typescript/agents/a2ui_agent/src/component-tree/component-node.ts b/typescript/agents/a2ui_agent/src/component-tree/component-node.ts new file mode 100644 index 0000000000..5b8bac79de --- /dev/null +++ b/typescript/agents/a2ui_agent/src/component-tree/component-node.ts @@ -0,0 +1,45 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A component written as a nested object, in the shape of the wire component. + * + * Any property may hold another node, directly, in an array, or inside a plain object + * such as `{path, componentId}`. `flattenComponentTree` replaces each nested node with + * its ID. Every object with a string `component` property counts as a node. + */ +export interface ComponentNode { + component: string; + /** Leave it out to have an ID allocated. */ + id?: string; + [property: string]: unknown; +} + +/** A component in a slot: a nested node, or the ID of a component already on the surface. */ +export type ComponentChild = ComponentNode | string; + +/** A component of the flat list `flattenComponentTree` returns. */ +export type FlatComponent = ComponentNode & {id: string}; + +/** Whether `value` is a component node rather than a literal value. */ +export function isComponentNode(value: unknown): value is ComponentNode { + return ( + typeof value === 'object' && + value !== null && + !Array.isArray(value) && + typeof (value as Record)['component'] === 'string' + ); +} diff --git a/typescript/agents/a2ui_agent/src/component-tree/flatten.ts b/typescript/agents/a2ui_agent/src/component-tree/flatten.ts new file mode 100644 index 0000000000..9283eec684 --- /dev/null +++ b/typescript/agents/a2ui_agent/src/component-tree/flatten.ts @@ -0,0 +1,141 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {ComponentChild, ComponentNode, FlatComponent, isComponentNode} from './component-node.js'; +import {IdAllocator} from './id-allocator.js'; + +/** Options for `flattenComponentTree`. */ +export interface FlattenComponentTreeOptions { + /** + * The ID of the root component, and the prefix of every other ID in the tree. Defaults + * to the root's own `id`; without one, the prefix is `root` and the root's ID is + * allocated like any other. + */ + rootId?: string; +} + +/** + * Flattens a nested component tree into the flat component list of `updateComponents`. + * + * Descendants are listed before their parents, so the root comes last. Nested nodes are + * replaced by their IDs, and ID references are kept as written. A descendant without an + * `id` gets `___`; one with an `id` gets `__`, and no + * allocated ID ever takes the place of an ID the author set. A node that appears in two + * places is listed once and referenced from both. Properties set to `undefined` are left + * out. + * + * An array of roots flattens each root on its own, with the prefix `_` + * when `rootId` is given. A root that is an ID reference adds nothing. + */ +export function flattenComponentTree( + root: ComponentChild | readonly ComponentChild[], + options: FlattenComponentTreeOptions = {}, +): FlatComponent[] { + const {rootId} = options; + if (Array.isArray(root)) { + return root.flatMap((item, index) => + flattenComponentTree(item, {rootId: rootId ? `${rootId}_${index}` : undefined}), + ); + } + if (!isComponentNode(root)) { + return []; + } + + const prefix = rootId || root.id || 'root'; + const reserved = reservedIds(root, prefix); + if (rootId) { + reserved.add(rootId); + } + const flattener = new TreeFlattener(new IdAllocator(prefix, reserved)); + return flattener.flatten(root, rootId || root.id); +} + +/** The IDs the authors set anywhere in the tree, bare and namespaced. */ +function reservedIds(root: ComponentNode, prefix: string): Set { + const reserved = new Set(); + const visited = new Set(); + const visit = (value: unknown): void => { + if (typeof value !== 'object' || value === null || visited.has(value)) { + return; + } + visited.add(value); + if (isComponentNode(value) && value.id) { + reserved.add(value.id); + reserved.add(`${prefix}__${value.id}`); + } + for (const nested of Object.values(value)) { + visit(nested); + } + }; + visit(root); + return reserved; +} + +class TreeFlattener { + private readonly components: FlatComponent[] = []; + private readonly assigned = new Map(); + + constructor(private readonly allocator: IdAllocator) {} + + flatten(root: ComponentNode, rootId: string | undefined): FlatComponent[] { + const id = rootId || this.allocator.allocate(root.component); + this.assigned.set(root, id); + this.components.push(this.toFlatComponent(root, id)); + return this.components; + } + + private emit(node: ComponentNode): string { + const assigned = this.assigned.get(node); + if (assigned !== undefined) { + return assigned; + } + // Allocated before the descendants' IDs: counters run in pre-order while the list is + // in post-order, which the conformance goldens pin. + const id = this.allocator.allocate(node.component, node.id); + this.assigned.set(node, id); + this.components.push(this.toFlatComponent(node, id)); + return id; + } + + private toFlatComponent(node: ComponentNode, id: string): FlatComponent { + const flat: FlatComponent = {component: node.component, id}; + for (const [key, value] of Object.entries(node)) { + if (key !== 'component' && key !== 'id' && value !== undefined) { + flat[key] = this.toWireValue(value); + } + } + return flat; + } + + private toWireValue(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(item => this.toWireValue(item)); + } + if (isComponentNode(value)) { + return this.emit(value); + } + if (typeof value === 'object' && value !== null) { + const wire: Record = {}; + for (const [key, nested] of Object.entries(value)) { + if (nested !== undefined) { + wire[key] = this.toWireValue(nested); + } + } + return wire; + } + return value; + } +} diff --git a/typescript/agents/a2ui_agent/src/component-tree/id-allocator.ts b/typescript/agents/a2ui_agent/src/component-tree/id-allocator.ts new file mode 100644 index 0000000000..624c364608 --- /dev/null +++ b/typescript/agents/a2ui_agent/src/component-tree/id-allocator.ts @@ -0,0 +1,52 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Allocates deterministic component IDs inside one scope. + * + * An allocated ID is `___`, with the component name lowercased and + * `n` counted per component name, skipping IDs that are already taken. An ID the author + * set is namespaced as `__`. + */ +export class IdAllocator { + private readonly counters = new Map(); + private readonly taken: Set; + + constructor( + private readonly prefix: string, + reserved: Iterable = [], + ) { + this.taken = new Set(reserved); + } + + allocate(componentName: string, preferredId?: string): string { + if (preferredId) { + const namespaced = `${this.prefix}__${preferredId}`; + this.taken.add(namespaced); + return namespaced; + } + const name = componentName.toLowerCase(); + for (;;) { + const next = (this.counters.get(name) ?? 0) + 1; + this.counters.set(name, next); + const candidate = `${this.prefix}__${name}_${next}`; + if (!this.taken.has(candidate)) { + this.taken.add(candidate); + return candidate; + } + } + } +} diff --git a/typescript/agents/a2ui_agent/src/index.ts b/typescript/agents/a2ui_agent/src/index.ts index 2687be780d..c18083a5c3 100644 --- a/typescript/agents/a2ui_agent/src/index.ts +++ b/typescript/agents/a2ui_agent/src/index.ts @@ -191,6 +191,14 @@ export { SkillSet, } from './skill/index.js'; +// Component trees +export { + type ComponentChild, + type ComponentNode, + type FlatComponent, +} from './component-tree/component-node.js'; +export {type FlattenComponentTreeOptions, flattenComponentTree} from './component-tree/flatten.js'; + // Renderer-to-agent messages export { type ProcessResult, diff --git a/typescript/agents/a2ui_agent/tests/conformance/builder-conformance.test.ts b/typescript/agents/a2ui_agent/tests/conformance/builder-conformance.test.ts new file mode 100644 index 0000000000..1d7dba8a27 --- /dev/null +++ b/typescript/agents/a2ui_agent/tests/conformance/builder-conformance.test.ts @@ -0,0 +1,114 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Runs `conformance/agent/builder/builder.yaml` against the plain-object component tree + * and `flattenComponentTree`. + * + * The suite was written for typed fluent builders. Its inputs are nested component + * objects, which is what the tree layer takes, but most goldens also hold the defaults a + * typed builder fills in for each catalog component. The tree layer emits only what the + * author wrote, so those cases are skipped with that reason. + */ + +import {readFileSync} from 'fs'; + +import {expect} from 'vitest'; + +import {ComponentChild, flattenComponentTree, validatePayload} from '../../src/index.js'; +import {loadBasicCatalog} from '../helpers/basic-catalogs.js'; +import {LoadedCase, loadCases} from './loader.js'; +import { + assertKnownKeys, + CASE_METADATA_KEYS, + conformancePath, + describeSuite, +} from './suite-helpers.js'; + +const SUITE = 'agent/builder/builder.yaml'; +const GOLDEN_DIR = conformancePath('agent/builder/golden'); + +const BUILDER_CASE_KEYS = new Set([ + ...CASE_METADATA_KEYS, + 'catalog_id', + 'data_model', + 'golden', + 'id', + 'input', + 'root_id', + 'surface_id', + 'validation', + 'version', +]); + +/** + * The v1.0 cases whose goldens hold builder defaults the input doesn't state, such as + * `Text.variant: "body"` or `Column.justify: "start"`. + */ +const CASES_WITH_BUILDER_DEFAULTS = new Set([ + '02_nested_hierarchy_and_slots_v1_0', + '03_automatic_id_allocation_v1_0', + '04_data_bindings_v1_0', + '05_accessibility_attributes_v1_0', + '06_actions_and_function_calls_v1_0', + '07_dynamic_child_list_v1_0', + '08_component_references_v1_0', + '09_surface_lifecycle_envelopes_v1_0', + '10_validation_rules_v1_0', + '11_nested_collection_templates_v1_0', +]); + +function skipReason(testCase: LoadedCase): string | undefined { + if (testCase['version'] !== 'v1.0') { + return 'the component tree layer targets v1.0 only'; + } + if (CASES_WITH_BUILDER_DEFAULTS.has(testCase.name)) { + return 'the golden holds catalog defaults that a typed builder fills in; the plain-object tree emits only what the author wrote'; + } + return undefined; +} + +describeSuite( + `Conformance: ${SUITE}`, + loadCases([conformancePath(SUITE)]), + testCase => { + assertKnownKeys(testCase, BUILDER_CASE_KEYS, 'builder case'); + const input = testCase['input'] as ComponentChild | ComponentChild[]; + const rootId = testCase['root_id'] as string | undefined; + const surfaceId = testCase['surface_id'] as string; + const catalogId = testCase['catalog_id'] as string | undefined; + const dataModel = (testCase['data_model'] ?? {}) as Record; + + const messages: Record[] = []; + if (catalogId !== undefined) { + messages.push({version: '1.0', createSurface: {surfaceId, catalogId}}); + } + messages.push({ + version: '1.0', + updateComponents: {surfaceId, components: flattenComponentTree(input, {rootId})}, + }); + for (const [path, value] of Object.entries(dataModel)) { + messages.push({version: '1.0', updateDataModel: {surfaceId, path, value}}); + } + + const golden = JSON.parse( + readFileSync(`${GOLDEN_DIR}/${testCase['golden'] as string}`, 'utf8'), + ) as unknown; + expect(messages).toEqual(golden); + validatePayload([loadBasicCatalog('1.0')], golden); + }, + {skipReason}, +); diff --git a/typescript/agents/a2ui_agent/tests/conformance/unsupported-suites.test.ts b/typescript/agents/a2ui_agent/tests/conformance/unsupported-suites.test.ts index bbb0ba5b3e..1872de18d0 100644 --- a/typescript/agents/a2ui_agent/tests/conformance/unsupported-suites.test.ts +++ b/typescript/agents/a2ui_agent/tests/conformance/unsupported-suites.test.ts @@ -34,6 +34,7 @@ import { export const ACTIVE_SUITES: ReadonlySet = new Set([ 'agent/agent_functions.yaml', + 'agent/builder/builder.yaml', 'agent/catalog_provider.yaml', 'agent/catalog_resolution.yaml', 'agent/catalog_transformer.yaml', @@ -65,8 +66,6 @@ export const PERFORMANCE_SUITES: ReadonlySet = new Set([ export const UNSUPPORTED_SUITES: Readonly> = { 'agent/atom/compiler.yaml': 'Elemental and Atom are experimental and Python-only', - 'agent/builder/builder.yaml': - 'the fluent builder API is a Python-only helper not implemented in TypeScript', 'agent/elemental/compiler.yaml': 'Elemental and Atom are experimental and Python-only', 'agent/macros/macros.yaml': 'the composite macro API is a Python-only helper not implemented in TypeScript', diff --git a/typescript/agents/a2ui_agent/tests/unit/component-tree/flatten.test.ts b/typescript/agents/a2ui_agent/tests/unit/component-tree/flatten.test.ts new file mode 100644 index 0000000000..399ae2e9e5 --- /dev/null +++ b/typescript/agents/a2ui_agent/tests/unit/component-tree/flatten.test.ts @@ -0,0 +1,170 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, expect, it} from 'vitest'; + +import {ComponentNode, flattenComponentTree} from '../../../src/index.js'; + +describe('flattenComponentTree', () => { + it('lists descendants before parents and allocates IDs parent first', () => { + const tree: ComponentNode = { + component: 'Column', + children: [{component: 'Column', children: [{component: 'Text', text: 'a'}]}], + }; + + expect(flattenComponentTree(tree, {rootId: 'panel'})).toEqual([ + {component: 'Text', id: 'panel__text_1', text: 'a'}, + {component: 'Column', id: 'panel__column_1', children: ['panel__text_1']}, + {component: 'Column', id: 'panel', children: ['panel__column_1']}, + ]); + }); + + it('namespaces author IDs under the root and keeps the root ID bare', () => { + const tree: ComponentNode = { + component: 'Card', + id: 'card', + child: {component: 'Text', id: 'title', text: 'Hi'}, + }; + + expect(flattenComponentTree(tree)).toEqual([ + {component: 'Text', id: 'card__title', text: 'Hi'}, + {component: 'Card', id: 'card', child: 'card__title'}, + ]); + }); + + it('gives the root the rootId instead of its own ID', () => { + const tree: ComponentNode = {component: 'Card', id: 'card', child: {component: 'Text'}}; + + expect(flattenComponentTree(tree, {rootId: 'instance'})).toEqual([ + {component: 'Text', id: 'instance__text_1'}, + {component: 'Card', id: 'instance', child: 'instance__text_1'}, + ]); + }); + + it('allocates the root ID under the "root" prefix when no ID is known', () => { + expect(flattenComponentTree({component: 'Card', child: {component: 'Text'}})).toEqual([ + {component: 'Text', id: 'root__text_1'}, + {component: 'Card', id: 'root__card_1', child: 'root__text_1'}, + ]); + }); + + it('never allocates an ID the author set', () => { + const tree: ComponentNode = { + component: 'Row', + children: [ + {component: 'Text', text: 'allocated'}, + {component: 'Text', id: 'text_1', text: 'authored'}, + ], + }; + + expect(flattenComponentTree(tree, {rootId: 'r'}).map(c => c.id)).toEqual([ + 'r__text_2', + 'r__text_1', + 'r', + ]); + }); + + it('keeps ID references as written', () => { + const tree: ComponentNode = { + component: 'Column', + children: ['existing', {component: 'Text', text: 'new'}], + }; + + expect(flattenComponentTree(tree, {rootId: 'c'})).toEqual([ + {component: 'Text', id: 'c__text_1', text: 'new'}, + {component: 'Column', id: 'c', children: ['existing', 'c__text_1']}, + ]); + }); + + it('lists a node that appears twice once and references it from both places', () => { + const shared: ComponentNode = {component: 'Text', text: 'shared'}; + const tree: ComponentNode = {component: 'Row', children: [shared, shared]}; + + expect(flattenComponentTree(tree, {rootId: 'r'})).toEqual([ + {component: 'Text', id: 'r__text_1', text: 'shared'}, + {component: 'Row', id: 'r', children: ['r__text_1', 'r__text_1']}, + ]); + }); + + it('finds nodes inside plain objects and arrays of objects', () => { + const tree: ComponentNode = { + component: 'Tabs', + tabs: [{title: 'One', child: {component: 'Text', text: '1'}}], + list: {path: '/items', componentId: {component: 'Text', text: {'@path': 'name'}}}, + }; + + expect(flattenComponentTree(tree, {rootId: 't'})).toEqual([ + {component: 'Text', id: 't__text_1', text: '1'}, + {component: 'Text', id: 't__text_2', text: {'@path': 'name'}}, + { + component: 'Tabs', + id: 't', + tabs: [{title: 'One', child: 't__text_1'}], + list: {path: '/items', componentId: 't__text_2'}, + }, + ]); + }); + + it('leaves out properties set to undefined and keeps null', () => { + const tree: ComponentNode = { + component: 'Card', + weight: undefined, + child: {component: 'Text', text: null, context: {a: undefined, b: 1}}, + }; + + expect(flattenComponentTree(tree, {rootId: 'c'})).toEqual([ + {component: 'Text', id: 'c__text_1', text: null, context: {b: 1}}, + {component: 'Card', id: 'c', child: 'c__text_1'}, + ]); + }); + + it('flattens each root of an array in its own scope', () => { + const roots: ComponentNode[] = [ + {component: 'Card', child: {component: 'Text'}}, + {component: 'Card', child: {component: 'Text'}}, + ]; + + expect(flattenComponentTree(roots, {rootId: 'row'}).map(c => c.id)).toEqual([ + 'row_0__text_1', + 'row_0', + 'row_1__text_1', + 'row_1', + ]); + }); + + it('adds nothing for a root that is an ID reference', () => { + expect(flattenComponentTree('existing')).toEqual([]); + }); + + it('does not change the tree it flattens', () => { + const tree: ComponentNode = {component: 'Card', child: {component: 'Text', text: 'a'}}; + const before = structuredClone(tree); + + flattenComponentTree(tree, {rootId: 'c'}); + + expect(tree).toEqual(before); + }); + + it('terminates on a tree that refers back to an ancestor', () => { + const card: ComponentNode = {component: 'Card'}; + card['child'] = {component: 'Column', children: [card]}; + + expect(flattenComponentTree(card, {rootId: 'c'})).toEqual([ + {component: 'Column', id: 'c__column_1', children: ['c']}, + {component: 'Card', id: 'c', child: 'c__column_1'}, + ]); + }); +}); From 9526e49e2b8cc0c463cc8394625d4278db8b71eb Mon Sep 17 00:00:00 2001 From: Manfred Steyer Date: Wed, 25 Nov 2026 00:43:43 +0100 Subject: [PATCH 2/9] feat(ts_agent): add macro definitions and macro catalogs Add `defineMacro` and the `param` vocabulary of the shared macro suite (`string`, `integer`, `component`, `childList`, `action`, `dynamicString`, `checkRuleList`, `accessibility` and the rest). The `render` arguments are typed from the parameters: a required parameter or one with a default has its value, an optional one without a default can be `undefined`. Macro names must be UAX #31 identifiers other than `Surface`. Add `MacroExpander` with the catalog side of the Python API: `toCatalog` exports the macros as a standalone v1.0 catalog, `transformToInferenceCatalog` adds them to one base catalog, and `transformCatalogs` prunes the base catalogs to `passthroughComponents` and appends the macro catalog. Base catalogs must be v1.0. Run `conformance/agent/macros/macros.yaml` with reference macros written with `defineMacro`, mirroring Python's `macro_suite.py`. The catalog cases pass; lowering cases follow in the next commits, and cases that need v0.9 macros are skipped. --- typescript/agents/a2ui_agent/src/index.ts | 15 + .../a2ui_agent/src/macros/define-macro.ts | 118 ++++++ .../agents/a2ui_agent/src/macros/expander.ts | 233 +++++++++++ .../src/macros/macro-protocol-error.ts | 24 ++ .../a2ui_agent/src/macros/parameter-values.ts | 81 ++++ .../a2ui_agent/src/macros/parameters.ts | 232 +++++++++++ .../tests/conformance/macro-suite.ts | 362 ++++++++++++++++++ .../conformance/macros-conformance.test.ts | 270 +++++++++++++ .../conformance/unsupported-suites.test.ts | 3 +- .../tests/unit/macros/define-macro.test.ts | 49 +++ .../unit/macros/expander-catalogs.test.ts | 131 +++++++ .../tests/unit/macros/parameters.test.ts | 96 +++++ 12 files changed, 1612 insertions(+), 2 deletions(-) create mode 100644 typescript/agents/a2ui_agent/src/macros/define-macro.ts create mode 100644 typescript/agents/a2ui_agent/src/macros/expander.ts create mode 100644 typescript/agents/a2ui_agent/src/macros/macro-protocol-error.ts create mode 100644 typescript/agents/a2ui_agent/src/macros/parameter-values.ts create mode 100644 typescript/agents/a2ui_agent/src/macros/parameters.ts create mode 100644 typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts create mode 100644 typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts create mode 100644 typescript/agents/a2ui_agent/tests/unit/macros/define-macro.test.ts create mode 100644 typescript/agents/a2ui_agent/tests/unit/macros/expander-catalogs.test.ts create mode 100644 typescript/agents/a2ui_agent/tests/unit/macros/parameters.test.ts diff --git a/typescript/agents/a2ui_agent/src/index.ts b/typescript/agents/a2ui_agent/src/index.ts index c18083a5c3..f1ca72be07 100644 --- a/typescript/agents/a2ui_agent/src/index.ts +++ b/typescript/agents/a2ui_agent/src/index.ts @@ -199,6 +199,21 @@ export { } from './component-tree/component-node.js'; export {type FlattenComponentTreeOptions, flattenComponentTree} from './component-tree/flatten.js'; +// Macros +export {defineMacro, type MacroConfig, type MacroDefinition} from './macros/define-macro.js'; +export {MacroExpander, type MacroExpanderOptions} from './macros/expander.js'; +export { + type MacroArgs, + type MacroInput, + type MacroParameter, + type MacroParameters, + type MacroParameterType, + param, + type ParameterOptions, + type ParameterPresence, + type StringParameterOptions, +} from './macros/parameters.js'; + // Renderer-to-agent messages export { type ProcessResult, diff --git a/typescript/agents/a2ui_agent/src/macros/define-macro.ts b/typescript/agents/a2ui_agent/src/macros/define-macro.ts new file mode 100644 index 0000000000..7c5bdbea5b --- /dev/null +++ b/typescript/agents/a2ui_agent/src/macros/define-macro.ts @@ -0,0 +1,118 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {ComponentNode} from '../component-tree/component-node.js'; +import {isValidUax31Identifier} from '../internal/web-core.js'; +import {MacroProtocolError} from './macro-protocol-error.js'; +import {MacroArgs, MacroInput, MacroParameters, parameterSchema} from './parameters.js'; + +/** What `defineMacro` takes. */ +export interface MacroConfig

{ + /** The component name the model writes. A UAX #31 identifier other than `Surface`. */ + name: string; + /** Tells the model what the macro is for. */ + description?: string; + parameters?: P; + /** + * Builds the component tree that an invocation lowers to. The root takes the ID of the + * invocation and every other ID is namespaced under it, so an invocation can be used + * more than once on a surface. + */ + render: (args: MacroArgs

) => ComponentNode; +} + +/** A macro, as `defineMacro` returns it. */ +export interface MacroDefinition

{ + readonly name: string; + readonly description?: string; + readonly parameters: P; + /** + * Builds the macro's tree with the defaults applied. Call it from another macro's + * `render` to inline this macro's tree there. + */ + render(input: MacroInput

): ComponentNode; +} + +/** + * Defines a macro: a component the model can use that lowers to a tree of catalog + * components before the messages reach the renderer. + * + * @throws {A2uiValidationError} If the name is not a valid v1.0 component name. + */ +export function defineMacro>( + config: MacroConfig

, +): MacroDefinition

{ + validateMacroName(config.name); + const parameters = config.parameters ?? ({} as P); + const definition: MacroDefinition

= { + name: config.name, + parameters, + render: input => config.render(withDefaults(parameters, input)), + }; + return config.description === undefined + ? definition + : {...definition, description: config.description}; +} + +function withDefaults

( + parameters: P, + input: MacroInput

, +): MacroArgs

{ + const given = input as Record; + const args: Record = {}; + for (const [name, parameter] of Object.entries(parameters)) { + args[name] = given[name] === undefined ? parameter.default : given[name]; + } + return args as MacroArgs

; +} + +/** Whether `name` is the reserved component name `Surface`, also in a compatibility form. */ +export function isReservedComponentName(name: string): boolean { + return name.normalize('NFKC') === 'Surface'; +} + +/** + * Throws unless `name` can name a v1.0 component. + * + * @throws {A2uiValidationError} If `name` is `Surface` or not a UAX #31 identifier. + */ +export function validateMacroName(name: string): void { + if (isReservedComponentName(name)) { + throw new MacroProtocolError( + "Macro name 'Surface' is reserved and cannot be used as a component name.", + ); + } + if (!isValidUax31Identifier(name)) { + throw new MacroProtocolError(`Macro name '${name}' must be a valid Unicode identifier.`); + } +} + +/** The catalog entry of a macro: its parameters as a v1.0 component schema. */ +export function macroComponentSchema(definition: MacroDefinition): Record { + const properties: Record = {component: {const: definition.name}}; + const required = ['component']; + for (const [name, parameter] of Object.entries(definition.parameters)) { + properties[name] = parameterSchema(parameter); + if (parameter.presence === 'required') { + required.push(name); + } + } + const schema: Record = {type: 'object', properties, required}; + if (definition.description !== undefined) { + schema['description'] = definition.description; + } + return schema; +} diff --git a/typescript/agents/a2ui_agent/src/macros/expander.ts b/typescript/agents/a2ui_agent/src/macros/expander.ts new file mode 100644 index 0000000000..3865b51fea --- /dev/null +++ b/typescript/agents/a2ui_agent/src/macros/expander.ts @@ -0,0 +1,233 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {ComponentPruningTransformer} from '../catalog-transformers/pruning.js'; +import { + A2uiCatalogError, + Catalog, + CatalogApi, + normalizeVersionString, + toCanonicalVersion, +} from '../internal/web-core.js'; +import {macroComponentSchema, MacroDefinition, validateMacroName} from './define-macro.js'; +import {MacroProtocolError} from './macro-protocol-error.js'; + +const DEFAULT_MACRO_CATALOG_ID = 'https://a2ui.org/catalogs/macros'; + +/** Options for `MacroExpander`. */ +export interface MacroExpanderOptions { + /** + * The base catalog components that inference catalogs keep next to the macros. All of + * them by default; `[]` keeps only the macros. + */ + passthroughComponents?: readonly string[]; + /** + * The catalog the macros belong to. When set, an invocation expands only when its + * `@catalogId`, or the default catalog of its surface, is this ID. It is also the ID of + * `toCatalog()`. Give each expander its own ID when several work on the same messages. + */ + catalogId?: string; + /** + * The transport catalogs that the lowered components come from. Registering them lets + * the expander tell a macro from a catalog component of the same name, and stamp the + * owning `@catalogId` on lowered components where the surface needs it. + */ + baseCatalogs?: readonly CatalogApi[]; + /** + * What to do when an invocation fails, for example on an argument of the wrong type: + * keep it unexpanded and log the error (`passthrough`, the default), or throw an + * `A2uiValidationError` (`raise`), for agents that retry with the error. + */ + onError?: 'passthrough' | 'raise'; +} + +/** + * Lowers macros to the catalog components a renderer knows. + * + * The model sees the macros through the inference catalogs `transformCatalogs` derives + * from the transport catalogs. Macros target A2UI v1.0. + */ +export class MacroExpander { + /** The catalog the macros belong to, as given in the options. */ + readonly catalogId: string | undefined; + readonly onError: 'passthrough' | 'raise'; + private readonly macros: ReadonlyMap; + private readonly passthroughComponents: ReadonlySet | undefined; + /** The component names of each known catalog, including the macros' own scoped catalog. */ + private readonly catalogComponents = new Map>(); + /** The IDs of the registered base catalogs, in the order they were registered. */ + private readonly baseCatalogIds: string[] = []; + + /** + * @throws {A2uiValidationError} If a macro name is not a valid v1.0 component name, or a + * base catalog targets a protocol version other than v1.0. + */ + constructor(macros: readonly MacroDefinition[], options: MacroExpanderOptions = {}) { + const onError = options.onError ?? 'passthrough'; + if (onError !== 'passthrough' && onError !== 'raise') { + throw new TypeError(`Invalid onError policy '${String(onError)}'.`); + } + this.onError = onError; + for (const macro of macros) { + validateMacroName(macro.name); + } + this.macros = new Map(macros.map(macro => [macro.name, macro])); + this.passthroughComponents = + options.passthroughComponents === undefined + ? undefined + : new Set(options.passthroughComponents); + this.catalogId = options.catalogId; + if (this.catalogId !== undefined) { + this.catalogComponents.set(this.catalogId, new Set()); + } + for (const catalog of options.baseCatalogs ?? []) { + this.registerCatalog(catalog); + } + } + + /** The ID of the standalone catalog `toCatalog()` exports. */ + get macroCatalogId(): string { + return this.catalogId ?? DEFAULT_MACRO_CATALOG_ID; + } + + /** + * Registers a base catalog, as `baseCatalogs` does. + * + * @throws {A2uiValidationError} If the catalog targets a protocol version other than v1.0. + */ + registerCatalog(catalog: CatalogApi): void { + assertV10( + catalog.protocolVersion, + version => `Cannot register v${version} catalog with a v1.0 MacroExpander.`, + ); + this.recordComponents(catalog); + } + + /** + * Derives the inference catalogs from the transport catalogs, and registers the + * transport catalogs as base catalogs. + * + * The base catalogs come back pruned to `passthroughComponents`, followed by the + * standalone macro catalog of `toCatalog()`. When one of them has the expander's + * `catalogId`, the macros are added to that catalog instead. + * + * @throws {A2uiValidationError} If a catalog targets a protocol version other than v1.0. + * @throws {A2uiCatalogError} If a macro has the name of a component of the catalog it is + * added to. + */ + transformCatalogs(catalogs: readonly CatalogApi[]): CatalogApi[] { + for (const catalog of catalogs) { + this.registerCatalog(catalog); + } + if (catalogs.length === 0) { + return this.macros.size > 0 ? [this.toCatalog()] : []; + } + const augmentsInPlace = + this.catalogId !== undefined && catalogs.some(catalog => catalog.id === this.catalogId); + const pruner = this.pruner(); + const inference = catalogs.map(catalog => { + if (augmentsInPlace && catalog.id === this.catalogId) { + return this.transformToInferenceCatalog(catalog); + } + return pruner ? pruner.transform(catalog) : catalog; + }); + if (!augmentsInPlace && this.macros.size > 0) { + inference.push(this.toCatalog()); + } + return inference; + } + + /** + * Adds the macros to a copy of one base catalog, pruned to `passthroughComponents`, and + * registers the catalog as a base catalog. For surfaces that use a single catalog. + * + * @throws {A2uiValidationError} If the catalog targets a protocol version other than v1.0. + * @throws {A2uiCatalogError} If a macro has the name of a component the catalog keeps. + */ + transformToInferenceCatalog(baseCatalog: CatalogApi): CatalogApi { + assertV10( + baseCatalog.protocolVersion, + version => `Cannot augment v${version} catalog with v1.0 macros.`, + ); + const pruned = this.pruner()?.transform(baseCatalog) ?? baseCatalog; + for (const name of this.macros.keys()) { + if (pruned.components.has(name)) { + throw new A2uiCatalogError( + `Macro component '${name}' collides with an existing component in the base catalog.`, + ); + } + } + const macroCatalog = this.toCatalog(); + const augmented = pruned.withEntries( + [...pruned.components.values(), ...macroCatalog.components.values()], + [...pruned.functions.values()], + ); + this.recordComponents(baseCatalog); + return augmented; + } + + /** Exports the macros as a standalone v1.0 catalog with the ID `macroCatalogId`. */ + toCatalog(): CatalogApi { + const components: Record = {}; + for (const macro of this.macros.values()) { + components[macro.name] = macroComponentSchema(macro); + } + const references = [...this.macros.keys()].map(name => ({$ref: `#/components/${name}`})); + return Catalog.fromJson({ + $schema: 'https://json-schema.org/draft/2020-12/schema', + protocolVersion: '1.0', + catalogId: this.macroCatalogId, + title: 'A2UI Macros Catalog', + description: 'Standalone catalog of high-level A2UI macro components.', + components, + $defs: { + anyComponent: + references.length > 0 + ? {oneOf: references, discriminator: {propertyName: 'component'}} + : {not: {}}, + anyFunction: {not: {}}, + }, + }); + } + + private pruner(): ComponentPruningTransformer | undefined { + return this.passthroughComponents === undefined + ? undefined + : new ComponentPruningTransformer([...this.passthroughComponents].sort()); + } + + /** Records the component names of a base catalog, without checking its version. */ + private recordComponents(catalog: CatalogApi): void { + if (!catalog.id) { + return; + } + this.catalogComponents.set(catalog.id, new Set(catalog.components.keys())); + if (!this.baseCatalogIds.includes(catalog.id)) { + this.baseCatalogIds.push(catalog.id); + } + } +} + +/** Throws a `MacroProtocolError` with `message(version)` unless `version` is v1.0. */ +function assertV10(version: string, message: (version: string) => string): void { + if (!isV10(version)) { + throw new MacroProtocolError(message(normalizeVersionString(version))); + } +} + +function isV10(version: string): boolean { + return toCanonicalVersion(normalizeVersionString(version)) === '1.0'; +} diff --git a/typescript/agents/a2ui_agent/src/macros/macro-protocol-error.ts b/typescript/agents/a2ui_agent/src/macros/macro-protocol-error.ts new file mode 100644 index 0000000000..2c6300ecfa --- /dev/null +++ b/typescript/agents/a2ui_agent/src/macros/macro-protocol-error.ts @@ -0,0 +1,24 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {A2uiValidationError} from '../internal/web-core.js'; + +/** + * A macro that breaks a protocol rule, such as a protocol version other than v1.0 or the + * reserved name `Surface`. Unlike a failed invocation, it is thrown whatever `onError` + * says. + */ +export class MacroProtocolError extends A2uiValidationError {} diff --git a/typescript/agents/a2ui_agent/src/macros/parameter-values.ts b/typescript/agents/a2ui_agent/src/macros/parameter-values.ts new file mode 100644 index 0000000000..279916df16 --- /dev/null +++ b/typescript/agents/a2ui_agent/src/macros/parameter-values.ts @@ -0,0 +1,81 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The v1.0 wire values that macro parameters hand to `render`, after the expander has + * turned the shorthands a model writes into their full form. + */ + +import {ComponentChild} from '../component-tree/component-node.js'; + +/** A binding to a value in the data model. */ +export interface DataBinding { + '@path': string; +} + +/** A call to a function of the catalog. */ +export interface FunctionCall { + '@call': string; + args?: Record; + returnType?: string; +} + +export type DynamicString = string | DataBinding | FunctionCall; +export type DynamicNumber = number | DataBinding | FunctionCall; +export type DynamicBoolean = boolean | DataBinding | FunctionCall; +export type DynamicStringList = string[] | DataBinding | FunctionCall; + +/** A literal of any JSON type, a data binding or a function call. */ +export type DynamicValue = + | string + | number + | boolean + | unknown[] + | Record + | DataBinding + | FunctionCall; + +/** An event sent to the agent. */ +export interface ActionEvent { + name: string; + context?: Record; + userMessage?: DynamicString; +} + +/** Sends an event to the agent or calls a function on the renderer. */ +export type Action = {event: ActionEvent} | {functionCall: FunctionCall}; + +/** A rule an input component checks on the renderer. */ +export interface CheckRule { + condition: DataBinding | FunctionCall; + message?: string; +} + +export interface AccessibilityAttributes { + label?: DynamicString; + description?: DynamicString; + live?: 'off' | 'polite' | 'assertive'; + hidden?: DynamicBoolean; +} + +/** Children generated from a data model list, one per item, from a template component. */ +export interface DynamicChildList { + path: string; + componentId: ComponentChild; +} + +/** A static list of children, or children generated from a data model list. */ +export type ChildList = ComponentChild[] | DynamicChildList; diff --git a/typescript/agents/a2ui_agent/src/macros/parameters.ts b/typescript/agents/a2ui_agent/src/macros/parameters.ts new file mode 100644 index 0000000000..6f63f60dcd --- /dev/null +++ b/typescript/agents/a2ui_agent/src/macros/parameters.ts @@ -0,0 +1,232 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The parameter vocabulary of macros. + * + * It mirrors the parameter types of the shared macro conformance suite + * (`conformance/agent/macros/README.md`): each type has a JSON Schema the model sees and a + * coercion that turns the model's argument into the value `render` receives. + */ + +import {ComponentChild} from '../component-tree/component-node.js'; +import { + AccessibilityAttributes, + Action, + CheckRule, + ChildList, + DynamicBoolean, + DynamicNumber, + DynamicString, + DynamicStringList, + DynamicValue, +} from './parameter-values.js'; + +/** The parameter types of the vocabulary. */ +export type MacroParameterType = + | 'string' + | 'integer' + | 'number' + | 'boolean' + | 'component' + | 'componentList' + | 'childList' + | 'action' + | 'dynamicString' + | 'dynamicNumber' + | 'dynamicBoolean' + | 'dynamicStringList' + | 'dynamicValue' + | 'checkRuleList' + | 'accessibility'; + +/** + * Whether an invocation must set a parameter: `required`, or `defaulted` and `optional` + * when it may leave it out, with or without a default. + */ +export type ParameterPresence = 'required' | 'defaulted' | 'optional'; + +/** A macro parameter, as the `param` functions create it. */ +export interface MacroParameter { + readonly type: MacroParameterType; + readonly presence: P; + readonly description?: string; + readonly enum?: readonly string[]; + readonly default?: T; +} + +/** The parameters of a macro, by name. */ +export type MacroParameters = Readonly>; + +export interface ParameterOptions { + /** Tells the model what the parameter is for. */ + description?: string; + /** The value `render` receives when an invocation leaves the parameter out. */ + default?: T; + /** `false` lets invocations leave the parameter out without a default. */ + required?: boolean; +} + +export interface StringParameterOptions extends ParameterOptions { + /** The values the parameter accepts. */ + enum?: readonly string[]; +} + +/** The presence a parameter's options give it. */ +export type PresenceOf = O extends {default: unknown} + ? 'defaulted' + : O extends {required: false} + ? 'optional' + : 'required'; + +/** The value type of a string parameter: the union of its `enum`, or `string`. */ +export type StringValue = O extends {enum: readonly (infer E extends string)[]} ? E : string; + +/** The value type of a parameter. */ +export type ParameterValue

= P extends MacroParameter ? T : never; + +/** + * The arguments `render` receives: a required parameter or one with a default has its + * value, an optional parameter without a default has its value or `undefined`. + */ +export type MacroArgs

= { + [K in keyof P]: P[K] extends MacroParameter + ? T | undefined + : ParameterValue; +}; + +type OmittableKeys

= { + [K in keyof P]: P[K] extends MacroParameter ? never : K; +}[keyof P]; + +/** The input of a direct `render` call, which may leave out parameters that aren't required. */ +export type MacroInput

= { + [K in Exclude>]: ParameterValue; +} & { + [K in OmittableKeys

]?: ParameterValue; +}; + +type NoOptions = Record; + +function createParameter( + type: MacroParameterType, + options: StringParameterOptions | ParameterOptions = {}, +): MacroParameter { + const presence: ParameterPresence = + options.default !== undefined + ? 'defaulted' + : options.required === false + ? 'optional' + : 'required'; + const parameter: {-readonly [K in keyof MacroParameter]: MacroParameter[K]} = { + type, + presence, + }; + if (options.description !== undefined) parameter.description = options.description; + if ('enum' in options && options.enum !== undefined) parameter.enum = [...options.enum]; + if (options.default !== undefined) parameter.default = options.default as T; + return parameter as MacroParameter; +} + +function parameterOfType(type: MacroParameterType) { + return = NoOptions>( + options?: O, + ): MacroParameter> => createParameter(type, options); +} + +/** + * Creates macro parameters. + * + * Each function takes `description`, `default` and `required: false`, and `string` also + * takes `enum`. The comment on each says what an invocation may pass and what `render` + * receives. + */ +export const param = { + /** A string, or one of `enum`. */ + string: ( + options?: O, + ): MacroParameter, PresenceOf> => + createParameter, PresenceOf>('string', options), + /** An integer. */ + integer: parameterOfType('integer'), + /** A number. */ + number: parameterOfType('number'), + /** A boolean. */ + boolean: parameterOfType('boolean'), + /** The ID of a component on the surface. */ + component: parameterOfType('component'), + /** A list of component IDs. */ + componentList: parameterOfType('componentList'), + /** A list of component IDs, or a `{path, componentId}` template over a data model list. */ + childList: parameterOfType('childList'), + /** + * An `Action`. An invocation may also pass an event name, an event body + * (`{name, context, userMessage}`), `{event: name, ...}`, or a bare `{'@call': ...}`. + */ + action: parameterOfType('action'), + /** A string, an `{'@path': ...}` binding or an `{'@call': ...}` function call. */ + dynamicString: parameterOfType('dynamicString'), + /** A number, a binding or a function call. */ + dynamicNumber: parameterOfType('dynamicNumber'), + /** A boolean, a binding or a function call. */ + dynamicBoolean: parameterOfType('dynamicBoolean'), + /** A list of strings, a binding or a function call. */ + dynamicStringList: parameterOfType('dynamicStringList'), + /** + * Any JSON value, a binding or a function call. An object is a binding only as + * `{'@path': ...}` and a call only with `'@call'`; any other object is kept as a literal. + */ + dynamicValue: parameterOfType('dynamicValue'), + /** A list of `CheckRule`s. */ + checkRuleList: parameterOfType('checkRuleList'), + /** + * `AccessibilityAttributes` for `render` to use. Without this parameter, an invocation's + * `@accessibility` is merged onto the root of the lowered tree instead. + */ + accessibility: parameterOfType('accessibility'), +}; + +const COMMON_TYPES = 'common_types.json#/$defs/'; + +const PARAMETER_SCHEMAS: Readonly>>> = { + string: {type: 'string'}, + integer: {type: 'integer'}, + number: {type: 'number'}, + boolean: {type: 'boolean'}, + component: {$ref: `${COMMON_TYPES}Child`}, + componentList: {$ref: `${COMMON_TYPES}ChildList`}, + childList: {$ref: `${COMMON_TYPES}ChildList`}, + action: {$ref: `${COMMON_TYPES}Action`}, + dynamicString: {$ref: `${COMMON_TYPES}DynamicString`}, + dynamicNumber: {$ref: `${COMMON_TYPES}DynamicNumber`}, + dynamicBoolean: {$ref: `${COMMON_TYPES}DynamicBoolean`}, + dynamicStringList: {$ref: `${COMMON_TYPES}DynamicStringList`}, + dynamicValue: {$ref: `${COMMON_TYPES}DynamicValue`}, + checkRuleList: {type: 'array', items: {$ref: `${COMMON_TYPES}CheckRule`}}, + accessibility: {$ref: `${COMMON_TYPES}AccessibilityAttributes`}, +}; + +/** The JSON Schema of a parameter in a macro's catalog entry. */ +export function parameterSchema(parameter: MacroParameter): Record { + const schema: Record = structuredClone(PARAMETER_SCHEMAS[parameter.type]); + if (parameter.enum !== undefined) { + schema['enum'] = [...parameter.enum]; + } + if (parameter.description !== undefined) { + schema['description'] = parameter.description; + } + return schema; +} diff --git a/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts b/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts new file mode 100644 index 0000000000..031e36b8b6 --- /dev/null +++ b/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts @@ -0,0 +1,362 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The reference macros and case runner for `conformance/agent/macros/macros.yaml`. + * + * The macros are written with `defineMacro`, mirroring the Python harness + * (`python/a2ui_agent/tests/conformance/macro_suite.py`), including its imperative + * transforms such as the uppercased status. The goldens were recorded from Python's typed + * builder, which fills in catalog defaults such as `Row.justify`; the node helpers below + * write the same defaults. + */ + +import {readFileSync} from 'fs'; + +import {load} from 'js-yaml'; + +import { + A2uiValidationError, + Catalog, + type CatalogApi, + type ComponentNode, + defineMacro, + type MacroDefinition, + MacroExpander, + param, +} from '../../src/index.js'; +import {loadBasicCatalog} from '../helpers/basic-catalogs.js'; +import {LoadedCase} from './loader.js'; +import {conformancePath} from './suite-helpers.js'; + +export const SUITE = 'agent/macros/macros.yaml'; +export const GOLDEN_DIR = conformancePath('agent/macros/golden'); + +const V1_0_BASIC_CID = 'https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json'; +const V0_9_BASIC_CID = 'https://a2ui.org/specification/v0_9/standard_catalog.json'; + +const RAW_SUITE = load(readFileSync(conformancePath(SUITE), 'utf8')) as { + custom_catalogs?: Record>; +}; +const CUSTOM_CATALOG_DOCUMENTS = RAW_SUITE.custom_catalogs ?? {}; + +// Node helpers with the defaults of the Python v1.0 builder classes. + +function builderNode(component: string, defaults: Record = {}) { + return (props: Record): ComponentNode => { + const node: ComponentNode = {component, ...props}; + for (const [key, value] of Object.entries(defaults)) { + if (node[key] === undefined) { + node[key] = value; + } + } + return node; + }; +} + +const Button = builderNode('Button', {variant: 'default'}); +const Card = builderNode('Card'); +const Column = builderNode('Column', {justify: 'start', align: 'stretch'}); +const List = builderNode('List', {direction: 'vertical', align: 'stretch'}); +const Row = builderNode('Row', {justify: 'start', align: 'stretch'}); +const Text = builderNode('Text', {variant: 'body'}); +const TextField = builderNode('TextField', {variant: 'shortText'}); + +// The v1.0 reference macros (`get_v1_0_suite_macros` in Python). + +const StatusBadge = defineMacro({ + name: 'StatusBadge', + description: 'Status badge with uppercase status and title.', + parameters: {status: param.string(), title: param.string()}, + render: ({status, title}) => + Card({ + child: Row({ + children: [Text({text: status.toUpperCase(), variant: 'caption'}), Text({text: title})], + }), + }), +}); + +const SlotContainer = defineMacro({ + name: 'SlotContainer', + description: 'Container accepting an external child slot.', + parameters: {title: param.string(), content: param.component()}, + render: ({title, content}) => Card({child: Column({children: [Text({text: title}), content]})}), +}); + +const MultiSlotContainer = defineMacro({ + name: 'MultiSlotContainer', + description: 'Container accepting a list of child slots.', + parameters: {header: param.string(), items: param.componentList()}, + render: ({header, items}) => Card({child: Column({children: [Text({text: header}), ...items]})}), +}); + +const ActionButton = defineMacro({ + name: 'ActionButton', + description: 'Button with coerced action.', + parameters: {label: param.string(), action: param.action()}, + render: ({label, action}) => Button({child: Text({text: label}), action, variant: 'primary'}), +}); + +const BoundMetric = defineMacro({ + name: 'BoundMetric', + description: 'Metric card displaying a dynamic value.', + parameters: {label: param.string(), value: param.dynamicString()}, + render: ({label, value}) => + Card({ + child: Column({children: [Text({text: label, variant: 'caption'}), Text({text: value})]}), + }), +}); + +const ConfigCard = defineMacro({ + name: 'ConfigCard', + description: 'Configuration card displaying primitives and metadata.', + parameters: {name: param.string(), port: param.integer(), active: param.boolean()}, + render: ({name, port, active}) => + Card({ + child: Column({ + children: [ + Text({text: name}), + Text({text: `Port: ${port}`}), + Text({text: `Active: ${String(active)}`}), + ], + }), + }), +}); + +const NestedMacroCard = defineMacro({ + name: 'NestedMacroCard', + description: 'Macro composing another macro.', + parameters: {title: param.string(), status: param.string()}, + render: ({title, status}) => + Card({ + child: Column({ + children: [Text({text: title}), StatusBadge.render({status, title: `${title} Status`})], + }), + }), +}); + +const RecursiveCard: MacroDefinition = defineMacro({ + name: 'RecursiveCard', + description: 'Macro composing itself recursively.', + parameters: {title: param.string()}, + render: ({title}) => Card({child: RecursiveCard.render({title})}), +}); + +const ComplexCard = defineMacro({ + name: 'ComplexCard', + description: 'Card testing protocol common types in macro parameter schemas.', + parameters: { + title: param.string(), + dynamic_title: param.dynamicString(), + metric: param.dynamicNumber(), + is_active: param.dynamicBoolean(), + tags: param.dynamicStringList(), + anything: param.dynamicValue(), + on_click: param.action(), + checks: param.checkRuleList(), + accessibility: param.accessibility(), + footer: param.component(), + items: param.componentList(), + theme: param.string({enum: ['primary', 'secondary']}), + }, + render: ({title}) => Card({child: Text({text: title})}), +}); + +const PayloadButton = defineMacro({ + name: 'PayloadButton', + description: 'Button sending dynamic payload values inside an Action event context.', + parameters: { + label: param.string(), + event_name: param.string(), + payload: param.dynamicValue(), + extra: param.dynamicValue(), + }, + render: ({label, event_name, payload, extra}) => + Button({ + child: Text({text: label}), + variant: 'primary', + action: {event: {name: event_name, context: {payload, extra}}}, + }), +}); + +const DynamicFormCard = defineMacro({ + name: 'DynamicFormCard', + description: 'Form card with dynamic child list, check rules, and submit action.', + parameters: { + label: param.string(), + placeholder: param.dynamicString(), + items: param.childList(), + checks: param.checkRuleList(), + on_submit: param.action(), + }, + render: ({label, placeholder, items, checks, on_submit}) => + Card({ + child: Column({ + children: [ + TextField({label, value: {'@path': '/form/email'}, placeholder, '@checks': checks}), + List({children: items}), + Button({child: Text({text: 'Submit'}), variant: 'primary', action: on_submit}), + ], + }), + }), +}); + +const AnnotatedBadge = defineMacro({ + name: 'AnnotatedBadge', + description: + 'Status badge whose root Card defines default accessibility and metadata extensions.', + parameters: {status: param.string(), title: param.string()}, + render: ({status, title}) => + Card({ + child: Row({ + children: [Text({text: status.toUpperCase(), variant: 'caption'}), Text({text: title})], + }), + '@accessibility': {description: 'Default badge description'}, + '@metadata': {extensions: {macroMeta: {source: 'AnnotatedBadge'}}}, + }), +}); + +const DeclaredA11yCard = defineMacro({ + name: 'DeclaredA11yCard', + description: 'Card declaring accessibility as an explicit macro parameter.', + parameters: {title: param.string(), accessibility: param.accessibility({required: false})}, + render: ({title, accessibility}) => + Card({ + child: Text({text: title}), + '@accessibility': { + label: + typeof accessibility?.label === 'string' ? `Custom: ${accessibility.label}` : 'Internal', + }, + }), +}); + +const WeightedCard = defineMacro({ + name: 'WeightedCard', + description: 'Card declaring weight as an explicit macro parameter.', + parameters: {label: param.string(), weight: param.number({required: false})}, + render: ({label, weight}) => Card({child: Text({text: label}), weight}), +}); + +const PositiveCountCard = defineMacro({ + name: 'PositiveCountCard', + description: 'Card raising ValidationError when count is negative.', + parameters: {count: param.integer()}, + render: ({count}) => { + if (count < 0) { + throw new A2uiValidationError('count must be non-negative'); + } + return Card({child: Text({text: `Count: ${count}`})}); + }, +}); + +export const SUITE_MACROS_V1_0: readonly MacroDefinition[] = [ + StatusBadge, + SlotContainer, + MultiSlotContainer, + ActionButton, + BoundMetric, + ConfigCard, + NestedMacroCard, + RecursiveCard, + ComplexCard, + PayloadButton, + DynamicFormCard, + AnnotatedBadge, + DeclaredA11yCard, + WeightedCard, + PositiveCountCard, +]; + +// Catalog resolution and case execution. + +/** The protocol version of a case's envelope: `1.0`, `v0.9` or `v0.8`. */ +export function envelopeVersion(testCase: LoadedCase): string { + const raw = (testCase['envelope_version'] ?? testCase['version']) as string | undefined; + if (raw === '1.0' || raw === 'v1.0') return '1.0'; + return raw ?? 'v0.9'; +} + +/** The protocol version the case's macros are written for, as Python's harness picks it. */ +export function macroVersion(testCase: LoadedCase): string { + const raw = testCase['macro_version'] as string | undefined; + if (raw === undefined) return envelopeVersion(testCase); + return raw === '1.0' || raw === 'v1.0' ? '1.0' : raw; +} + +function basicCatalog(version: string): CatalogApi { + return loadBasicCatalog(version === '1.0' ? '1.0' : 'v0.9.1'); +} + +/** Resolves a catalog ID from `custom_catalogs` or the basic catalog, as Python does. */ +export function resolveCatalog(catalogId: string, version: string): CatalogApi { + const custom = CUSTOM_CATALOG_DOCUMENTS[catalogId]; + if (custom) { + return Catalog.fromJson(structuredClone(custom)); + } + if (catalogId === V1_0_BASIC_CID) return basicCatalog('1.0'); + if (catalogId === V0_9_BASIC_CID) return basicCatalog('v0.9'); + const basic = basicCatalog(version); + return catalogId === basic.id ? basic : Catalog.fromJson(basic.toJson(), undefined, catalogId); +} + +function selectMacros(testCase: LoadedCase): readonly MacroDefinition[] { + if (testCase['empty_macros']) { + return []; + } + const colliding = testCase['colliding_macro'] as string | undefined; + if (colliding !== undefined) { + return [defineMacro({name: colliding, render: () => Card({child: Text({text: 'colliding'})})})]; + } + return SUITE_MACROS_V1_0; +} + +function buildExpander(testCase: LoadedCase): MacroExpander { + const protocolVersion = testCase['expander_protocol_version'] as string | undefined; + if (protocolVersion !== undefined && protocolVersion !== '1.0') { + throw new Error(`Unexpected expander_protocol_version ${protocolVersion}`); + } + const macroCatalogId = testCase['macro_catalog_id'] as string | undefined; + const scoped = (testCase['expander_scoped'] as boolean | undefined) ?? true; + const catalogId = + (testCase['expander_catalog_id'] as string | undefined) ?? + (scoped ? macroCatalogId : undefined); + const version = envelopeVersion(testCase); + const baseCatalogs = (testCase['base_catalogs'] as string[] | undefined)?.map(id => + resolveCatalog(id, version), + ); + return new MacroExpander(selectMacros(testCase), { + passthroughComponents: testCase['passthrough_components'] as string[] | undefined, + catalogId, + baseCatalogs, + onError: testCase['on_error'] as 'passthrough' | 'raise' | undefined, + }); +} + +/** Runs a catalog case and returns the catalog it produces, or `undefined` for none. */ +export function runCatalogCase(testCase: LoadedCase): CatalogApi | undefined { + const expander = buildExpander(testCase); + switch (testCase.action) { + case 'to_catalog': + return expander.toCatalog(); + case 'transform_catalog': + expander.transformToInferenceCatalog(basicCatalog(envelopeVersion(testCase))); + return undefined; + case 'transform_to_inference_catalog': + return expander.transformToInferenceCatalog(basicCatalog(envelopeVersion(testCase))); + default: + throw new Error(`Unexpected catalog action ${testCase.action}`); + } +} diff --git a/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts b/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts new file mode 100644 index 0000000000..1783322e90 --- /dev/null +++ b/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts @@ -0,0 +1,270 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Runs `conformance/agent/macros/macros.yaml` against `MacroExpander`, with the reference + * macros of `macro-suite.ts`. + * + * Each case is checked as Python's harness checks it: a golden or `expect` case against + * its expectations, and an `expect_error` case against the error category. Macros target + * v1.0, so cases that need v0.9 macros are skipped. + */ + +import {expect} from 'vitest'; + +import { + A2uiCatalogError, + A2uiRecursionError, + A2uiValidationError, + type CatalogApi, +} from '../../src/index.js'; +import {LoadedCase, loadCases} from './loader.js'; +import {macroVersion, runCatalogCase, SUITE} from './macro-suite.js'; +import { + assertKnownKeys, + CASE_METADATA_KEYS, + conformancePath, + describeSuite, + EXPECT_ERROR_KEYS, +} from './suite-helpers.js'; + +const MACRO_CASE_KEYS = new Set([ + ...CASE_METADATA_KEYS, + 'base_catalogs', + 'catalog_id', + 'colliding_macro', + 'empty_macros', + 'envelope_version', + 'expander_catalog_id', + 'expander_protocol_version', + 'expander_scoped', + 'expect', + 'expect_error', + 'golden', + 'id', + 'input', + 'macro_catalog_id', + 'macro_version', + 'messages', + 'on_error', + 'passthrough_components', + 'surface_catalogs', + 'surface_id', + 'validation', + 'validation_catalogs', + 'version', +]); + +const MACRO_EXPECT_KEYS = new Set([ + 'absent_any_component_references', + 'absent_components', + 'absent_property_on_all_components', + 'any_component_references', + 'augmented_components', + 'catalog_id', + 'component_count', + 'component_properties', + 'component_types', + 'components', + 'create_surface_catalog_id', + 'has_any_component_discriminator', + 'has_any_function', + 'protocol_version', +]); + +const CATALOG_ACTIONS = new Set([ + 'to_catalog', + 'transform_catalog', + 'transform_to_inference_catalog', +]); + +const ERROR_BY_CATEGORY: Record Error> = { + CatalogError: A2uiCatalogError, + RecursionError: A2uiRecursionError, + ValidationError: A2uiValidationError, +}; + +/** + * Cases that check that the expander rejects an envelope version other than v1.0. They + * don't depend on the version of the macros, so they run with the v1.0 reference macros. + */ +const VERSION_REJECTION_CASES = new Set(['13_error_envelope_version_mismatch']); + +/** Cases whose behavior lands in a later commit of this change. */ +const PENDING = new Set([ + '01_status_badge_expansion_v1_0', + '02_slot_boundary_preservation_v1_0', + '03_multi_slot_list_coercion_v1_0', + '04_action_string_coercion_v1_0', + '05_data_binding_coercion_v1_0', + '06_primitive_and_dict_arguments_v1_0', + '07_nested_macro_composition_v1_0', + '08_surface_lifecycle_envelopes_v1_0', + '13_error_envelope_version_mismatch', + '14_multiple_macro_instances_namespacing_v1_0', + '15_mixed_primitive_and_macro_envelope_v1_0', + '19_envelope_attributes_preservation', + '20_mixable_catalogs_resolution', + '21_v1_0_data_binding_and_function_call_coercion', + '22_v1_0_action_user_message_coercion', + '25_v1_0_literal_object_preservation', + '26_v1_0_dynamic_child_list_and_checks', + '30_root_envelope_deep_merge_and_declared_override', + '32_v1_0_action_function_call_shorthand', + '33_runtime_failure_and_undeclared_property_fallback', + '33b_error_on_error_raise_surfaces_validation_error', + '34_v1_0_multi_catalog_foo_bar_baz_and_defaultless_surface', + '35_v1_0_auto_stamping_from_base_catalogs_on_defaultless_surface', + '35b_error_ambiguous_primitive_on_defaultless_surface', + '36_surface_lifecycle_delete_recreate_and_null_catalog_id', + '37a_stateless_surface_catalogs_override_expands', + '37b_stateless_surface_catalogs_override_skips', + '37c_scoped_expander_skips_untracked_and_invalid_catalog_id', + '37d_default_macro_catalog_id_expands_after_base_registration', + '37e_standalone_macro_catalog_surface_default', + '38a_custom_catalog_collision_and_same_name_wrapper', + '38b_scoped_nested_macro_and_non_basic_surface', + '39a_error_deferred_self_recursion_untracked', + '39b_error_mutual_recursion_defaultless_surface', + '39c_error_mutual_recursion_foreign_surface', + '40c_error_lower_v0_9_envelope_with_v1_0_macros', + '40i_error_v1_0_macro_emitting_reserved_surface_component', +]); + +function skipReason(testCase: LoadedCase): string | undefined { + const needsV09Macros = + !testCase['empty_macros'] && + macroVersion(testCase) !== '1.0' && + !VERSION_REJECTION_CASES.has(testCase.name); + if (needsV09Macros) { + return 'macros support v1.0 only'; + } + if (PENDING.has(testCase.name)) { + return 'not implemented yet'; + } + return undefined; +} + +function runCase(testCase: LoadedCase): CatalogApi | undefined { + if (CATALOG_ACTIONS.has(testCase.action)) { + return runCatalogCase(testCase); + } + throw new Error(`Unsupported action ${testCase.action}`); +} + +function expectError(testCase: LoadedCase): void { + const expected = testCase['expect_error'] as Record; + assertKnownKeys(expected, EXPECT_ERROR_KEYS, 'expect_error'); + const errorClass = ERROR_BY_CATEGORY[expected['category'] as string]; + let thrown: unknown; + try { + runCase(testCase); + } catch (e) { + thrown = e; + } + expect(thrown, `Expected case ${testCase.name} to throw`).toBeInstanceOf(errorClass); + if (typeof expected['message'] === 'string') { + expect((thrown as Error).message).toMatch(new RegExp(expected['message'])); + } +} + +function refTargets(catalog: CatalogApi): string[] { + const defs = (catalog.validationSchema['$defs'] ?? {}) as Record; + const anyComponent = (defs['anyComponent'] ?? {}) as {oneOf?: Array<{$ref?: string}>}; + return (anyComponent.oneOf ?? []).map(ref => ref.$ref ?? ''); +} + +function expectCatalog(catalog: CatalogApi, expected: Record): void { + const document = catalog.toJson(); + const documentComponents = (document['components'] ?? {}) as Record; + const defs = (document['$defs'] ?? {}) as Record>; + const validationComponents = (catalog.validationSchema['components'] ?? {}) as Record< + string, + unknown + >; + + if ('catalog_id' in expected) { + expect(catalog.id).toBe(expected['catalog_id']); + expect(document['catalogId']).toBe(expected['catalog_id']); + } + if ('component_count' in expected) { + expect(Object.keys(documentComponents)).toHaveLength(expected['component_count'] as number); + } + if ('has_any_component_discriminator' in expected) { + const discriminator = defs['anyComponent']?.['discriminator']; + if (expected['has_any_component_discriminator']) { + expect(discriminator).toEqual({propertyName: 'component'}); + } else { + expect(discriminator).toBeUndefined(); + } + } + if ('has_any_function' in expected) { + expect('anyFunction' in defs).toBe(Boolean(expected['has_any_function'])); + } + for (const name of (expected['augmented_components'] ?? []) as string[]) { + expect(validationComponents, `Expected ${name} in the catalog`).toHaveProperty([name]); + } + for (const name of (expected['absent_components'] ?? []) as string[]) { + expect(validationComponents, `Expected no ${name} in the catalog`).not.toHaveProperty([name]); + } + for (const ref of (expected['any_component_references'] ?? []) as string[]) { + expect(refTargets(catalog)).toContain(ref); + } + for (const name of (expected['absent_any_component_references'] ?? []) as string[]) { + expect(refTargets(catalog).filter(ref => ref.endsWith(`/${name}`))).toEqual([]); + } + const componentProperties = (expected['component_properties'] ?? {}) as Record< + string, + Record> + >; + for (const [name, properties] of Object.entries(componentProperties)) { + const component = documentComponents[name] as {properties?: Record}; + expect(component, `${name} not found in the catalog`).toBeDefined(); + for (const [property, schema] of Object.entries(properties)) { + const actual = component.properties?.[property] as Record | undefined; + expect(actual, `Property ${property} missing from ${name}`).toBeDefined(); + for (const [key, value] of Object.entries(schema)) { + expect(actual?.[key], `${name}.${property}.${key}`).toEqual(value); + } + } + } + if ('protocol_version' in expected) { + expect(catalog.protocolVersion).toBe(expected['protocol_version']); + } +} + +describeSuite( + `Conformance: ${SUITE}`, + loadCases([conformancePath(SUITE)]), + testCase => { + assertKnownKeys(testCase, MACRO_CASE_KEYS, 'macros case'); + if (testCase['expect_error'] !== undefined) { + expectError(testCase); + return; + } + const expected = testCase['expect'] as Record | undefined; + if (expected === undefined) { + throw new Error(`Case ${testCase.name} has no expectation this harness checks`); + } + assertKnownKeys(expected, MACRO_EXPECT_KEYS, 'macros expect'); + const catalog = runCase(testCase); + if (catalog === undefined) { + throw new Error(`Case ${testCase.name} produced no catalog`); + } + expectCatalog(catalog, expected); + }, + {skipReason}, +); diff --git a/typescript/agents/a2ui_agent/tests/conformance/unsupported-suites.test.ts b/typescript/agents/a2ui_agent/tests/conformance/unsupported-suites.test.ts index 1872de18d0..ea16701e0f 100644 --- a/typescript/agents/a2ui_agent/tests/conformance/unsupported-suites.test.ts +++ b/typescript/agents/a2ui_agent/tests/conformance/unsupported-suites.test.ts @@ -50,6 +50,7 @@ export const ACTIVE_SUITES: ReadonlySet = new Set([ 'agent/express/response_streaming.yaml', 'agent/legacy/inference_format.yaml', 'agent/legacy/parser.yaml', + 'agent/macros/macros.yaml', 'agent/multi_catalog_formats.yaml', 'agent/renderer_capabilities.yaml', 'agent/renderer_function_calls.yaml', @@ -67,8 +68,6 @@ export const PERFORMANCE_SUITES: ReadonlySet = new Set([ export const UNSUPPORTED_SUITES: Readonly> = { 'agent/atom/compiler.yaml': 'Elemental and Atom are experimental and Python-only', 'agent/elemental/compiler.yaml': 'Elemental and Atom are experimental and Python-only', - 'agent/macros/macros.yaml': - 'the composite macro API is a Python-only helper not implemented in TypeScript', 'agent/legacy/streaming_parser.yaml': 'superseded by direct_json/response_streaming.yaml and express/response_streaming.yaml', }; diff --git a/typescript/agents/a2ui_agent/tests/unit/macros/define-macro.test.ts b/typescript/agents/a2ui_agent/tests/unit/macros/define-macro.test.ts new file mode 100644 index 0000000000..a38fc8b0b5 --- /dev/null +++ b/typescript/agents/a2ui_agent/tests/unit/macros/define-macro.test.ts @@ -0,0 +1,49 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, expect, it} from 'vitest'; + +import {A2uiValidationError, type ComponentNode, defineMacro, param} from '../../../src/index.js'; + +describe('defineMacro', () => { + it.each(['Surface', 'ï¼³urface', '123-invalid!', 'has space'])( + 'rejects the component name %j', + name => { + expect(() => defineMacro({name, render: () => ({component: 'Text'})})).toThrow( + A2uiValidationError, + ); + }, + ); + + it('fills in defaults for the parameters an input leaves out', () => { + const seen: unknown[] = []; + const Badge = defineMacro({ + name: 'Badge', + parameters: { + label: param.string(), + variant: param.string({default: 'body'}), + weight: param.number({required: false}), + }, + render: (args): ComponentNode => { + seen.push(args); + return {component: 'Text', text: args.label, variant: args.variant}; + }, + }); + + expect(Badge.render({label: 'Hi'})).toEqual({component: 'Text', text: 'Hi', variant: 'body'}); + expect(seen).toEqual([{label: 'Hi', variant: 'body', weight: undefined}]); + }); +}); diff --git a/typescript/agents/a2ui_agent/tests/unit/macros/expander-catalogs.test.ts b/typescript/agents/a2ui_agent/tests/unit/macros/expander-catalogs.test.ts new file mode 100644 index 0000000000..2fdb39c54f --- /dev/null +++ b/typescript/agents/a2ui_agent/tests/unit/macros/expander-catalogs.test.ts @@ -0,0 +1,131 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, expect, it} from 'vitest'; + +import { + A2uiCatalogError, + A2uiValidationError, + defineMacro, + MacroExpander, + param, +} from '../../../src/index.js'; +import {BASIC_CATALOG_IDS, loadBasicCatalog} from '../../helpers/basic-catalogs.js'; + +const Badge = defineMacro({ + name: 'Badge', + description: 'A badge.', + parameters: { + label: param.string({description: 'The label.'}), + tone: param.string({enum: ['info', 'warning'], default: 'info'}), + weight: param.number({required: false}), + }, + render: ({label}) => ({component: 'Text', text: label}), +}); + +describe('MacroExpander catalogs', () => { + it('exports the macros as a standalone v1.0 catalog', () => { + const catalog = new MacroExpander([Badge]).toCatalog(); + + expect(catalog.toJson()).toEqual({ + $schema: 'https://json-schema.org/draft/2020-12/schema', + protocolVersion: '1.0', + catalogId: 'https://a2ui.org/catalogs/macros', + title: 'A2UI Macros Catalog', + description: 'Standalone catalog of high-level A2UI macro components.', + components: { + Badge: { + type: 'object', + properties: { + component: {const: 'Badge'}, + label: {type: 'string', description: 'The label.'}, + tone: {type: 'string', enum: ['info', 'warning']}, + weight: {type: 'number'}, + }, + required: ['component', 'label'], + description: 'A badge.', + }, + }, + $defs: { + anyComponent: { + oneOf: [{$ref: '#/components/Badge'}], + discriminator: {propertyName: 'component'}, + }, + anyFunction: {not: {}}, + }, + }); + }); + + it('keeps only the passthrough components next to the macros', () => { + const expander = new MacroExpander([Badge], {passthroughComponents: ['Text', 'Row']}); + + const catalog = expander.transformToInferenceCatalog(loadBasicCatalog('1.0')); + + expect([...catalog.components.keys()].sort()).toEqual(['Badge', 'Row', 'Text']); + expect(catalog.id).toBe(BASIC_CATALOG_IDS['1.0']); + }); + + it('lets a macro take the name of a component that passthrough prunes', () => { + const Text = defineMacro({name: 'Text', render: () => ({component: 'Card'})}); + + expect(() => + new MacroExpander([Text]).transformToInferenceCatalog(loadBasicCatalog('1.0')), + ).toThrow(A2uiCatalogError); + const catalog = new MacroExpander([Text], { + passthroughComponents: [], + }).transformToInferenceCatalog(loadBasicCatalog('1.0')); + expect([...catalog.components.keys()]).toEqual(['Text']); + }); + + it('prunes the base catalogs and appends the macro catalog', () => { + const expander = new MacroExpander([Badge], {passthroughComponents: ['Text']}); + + const catalogs = expander.transformCatalogs([loadBasicCatalog('1.0')]); + + expect(catalogs.map(catalog => catalog.id)).toEqual([ + BASIC_CATALOG_IDS['1.0'], + 'https://a2ui.org/catalogs/macros', + ]); + expect([...catalogs[0].components.keys()]).toEqual(['Text']); + expect([...catalogs[1].components.keys()]).toEqual(['Badge']); + }); + + it('adds the macros to the base catalog that has the expander catalog ID', () => { + const expander = new MacroExpander([Badge], {catalogId: BASIC_CATALOG_IDS['1.0']}); + + const catalogs = expander.transformCatalogs([loadBasicCatalog('1.0')]); + + expect(catalogs).toHaveLength(1); + expect(catalogs[0].components.has('Badge')).toBe(true); + expect(catalogs[0].components.has('Text')).toBe(true); + }); + + it('returns the macro catalog alone, or nothing, without base catalogs', () => { + expect(new MacroExpander([Badge]).transformCatalogs([]).map(c => c.id)).toEqual([ + 'https://a2ui.org/catalogs/macros', + ]); + expect(new MacroExpander([]).transformCatalogs([])).toEqual([]); + }); + + it('rejects base catalogs of another protocol version', () => { + expect(() => new MacroExpander([Badge], {baseCatalogs: [loadBasicCatalog('v0.9')]})).toThrow( + A2uiValidationError, + ); + expect(() => new MacroExpander([Badge]).transformCatalogs([loadBasicCatalog('v0.9')])).toThrow( + A2uiValidationError, + ); + }); +}); diff --git a/typescript/agents/a2ui_agent/tests/unit/macros/parameters.test.ts b/typescript/agents/a2ui_agent/tests/unit/macros/parameters.test.ts new file mode 100644 index 0000000000..139529f9d9 --- /dev/null +++ b/typescript/agents/a2ui_agent/tests/unit/macros/parameters.test.ts @@ -0,0 +1,96 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, expect, expectTypeOf, it} from 'vitest'; + +import {type ComponentChild, defineMacro, type MacroInput, param} from '../../../src/index.js'; + +describe('param', () => { + it('records the presence its options give a parameter', () => { + expect(param.string()).toEqual({type: 'string', presence: 'required'}); + expect(param.integer({default: 10})).toEqual({ + type: 'integer', + presence: 'defaulted', + default: 10, + }); + expect(param.number({required: false, description: 'Weight'})).toEqual({ + type: 'number', + presence: 'optional', + description: 'Weight', + }); + expect(param.string({enum: ['a', 'b'], default: 'a'})).toEqual({ + type: 'string', + presence: 'defaulted', + enum: ['a', 'b'], + default: 'a', + }); + }); + + it('infers the render arguments from the parameters', () => { + type Items = ComponentChild[] | {path: string; componentId: ComponentChild}; + const Typed = defineMacro({ + name: 'Typed', + parameters: { + title: param.string(), + variant: param.string({enum: ['primary', 'secondary'], default: 'primary'}), + weight: param.number({required: false}), + content: param.component(), + items: param.childList(), + active: param.boolean({default: true}), + }, + render: args => { + expectTypeOf(args).toEqualTypeOf<{ + readonly title: string; + readonly variant: 'primary' | 'secondary'; + readonly weight: number | undefined; + readonly content: ComponentChild; + readonly items: Items; + readonly active: boolean; + }>(); + return {component: 'Text'}; + }, + }); + + expectTypeOf(Typed.render).parameter(0).toEqualTypeOf>(); + expectTypeOf>().toEqualTypeOf< + {title: string; content: ComponentChild; items: Items} & { + variant?: 'primary' | 'secondary'; + weight?: number; + active?: boolean; + } + >(); + }); + + it('types the action and dynamic parameters as their v1.0 wire forms', () => { + defineMacro({ + name: 'Wired', + parameters: { + onClick: param.action(), + label: param.dynamicString(), + checks: param.checkRuleList(), + }, + render: _args => { + expectTypeOf<{event: {name: string}}>().toExtend(); + expectTypeOf<{functionCall: {'@call': string}}>().toExtend(); + expectTypeOf<{'@path': string}>().toExtend(); + expectTypeOf<[{condition: {'@call': string}; message: string}]>().toExtend< + typeof _args.checks + >(); + return {component: 'Text'}; + }, + }); + }); +}); From 1e3ec27bf79574d8cf7c9c862fbbe0ef8ef73ef0 Mon Sep 17 00:00:00 2001 From: Manfred Steyer Date: Wed, 25 Nov 2026 00:47:24 +0100 Subject: [PATCH 3/9] feat(ts_agent): lower macro invocations in transport messages Add `MacroExpander.transformToTransport`. It replaces each macro invocation in `createSurface` and `updateComponents` messages with the flat components of the tree its `render` returns: the root takes the invocation's ID and the other IDs are namespaced under it, so the same macro can be used more than once on a surface. Macros used inside a rendered tree are lowered too, up to 16 levels; deeper nesting, or a `render` that calls itself without end, throws `A2uiRecursionError`. Arguments are checked against the macro's parameters before `render` runs: primitives must have their type, strings their `enum`, component slots take IDs, and parameters left out get their defaults. Unknown arguments and missing required ones are rejected. Cases `01`, `02`, `03`, `06`, `07`, `08`, `14` and `15` (v1.0) of the macro suite now pass. --- .../agents/a2ui_agent/src/macros/coercion.ts | 89 +++++++++ .../agents/a2ui_agent/src/macros/expander.ts | 108 ++++++++++- .../tests/conformance/macro-suite.ts | 39 ++++ .../conformance/macros-conformance.test.ts | 97 ++++++++-- .../unit/macros/expander-transport.test.ts | 176 ++++++++++++++++++ 5 files changed, 494 insertions(+), 15 deletions(-) create mode 100644 typescript/agents/a2ui_agent/src/macros/coercion.ts create mode 100644 typescript/agents/a2ui_agent/tests/unit/macros/expander-transport.test.ts diff --git a/typescript/agents/a2ui_agent/src/macros/coercion.ts b/typescript/agents/a2ui_agent/src/macros/coercion.ts new file mode 100644 index 0000000000..61b07340a7 --- /dev/null +++ b/typescript/agents/a2ui_agent/src/macros/coercion.ts @@ -0,0 +1,89 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {A2uiValidationError} from '../internal/web-core.js'; +import {MacroDefinition} from './define-macro.js'; +import {MacroParameter} from './parameters.js'; + +/** + * Turns the arguments of an invocation into the arguments `render` receives. + * + * Every argument must match its parameter. A parameter the invocation leaves out, or sets + * to `null`, gets its default. + * + * @throws {A2uiValidationError} If an argument has no parameter or doesn't match it, or a + * required parameter has no argument. + */ +export function coerceArguments( + macro: MacroDefinition, + args: Readonly>, +): Record { + for (const name of Object.keys(args)) { + if (!Object.hasOwn(macro.parameters, name)) { + throw new A2uiValidationError(`Macro '${macro.name}' has no parameter '${name}'.`); + } + } + const coerced: Record = {}; + for (const [name, parameter] of Object.entries(macro.parameters)) { + const value = args[name]; + if (value === undefined || value === null) { + if (parameter.presence === 'required') { + throw new A2uiValidationError(`Macro '${macro.name}' requires parameter '${name}'.`); + } + coerced[name] = parameter.default; + continue; + } + coerced[name] = coerceValue(value, parameter, `'${name}' of macro '${macro.name}'`); + } + return coerced; +} + +function coerceValue(value: unknown, parameter: MacroParameter, where: string): unknown { + const mismatch = (expected: string) => + new A2uiValidationError( + `Parameter ${where} expects ${expected}, got ${JSON.stringify(value)}.`, + ); + switch (parameter.type) { + case 'string': + if (typeof value !== 'string') throw mismatch('a string'); + if (parameter.enum !== undefined && !parameter.enum.includes(value)) { + throw mismatch(`one of ${JSON.stringify(parameter.enum)}`); + } + return value; + case 'integer': + if (!Number.isInteger(value)) throw mismatch('an integer'); + return value; + case 'number': + if (typeof value !== 'number' || !Number.isFinite(value)) throw mismatch('a number'); + return value; + case 'boolean': + if (typeof value !== 'boolean') throw mismatch('a boolean'); + return value; + case 'component': + if (typeof value !== 'string') throw mismatch('a component ID'); + return value; + case 'componentList': + case 'childList': + if (!isStringArray(value)) throw mismatch('a list of component IDs'); + return value; + default: + return value; + } +} + +function isStringArray(value: unknown): value is string[] { + return Array.isArray(value) && value.every(item => typeof item === 'string'); +} diff --git a/typescript/agents/a2ui_agent/src/macros/expander.ts b/typescript/agents/a2ui_agent/src/macros/expander.ts index 3865b51fea..311b724ed6 100644 --- a/typescript/agents/a2ui_agent/src/macros/expander.ts +++ b/typescript/agents/a2ui_agent/src/macros/expander.ts @@ -15,17 +15,27 @@ */ import {ComponentPruningTransformer} from '../catalog-transformers/pruning.js'; +import {ComponentNode, isComponentNode} from '../component-tree/component-node.js'; +import {flattenComponentTree} from '../component-tree/flatten.js'; import { A2uiCatalogError, + A2uiRecursionError, + A2uiValidationError, + AgentToRendererMessage, Catalog, CatalogApi, normalizeVersionString, toCanonicalVersion, } from '../internal/web-core.js'; +import {coerceArguments} from './coercion.js'; import {macroComponentSchema, MacroDefinition, validateMacroName} from './define-macro.js'; import {MacroProtocolError} from './macro-protocol-error.js'; const DEFAULT_MACRO_CATALOG_ID = 'https://a2ui.org/catalogs/macros'; +const MAX_EXPANSION_DEPTH = 16; +const COMPONENT_BODY_KEYS = ['createSurface', 'updateComponents'] as const; + +type JsonObject = Record; /** Options for `MacroExpander`. */ export interface MacroExpanderOptions { @@ -58,7 +68,9 @@ export interface MacroExpanderOptions { * Lowers macros to the catalog components a renderer knows. * * The model sees the macros through the inference catalogs `transformCatalogs` derives - * from the transport catalogs. Macros target A2UI v1.0. + * from the transport catalogs. The expander lowers the model's messages back to the + * transport catalogs with `transformToTransport` before they reach the renderer. Macros + * target A2UI v1.0. */ export class MacroExpander { /** The catalog the macros belong to, as given in the options. */ @@ -203,6 +215,76 @@ export class MacroExpander { }); } + /** + * Lowers the macro invocations in `createSurface` and `updateComponents` messages to the + * catalog components they render. Other messages and components are kept as they are. + * + * An invocation's components replace it in the list, descendants first, as + * `flattenComponentTree` lists them: the root takes the invocation's ID, and the other + * IDs are namespaced under it. Macros used inside a rendered tree are lowered too. + * + * @returns New messages; `messages` is left unchanged. + * @throws {A2uiValidationError} If an invocation's arguments don't match its macro, or + * its `render` throws. + * @throws {A2uiRecursionError} If macros keep invoking macros beyond 16 levels. + */ + transformToTransport(messages: readonly AgentToRendererMessage[]): AgentToRendererMessage[] { + return messages.map(message => this.lowerMessage(message)); + } + + private lowerMessage(message: AgentToRendererMessage): AgentToRendererMessage { + if (this.macros.size === 0) { + return message; + } + const lowered: JsonObject = {...(message as unknown as JsonObject)}; + for (const bodyKey of COMPONENT_BODY_KEYS) { + const body = lowered[bodyKey]; + if (!isJsonObject(body) || !Array.isArray(body['components'])) { + continue; + } + lowered[bodyKey] = { + ...body, + components: this.expandComponents(structuredClone(body['components']), 0), + }; + } + return lowered as unknown as AgentToRendererMessage; + } + + private expandComponents(components: readonly unknown[], depth: number): unknown[] { + if (depth > MAX_EXPANSION_DEPTH) { + throw new A2uiRecursionError( + `Macro expansion exceeded maximum recursion depth of ${MAX_EXPANSION_DEPTH}.`, + ); + } + const expanded: unknown[] = []; + for (const component of components) { + const macro = isJsonObject(component) ? this.invokedMacro(component) : undefined; + if (macro === undefined) { + expanded.push(component); + } else { + expanded.push(...this.expandInvocation(component as JsonObject, macro, depth)); + } + } + return expanded; + } + + private invokedMacro(component: JsonObject): MacroDefinition | undefined { + const name = component['component']; + return typeof name === 'string' ? this.macros.get(name) : undefined; + } + + private expandInvocation( + component: JsonObject, + macro: MacroDefinition, + depth: number, + ): unknown[] { + const {component: _name, id, ...args} = component; + const instanceId = typeof id === 'string' ? id : undefined; + const tree = renderMacro(macro, coerceArguments(macro, args)); + const lowered = flattenComponentTree(tree, {rootId: instanceId}); + return this.expandComponents(lowered, depth + 1); + } + private pruner(): ComponentPruningTransformer | undefined { return this.passthroughComponents === undefined ? undefined @@ -231,3 +313,27 @@ function assertV10(version: string, message: (version: string) => string): void function isV10(version: string): boolean { return toCanonicalVersion(normalizeVersionString(version)) === '1.0'; } + +/** + * Calls a macro's `render`. A `render` that keeps calling itself overflows the stack, which + * is reported as the recursion it is. + */ +function renderMacro(macro: MacroDefinition, args: JsonObject): ComponentNode { + let tree: unknown; + try { + tree = macro.render(args as never); + } catch (e) { + if (e instanceof RangeError && /call stack/i.test(e.message)) { + throw new A2uiRecursionError(`Macro '${macro.name}' renders itself without end.`); + } + throw e; + } + if (!isComponentNode(tree)) { + throw new A2uiValidationError(`Macro '${macro.name}' must return a component node.`); + } + return tree; +} + +function isJsonObject(value: unknown): value is JsonObject { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts b/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts index 031e36b8b6..9b9caee01f 100644 --- a/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts +++ b/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts @@ -30,6 +30,7 @@ import {load} from 'js-yaml'; import { A2uiValidationError, + type AgentToRendererMessage, Catalog, type CatalogApi, type ComponentNode, @@ -360,3 +361,41 @@ export function runCatalogCase(testCase: LoadedCase): CatalogApi | undefined { throw new Error(`Unexpected catalog action ${testCase.action}`); } } + +/** Runs a transport case and returns the lowered messages. */ +export function runTransportCase(testCase: LoadedCase): AgentToRendererMessage[] { + const expander = buildExpander(testCase); + return expander.transformToTransport(transportMessages(testCase)); +} + +/** The messages a transport case sends: its `messages`, or messages built from `input`. */ +function transportMessages(testCase: LoadedCase): AgentToRendererMessage[] { + if (testCase['messages'] !== undefined) { + return structuredClone(testCase['messages']) as AgentToRendererMessage[]; + } + const version = envelopeVersion(testCase); + const surfaceId = (testCase['surface_id'] as string | undefined) ?? 'conformance'; + const input = testCase['input']; + const components = structuredClone(Array.isArray(input) ? input : [input]); + const messages: Record[] = []; + if (testCase['catalog_id'] !== undefined) { + messages.push({version, createSurface: {surfaceId, catalogId: testCase['catalog_id']}}); + } + messages.push({version, updateComponents: {surfaceId, components}}); + return messages as unknown as AgentToRendererMessage[]; +} + +/** The catalogs a renderer would check the lowered messages against. */ +export function validationCatalogs(testCase: LoadedCase): CatalogApi[] { + const version = envelopeVersion(testCase); + const ids = testCase['validation_catalogs'] as string[] | undefined; + if (ids !== undefined) { + return ids.map(id => resolveCatalog(id, version)); + } + const catalogs = [basicCatalog(version)]; + const catalogId = testCase['catalog_id'] as string | undefined; + if (catalogId !== undefined && catalogId !== catalogs[0].id) { + catalogs.push(resolveCatalog(catalogId, version)); + } + return catalogs; +} diff --git a/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts b/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts index 1783322e90..6ae4be1113 100644 --- a/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts +++ b/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts @@ -23,16 +23,27 @@ * v1.0, so cases that need v0.9 macros are skipped. */ +import {readFileSync} from 'fs'; + import {expect} from 'vitest'; import { A2uiCatalogError, A2uiRecursionError, A2uiValidationError, + type AgentToRendererMessage, type CatalogApi, + validatePayload, } from '../../src/index.js'; import {LoadedCase, loadCases} from './loader.js'; -import {macroVersion, runCatalogCase, SUITE} from './macro-suite.js'; +import { + GOLDEN_DIR, + macroVersion, + runCatalogCase, + runTransportCase, + SUITE, + validationCatalogs, +} from './macro-suite.js'; import { assertKnownKeys, CASE_METADATA_KEYS, @@ -91,6 +102,13 @@ const CATALOG_ACTIONS = new Set([ 'transform_to_inference_catalog', ]); +const VALIDATION_KEYS = new Set([ + 'allow_dangling_references', + 'allow_missing_root', + 'allow_orphan_components', + 'skip_renderer_validation', +]); + const ERROR_BY_CATEGORY: Record Error> = { CatalogError: A2uiCatalogError, RecursionError: A2uiRecursionError, @@ -105,17 +123,9 @@ const VERSION_REJECTION_CASES = new Set(['13_error_envelope_version_mismatch']); /** Cases whose behavior lands in a later commit of this change. */ const PENDING = new Set([ - '01_status_badge_expansion_v1_0', - '02_slot_boundary_preservation_v1_0', - '03_multi_slot_list_coercion_v1_0', '04_action_string_coercion_v1_0', '05_data_binding_coercion_v1_0', - '06_primitive_and_dict_arguments_v1_0', - '07_nested_macro_composition_v1_0', - '08_surface_lifecycle_envelopes_v1_0', '13_error_envelope_version_mismatch', - '14_multiple_macro_instances_namespacing_v1_0', - '15_mixed_primitive_and_macro_envelope_v1_0', '19_envelope_attributes_preservation', '20_mixable_catalogs_resolution', '21_v1_0_data_binding_and_function_call_coercion', @@ -158,13 +168,62 @@ function skipReason(testCase: LoadedCase): string | undefined { return undefined; } -function runCase(testCase: LoadedCase): CatalogApi | undefined { +function runCase(testCase: LoadedCase): CatalogApi | AgentToRendererMessage[] | undefined { if (CATALOG_ACTIONS.has(testCase.action)) { return runCatalogCase(testCase); } + if (testCase.action === 'build') { + const messages = runTransportCase(testCase); + if (messages.length > 0) { + validateLowered(testCase, messages); + } + return messages; + } throw new Error(`Unsupported action ${testCase.action}`); } +/** + * Checks lowered messages the way a renderer holding the case's catalogs would, unless the + * case says the renderer would reject them. `validatePayload` accepts a missing root, + * dangling references and unreachable components on a surface the payload doesn't + * create, which covers the relaxations the cases ask for. + */ +function validateLowered(testCase: LoadedCase, messages: unknown): void { + const validation = (testCase['validation'] ?? {}) as Record; + assertKnownKeys(validation, VALIDATION_KEYS, 'validation'); + if (!validation['skip_renderer_validation']) { + validatePayload(validationCatalogs(testCase), messages); + } +} + +function expectTransport( + messages: AgentToRendererMessage[], + expected: Record, +): void { + const records = messages as unknown as Array>>; + const components = records.flatMap( + message => + (message['updateComponents']?.['components'] ?? []) as Array>, + ); + if ('create_surface_catalog_id' in expected) { + const created = records.filter(message => 'createSurface' in message); + expect(created).toHaveLength(1); + expect(created[0]['createSurface']['catalogId']).toBe(expected['create_surface_catalog_id']); + } + if ('components' in expected) { + expect(components).toEqual(expected['components']); + } + if ('component_types' in expected) { + expect(components.map(component => component['component'])).toEqual( + expected['component_types'], + ); + } + if ('absent_property_on_all_components' in expected) { + const property = expected['absent_property_on_all_components'] as string; + expect(components.filter(component => property in component)).toEqual([]); + } +} + function expectError(testCase: LoadedCase): void { const expected = testCase['expect_error'] as Record; assertKnownKeys(expected, EXPECT_ERROR_KEYS, 'expect_error'); @@ -255,16 +314,26 @@ describeSuite( expectError(testCase); return; } + const result = runCase(testCase); + if (testCase['golden'] !== undefined) { + const golden = JSON.parse( + readFileSync(`${GOLDEN_DIR}/${testCase['golden'] as string}`, 'utf8'), + ) as unknown; + expect(result).toEqual(golden); + return; + } const expected = testCase['expect'] as Record | undefined; if (expected === undefined) { throw new Error(`Case ${testCase.name} has no expectation this harness checks`); } assertKnownKeys(expected, MACRO_EXPECT_KEYS, 'macros expect'); - const catalog = runCase(testCase); - if (catalog === undefined) { - throw new Error(`Case ${testCase.name} produced no catalog`); + if (Array.isArray(result)) { + expectTransport(result, expected); + } else if (result !== undefined) { + expectCatalog(result, expected); + } else { + throw new Error(`Case ${testCase.name} produced nothing to check`); } - expectCatalog(catalog, expected); }, {skipReason}, ); diff --git a/typescript/agents/a2ui_agent/tests/unit/macros/expander-transport.test.ts b/typescript/agents/a2ui_agent/tests/unit/macros/expander-transport.test.ts new file mode 100644 index 0000000000..5748922970 --- /dev/null +++ b/typescript/agents/a2ui_agent/tests/unit/macros/expander-transport.test.ts @@ -0,0 +1,176 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, expect, it} from 'vitest'; + +import { + A2uiRecursionError, + A2uiValidationError, + type AgentToRendererMessage, + type ComponentNode, + defineMacro, + type MacroDefinition, + MacroExpander, + param, +} from '../../../src/index.js'; + +const Label = defineMacro({ + name: 'Label', + parameters: { + text: param.string(), + tone: param.string({enum: ['info', 'warning'], default: 'info'}), + count: param.integer({required: false}), + targets: param.componentList({required: false}), + }, + render: ({text, tone, targets}) => ({ + component: 'Column', + children: [{component: 'Text', text, variant: tone}, ...(targets ?? [])], + }), +}); + +function update(components: unknown[]): AgentToRendererMessage[] { + return [ + {version: 'v1.0', updateComponents: {surfaceId: 's', components}}, + ] as unknown as AgentToRendererMessage[]; +} + +function lowerComponents( + macros: readonly MacroDefinition[], + components: unknown[], +): Array> { + const [message] = new MacroExpander(macros, {onError: 'raise'}).transformToTransport( + update(components), + ) as unknown as Array<{updateComponents: {components: Array>}}>; + return message.updateComponents.components; +} + +describe('MacroExpander.transformToTransport', () => { + it('replaces an invocation with its components, root last with the invocation ID', () => { + expect(lowerComponents([Label], [{component: 'Label', id: 'l', text: 'Hi'}])).toEqual([ + {component: 'Text', id: 'l__text_1', text: 'Hi', variant: 'info'}, + {component: 'Column', id: 'l', children: ['l__text_1']}, + ]); + }); + + it('lowers invocations in createSurface components and keeps other messages', () => { + const messages = [ + { + version: 'v1.0', + createSurface: { + surfaceId: 's', + catalogId: 'c', + components: [{component: 'Label', id: 'a', text: 'A'}], + }, + }, + {version: 'v1.0', deleteSurface: {surfaceId: 's'}}, + ] as unknown as AgentToRendererMessage[]; + + const lowered = new MacroExpander([Label]).transformToTransport(messages); + + expect(lowered).toEqual([ + { + version: 'v1.0', + createSurface: { + surfaceId: 's', + catalogId: 'c', + components: [ + {component: 'Text', id: 'a__text_1', text: 'A', variant: 'info'}, + {component: 'Column', id: 'a', children: ['a__text_1']}, + ], + }, + }, + {version: 'v1.0', deleteSurface: {surfaceId: 's'}}, + ]); + }); + + it('leaves the messages it was given unchanged', () => { + const messages = update([ + {component: 'Text', id: 't', text: 'plain'}, + {component: 'Label', id: 'l', text: 'Hi', targets: ['t']}, + ]); + const before = structuredClone(messages); + + new MacroExpander([Label]).transformToTransport(messages); + + expect(messages).toEqual(before); + }); + + it('lowers macros that a rendered tree uses, namespaced under their own ID', () => { + const Outer = defineMacro({ + name: 'Outer', + render: (): ComponentNode => ({component: 'Card', child: {component: 'Label', text: 'In'}}), + }); + + expect(lowerComponents([Label, Outer], [{component: 'Outer', id: 'o'}])).toEqual([ + {component: 'Text', id: 'o__label_1__text_1', text: 'In', variant: 'info'}, + {component: 'Column', id: 'o__label_1', children: ['o__label_1__text_1']}, + {component: 'Card', id: 'o', child: 'o__label_1'}, + ]); + }); + + it('throws A2uiRecursionError for a render that calls itself', () => { + const Loop: MacroDefinition = defineMacro({ + name: 'Loop', + render: () => ({component: 'Card', child: Loop.render({})}), + }); + + expect(() => lowerComponents([Loop], [{component: 'Loop', id: 'x'}])).toThrow( + A2uiRecursionError, + ); + }); + + it('throws A2uiRecursionError for a macro whose tree uses it again', () => { + const Loop = defineMacro({ + name: 'Loop', + render: (): ComponentNode => ({component: 'Card', child: {component: 'Loop'}}), + }); + + expect(() => lowerComponents([Loop], [{component: 'Loop', id: 'x'}])).toThrow( + A2uiRecursionError, + ); + }); + + it('throws when render returns something other than a component node', () => { + const Broken = defineMacro({ + name: 'Broken', + render: () => 'Text' as unknown as ComponentNode, + }); + + expect(() => lowerComponents([Broken], [{component: 'Broken', id: 'x'}])).toThrow( + A2uiValidationError, + ); + }); + + it('passes the default for an argument set to null', () => { + expect( + lowerComponents([Label], [{component: 'Label', id: 'l', text: 'Hi', tone: null}])[0], + ).toEqual({component: 'Text', id: 'l__text_1', text: 'Hi', variant: 'info'}); + }); + + it.each([ + ['an argument without a parameter', {text: 'Hi', weight: 2}], + ['a missing required argument', {}], + ['a value outside the enum', {text: 'Hi', tone: 'loud'}], + ['a binding for a string', {text: {'@path': '/t'}}], + ['a boolean for an integer', {text: 'Hi', count: true}], + ['a fraction for an integer', {text: 'Hi', count: 1.5}], + ['a template map for a component list', {text: 'Hi', targets: {path: '/p', componentId: 't'}}], + ])('rejects %s', (_case, args) => { + expect(() => lowerComponents([Label], [{component: 'Label', id: 'l', ...args}])).toThrow( + A2uiValidationError, + ); + }); +}); From 2e217e4dd512ec4ae29085564938c5c2c2e64389 Mon Sep 17 00:00:00 2001 From: Manfred Steyer Date: Wed, 25 Nov 2026 00:49:17 +0100 Subject: [PATCH 4/9] feat(ts_agent): coerce v1.0 common types in macro arguments Accept the forms a model writes for the v1.0 common types: - `action` takes an event name, an event body with `userMessage` and `context`, `{event: name, ...}`, a bare `{'@call': ...}` or a full `Action`, and hands `render` a full `Action`. - `dynamicString`, `dynamicNumber`, `dynamicBoolean` and `dynamicStringList` take a literal of their type, an `{'@path': ...}` binding or an `{'@call': ...}` function call. - `dynamicValue` takes any value; objects without `@path` or `@call` stay literal objects. - `childList` also takes a `{path, componentId}` template. - `checkRuleList` and `accessibility` are checked for their shape. Cases `04` and `05` (v1.0), `21`, `22`, `25`, `26` and `32` of the macro suite now pass. --- .../agents/a2ui_agent/src/macros/coercion.ts | 115 +++++++++++++++- .../conformance/macros-conformance.test.ts | 7 - .../tests/unit/macros/coercion.test.ts | 128 ++++++++++++++++++ 3 files changed, 239 insertions(+), 11 deletions(-) create mode 100644 typescript/agents/a2ui_agent/tests/unit/macros/coercion.test.ts diff --git a/typescript/agents/a2ui_agent/src/macros/coercion.ts b/typescript/agents/a2ui_agent/src/macros/coercion.ts index 61b07340a7..28ee4d51e1 100644 --- a/typescript/agents/a2ui_agent/src/macros/coercion.ts +++ b/typescript/agents/a2ui_agent/src/macros/coercion.ts @@ -18,11 +18,14 @@ import {A2uiValidationError} from '../internal/web-core.js'; import {MacroDefinition} from './define-macro.js'; import {MacroParameter} from './parameters.js'; +type JsonObject = Record; + /** * Turns the arguments of an invocation into the arguments `render` receives. * - * Every argument must match its parameter. A parameter the invocation leaves out, or sets - * to `null`, gets its default. + * Every argument must match its parameter, in one of the forms `param` lists for it, and + * the shorthands for an action become a full `Action`. A parameter the invocation leaves + * out, or sets to `null`, gets its default. * * @throws {A2uiValidationError} If an argument has no parameter or doesn't match it, or a * required parameter has no argument. @@ -76,14 +79,118 @@ function coerceValue(value: unknown, parameter: MacroParameter, where: string): if (typeof value !== 'string') throw mismatch('a component ID'); return value; case 'componentList': - case 'childList': if (!isStringArray(value)) throw mismatch('a list of component IDs'); return value; - default: + case 'childList': + if (!isStringArray(value) && !isDynamicChildList(value)) { + throw mismatch('a list of component IDs or a {path, componentId} template'); + } + return value; + case 'action': { + const action = toAction(value); + if (action === undefined) throw mismatch('an action'); + return action; + } + case 'dynamicString': + if (typeof value !== 'string' && !isBindingOrCall(value)) throw mismatch('a dynamic string'); + return value; + case 'dynamicNumber': + if (typeof value !== 'number' && !isBindingOrCall(value)) throw mismatch('a dynamic number'); + return value; + case 'dynamicBoolean': + if (typeof value !== 'boolean' && !isBindingOrCall(value)) { + throw mismatch('a dynamic boolean'); + } + return value; + case 'dynamicStringList': + if (!isStringArray(value) && !isBindingOrCall(value)) { + throw mismatch('a dynamic string list'); + } + return value; + case 'dynamicValue': + // Bindings, calls and literals all pass as written. A `{path}` or `{call}` object + // stays a literal object, since v1.0 binds only with `@path` and calls with `@call`. + return value; + case 'checkRuleList': + if (!Array.isArray(value) || !value.every(isCheckRule)) { + throw mismatch('a list of check rules'); + } + return value; + case 'accessibility': + if (!isJsonObject(value) || !Object.keys(value).every(key => ACCESSIBILITY_KEYS.has(key))) { + throw mismatch('accessibility attributes'); + } return value; } } +const ACCESSIBILITY_KEYS: ReadonlySet = new Set(['label', 'description', 'live', 'hidden']); + +/** + * Turns the forms a model writes for an action into an `Action`: an event name, an event + * body (`{name, context, userMessage}`), `{event: name, ...}` with the event body's other + * fields beside it, or a function call (`{'@call': ...}`). A full `Action` is kept. + * + * @returns The action, or `undefined` if `value` is none of these. + */ +function toAction(value: unknown): JsonObject | undefined { + if (typeof value === 'string') { + return {event: {name: value}}; + } + if (!isJsonObject(value)) { + return undefined; + } + const {event, ...rest} = value; + if (typeof event === 'string' && !('functionCall' in value)) { + return {event: {...rest, name: event}}; + } + if (event === undefined && !('functionCall' in value)) { + if (isFunctionCall(value)) { + return {functionCall: value}; + } + return typeof value['name'] === 'string' ? {event: value} : undefined; + } + const isEvent = isJsonObject(event) && typeof event['name'] === 'string'; + const isCall = event === undefined && isFunctionCall(value['functionCall']); + return (isEvent && !('functionCall' in value)) || isCall ? value : undefined; +} + +function isCheckRule(value: unknown): boolean { + return ( + isJsonObject(value) && + isBindingOrCall(value['condition']) && + (value['message'] === undefined || typeof value['message'] === 'string') + ); +} + +function isDynamicChildList(value: unknown): boolean { + return ( + isJsonObject(value) && + Object.keys(value).length === 2 && + typeof value['path'] === 'string' && + typeof value['componentId'] === 'string' + ); +} + +/** Whether `value` is a data binding (`{'@path': ...}`) or a function call. */ +function isBindingOrCall(value: unknown): boolean { + return isFunctionCall(value) || isDataBinding(value); +} + +function isDataBinding(value: unknown): boolean { + return ( + isJsonObject(value) && Object.keys(value).length === 1 && typeof value['@path'] === 'string' + ); +} + +function isFunctionCall(value: unknown): value is JsonObject { + return isJsonObject(value) && typeof value['@call'] === 'string'; +} + function isStringArray(value: unknown): value is string[] { return Array.isArray(value) && value.every(item => typeof item === 'string'); } + +function isJsonObject(value: unknown): value is JsonObject { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts b/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts index 6ae4be1113..89ef3309ea 100644 --- a/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts +++ b/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts @@ -123,17 +123,10 @@ const VERSION_REJECTION_CASES = new Set(['13_error_envelope_version_mismatch']); /** Cases whose behavior lands in a later commit of this change. */ const PENDING = new Set([ - '04_action_string_coercion_v1_0', - '05_data_binding_coercion_v1_0', '13_error_envelope_version_mismatch', '19_envelope_attributes_preservation', '20_mixable_catalogs_resolution', - '21_v1_0_data_binding_and_function_call_coercion', - '22_v1_0_action_user_message_coercion', - '25_v1_0_literal_object_preservation', - '26_v1_0_dynamic_child_list_and_checks', '30_root_envelope_deep_merge_and_declared_override', - '32_v1_0_action_function_call_shorthand', '33_runtime_failure_and_undeclared_property_fallback', '33b_error_on_error_raise_surfaces_validation_error', '34_v1_0_multi_catalog_foo_bar_baz_and_defaultless_surface', diff --git a/typescript/agents/a2ui_agent/tests/unit/macros/coercion.test.ts b/typescript/agents/a2ui_agent/tests/unit/macros/coercion.test.ts new file mode 100644 index 0000000000..30e60d9acb --- /dev/null +++ b/typescript/agents/a2ui_agent/tests/unit/macros/coercion.test.ts @@ -0,0 +1,128 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, expect, it} from 'vitest'; + +import { + A2uiValidationError, + type AgentToRendererMessage, + defineMacro, + type MacroParameter, + MacroExpander, + param, +} from '../../../src/index.js'; + +/** The argument `render` receives for `value`, passed to a parameter of the given kind. */ +function coerce(parameter: MacroParameter, value: unknown): unknown { + let received: unknown; + const Probe = defineMacro({ + name: 'Probe', + parameters: {value: parameter}, + render: ({value: coerced}) => { + received = coerced; + return {component: 'Text'}; + }, + }); + const messages = [ + { + version: 'v1.0', + updateComponents: {surfaceId: 's', components: [{component: 'Probe', id: 'p', value}]}, + }, + ] as unknown as AgentToRendererMessage[]; + new MacroExpander([Probe], {onError: 'raise'}).transformToTransport(messages); + return received; +} + +describe('argument coercion', () => { + it.each([ + ['an event name', 'save', {event: {name: 'save'}}], + [ + 'an event name with the event fields beside it', + {event: 'save', userMessage: 'Saved', context: {id: {'@path': '/id'}}}, + {event: {name: 'save', userMessage: 'Saved', context: {id: {'@path': '/id'}}}}, + ], + ['an event body', {name: 'save', context: {a: 1}}, {event: {name: 'save', context: {a: 1}}}], + [ + 'a function call', + {'@call': 'openUrl', args: {url: 'u'}}, + {functionCall: {'@call': 'openUrl', args: {url: 'u'}}}, + ], + ['a full event action', {event: {name: 'save'}}, {event: {name: 'save'}}], + [ + 'a full function call action', + {functionCall: {'@call': 'openUrl'}}, + {functionCall: {'@call': 'openUrl'}}, + ], + ])('turns %s into an action', (_case, value, expected) => { + expect(coerce(param.action(), value)).toEqual(expected); + }); + + it.each([ + ['a number', 1], + ['an object without a name', {context: {}}], + ['an event and a function call', {event: {name: 'a'}, functionCall: {'@call': 'b'}}], + ['an event name and a function call', {event: 'a', functionCall: {'@call': 'b'}}], + ])('rejects %s as an action', (_case, value) => { + expect(() => coerce(param.action(), value)).toThrow(A2uiValidationError); + }); + + it.each([ + [param.dynamicString(), 'text'], + [param.dynamicString(), {'@path': '/name'}], + [param.dynamicString(), {'@call': 'formatString', args: {value: 'x'}}], + [param.dynamicNumber(), 3], + [param.dynamicBoolean(), false], + [param.dynamicStringList(), ['a', 'b']], + [param.dynamicStringList(), {'@path': '/tags'}], + ])('passes a %o argument %j as written', (parameter, value) => { + expect(coerce(parameter, value)).toEqual(value); + }); + + it.each([ + [param.dynamicString(), {path: '/name'}], + [param.dynamicString(), {'@path': '/name', extra: 1}], + [param.dynamicString(), 3], + [param.dynamicNumber(), '3'], + [param.dynamicBoolean(), 'true'], + [param.dynamicStringList(), [1]], + ])('rejects %o argument %j', (parameter, value) => { + expect(() => coerce(parameter, value)).toThrow(A2uiValidationError); + }); + + it('keeps objects that are no binding or call as literal dynamic values', () => { + expect(coerce(param.dynamicValue(), {path: '/usr/bin'})).toEqual({path: '/usr/bin'}); + expect(coerce(param.dynamicValue(), {call: 'x', ext: '1'})).toEqual({call: 'x', ext: '1'}); + }); + + it('accepts a static list or a template for a child list', () => { + expect(coerce(param.childList(), ['a', 'b'])).toEqual(['a', 'b']); + expect(coerce(param.childList(), {path: '/items', componentId: 'row'})).toEqual({ + path: '/items', + componentId: 'row', + }); + expect(() => coerce(param.childList(), {path: '/items', template: 'row'})).toThrow( + A2uiValidationError, + ); + }); + + it('checks check rules and accessibility attributes', () => { + const rule = {condition: {'@call': 'required', args: {value: {'@path': '/v'}}}, message: 'm'}; + expect(coerce(param.checkRuleList(), [rule])).toEqual([rule]); + expect(() => coerce(param.checkRuleList(), [{condition: true}])).toThrow(A2uiValidationError); + expect(coerce(param.accessibility(), {label: 'Save'})).toEqual({label: 'Save'}); + expect(() => coerce(param.accessibility(), {role: 'button'})).toThrow(A2uiValidationError); + }); +}); From 475e5237eab69f49d40d42667635e58b8b0fca20 Mon Sep 17 00:00:00 2001 From: Manfred Steyer Date: Wed, 25 Nov 2026 00:52:37 +0100 Subject: [PATCH 5/9] feat(ts_agent): handle envelope fields and errors when lowering macros A macro invocation can carry the v1.0 component envelope fields. They are not passed to `render`: `@accessibility` and `@metadata` (including `extensions`) are merged with the root's own, and `@checks` are appended to the root's checks. `@catalogId` is never copied. The bare names of payloads written before the `@` prefix are read too, unless the macro declares a parameter of that name, which then is an ordinary argument. Add `onError`: by default an invocation that fails is logged and kept unexpanded, so its valid siblings still lower; `onError: 'raise'` throws `A2uiValidationError` for agents that retry with the error. Protocol errors throw either way: a message with a version other than v1.0, or a macro that renders a component named `Surface`. Cases `19`, `30`, `33`, `33b` and `40i` of the macro suite now pass, and so do `13` and `40c`, which check that v0.8 and v0.9 envelopes are rejected. --- .../agents/a2ui_agent/src/macros/expander.ts | 67 +++++- .../src/macros/invocation-envelope.ts | 126 ++++++++++ .../tests/conformance/macro-suite.ts | 226 ++++++++++++++++++ .../conformance/macros-conformance.test.ts | 18 +- .../unit/macros/expander-transport.test.ts | 54 ++++- .../unit/macros/invocation-envelope.test.ts | 118 +++++++++ 6 files changed, 590 insertions(+), 19 deletions(-) create mode 100644 typescript/agents/a2ui_agent/src/macros/invocation-envelope.ts create mode 100644 typescript/agents/a2ui_agent/tests/unit/macros/invocation-envelope.test.ts diff --git a/typescript/agents/a2ui_agent/src/macros/expander.ts b/typescript/agents/a2ui_agent/src/macros/expander.ts index 311b724ed6..d8a51bd44e 100644 --- a/typescript/agents/a2ui_agent/src/macros/expander.ts +++ b/typescript/agents/a2ui_agent/src/macros/expander.ts @@ -28,7 +28,13 @@ import { toCanonicalVersion, } from '../internal/web-core.js'; import {coerceArguments} from './coercion.js'; -import {macroComponentSchema, MacroDefinition, validateMacroName} from './define-macro.js'; +import { + isReservedComponentName, + macroComponentSchema, + MacroDefinition, + validateMacroName, +} from './define-macro.js'; +import {invocationArguments, mergeEnvelopeFields} from './invocation-envelope.js'; import {MacroProtocolError} from './macro-protocol-error.js'; const DEFAULT_MACRO_CATALOG_ID = 'https://a2ui.org/catalogs/macros'; @@ -221,11 +227,16 @@ export class MacroExpander { * * An invocation's components replace it in the list, descendants first, as * `flattenComponentTree` lists them: the root takes the invocation's ID, and the other - * IDs are namespaced under it. Macros used inside a rendered tree are lowered too. + * IDs are namespaced under it. The invocation's `@accessibility`, `@metadata` and + * `@checks` are merged onto the root. Macros used inside a rendered tree are lowered too. + * + * An invocation that fails, for example on an argument that doesn't match its parameter, + * is kept unexpanded and logged, or throws under `onError: 'raise'`. * * @returns New messages; `messages` is left unchanged. - * @throws {A2uiValidationError} If an invocation's arguments don't match its macro, or - * its `render` throws. + * @throws {A2uiValidationError} If a message has a protocol version other than v1.0, a + * macro renders a component named `Surface`, or, under `onError: 'raise'`, an + * invocation fails. * @throws {A2uiRecursionError} If macros keep invoking macros beyond 16 levels. */ transformToTransport(messages: readonly AgentToRendererMessage[]): AgentToRendererMessage[] { @@ -233,6 +244,13 @@ export class MacroExpander { } private lowerMessage(message: AgentToRendererMessage): AgentToRendererMessage { + const version = (message as unknown as JsonObject)['version']; + if (typeof version === 'string') { + assertV10( + version, + normalized => `Cannot lower v${normalized} message envelope with a v1.0 MacroExpander.`, + ); + } if (this.macros.size === 0) { return message; } @@ -274,15 +292,44 @@ export class MacroExpander { } private expandInvocation( - component: JsonObject, + invocation: JsonObject, macro: MacroDefinition, depth: number, ): unknown[] { - const {component: _name, id, ...args} = component; - const instanceId = typeof id === 'string' ? id : undefined; - const tree = renderMacro(macro, coerceArguments(macro, args)); - const lowered = flattenComponentTree(tree, {rootId: instanceId}); - return this.expandComponents(lowered, depth + 1); + const instanceId = typeof invocation['id'] === 'string' ? invocation['id'] : undefined; + try { + const declared = new Set(Object.keys(macro.parameters)); + const args = structuredClone(invocationArguments(invocation, declared)); + const tree = renderMacro(macro, coerceArguments(macro, args)); + const lowered = flattenComponentTree(tree, {rootId: instanceId}); + for (const component of lowered) { + if (isReservedComponentName(component.component)) { + throw new MacroProtocolError( + `Macro '${macro.name}' emitted reserved component name 'Surface'.`, + ); + } + } + mergeEnvelopeFields(invocation, declared, lowered, instanceId); + return this.expandComponents(lowered, depth + 1); + } catch (e) { + if ( + e instanceof A2uiRecursionError || + e instanceof MacroProtocolError || + e instanceof A2uiCatalogError + ) { + throw e; + } + if (this.onError === 'raise') { + if (e instanceof A2uiValidationError) { + throw e; + } + throw new A2uiValidationError( + `Failed to expand macro '${macro.name}' (id=${JSON.stringify(instanceId)}): ${String(e)}`, + ); + } + console.error(`Failed to expand macro '${macro.name}':`, e); + return [invocation]; + } } private pruner(): ComponentPruningTransformer | undefined { diff --git a/typescript/agents/a2ui_agent/src/macros/invocation-envelope.ts b/typescript/agents/a2ui_agent/src/macros/invocation-envelope.ts new file mode 100644 index 0000000000..de6beba396 --- /dev/null +++ b/typescript/agents/a2ui_agent/src/macros/invocation-envelope.ts @@ -0,0 +1,126 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The component envelope of a macro invocation. + * + * An invocation can carry the envelope fields every v1.0 component has: `@catalogId`, + * `@accessibility`, `@metadata` and `@checks`. They are not arguments of the macro. + * `@catalogId` selects the macro's catalog; the others are merged onto the root of the + * lowered tree. For payloads written before the `@` prefix, the bare names are read too, + * unless the macro declares a parameter of that name, which then is an ordinary argument. + */ + +import { + AT_ENVELOPE_MIXIN_KEYS, + ENVELOPE_MIXIN_NAMES, + envelopeReadKey, +} from '../inference-formats/express/schema-helper.js'; + +type JsonObject = Record; + +/** The arguments of an invocation: its properties other than `component`, `id` and the envelope. */ +export function invocationArguments( + invocation: JsonObject, + declared: ReadonlySet, +): JsonObject { + const nested = invocation['parameters']; + if (!declared.has('parameters') && isJsonObject(nested)) { + // The arguments are nested under `parameters`; a declared envelope name beside them + // is an argument too. + const args = {...nested}; + for (const name of ENVELOPE_MIXIN_NAMES) { + if (declared.has(name) && invocation[name] != null && !(name in args)) { + args[name] = invocation[name]; + } + } + return args; + } + const args: JsonObject = {}; + for (const [key, value] of Object.entries(invocation)) { + const excluded = + key === 'component' || + key === 'id' || + (key === 'parameters' && !declared.has(key)) || + isEnvelopeKey(key, declared); + if (!excluded) { + args[key] = value; + } + } + return args; +} + +/** + * Merges the invocation's envelope fields onto the root of its lowered components: + * `@accessibility` and `@metadata` (with its `extensions`) are merged with the root's own, + * and `@checks` are appended to the root's checks. + * + * @param lowered The lowered components; the root is the one with the invocation's ID, or + * the last one. It is changed in place. + */ +export function mergeEnvelopeFields( + invocation: JsonObject, + declared: ReadonlySet, + lowered: JsonObject[], + instanceId: string | undefined, +): void { + const root = lowered.findLast(component => component['id'] === instanceId) ?? lowered.at(-1); + if (root === undefined) { + return; + } + const read = (name: string): unknown => { + const key = envelopeReadKey(invocation, name, true, declared); + return key === undefined ? undefined : structuredClone(invocation[key]); + }; + + const accessibility = read('accessibility'); + if (accessibility != null) { + const own = root['@accessibility']; + root['@accessibility'] = + isJsonObject(own) && isJsonObject(accessibility) ? {...own, ...accessibility} : accessibility; + } + + const checks = read('checks'); + if (checks != null) { + const own = root['@checks']; + root['@checks'] = Array.isArray(own) && Array.isArray(checks) ? [...own, ...checks] : checks; + } + + const metadata = read('metadata'); + if (metadata != null) { + const own = root['@metadata']; + if (isJsonObject(own) && isJsonObject(metadata)) { + const merged = {...own, ...metadata}; + if (isJsonObject(own['extensions']) && isJsonObject(metadata['extensions'])) { + merged['extensions'] = {...own['extensions'], ...metadata['extensions']}; + } + root['@metadata'] = merged; + } else { + root['@metadata'] = metadata; + } + } +} + +function isEnvelopeKey(key: string, declared: ReadonlySet): boolean { + if (AT_ENVELOPE_MIXIN_KEYS.has(key)) { + return true; + } + return (ENVELOPE_MIXIN_NAMES as readonly string[]).includes(key) && !declared.has(key); +} + +function isJsonObject(value: unknown): value is JsonObject { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts b/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts index 9b9caee01f..39d7965b02 100644 --- a/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts +++ b/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts @@ -48,6 +48,13 @@ export const GOLDEN_DIR = conformancePath('agent/macros/golden'); const V1_0_BASIC_CID = 'https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json'; const V0_9_BASIC_CID = 'https://a2ui.org/specification/v0_9/standard_catalog.json'; +const FOO_CID = 'https://example.com/catalogs/foo/v1/catalog.json'; +const BAR_CID = 'https://example.com/catalogs/bar/v1/catalog.json'; +const BRAND_CID = 'https://example.com/brand.json'; +const BRAND_SURFACE_CID = 'https://example.com/brand_surface.json'; +const CAT_A_CID = 'https://example.com/catalog_a.json'; +const CAT_B_CID = 'https://example.com/catalog_b.json'; +const BAZ_MACROS_CID = 'https://example.com/catalogs/baz_macros.json'; const RAW_SUITE = load(readFileSync(conformancePath(SUITE), 'utf8')) as { custom_catalogs?: Record>; @@ -281,6 +288,217 @@ export const SUITE_MACROS_V1_0: readonly MacroDefinition[] = [ PositiveCountCard, ]; +// The catalog-scoped reference macros (`get_scoped_suite_macros` in Python), by the +// `macro_catalog_id` of the cases that use them. + +const BarBadge = builderNode('BarBadge'); +const BarButton = builderNode('BarButton'); +const BrandBox = builderNode('BrandBox'); +const Chart = builderNode('Chart'); +const ChartCard = builderNode('ChartCard'); +const FooHeader = builderNode('FooHeader'); +const FooPanel = builderNode('FooPanel'); + +const BrandText = defineMacro({ + name: 'Text', + description: 'Custom brand Text macro wrapping a basic Text inside a Card.', + parameters: {text: param.string(), variant: param.string({default: 'body'})}, + render: ({text, variant}) => Card({child: Text({text: `[Brand] ${text}`, variant})}), +}); + +const UnannotatedBrandCard = defineMacro({ + name: 'UnannotatedBrandCard', + description: 'Brand card emitting unannotated Card, BrandBox, and Text nodes.', + parameters: {title: param.string()}, + render: ({title}) => Card({child: BrandBox({child: Text({text: title, variant: 'body'})})}), +}); + +const BrandBadge = defineMacro({ + name: 'BrandBadge', + description: 'Brand badge emitting basic Card and Text with explicit catalogId.', + parameters: {label: param.string()}, + render: ({label}) => + Card({ + '@catalogId': V1_0_BASIC_CID, + child: Text({'@catalogId': V1_0_BASIC_CID, text: `[Badge] ${label}`, variant: 'body'}), + }), +}); + +const InnerBadgeScoped = defineMacro({ + name: 'InnerBadgeScoped', + description: 'Scoped inner badge emitting BrandBox and unannotated basic Text.', + parameters: {label: param.string()}, + render: ({label}) => + BrandBox({ + '@catalogId': BRAND_CID, + child: Text({text: `Scoped Badge: ${label}`, variant: 'caption'}), + }), +}); + +const OuterPanelScoped = defineMacro({ + name: 'OuterPanelScoped', + description: 'Scoped outer panel emitting unannotated Text alongside deferred InnerBadgeScoped.', + parameters: {title: param.string()}, + render: ({title}) => + Card({ + child: Column({ + children: [ + Text({text: title, variant: 'body'}), + {component: 'InnerBadgeScoped', label: title, '@catalogId': BRAND_CID}, + ], + }), + }), +}); + +const BrandChart = defineMacro({ + name: 'Chart', + description: 'Brand Chart macro emitting ChartCard wrapping an unannotated Chart primitive.', + parameters: {series: param.string()}, + render: ({series}) => ChartCard({child: Chart({series: `[Brand] ${series}`})}), +}); + +const BrandSurfaceText = defineMacro({ + name: 'Text', + description: + 'Brand surface Text macro emitting cross-catalog basic Card and Text around BrandBox.', + parameters: {text: param.string(), variant: param.string({default: 'body'})}, + render: ({text, variant}) => + Card({ + '@catalogId': V1_0_BASIC_CID, + child: BrandBox({ + '@catalogId': BRAND_SURFACE_CID, + child: Text({'@catalogId': V1_0_BASIC_CID, text: `[Brand] ${text}`, variant}), + }), + }), +}); + +const BrandSurfaceBadge = defineMacro({ + name: 'BrandBadge', + description: 'Brand surface badge emitting cross-catalog basic Card and Text around BrandBox.', + parameters: {label: param.string()}, + render: ({label}) => + Card({ + '@catalogId': V1_0_BASIC_CID, + child: BrandBox({ + '@catalogId': BRAND_SURFACE_CID, + child: Text({'@catalogId': V1_0_BASIC_CID, text: `[Badge] ${label}`, variant: 'body'}), + }), + }), +}); + +const BazMacro = defineMacro({ + name: 'BazMacro', + description: + 'Composite macro combining FooCatalog and BarCatalog primitives with explicit catalogIds.', + parameters: { + headline: param.dynamicString(), + badge_tag: param.string(), + cta_label: param.string(), + on_cta: param.action(), + }, + render: ({headline, badge_tag, cta_label, on_cta}) => + FooPanel({ + '@catalogId': FOO_CID, + children: [ + FooHeader({'@catalogId': FOO_CID, title: headline}), + BarBadge({'@catalogId': BAR_CID, tag: badge_tag}), + BarButton({'@catalogId': BAR_CID, label: cta_label, action: on_cta}), + ], + }), +}); + +const ProductCard = defineMacro({ + name: 'ProductCard', + description: 'Macro sharing its name with ProductCard primitive in catalog_a.json.', + parameters: {name: param.string()}, + render: ({name}) => Card({child: Text({text: `Product: ${name}`})}), +}); + +const BrandBoxMacro = defineMacro({ + name: 'BrandBox', + description: 'Macro wrapping a same-named BrandBox primitive from catalog_a.json.', + parameters: {title: param.string()}, + render: ({title}) => + Card({child: BrandBox({'@catalogId': CAT_A_CID, child: Text({text: title})})}), +}); + +const InnerBadgeInherited = defineMacro({ + name: 'InnerBadgeInherited', + description: + 'Deferred inner macro inheriting enclosing catalogId when surface catalog is registered.', + parameters: {label: param.string()}, + render: ({label}) => + BrandBox({ + '@catalogId': CAT_A_CID, + child: Text({text: `Inherited Badge: ${label}`, variant: 'caption'}), + }), +}); + +const OuterPanelInherited = defineMacro({ + name: 'OuterPanelInherited', + description: 'Outer macro emitting unannotated deferred InnerBadgeInherited node.', + parameters: {title: param.string()}, + render: ({title}) => + Card({ + child: Column({ + children: [ + Text({text: title, variant: 'body'}), + {component: 'InnerBadgeInherited', label: title}, + ], + }), + }), +}); + +const DeferredCycle = defineMacro({ + name: 'DeferredCycle', + description: 'Deferred self-recursive macro node.', + parameters: {label: param.string()}, + render: ({label}) => Card({child: {component: 'DeferredCycle', label}}), +}); + +const CycleA = defineMacro({ + name: 'CycleA', + description: 'Mutually recursive deferred macro A referencing CycleB.', + parameters: {label: param.string()}, + render: ({label}) => Card({child: {component: 'CycleB', label}}), +}); + +const CycleB = defineMacro({ + name: 'CycleB', + description: 'Mutually recursive deferred macro B referencing CycleA.', + parameters: {label: param.string()}, + render: ({label}) => Card({child: {component: 'CycleA', label}}), +}); + +const EmitsSurface = defineMacro({ + name: 'EmitsSurface', + description: 'Macro illegally emitting reserved Surface component in v1.0.', + render: () => ({component: 'Surface'}), +}); + +export const SCOPED_SUITE_MACROS: Readonly> = { + [BRAND_CID]: [ + BrandText, + UnannotatedBrandCard, + BrandBadge, + InnerBadgeScoped, + OuterPanelScoped, + BrandChart, + ], + [BRAND_SURFACE_CID]: [BrandSurfaceText, BrandSurfaceBadge], + [BAZ_MACROS_CID]: [BazMacro], + [CAT_B_CID]: [ + ProductCard, + BrandBoxMacro, + InnerBadgeInherited, + OuterPanelInherited, + DeferredCycle, + CycleA, + CycleB, + EmitsSurface, + ], +}; + // Catalog resolution and case execution. /** The protocol version of a case's envelope: `1.0`, `v0.9` or `v0.8`. */ @@ -321,6 +539,14 @@ function selectMacros(testCase: LoadedCase): readonly MacroDefinition[] { if (colliding !== undefined) { return [defineMacro({name: colliding, render: () => Card({child: Text({text: 'colliding'})})})]; } + const macroCatalogId = testCase['macro_catalog_id'] as string | undefined; + if (macroCatalogId !== undefined) { + const scoped = SCOPED_SUITE_MACROS[macroCatalogId]; + if (scoped === undefined) { + throw new Error(`No scoped macros registered for macro_catalog_id ${macroCatalogId}`); + } + return scoped; + } return SUITE_MACROS_V1_0; } diff --git a/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts b/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts index 89ef3309ea..6937bbc9b4 100644 --- a/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts +++ b/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts @@ -25,7 +25,7 @@ import {readFileSync} from 'fs'; -import {expect} from 'vitest'; +import {afterEach, beforeEach, expect, vi} from 'vitest'; import { A2uiCatalogError, @@ -123,12 +123,7 @@ const VERSION_REJECTION_CASES = new Set(['13_error_envelope_version_mismatch']); /** Cases whose behavior lands in a later commit of this change. */ const PENDING = new Set([ - '13_error_envelope_version_mismatch', - '19_envelope_attributes_preservation', '20_mixable_catalogs_resolution', - '30_root_envelope_deep_merge_and_declared_override', - '33_runtime_failure_and_undeclared_property_fallback', - '33b_error_on_error_raise_surfaces_validation_error', '34_v1_0_multi_catalog_foo_bar_baz_and_defaultless_surface', '35_v1_0_auto_stamping_from_base_catalogs_on_defaultless_surface', '35b_error_ambiguous_primitive_on_defaultless_surface', @@ -143,8 +138,6 @@ const PENDING = new Set([ '39a_error_deferred_self_recursion_untracked', '39b_error_mutual_recursion_defaultless_surface', '39c_error_mutual_recursion_foreign_surface', - '40c_error_lower_v0_9_envelope_with_v1_0_macros', - '40i_error_v1_0_macro_emitting_reserved_surface_component', ]); function skipReason(testCase: LoadedCase): string | undefined { @@ -298,6 +291,15 @@ function expectCatalog(catalog: CatalogApi, expected: Record): } } +// Invocations that fail under `onError: 'passthrough'` are logged; the cases check the +// lowered messages instead. +beforeEach(() => { + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); +afterEach(() => { + vi.restoreAllMocks(); +}); + describeSuite( `Conformance: ${SUITE}`, loadCases([conformancePath(SUITE)]), diff --git a/typescript/agents/a2ui_agent/tests/unit/macros/expander-transport.test.ts b/typescript/agents/a2ui_agent/tests/unit/macros/expander-transport.test.ts index 5748922970..c34bf3206b 100644 --- a/typescript/agents/a2ui_agent/tests/unit/macros/expander-transport.test.ts +++ b/typescript/agents/a2ui_agent/tests/unit/macros/expander-transport.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {describe, expect, it} from 'vitest'; +import {afterEach, describe, expect, it, vi} from 'vitest'; import { A2uiRecursionError, @@ -58,6 +58,10 @@ function lowerComponents( } describe('MacroExpander.transformToTransport', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + it('replaces an invocation with its components, root last with the invocation ID', () => { expect(lowerComponents([Label], [{component: 'Label', id: 'l', text: 'Hi'}])).toEqual([ {component: 'Text', id: 'l__text_1', text: 'Hi', variant: 'info'}, @@ -173,4 +177,52 @@ describe('MacroExpander.transformToTransport', () => { A2uiValidationError, ); }); + + it('rejects messages of another protocol version, with or without macros', () => { + const v09 = [ + {version: 'v0.9', updateComponents: {surfaceId: 's', components: []}}, + ] as unknown as AgentToRendererMessage[]; + + expect(() => new MacroExpander([Label]).transformToTransport(v09)).toThrow(A2uiValidationError); + expect(() => new MacroExpander([]).transformToTransport(v09)).toThrow(A2uiValidationError); + }); + + it('throws for a macro that renders a Surface whatever onError says', () => { + const Bad = defineMacro({name: 'Bad', render: () => ({component: 'ï¼³urface'})}); + + expect(() => + new MacroExpander([Bad]).transformToTransport(update([{component: 'Bad', id: 'b'}])), + ).toThrow(A2uiValidationError); + }); + + it('keeps a failed invocation unexpanded and logs it under onError passthrough', () => { + const logged = vi.spyOn(console, 'error').mockImplementation(() => {}); + + const [message] = new MacroExpander([Label]).transformToTransport( + update([ + {component: 'Label', id: 'bad', text: 'Hi', weight: 2}, + {component: 'Label', id: 'ok', text: 'Ok'}, + ]), + ) as unknown as Array<{updateComponents: {components: Array>}}>; + + expect(message.updateComponents.components.map(component => component['id'])).toEqual([ + 'bad', + 'ok__text_1', + 'ok', + ]); + expect(logged).toHaveBeenCalledTimes(1); + }); + + it('wraps an error from render in A2uiValidationError under onError raise', () => { + const Throws = defineMacro({ + name: 'Throws', + render: (): ComponentNode => { + throw new Error('boom'); + }, + }); + + expect(() => lowerComponents([Throws], [{component: 'Throws', id: 't'}])).toThrow( + /Failed to expand macro 'Throws' \(id="t"\): Error: boom/, + ); + }); }); diff --git a/typescript/agents/a2ui_agent/tests/unit/macros/invocation-envelope.test.ts b/typescript/agents/a2ui_agent/tests/unit/macros/invocation-envelope.test.ts new file mode 100644 index 0000000000..e35b64bc8f --- /dev/null +++ b/typescript/agents/a2ui_agent/tests/unit/macros/invocation-envelope.test.ts @@ -0,0 +1,118 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, expect, it} from 'vitest'; + +import { + type AgentToRendererMessage, + type ComponentNode, + defineMacro, + type MacroDefinition, + MacroExpander, + param, +} from '../../../src/index.js'; + +const Panel = defineMacro({ + name: 'Panel', + parameters: {title: param.string()}, + render: ({title}): ComponentNode => ({ + component: 'Card', + '@accessibility': {description: 'Panel'}, + '@checks': [{condition: {'@path': '/ok'}}], + '@metadata': {extensions: {source: 'Panel'}, other: 1}, + child: {component: 'Text', text: title}, + }), +}); + +function lowerRoot(macro: MacroDefinition, invocation: Record) { + const messages = [ + { + version: 'v1.0', + updateComponents: { + surfaceId: 's', + components: [{component: macro.name, id: 'p', ...invocation}], + }, + }, + ] as unknown as AgentToRendererMessage[]; + const [message] = new MacroExpander([macro], {onError: 'raise'}).transformToTransport( + messages, + ) as unknown as Array<{updateComponents: {components: Array>}}>; + return message.updateComponents.components.find(component => component['id'] === 'p'); +} + +describe('macro invocation envelope', () => { + it('merges the envelope fields onto the root and drops @catalogId', () => { + expect( + lowerRoot(Panel, { + title: 'T', + '@catalogId': 'https://example.com/macros.json', + '@accessibility': {label: 'Main panel'}, + '@checks': [{condition: {'@path': '/valid'}, message: 'Invalid'}], + '@metadata': {extensions: {trace: 't1'}}, + }), + ).toEqual({ + component: 'Card', + id: 'p', + '@accessibility': {description: 'Panel', label: 'Main panel'}, + '@checks': [ + {condition: {'@path': '/ok'}}, + {condition: {'@path': '/valid'}, message: 'Invalid'}, + ], + '@metadata': {extensions: {source: 'Panel', trace: 't1'}, other: 1}, + child: 'p__text_1', + }); + }); + + it('reads the bare envelope names of payloads written before the @ prefix', () => { + expect( + lowerRoot(Panel, {title: 'T', accessibility: {label: 'Legacy'}, catalogId: 'x'}), + ).toEqual(expect.objectContaining({'@accessibility': {description: 'Panel', label: 'Legacy'}})); + }); + + it('passes a bare envelope name the macro declares as an argument', () => { + const Labeled = defineMacro({ + name: 'Labeled', + parameters: {accessibility: param.accessibility({required: false})}, + render: ({accessibility}): ComponentNode => ({ + component: 'Text', + text: String(accessibility?.label ?? 'none'), + }), + }); + + expect(lowerRoot(Labeled, {accessibility: {label: 'Arg'}})).toEqual({ + component: 'Text', + id: 'p', + text: 'Arg', + }); + expect(lowerRoot(Labeled, {'@accessibility': {label: 'Envelope'}})).toEqual({ + component: 'Text', + id: 'p', + text: 'none', + '@accessibility': {label: 'Envelope'}, + }); + }); + + it('reads arguments nested under parameters', () => { + expect( + lowerRoot(Panel, {parameters: {title: 'Nested'}, '@accessibility': {label: 'L'}}), + ).toEqual( + expect.objectContaining({ + child: 'p__text_1', + '@accessibility': {description: 'Panel', label: 'L'}, + }), + ); + }); +}); From 6764fa9dea3cbd319932ad023827f11d0de12b9e Mon Sep 17 00:00:00 2001 From: Manfred Steyer Date: Wed, 25 Nov 2026 00:56:28 +0100 Subject: [PATCH 6/9] feat(ts_agent): resolve macros across mixable v1.0 catalogs On a v1.0 surface that mixes catalogs, decide per component whether it invokes a macro, as the Python SDK does: its catalog is its `@catalogId`, the catalog of the macro whose tree it is in, or the surface's default, which the expander learns from `createSurface`. A scoped expander (`catalogId`) expands only components of its catalog; an unscoped one leaves alone a component whose catalog defines a component of that name, so a macro can wrap a catalog component of the same name. `"@catalogId": null` counts as unset, and an empty or non-string `@catalogId` leaves the component unexpanded with a warning. After lowering, a component without `@catalogId` gets the one registered base catalog that defines it where the surface's default doesn't, and `A2uiCatalogError` is thrown when none or several do. A `createSurface` whose default is the standalone macro catalog gets the transport catalog instead, or no default when several are registered. Cases `20`, `34`, `35`, `35b`, `37d`, `37e`, `38a` and `38b` of the macro suite now pass, and so do `36`, `37c`, `39a`, `39b` and `39c`, whose behavior this resolution covers. --- .../agents/a2ui_agent/src/macros/expander.ts | 354 +++++++++++++++++- .../conformance/macros-conformance.test.ts | 18 +- .../unit/macros/catalog-resolution.test.ts | 181 +++++++++ 3 files changed, 521 insertions(+), 32 deletions(-) create mode 100644 typescript/agents/a2ui_agent/tests/unit/macros/catalog-resolution.test.ts diff --git a/typescript/agents/a2ui_agent/src/macros/expander.ts b/typescript/agents/a2ui_agent/src/macros/expander.ts index d8a51bd44e..f07c666413 100644 --- a/typescript/agents/a2ui_agent/src/macros/expander.ts +++ b/typescript/agents/a2ui_agent/src/macros/expander.ts @@ -17,6 +17,7 @@ import {ComponentPruningTransformer} from '../catalog-transformers/pruning.js'; import {ComponentNode, isComponentNode} from '../component-tree/component-node.js'; import {flattenComponentTree} from '../component-tree/flatten.js'; +import {CatalogSchemaHelper, getEnvelopeValue} from '../inference-formats/express/schema-helper.js'; import { A2uiCatalogError, A2uiRecursionError, @@ -43,6 +44,38 @@ const COMPONENT_BODY_KEYS = ['createSurface', 'updateComponents'] as const; type JsonObject = Record; +/** What the expander knows about the surface that a list of components belongs to. */ +interface SurfaceScope { + readonly surfaceId: string | undefined; + /** The surface's default catalog as the model sees it; may be the macro catalog. */ + readonly catalogId: string | undefined; + /** The surface's default catalog as the renderer sees it. */ + readonly transportCatalogId: string | undefined; + /** Whether the expander has seen the surface created. */ + readonly known: boolean; +} + +/** Where in the nesting of macro trees a list of components is. */ +interface ExpansionLevel { + readonly depth: number; + /** The macros whose trees enclose this level. */ + readonly activeMacros: ReadonlySet; + /** The catalog of the macro whose tree this level is. */ + readonly enclosingCatalogId: string | undefined; +} + +const TOP_LEVEL: ExpansionLevel = { + depth: 0, + activeMacros: new Set(), + enclosingCatalogId: undefined, +}; + +/** A component that invokes a macro, and the catalog it invokes it in. */ +interface ResolvedInvocation { + readonly macro: MacroDefinition; + readonly catalogId: string | undefined; +} + /** Options for `MacroExpander`. */ export interface MacroExpanderOptions { /** @@ -88,6 +121,9 @@ export class MacroExpander { private readonly catalogComponents = new Map>(); /** The IDs of the registered base catalogs, in the order they were registered. */ private readonly baseCatalogIds: string[] = []; + private readonly schemaHelpers = new Map(); + /** The default catalog of each surface seen created; `null` for none. */ + private readonly surfaceCatalogs = new Map(); /** * @throws {A2uiValidationError} If a macro name is not a valid v1.0 component name, or a @@ -230,6 +266,13 @@ export class MacroExpander { * IDs are namespaced under it. The invocation's `@accessibility`, `@metadata` and * `@checks` are merged onto the root. Macros used inside a rendered tree are lowered too. * + * On a surface that mixes catalogs, a component invokes a macro only in the macros' + * catalog: by its `@catalogId`, the catalog of the macro whose tree it is in, or the + * surface's default, which the expander learns from `createSurface`. A lowered + * component without `@catalogId` gets the one registered base catalog that defines it, + * where the surface's default catalog doesn't. A surface whose default is the standalone + * macro catalog gets the transport catalog as its default instead. + * * An invocation that fails, for example on an argument that doesn't match its parameter, * is kept unexpanded and logged, or throws under `onError: 'raise'`. * @@ -237,13 +280,19 @@ export class MacroExpander { * @throws {A2uiValidationError} If a message has a protocol version other than v1.0, a * macro renders a component named `Surface`, or, under `onError: 'raise'`, an * invocation fails. + * @throws {A2uiCatalogError} If no registered base catalog, or more than one, defines a + * lowered component that needs a catalog, or a surface's default is the standalone + * macro catalog without a base catalog to replace it. * @throws {A2uiRecursionError} If macros keep invoking macros beyond 16 levels. */ transformToTransport(messages: readonly AgentToRendererMessage[]): AgentToRendererMessage[] { - return messages.map(message => this.lowerMessage(message)); + return messages.map(message => this.lowerMessage(message, this.surfaceCatalogs)); } - private lowerMessage(message: AgentToRendererMessage): AgentToRendererMessage { + private lowerMessage( + message: AgentToRendererMessage, + surfaces: Map, + ): AgentToRendererMessage { const version = (message as unknown as JsonObject)['version']; if (typeof version === 'string') { assertV10( @@ -257,46 +306,215 @@ export class MacroExpander { const lowered: JsonObject = {...(message as unknown as JsonObject)}; for (const bodyKey of COMPONENT_BODY_KEYS) { const body = lowered[bodyKey]; - if (!isJsonObject(body) || !Array.isArray(body['components'])) { + if (!isJsonObject(body)) { continue; } - lowered[bodyKey] = { - ...body, - components: this.expandComponents(structuredClone(body['components']), 0), - }; + const loweredBody = {...body}; + const surfaceId = typeof body['surfaceId'] === 'string' ? body['surfaceId'] : undefined; + if (bodyKey === 'createSurface' && surfaceId !== undefined) { + this.trackCreatedSurface(loweredBody, surfaceId, surfaces); + } + const components = body['components']; + if (Array.isArray(components) && components.length > 0) { + loweredBody['components'] = this.expandComponents( + structuredClone(components), + TOP_LEVEL, + this.surfaceScope(surfaceId, surfaces), + ); + } + lowered[bodyKey] = loweredBody; } return lowered as unknown as AgentToRendererMessage; } - private expandComponents(components: readonly unknown[], depth: number): unknown[] { - if (depth > MAX_EXPANSION_DEPTH) { + /** + * Records the default catalog of a created surface. A default that names the standalone + * macro catalog is replaced by the transport catalog the renderer knows. + */ + private trackCreatedSurface( + body: JsonObject, + surfaceId: string, + surfaces: Map, + ): void { + const declared = nonEmptyString(body['catalogId']); + const [inferenceCatalogId, transportCatalogId] = this.surfaceCatalogPair(declared, true); + if (transportCatalogId !== declared) { + if (transportCatalogId === undefined) { + delete body['catalogId']; + } else { + body['catalogId'] = transportCatalogId; + } + } + surfaces.delete(surfaceId); + surfaces.set(surfaceId, inferenceCatalogId ?? null); + } + + private surfaceScope( + surfaceId: string | undefined, + surfaces: ReadonlyMap, + ): SurfaceScope { + if (surfaceId === undefined || !surfaces.has(surfaceId)) { + return {surfaceId, catalogId: undefined, transportCatalogId: undefined, known: false}; + } + const [catalogId, transportCatalogId] = this.surfaceCatalogPair( + surfaces.get(surfaceId) ?? undefined, + false, + ); + return {surfaceId, catalogId, transportCatalogId, known: true}; + } + + /** + * The default catalog of a surface as the model sees it and as the renderer sees it. + * They differ when the model's default is the standalone macro catalog, which the + * renderer doesn't know: the renderer then gets the only registered base catalog, or no + * default when several are registered. + * + * @throws {A2uiCatalogError} If a created surface's default is the standalone macro + * catalog and no base catalog is registered. + */ + private surfaceCatalogPair( + catalogId: string | undefined, + isCreated: boolean, + ): [string | undefined, string | undefined] { + const isMacroCatalog = + catalogId === this.macroCatalogId && !this.baseCatalogIds.includes(catalogId); + if (!isMacroCatalog) { + return [catalogId, catalogId]; + } + if (this.baseCatalogIds.length === 0 && isCreated) { + throw new A2uiCatalogError( + `Surface default catalogId '${catalogId}' is a standalone macro catalog, and no ` + + 'base catalogs are registered on MacroExpander to resolve a transport catalog.', + ); + } + return [catalogId, this.baseCatalogIds.length === 1 ? this.baseCatalogIds[0] : undefined]; + } + + private expandComponents( + components: readonly unknown[], + level: ExpansionLevel, + surface: SurfaceScope, + ): unknown[] { + if (level.depth > MAX_EXPANSION_DEPTH) { throw new A2uiRecursionError( `Macro expansion exceeded maximum recursion depth of ${MAX_EXPANSION_DEPTH}.`, ); } const expanded: unknown[] = []; for (const component of components) { - const macro = isJsonObject(component) ? this.invokedMacro(component) : undefined; - if (macro === undefined) { + const invocation = isJsonObject(component) + ? this.resolveInvocation(component, level, surface) + : undefined; + if (invocation === undefined) { expanded.push(component); } else { - expanded.push(...this.expandInvocation(component as JsonObject, macro, depth)); + expanded.push( + ...this.expandInvocation(component as JsonObject, invocation, level, surface), + ); } } return expanded; } - private invokedMacro(component: JsonObject): MacroDefinition | undefined { + /** + * Decides whether a component invokes one of the macros, and in which catalog. + * + * The component's catalog is its `@catalogId`; inside a macro's tree, the catalog of + * that macro when the component names no catalog component; otherwise the surface's + * default. A scoped expander expands only components of its own catalog. An unscoped + * one with base catalogs leaves alone a component whose catalog has a component of that + * name, unless `passthroughComponents` pruned it, and one whose catalog it doesn't know. + */ + private resolveInvocation( + component: JsonObject, + level: ExpansionLevel, + surface: SurfaceScope, + ): ResolvedInvocation | undefined { const name = component['component']; - return typeof name === 'string' ? this.macros.get(name) : undefined; + if (typeof name !== 'string') { + return undefined; + } + const macro = this.macros.get(name); + if (macro === undefined) { + return undefined; + } + const declared = new Set(Object.keys(macro.parameters)); + const ownCatalogId = getEnvelopeValue(component, 'catalogId', true, declared) ?? undefined; + let catalogId: string | undefined; + if (ownCatalogId !== undefined) { + if (typeof ownCatalogId !== 'string' || ownCatalogId === '') { + console.warn( + `Skipping macro '${name}' on component ${JSON.stringify(component['id'])}: ` + + `invalid catalogId ${JSON.stringify(ownCatalogId)}.`, + ); + return undefined; + } + catalogId = ownCatalogId; + } else if (this.inheritsEnclosingCatalog(name, level, surface)) { + catalogId = level.enclosingCatalogId; + } else { + catalogId = surface.catalogId; + } + + if (level.depth > 0 && ownCatalogId === undefined && this.isCatalogComponent(name)) { + return undefined; + } + if (level.activeMacros.has(name)) { + // Inside its own tree, a macro's name is the catalog component it wraps. + const wrapsCatalogComponent = + catalogId !== level.enclosingCatalogId || + (catalogId !== undefined && this.catalogHasComponent(catalogId, name)) || + (ownCatalogId === undefined && this.isCatalogComponent(name)); + if (wrapsCatalogComponent) { + return undefined; + } + } + if (this.catalogId !== undefined) { + return catalogId === this.catalogId ? {macro, catalogId} : undefined; + } + if (this.catalogComponents.size > 0 && catalogId !== undefined) { + if (!this.catalogComponents.has(catalogId) && catalogId !== this.macroCatalogId) { + return undefined; + } + const keptCatalogComponent = + this.catalogHasComponent(catalogId, name) && + (this.passthroughComponents === undefined || this.passthroughComponents.has(name)); + if (keptCatalogComponent) { + return undefined; + } + } + return {macro, catalogId}; + } + + /** Whether an unannotated component in a macro's tree belongs to that macro's catalog. */ + private inheritsEnclosingCatalog( + name: string, + level: ExpansionLevel, + surface: SurfaceScope, + ): boolean { + if (level.depth === 0 || level.enclosingCatalogId === undefined) { + return false; + } + const surfaceCatalogIsForeign = + surface.catalogId !== undefined && + surface.catalogId !== level.enclosingCatalogId && + surface.catalogId !== this.macroCatalogId && + !this.catalogComponents.has(surface.catalogId); + if (surfaceCatalogIsForeign || this.isCatalogComponent(name)) { + return false; + } + const anyCatalogComponents = [...this.catalogComponents.values()].some(names => names.size > 0); + return !(level.activeMacros.has(name) && !anyCatalogComponents); } private expandInvocation( invocation: JsonObject, - macro: MacroDefinition, - depth: number, + {macro, catalogId}: ResolvedInvocation, + level: ExpansionLevel, + surface: SurfaceScope, ): unknown[] { const instanceId = typeof invocation['id'] === 'string' ? invocation['id'] : undefined; + let expanded: unknown[]; try { const declared = new Set(Object.keys(macro.parameters)); const args = structuredClone(invocationArguments(invocation, declared)); @@ -310,7 +528,15 @@ export class MacroExpander { } } mergeEnvelopeFields(invocation, declared, lowered, instanceId); - return this.expandComponents(lowered, depth + 1); + expanded = this.expandComponents( + lowered, + { + depth: level.depth + 1, + activeMacros: new Set([...level.activeMacros, macro.name]), + enclosingCatalogId: catalogId ?? this.catalogId, + }, + surface, + ); } catch (e) { if ( e instanceof A2uiRecursionError || @@ -330,6 +556,90 @@ export class MacroExpander { console.error(`Failed to expand macro '${macro.name}':`, e); return [invocation]; } + if (level.depth === 0) { + this.stampOwningCatalogs(expanded, surface); + } + return expanded; + } + + /** + * Stamps `@catalogId` on lowered components that name no catalog where the renderer + * would otherwise look in the wrong one: on a surface without a default catalog, or + * with a default that doesn't define the component. The stamp is the one registered + * base catalog that defines the component. + * + * @throws {A2uiCatalogError} If no registered base catalog, or more than one, defines + * such a component. + */ + private stampOwningCatalogs(components: readonly unknown[], surface: SurfaceScope): void { + if (!surface.known || this.baseCatalogIds.length === 0) { + return; + } + const surfaceDefault = surface.transportCatalogId; + for (const component of components) { + if (!isJsonObject(component) || typeof component['component'] !== 'string') { + continue; + } + const name = component['component']; + const owners = this.baseCatalogIds.filter(id => this.catalogHasComponent(id, name)); + if (this.onError === 'passthrough' && this.macros.has(name) && owners.length === 0) { + // An invocation that failed and was kept as it is. + continue; + } + if ( + getEnvelopeValue(component, 'catalogId', true, this.customCatalogIdOwners(name, owners)) != + null + ) { + continue; + } + const needsStamp = + surfaceDefault === undefined || + (this.baseCatalogIds.includes(surfaceDefault) && + !this.catalogHasComponent(surfaceDefault, name)); + if (!needsStamp) { + continue; + } + const where = + surfaceDefault === undefined + ? `defaultless surface '${surface.surfaceId}'` + : `surface '${surface.surfaceId}' (default '${surfaceDefault}')`; + if (owners.length === 1) { + component['@catalogId'] = owners[0]; + } else if (owners.length > 1) { + throw new A2uiCatalogError( + `Expanded component '${name}' has no catalogId on ${where} and is defined in ` + + `multiple base catalogs: ${owners.join(', ')}. Set @catalogId explicitly in the ` + + 'macro.', + ); + } else { + throw new A2uiCatalogError( + `Expanded component '${name}' has no catalogId on ${where} and is not found in ` + + `any registered base catalog: ${this.baseCatalogIds.join(', ')}.`, + ); + } + } + } + + /** + * `catalogId` when every catalog that defines the component declares a `catalogId` + * property of its own, which a bare `catalogId` then is, rather than the envelope field. + */ + private customCatalogIdOwners(name: string, owners: readonly string[]): ReadonlySet { + const custom = + owners.length > 0 && + owners.every(id => + this.schemaHelpers.get(id)?.getCustomEnvelopeProperties(name).has('catalogId'), + ); + return custom ? new Set(['catalogId']) : new Set(); + } + + private catalogHasComponent(catalogId: string, name: string): boolean { + return this.catalogComponents.get(catalogId)?.has(name) ?? false; + } + + /** Whether a registered catalog defines a component of this name. */ + private isCatalogComponent(name: string): boolean { + return [...this.catalogComponents.values()].some(names => names.has(name)); } private pruner(): ComponentPruningTransformer | undefined { @@ -344,6 +654,12 @@ export class MacroExpander { return; } this.catalogComponents.set(catalog.id, new Set(catalog.components.keys())); + try { + this.schemaHelpers.set(catalog.id, new CatalogSchemaHelper(catalog, '1.0')); + } catch { + // Without a schema helper, the catalog counts as declaring no custom envelope + // properties. + } if (!this.baseCatalogIds.includes(catalog.id)) { this.baseCatalogIds.push(catalog.id); } @@ -381,6 +697,10 @@ function renderMacro(macro: MacroDefinition, args: JsonObject): ComponentNode { return tree; } +function nonEmptyString(value: unknown): string | undefined { + return typeof value === 'string' && value !== '' ? value : undefined; +} + function isJsonObject(value: unknown): value is JsonObject { return typeof value === 'object' && value !== null && !Array.isArray(value); } diff --git a/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts b/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts index 6937bbc9b4..95bfda1e41 100644 --- a/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts +++ b/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts @@ -123,21 +123,8 @@ const VERSION_REJECTION_CASES = new Set(['13_error_envelope_version_mismatch']); /** Cases whose behavior lands in a later commit of this change. */ const PENDING = new Set([ - '20_mixable_catalogs_resolution', - '34_v1_0_multi_catalog_foo_bar_baz_and_defaultless_surface', - '35_v1_0_auto_stamping_from_base_catalogs_on_defaultless_surface', - '35b_error_ambiguous_primitive_on_defaultless_surface', - '36_surface_lifecycle_delete_recreate_and_null_catalog_id', '37a_stateless_surface_catalogs_override_expands', '37b_stateless_surface_catalogs_override_skips', - '37c_scoped_expander_skips_untracked_and_invalid_catalog_id', - '37d_default_macro_catalog_id_expands_after_base_registration', - '37e_standalone_macro_catalog_surface_default', - '38a_custom_catalog_collision_and_same_name_wrapper', - '38b_scoped_nested_macro_and_non_basic_surface', - '39a_error_deferred_self_recursion_untracked', - '39b_error_mutual_recursion_defaultless_surface', - '39c_error_mutual_recursion_foreign_surface', ]); function skipReason(testCase: LoadedCase): string | undefined { @@ -291,10 +278,11 @@ function expectCatalog(catalog: CatalogApi, expected: Record): } } -// Invocations that fail under `onError: 'passthrough'` are logged; the cases check the -// lowered messages instead. +// The expander logs invocations it skips or that fail under `onError: 'passthrough'`; the +// cases check the lowered messages instead. beforeEach(() => { vi.spyOn(console, 'error').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { vi.restoreAllMocks(); diff --git a/typescript/agents/a2ui_agent/tests/unit/macros/catalog-resolution.test.ts b/typescript/agents/a2ui_agent/tests/unit/macros/catalog-resolution.test.ts new file mode 100644 index 0000000000..e4537b65dd --- /dev/null +++ b/typescript/agents/a2ui_agent/tests/unit/macros/catalog-resolution.test.ts @@ -0,0 +1,181 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {afterEach, describe, expect, it, vi} from 'vitest'; + +import { + A2uiCatalogError, + type AgentToRendererMessage, + Catalog, + type CatalogApi, + type ComponentNode, + defineMacro, + MacroExpander, +} from '../../../src/index.js'; +import {BASIC_CATALOG_IDS, loadBasicCatalog} from '../../helpers/basic-catalogs.js'; + +const MACROS_ID = 'https://a2ui.org/catalogs/macros'; +const WIDGETS_ID = 'https://example.com/widgets.json'; + +/** A v1.0 catalog with one `Widget` component, which may declare its own `catalogId`. */ +function widgetsCatalog(widgetProperties: Record = {}): CatalogApi { + return Catalog.fromJson({ + protocolVersion: '1.0', + catalogId: WIDGETS_ID, + components: { + Widget: { + type: 'object', + properties: {component: {const: 'Widget'}, ...widgetProperties}, + required: ['component'], + }, + }, + $defs: { + anyComponent: { + oneOf: [{$ref: '#/components/Widget'}], + discriminator: {propertyName: 'component'}, + }, + anyFunction: {not: {}}, + }, + }); +} + +const Hello = defineMacro({ + name: 'Hello', + render: (): ComponentNode => ({component: 'Text', text: 'Hello'}), +}); + +function lower( + expander: MacroExpander, + messages: unknown[], +): Array>> { + return expander.transformToTransport(messages as AgentToRendererMessage[]) as unknown as Array< + Record> + >; +} + +describe('MacroExpander catalog resolution', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('drops a macro-catalog surface default when several base catalogs are registered', () => { + const expander = new MacroExpander([Hello], { + baseCatalogs: [loadBasicCatalog('1.0'), widgetsCatalog()], + }); + + const [created, updated] = lower(expander, [ + {version: 'v1.0', createSurface: {surfaceId: 's', catalogId: MACROS_ID}}, + { + version: 'v1.0', + updateComponents: {surfaceId: 's', components: [{component: 'Hello', id: 'h'}]}, + }, + ]); + + expect(created['createSurface']).toEqual({surfaceId: 's'}); + expect(updated['updateComponents']['components']).toEqual([ + {component: 'Text', id: 'h', text: 'Hello', '@catalogId': BASIC_CATALOG_IDS['1.0']}, + ]); + }); + + it('rejects a macro-catalog surface default without a base catalog to replace it', () => { + expect(() => + lower(new MacroExpander([Hello]), [ + {version: 'v1.0', createSurface: {surfaceId: 's', catalogId: MACROS_ID}}, + ]), + ).toThrow(A2uiCatalogError); + }); + + it('expands a macro named like a base component that passthroughComponents prunes', () => { + const Text = defineMacro({ + name: 'Text', + render: (): ComponentNode => ({component: 'Card', child: 'other'}), + }); + const update = { + version: 'v1.0', + updateComponents: {surfaceId: 's', components: [{component: 'Text', id: 't'}]}, + }; + const created = { + version: 'v1.0', + createSurface: {surfaceId: 's', catalogId: BASIC_CATALOG_IDS['1.0']}, + }; + + const kept = lower(new MacroExpander([Text], {baseCatalogs: [loadBasicCatalog('1.0')]}), [ + created, + update, + ]); + const pruned = lower( + new MacroExpander([Text], { + baseCatalogs: [loadBasicCatalog('1.0')], + passthroughComponents: ['Card'], + }), + [created, update], + ); + + expect(kept[1]['updateComponents']['components']).toEqual([{component: 'Text', id: 't'}]); + expect(pruned[1]['updateComponents']['components']).toEqual([ + {component: 'Card', id: 't', child: 'other'}, + ]); + }); + + it('stamps a component whose bare catalogId is a property its catalog declares', () => { + const Wrapped = defineMacro({ + name: 'Wrapped', + render: (): ComponentNode => ({component: 'Widget', catalogId: 'sku-1'}), + }); + const messages = [ + {version: 'v1.0', createSurface: {surfaceId: 's'}}, + { + version: 'v1.0', + updateComponents: {surfaceId: 's', components: [{component: 'Wrapped', id: 'w'}]}, + }, + ]; + + const custom = lower( + new MacroExpander([Wrapped], {baseCatalogs: [widgetsCatalog({catalogId: {type: 'string'}})]}), + messages, + ); + const legacy = lower( + new MacroExpander([Wrapped], {baseCatalogs: [widgetsCatalog()]}), + messages, + ); + + expect(custom[1]['updateComponents']['components']).toEqual([ + {component: 'Widget', id: 'w', catalogId: 'sku-1', '@catalogId': WIDGETS_ID}, + ]); + expect(legacy[1]['updateComponents']['components']).toEqual([ + {component: 'Widget', id: 'w', catalogId: 'sku-1'}, + ]); + }); + + it('skips an invocation with an empty catalogId and warns', () => { + const warned = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + const [message] = lower(new MacroExpander([Hello]), [ + { + version: 'v1.0', + updateComponents: { + surfaceId: 's', + components: [{component: 'Hello', id: 'h', '@catalogId': ''}], + }, + }, + ]); + + expect(message['updateComponents']['components']).toEqual([ + {component: 'Hello', id: 'h', '@catalogId': ''}, + ]); + expect(warned).toHaveBeenCalledTimes(1); + }); +}); From 9484be88a36dfde1237e2c1a74fa387575d527cd Mon Sep 17 00:00:00 2001 From: Manfred Steyer Date: Wed, 25 Nov 2026 00:57:47 +0100 Subject: [PATCH 7/9] feat(ts_agent): track surfaces and accept per-call surface catalogs The expander now forgets a surface's default catalog on `deleteSurface`, and remembers at most 256 surfaces, dropping the oldest with a warning. Add a `surfaceCatalogs` option to `transformToTransport`. It gives the default catalog of each surface for that call, which then works on a copy and leaves the expander's own record of surfaces unchanged, so one expander can serve several sessions. Cases `37a` and `37b` of the macro suite now pass. With them, 42 of the 44 v1.0 cases pass; `40b` and `40d` need v0.9 macros. --- typescript/agents/a2ui_agent/src/index.ts | 6 +- .../agents/a2ui_agent/src/macros/expander.ts | 38 ++++++- .../tests/conformance/macro-suite.ts | 3 +- .../conformance/macros-conformance.test.ts | 14 +-- .../unit/macros/surface-tracking.test.ts | 104 ++++++++++++++++++ 5 files changed, 148 insertions(+), 17 deletions(-) create mode 100644 typescript/agents/a2ui_agent/tests/unit/macros/surface-tracking.test.ts diff --git a/typescript/agents/a2ui_agent/src/index.ts b/typescript/agents/a2ui_agent/src/index.ts index f1ca72be07..b38bb996d5 100644 --- a/typescript/agents/a2ui_agent/src/index.ts +++ b/typescript/agents/a2ui_agent/src/index.ts @@ -201,7 +201,11 @@ export {type FlattenComponentTreeOptions, flattenComponentTree} from './componen // Macros export {defineMacro, type MacroConfig, type MacroDefinition} from './macros/define-macro.js'; -export {MacroExpander, type MacroExpanderOptions} from './macros/expander.js'; +export { + MacroExpander, + type MacroExpanderOptions, + type TransformToTransportOptions, +} from './macros/expander.js'; export { type MacroArgs, type MacroInput, diff --git a/typescript/agents/a2ui_agent/src/macros/expander.ts b/typescript/agents/a2ui_agent/src/macros/expander.ts index f07c666413..e349cbe27c 100644 --- a/typescript/agents/a2ui_agent/src/macros/expander.ts +++ b/typescript/agents/a2ui_agent/src/macros/expander.ts @@ -40,6 +40,7 @@ import {MacroProtocolError} from './macro-protocol-error.js'; const DEFAULT_MACRO_CATALOG_ID = 'https://a2ui.org/catalogs/macros'; const MAX_EXPANSION_DEPTH = 16; +const MAX_TRACKED_SURFACES = 256; const COMPONENT_BODY_KEYS = ['createSurface', 'updateComponents'] as const; type JsonObject = Record; @@ -103,6 +104,16 @@ export interface MacroExpanderOptions { onError?: 'passthrough' | 'raise'; } +/** Options for `MacroExpander.transformToTransport`. */ +export interface TransformToTransportOptions { + /** + * The default catalog of each surface by ID, or `null` for a surface without one. When + * given, the call starts from this map and leaves the expander's own record of surfaces + * unchanged, so one expander can serve several sessions. + */ + surfaceCatalogs?: Readonly>; +} + /** * Lowers macros to the catalog components a renderer knows. * @@ -110,6 +121,10 @@ export interface MacroExpanderOptions { * from the transport catalogs. The expander lowers the model's messages back to the * transport catalogs with `transformToTransport` before they reach the renderer. Macros * target A2UI v1.0. + * + * The expander remembers the default catalog of the last 256 surfaces it sees created, + * until they are deleted. Use one expander per session, or pass `surfaceCatalogs` to + * `transformToTransport`. */ export class MacroExpander { /** The catalog the macros belong to, as given in the options. */ @@ -285,8 +300,15 @@ export class MacroExpander { * macro catalog without a base catalog to replace it. * @throws {A2uiRecursionError} If macros keep invoking macros beyond 16 levels. */ - transformToTransport(messages: readonly AgentToRendererMessage[]): AgentToRendererMessage[] { - return messages.map(message => this.lowerMessage(message, this.surfaceCatalogs)); + transformToTransport( + messages: readonly AgentToRendererMessage[], + options: TransformToTransportOptions = {}, + ): AgentToRendererMessage[] { + const surfaces = + options.surfaceCatalogs === undefined + ? this.surfaceCatalogs + : new Map(Object.entries(options.surfaceCatalogs)); + return messages.map(message => this.lowerMessage(message, surfaces)); } private lowerMessage( @@ -303,6 +325,10 @@ export class MacroExpander { if (this.macros.size === 0) { return message; } + const deleted = (message as unknown as JsonObject)['deleteSurface']; + if (isJsonObject(deleted) && typeof deleted['surfaceId'] === 'string') { + surfaces.delete(deleted['surfaceId']); + } const lowered: JsonObject = {...(message as unknown as JsonObject)}; for (const bodyKey of COMPONENT_BODY_KEYS) { const body = lowered[bodyKey]; @@ -347,6 +373,14 @@ export class MacroExpander { } surfaces.delete(surfaceId); surfaces.set(surfaceId, inferenceCatalogId ?? null); + if (surfaces.size > MAX_TRACKED_SURFACES) { + const [oldest] = surfaces.keys(); + surfaces.delete(oldest); + console.warn( + `Evicted oldest tracked surface '${oldest}' from MacroExpander ` + + `(limit=${MAX_TRACKED_SURFACES}).`, + ); + } } private surfaceScope( diff --git a/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts b/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts index 39d7965b02..26eff414ca 100644 --- a/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts +++ b/typescript/agents/a2ui_agent/tests/conformance/macro-suite.ts @@ -591,7 +591,8 @@ export function runCatalogCase(testCase: LoadedCase): CatalogApi | undefined { /** Runs a transport case and returns the lowered messages. */ export function runTransportCase(testCase: LoadedCase): AgentToRendererMessage[] { const expander = buildExpander(testCase); - return expander.transformToTransport(transportMessages(testCase)); + const surfaceCatalogs = testCase['surface_catalogs'] as Record | undefined; + return expander.transformToTransport(transportMessages(testCase), {surfaceCatalogs}); } /** The messages a transport case sends: its `messages`, or messages built from `input`. */ diff --git a/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts b/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts index 95bfda1e41..5173f26ad1 100644 --- a/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts +++ b/typescript/agents/a2ui_agent/tests/conformance/macros-conformance.test.ts @@ -121,24 +121,12 @@ const ERROR_BY_CATEGORY: Record Error> = { */ const VERSION_REJECTION_CASES = new Set(['13_error_envelope_version_mismatch']); -/** Cases whose behavior lands in a later commit of this change. */ -const PENDING = new Set([ - '37a_stateless_surface_catalogs_override_expands', - '37b_stateless_surface_catalogs_override_skips', -]); - function skipReason(testCase: LoadedCase): string | undefined { const needsV09Macros = !testCase['empty_macros'] && macroVersion(testCase) !== '1.0' && !VERSION_REJECTION_CASES.has(testCase.name); - if (needsV09Macros) { - return 'macros support v1.0 only'; - } - if (PENDING.has(testCase.name)) { - return 'not implemented yet'; - } - return undefined; + return needsV09Macros ? 'macros support v1.0 only' : undefined; } function runCase(testCase: LoadedCase): CatalogApi | AgentToRendererMessage[] | undefined { diff --git a/typescript/agents/a2ui_agent/tests/unit/macros/surface-tracking.test.ts b/typescript/agents/a2ui_agent/tests/unit/macros/surface-tracking.test.ts new file mode 100644 index 0000000000..48a078827c --- /dev/null +++ b/typescript/agents/a2ui_agent/tests/unit/macros/surface-tracking.test.ts @@ -0,0 +1,104 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {afterEach, describe, expect, it, vi} from 'vitest'; + +import { + type AgentToRendererMessage, + type ComponentNode, + defineMacro, + MacroExpander, +} from '../../../src/index.js'; +import {BASIC_CATALOG_IDS, loadBasicCatalog} from '../../helpers/basic-catalogs.js'; + +const BASIC = BASIC_CATALOG_IDS['1.0']; + +/** A macro named like the basic `Text`: it expands only where `Text` isn't the basic one. */ +const Text = defineMacro({ + name: 'Text', + render: (): ComponentNode => ({component: 'Card', child: 'content'}), +}); + +function expander(): MacroExpander { + return new MacroExpander([Text], {baseCatalogs: [loadBasicCatalog('1.0')]}); +} + +function created(surfaceId: string): unknown { + return {version: 'v1.0', createSurface: {surfaceId, catalogId: BASIC}}; +} + +function textUpdate(surfaceId: string): unknown { + return { + version: 'v1.0', + updateComponents: {surfaceId, components: [{component: 'Text', id: 't'}]}, + }; +} + +/** Whether `Text` is lowered there: only on a surface the expander doesn't know. */ +function lowersText( + target: MacroExpander, + surfaceId: string, + options?: Parameters[1], +): boolean { + const [message] = target.transformToTransport( + [textUpdate(surfaceId)] as AgentToRendererMessage[], + options, + ) as unknown as Array<{updateComponents: {components: Array<{component: string}>}}>; + return message.updateComponents.components[0].component === 'Card'; +} + +describe('MacroExpander surface tracking', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('forgets the default catalog of a deleted surface', () => { + const target = expander(); + target.transformToTransport([created('s')] as AgentToRendererMessage[]); + expect(lowersText(target, 's')).toBe(false); + + target.transformToTransport([ + {version: 'v1.0', deleteSurface: {surfaceId: 's'}}, + ] as unknown as AgentToRendererMessage[]); + + expect(lowersText(target, 's')).toBe(true); + }); + + it('uses surfaceCatalogs instead of its own record, and leaves the record unchanged', () => { + const target = expander(); + + expect(lowersText(target, 's', {surfaceCatalogs: {s: BASIC}})).toBe(false); + target.transformToTransport([created('other')] as AgentToRendererMessage[], { + surfaceCatalogs: {}, + }); + + expect(lowersText(target, 's')).toBe(true); + expect(lowersText(target, 'other')).toBe(true); + }); + + it('forgets the oldest surface beyond 256 and warns', () => { + const warned = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const target = expander(); + const surfaces = Array.from({length: 257}, (_, index) => created(`s${index}`)); + + target.transformToTransport(surfaces as AgentToRendererMessage[]); + + expect(warned).toHaveBeenCalledTimes(1); + expect(lowersText(target, 's0')).toBe(true); + expect(lowersText(target, 's1')).toBe(false); + expect(lowersText(target, 's256')).toBe(false); + }); +}); From 2e307d21fee786620f2e17c1f92e6bad1b6468df Mon Sep 17 00:00:00 2001 From: Manfred Steyer Date: Wed, 25 Nov 2026 01:00:21 +0100 Subject: [PATCH 8/9] docs(ts_agent): document macros and the component tree Add a "Macros" section to the README: defining a macro with `defineMacro` and `param`, how IDs are allocated, and how to put the macros into the catalog the model sees and lower its responses with `MacroExpander`. A test runs that flow through `A2uiGenerator`, from the prompt to the lowered messages. Add the changelog entry, and in `KNOWN_GAPS.md` record that the builder and macro suites now run, that macros support v1.0 only, that component trees carry no catalog defaults, and that the expander checks primitive arguments where Python doesn't. --- typescript/agents/a2ui_agent/CHANGELOG.md | 4 ++ typescript/agents/a2ui_agent/KNOWN_GAPS.md | 18 ++++- typescript/agents/a2ui_agent/README.md | 63 ++++++++++++++++ .../unit/macros/generator-integration.test.ts | 72 +++++++++++++++++++ 4 files changed, 155 insertions(+), 2 deletions(-) create mode 100644 typescript/agents/a2ui_agent/tests/unit/macros/generator-integration.test.ts diff --git a/typescript/agents/a2ui_agent/CHANGELOG.md b/typescript/agents/a2ui_agent/CHANGELOG.md index 9f17f6f99f..74f7e4aa7f 100644 --- a/typescript/agents/a2ui_agent/CHANGELOG.md +++ b/typescript/agents/a2ui_agent/CHANGELOG.md @@ -2,6 +2,10 @@ - **BREAKING CHANGE**: (v1_0) `validatePayload`, `RendererState.apply`, and inference format parsers check function calls nested in `callRendererFunction.callFunction.args` under the agent's caller boundary instead of the renderer's, rejecting `rendererOnly` functions while accepting `agentOnly` and `rendererOrAgent` functions. Recommended migration: set `allowedCallers` to `'rendererOrAgent'` or `'agentOnly'` on functions nested inside `callRendererFunction` arguments ([#3774](https://github.com/a2ui-project/a2ui/issues/3774), [#4336](https://github.com/a2ui-project/a2ui/pull/4336)). - **BREAKING CHANGE**: `resolveCatalogs` and `readRendererCapabilities` reject inline catalogs whose local `#...` `$ref` pointers do not resolve against the inline catalog document or the protocol version's `common_types.json`, throwing `A2uiCatalogError` naming the inline `catalogId` and `$ref` even when `acceptsInlineCatalogs` is `false`. `resolveCatalogs` also drops inline catalogs whose `catalogId` matches an already-active catalog and emits a `console.warn` diagnostic. Recommended migration: point each local `$ref` in an inline catalog to a definition declared in that inline catalog or in the target protocol version's `common_types.json` ([#3165](https://github.com/a2ui-project/a2ui/issues/3165), [#4367](https://github.com/a2ui-project/a2ui/pull/4367)). +- (v1_0) Add macros: components the model can use that the agent lowers to catalog components before the messages reach the renderer, as in the Python SDK ([#4413](https://github.com/a2ui-project/a2ui/pull/4413)). + - `defineMacro` and the `param` vocabulary define a macro. The arguments of its `render` are typed from its parameters. + - `MacroExpander` adds the macros to the inference catalogs (`transformCatalogs`, `transformToInferenceCatalog`, `toCatalog`) and lowers the model's messages to the transport catalogs (`transformToTransport`), including surfaces that mix v1.0 catalogs, the component envelope fields of an invocation and an `onError` policy. + - `flattenComponentTree` turns a tree of nested component objects into the flat component list of `updateComponents`, with IDs allocated and namespaced under the root. - `ExpressPromptGenerator` and `ExpressCompiler` now traverse `oneOf`, `anyOf`, `allOf`, and local `#/$defs/...` references when extracting structured map-key prompt instructions, enum constraints, and option-object array coercion rules ([#3400](https://github.com/a2ui-project/a2ui/issues/3400), [#4184](https://github.com/a2ui-project/a2ui/pull/4184)). - (v0_9_1) `DirectJsonPromptGenerator` gives the v0.9.1 agent-to-renderer schema the `$id` `https://a2ui.org/specification/v0_9_1/server_to_client.json`, which `specification/v0_9_1/json/server_to_client.json` declares. It gave it v0.9's `$id` ([#3974](https://github.com/a2ui-project/a2ui/issues/3974), [#3975](https://github.com/a2ui-project/a2ui/pull/3975)). diff --git a/typescript/agents/a2ui_agent/KNOWN_GAPS.md b/typescript/agents/a2ui_agent/KNOWN_GAPS.md index 2e45233ef0..06d98c6136 100644 --- a/typescript/agents/a2ui_agent/KNOWN_GAPS.md +++ b/typescript/agents/a2ui_agent/KNOWN_GAPS.md @@ -43,11 +43,25 @@ Most of these are deliberate scope boundaries rather than defects. However, a fe ### Some blueprint conformance suites are not run -- **What it is:** Merging `main` into `v1_0` reorganized `conformance/agent/`. The parser and inference format suites this harness runs moved unchanged to `agent/legacy/`, and the harness still reads `legacy/parser.yaml` and `legacy/inference_format.yaml` there, skipping the cases the newer suites replaced. The blueprint suites `agent/catalog_provider.yaml`, `agent/catalog_resolution.yaml`, `agent/catalog_transformer.yaml`, `agent/multi_catalog_formats.yaml`, `agent/request_processor.yaml`, `agent/skill.yaml`, every `agent/direct_json/*.yaml` file and every `agent/express/*.yaml` file run. The timing suites among them, `agent/direct_json/scaling.yaml` and `agent/express/scaling.yaml`, run with `yarn test:timing` rather than `yarn test`. `agent/builder/` and `agent/macros/` do not run. +- **What it is:** Merging `main` into `v1_0` reorganized `conformance/agent/`. The parser and inference format suites this harness runs moved unchanged to `agent/legacy/`, and the harness still reads `legacy/parser.yaml` and `legacy/inference_format.yaml` there, skipping the cases the newer suites replaced. The blueprint suites `agent/catalog_provider.yaml`, `agent/catalog_resolution.yaml`, `agent/catalog_transformer.yaml`, `agent/multi_catalog_formats.yaml`, `agent/request_processor.yaml`, `agent/skill.yaml`, every `agent/direct_json/*.yaml` file, every `agent/express/*.yaml` file, `agent/builder/builder.yaml` and `agent/macros/macros.yaml` run. The timing suites among them, `agent/direct_json/scaling.yaml` and `agent/express/scaling.yaml`, run with `yarn test:timing` rather than `yarn test`. - **Why it exists:** Those suites exercise blueprint APIs this package does not implement yet. - **What it risks:** Behaviour they pin can drift in this package without a failing test. - **Done looks like:** The harness runs every blueprint suite and stops reading `agent/legacy/`, which the conformance README keeps for the earlier agent interface. +### Macros support v1.0 only + +- **What it is:** `defineMacro`, `param` and `MacroExpander` target v1.0, and the expander rejects catalogs and messages of other versions. The cases of `conformance/agent/macros/macros.yaml` that need v0.9 macros are skipped: the v0.9 cases, and `40a`, `40b` and `40d`, which combine v0.9 macros with v1.0. Python's macros support v0.9 too. +- **Why it exists:** A scope decision for the first port, which follows the current protocol. +- **What it blocks:** Agents on v0.9 can't use macros. +- **Done looks like:** A v0.9 mode with `ComponentId` schemas, bare envelope keys and `path`/`call` bindings in argument coercion, and the skipped cases running. + +### Component trees carry no catalog defaults + +- **What it is:** `flattenComponentTree` and the trees macros render emit only the properties their author wrote. Python's typed builder also fills in catalog defaults, such as `Text.variant: "body"` and `Column.justify: "start"`. Of `conformance/agent/builder/builder.yaml`, only `01_primitive_components_v1_0` runs: the goldens of the other v1.0 cases hold those defaults, and the v0.9 cases are skipped. +- **Why it exists:** The plain-object tree has no knowledge of each component; a typed builder is out of scope for the first port. +- **What it risks:** A macro that leaves out a property with a default lowers to different messages than its Python twin. +- **Done looks like:** A typed builder on top of the tree, for example generated from the catalogs, and the skipped builder cases running. + ### `no-explicit-any` lint warnings - **What it is:** There are eslint warnings for `no-explicit-any` in `tests/conformance/direct-json-conformance.test.ts`. The package source has none. @@ -91,7 +105,7 @@ Most of these are deliberate scope boundaries rather than defects. However, a fe ### Behaviours TypeScript enforces that no conformance case pins -- **What it is:** TypeScript's Express throws in several places where no conformance case says what should happen: an inline component id that collides with a declared variable (`ExpressIdCollisionError`); decompiling messages for a catalog the decompiler was not given (`A2uiCatalogError`); and catalogs, or a requested version, from different release lines such as v0.9 and v1.0 (`A2uiCatalogError`). +- **What it is:** TypeScript's Express throws in several places where no conformance case says what should happen: an inline component id that collides with a declared variable (`ExpressIdCollisionError`); decompiling messages for a catalog the decompiler was not given (`A2uiCatalogError`); and catalogs, or a requested version, from different release lines such as v0.9 and v1.0 (`A2uiCatalogError`). `MacroExpander` checks that a primitive or enum argument matches its parameter's type and values, where Python passes it to the macro unchecked (`A2uiValidationError`). - **Why it exists:** Each was decided while making TypeScript follow the suite: throwing is preferred to silently producing wrong output. - **What it risks:** Python may choose differently, and nothing would catch the drift. - **Done looks like:** Conformance cases pin each behaviour, so both SDKs are held to it. diff --git a/typescript/agents/a2ui_agent/README.md b/typescript/agents/a2ui_agent/README.md index 4118cfb959..2fd48a8b45 100644 --- a/typescript/agents/a2ui_agent/README.md +++ b/typescript/agents/a2ui_agent/README.md @@ -207,6 +207,69 @@ Each instance keeps its pending calls in memory, so a response must reach the sa A call fails with `CANCELLED` when it is cancelled or the instance disposed, and with the renderer's error code when the renderer reports one. +## Macros + +A macro is a component the model can use that the agent lowers to catalog components before the messages reach the renderer, so the renderer needs only the catalogs it already has. Macros target v1.0. + +Define a macro with `defineMacro`. Its parameters come from `param`, which has the parameter types of the shared macro conformance suite, and `render` returns a tree of nested component objects: + +```ts +import {defineMacro, param} from '@a2ui/agent'; + +const FlightCard = defineMacro({ + name: 'FlightCard', + description: 'A card with one flight.', + parameters: { + from: param.string({description: 'Departure city'}), + to: param.string({description: 'Destination city'}), + status: param.string({enum: ['onTime', 'delayed'], default: 'onTime'}), + onBook: param.action({required: false}), + }, + render: ({from, to, status, onBook}) => ({ + component: 'Card', + child: { + component: 'Column', + children: [ + {component: 'Text', text: `${from} to ${to}`}, + {component: 'Text', text: status === 'delayed' ? 'Delayed' : 'On time', variant: 'caption'}, + ...(onBook + ? [{component: 'Button', child: {component: 'Text', text: 'Book'}, action: onBook}] + : []), + ], + }, + }), +}); +``` + +The arguments of `render` are typed from the parameters: `from` and `to` are strings, `status` is `'onTime' | 'delayed'`, and `onBook` is an `Action` or `undefined`. Before `render` runs, the expander checks each argument against its parameter and turns the shorthands a model writes into full values, such as an event name into `{event: {name}}`. + +The nested components need no IDs. When an invocation is lowered, the root of its tree takes the invocation's ID and the other components get IDs under it, such as `flight_1__text_1`, so a macro can be used more than once on a surface. A slot can also hold the ID of a component already on the surface. For trees built without macros, `flattenComponentTree` does this flattening on its own. + +Add the macros to the catalog the model sees, and lower each response before you send it: + +```ts +import {A2uiGenerator, CatalogConfig, MacroExpander} from '@a2ui/agent'; + +const expander = new MacroExpander([FlightCard], {onError: 'raise'}); +const generator = new A2uiGenerator([ + new CatalogConfig(expander.transformToInferenceCatalog(basicCatalog)), +]); + +const processor = generator.createProcessor(capabilities); +for (const part of processor.parseResponse(llmResponse)) { + if (part.type === 'a2ui') send(expander.transformToTransport(part.a2ui)); +} +``` + +`transformToInferenceCatalog` adds the macros to a copy of one catalog that keeps its ID, so it still matches the catalog the client supports. For a surface that mixes catalogs, use `transformCatalogs`, which returns the base catalogs followed by a standalone catalog of the macros. The expander then decides by `@catalogId` which components are macros, and stamps the owning `@catalogId` on lowered components where the surface needs it. `passthroughComponents` limits the catalog components the model sees next to the macros. + +A few things to keep in mind: + +1. With `onError: 'raise'`, an invocation that doesn't match its macro throws an `A2uiValidationError` that an agent can hand back to the model. By default the expander logs it and leaves the invocation unexpanded. +2. The response is checked against the catalog with the macros, so a `RendererState` holds the macro invocations, not their lowered components. +3. The expander remembers the default catalog of the surfaces it sees created. Use one expander per session, or pass `surfaceCatalogs` to `transformToTransport`. +4. A macro's `render` can call another macro's `render` to inline its tree, or use another macro by name in its tree, which the expander lowers too. + ## Development ```sh diff --git a/typescript/agents/a2ui_agent/tests/unit/macros/generator-integration.test.ts b/typescript/agents/a2ui_agent/tests/unit/macros/generator-integration.test.ts new file mode 100644 index 0000000000..4b60e714c6 --- /dev/null +++ b/typescript/agents/a2ui_agent/tests/unit/macros/generator-integration.test.ts @@ -0,0 +1,72 @@ +/* + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, expect, it} from 'vitest'; + +import { + A2uiGenerator, + CatalogConfig, + defineMacro, + MacroExpander, + param, + validatePayload, +} from '../../../src/index.js'; +import {loadBasicCatalog} from '../../helpers/basic-catalogs.js'; + +const Greeting = defineMacro({ + name: 'Greeting', + description: 'A card that greets someone.', + parameters: {name: param.string({description: 'Who to greet'})}, + render: ({name}) => ({ + component: 'Card', + child: {component: 'Text', text: `Hello, ${name}!`, variant: 'caption'}, + }), +}); + +describe('macros with A2uiGenerator', () => { + it('prompts for a macro, parses it, and lowers it to the base catalog', () => { + const basic = loadBasicCatalog('1.0'); + const expander = new MacroExpander([Greeting], {onError: 'raise'}); + const generator = new A2uiGenerator([ + new CatalogConfig(expander.transformToInferenceCatalog(basic)), + ]); + const processor = generator.createProcessor({supportedCatalogIds: [basic.id]}); + + expect(processor.promptSnippet).toContain('Greeting'); + + const parts = processor.parseResponse( + '\nsurface("main")\nroot = Greeting(name="Ada")\n', + ); + const messages = parts.flatMap(part => + part.type === 'a2ui' ? expander.transformToTransport(part.a2ui) : [], + ); + + expect(messages).toEqual([ + { + version: '1.0', + createSurface: { + surfaceId: 'main', + catalogId: basic.id, + components: [ + {component: 'Text', id: 'root__text_1', text: 'Hello, Ada!', variant: 'caption'}, + {component: 'Card', id: 'root', child: 'root__text_1'}, + ], + }, + }, + ]); + validatePayload([basic], messages); + }); +}); From 3f487a41a0075479bb2b9f1bea3e759541d6fbf6 Mon Sep 17 00:00:00 2001 From: Manfred Steyer Date: Mon, 30 Nov 2026 18:21:51 +0100 Subject: [PATCH 9/9] fix(ts_agent): tighten macro checks after review Address the review comments on the macro port: - `mergeEnvelopeFields` looks up the root by the invocation's ID only when the invocation has one. The lowered components always have IDs, so the old lookup found the right root too; the explicit check no longer depends on that, as in Python. - An `accessibility` argument is checked value by value: `label` and `description` as dynamic strings, `live` against its enum, `hidden` as a dynamic boolean. - `MacroExpander` rejects two macros with the same name instead of keeping the last one. - A stack overflow in `render` is recognized in SpiderMonkey too, which throws `InternalError` ("too much recursion") where V8 throws a `RangeError`. - `transformCatalogs` documents that the catalogs it registers stay registered for the expander's lifetime. --- typescript/agents/a2ui_agent/KNOWN_GAPS.md | 2 +- .../agents/a2ui_agent/src/macros/coercion.ts | 20 +++++++++++-- .../agents/a2ui_agent/src/macros/expander.ts | 30 ++++++++++++++++--- .../src/macros/invocation-envelope.ts | 9 ++++-- .../tests/unit/macros/coercion.test.ts | 20 +++++++++++++ .../unit/macros/expander-catalogs.test.ts | 6 ++++ .../unit/macros/expander-transport.test.ts | 15 ++++++++++ .../unit/macros/invocation-envelope.test.ts | 25 ++++++++++++++++ 8 files changed, 117 insertions(+), 10 deletions(-) diff --git a/typescript/agents/a2ui_agent/KNOWN_GAPS.md b/typescript/agents/a2ui_agent/KNOWN_GAPS.md index 06d98c6136..c95ffa6eea 100644 --- a/typescript/agents/a2ui_agent/KNOWN_GAPS.md +++ b/typescript/agents/a2ui_agent/KNOWN_GAPS.md @@ -105,7 +105,7 @@ Most of these are deliberate scope boundaries rather than defects. However, a fe ### Behaviours TypeScript enforces that no conformance case pins -- **What it is:** TypeScript's Express throws in several places where no conformance case says what should happen: an inline component id that collides with a declared variable (`ExpressIdCollisionError`); decompiling messages for a catalog the decompiler was not given (`A2uiCatalogError`); and catalogs, or a requested version, from different release lines such as v0.9 and v1.0 (`A2uiCatalogError`). `MacroExpander` checks that a primitive or enum argument matches its parameter's type and values, where Python passes it to the macro unchecked (`A2uiValidationError`). +- **What it is:** TypeScript's Express throws in several places where no conformance case says what should happen: an inline component id that collides with a declared variable (`ExpressIdCollisionError`); decompiling messages for a catalog the decompiler was not given (`A2uiCatalogError`); and catalogs, or a requested version, from different release lines such as v0.9 and v1.0 (`A2uiCatalogError`). `MacroExpander` checks that a primitive, enum or accessibility argument matches its parameter's type and values, where Python passes a primitive or enum to the macro unchecked, and it rejects two macros with the same name, where Python keeps the last one (both `A2uiValidationError`). - **Why it exists:** Each was decided while making TypeScript follow the suite: throwing is preferred to silently producing wrong output. - **What it risks:** Python may choose differently, and nothing would catch the drift. - **Done looks like:** Conformance cases pin each behaviour, so both SDKs are held to it. diff --git a/typescript/agents/a2ui_agent/src/macros/coercion.ts b/typescript/agents/a2ui_agent/src/macros/coercion.ts index 28ee4d51e1..68361544c8 100644 --- a/typescript/agents/a2ui_agent/src/macros/coercion.ts +++ b/typescript/agents/a2ui_agent/src/macros/coercion.ts @@ -117,14 +117,30 @@ function coerceValue(value: unknown, parameter: MacroParameter, where: string): } return value; case 'accessibility': - if (!isJsonObject(value) || !Object.keys(value).every(key => ACCESSIBILITY_KEYS.has(key))) { + if (!isAccessibilityAttributes(value)) { throw mismatch('accessibility attributes'); } return value; } } -const ACCESSIBILITY_KEYS: ReadonlySet = new Set(['label', 'description', 'live', 'hidden']); +/** Checks each accessibility attribute's value against its type in `common_types.json`. */ +const ACCESSIBILITY_ATTRIBUTES: Readonly boolean>> = { + label: value => typeof value === 'string' || isBindingOrCall(value), + description: value => typeof value === 'string' || isBindingOrCall(value), + live: value => value === 'off' || value === 'polite' || value === 'assertive', + hidden: value => typeof value === 'boolean' || isBindingOrCall(value), +}; + +function isAccessibilityAttributes(value: unknown): boolean { + return ( + isJsonObject(value) && + Object.entries(value).every( + ([key, attribute]) => + Object.hasOwn(ACCESSIBILITY_ATTRIBUTES, key) && ACCESSIBILITY_ATTRIBUTES[key](attribute), + ) + ); +} /** * Turns the forms a model writes for an action into an `Action`: an event name, an event diff --git a/typescript/agents/a2ui_agent/src/macros/expander.ts b/typescript/agents/a2ui_agent/src/macros/expander.ts index e349cbe27c..a16b886422 100644 --- a/typescript/agents/a2ui_agent/src/macros/expander.ts +++ b/typescript/agents/a2ui_agent/src/macros/expander.ts @@ -141,8 +141,9 @@ export class MacroExpander { private readonly surfaceCatalogs = new Map(); /** - * @throws {A2uiValidationError} If a macro name is not a valid v1.0 component name, or a - * base catalog targets a protocol version other than v1.0. + * @throws {A2uiValidationError} If a macro name is not a valid v1.0 component name, two + * macros have the same name, or a base catalog targets a protocol version other than + * v1.0. */ constructor(macros: readonly MacroDefinition[], options: MacroExpanderOptions = {}) { const onError = options.onError ?? 'passthrough'; @@ -150,10 +151,15 @@ export class MacroExpander { throw new TypeError(`Invalid onError policy '${String(onError)}'.`); } this.onError = onError; + const byName = new Map(); for (const macro of macros) { validateMacroName(macro.name); + if (byName.has(macro.name)) { + throw new A2uiValidationError(`Two macros are named '${macro.name}'.`); + } + byName.set(macro.name, macro); } - this.macros = new Map(macros.map(macro => [macro.name, macro])); + this.macros = byName; this.passthroughComponents = options.passthroughComponents === undefined ? undefined @@ -193,6 +199,10 @@ export class MacroExpander { * standalone macro catalog of `toCatalog()`. When one of them has the expander's * `catalogId`, the macros are added to that catalog instead. * + * The catalogs stay registered for the expander's lifetime, so `transformToTransport` + * can tell a macro from a catalog component of the same name. Use one expander per set + * of transport catalogs, such as one per session. + * * @throws {A2uiValidationError} If a catalog targets a protocol version other than v1.0. * @throws {A2uiCatalogError} If a macro has the name of a component of the catalog it is * added to. @@ -711,6 +721,18 @@ function isV10(version: string): boolean { return toCanonicalVersion(normalizeVersionString(version)) === '1.0'; } +/** + * Whether `e` is a stack overflow: V8 and JavaScriptCore throw a `RangeError` ("Maximum call + * stack size exceeded"), SpiderMonkey an `InternalError` ("too much recursion"). + */ +function isStackOverflow(e: unknown): boolean { + return ( + e instanceof Error && + (e instanceof RangeError || e.name === 'InternalError') && + /call stack|recursion/i.test(e.message) + ); +} + /** * Calls a macro's `render`. A `render` that keeps calling itself overflows the stack, which * is reported as the recursion it is. @@ -720,7 +742,7 @@ function renderMacro(macro: MacroDefinition, args: JsonObject): ComponentNode { try { tree = macro.render(args as never); } catch (e) { - if (e instanceof RangeError && /call stack/i.test(e.message)) { + if (isStackOverflow(e)) { throw new A2uiRecursionError(`Macro '${macro.name}' renders itself without end.`); } throw e; diff --git a/typescript/agents/a2ui_agent/src/macros/invocation-envelope.ts b/typescript/agents/a2ui_agent/src/macros/invocation-envelope.ts index de6beba396..b2a9a5e65d 100644 --- a/typescript/agents/a2ui_agent/src/macros/invocation-envelope.ts +++ b/typescript/agents/a2ui_agent/src/macros/invocation-envelope.ts @@ -68,8 +68,8 @@ export function invocationArguments( * `@accessibility` and `@metadata` (with its `extensions`) are merged with the root's own, * and `@checks` are appended to the root's checks. * - * @param lowered The lowered components; the root is the one with the invocation's ID, or - * the last one. It is changed in place. + * @param lowered The lowered components; the root is the one with the invocation's ID, or, + * for an invocation without an ID, the last one. It is changed in place. */ export function mergeEnvelopeFields( invocation: JsonObject, @@ -77,7 +77,10 @@ export function mergeEnvelopeFields( lowered: JsonObject[], instanceId: string | undefined, ): void { - const root = lowered.findLast(component => component['id'] === instanceId) ?? lowered.at(-1); + const root = + (instanceId !== undefined + ? lowered.findLast(component => component['id'] === instanceId) + : undefined) ?? lowered.at(-1); if (root === undefined) { return; } diff --git a/typescript/agents/a2ui_agent/tests/unit/macros/coercion.test.ts b/typescript/agents/a2ui_agent/tests/unit/macros/coercion.test.ts index 30e60d9acb..cc3ffac884 100644 --- a/typescript/agents/a2ui_agent/tests/unit/macros/coercion.test.ts +++ b/typescript/agents/a2ui_agent/tests/unit/macros/coercion.test.ts @@ -125,4 +125,24 @@ describe('argument coercion', () => { expect(coerce(param.accessibility(), {label: 'Save'})).toEqual({label: 'Save'}); expect(() => coerce(param.accessibility(), {role: 'button'})).toThrow(A2uiValidationError); }); + + it('accepts accessibility attributes whose values have their types', () => { + const attributes = { + label: {'@path': '/label'}, + description: 'Saves the form', + live: 'polite', + hidden: {'@call': 'not', args: {value: {'@path': '/visible'}}}, + }; + + expect(coerce(param.accessibility(), attributes)).toEqual(attributes); + }); + + it.each([ + ['a number label', {label: 3}], + ['a description that is no binding', {description: {path: '/d'}}], + ['a live value outside its enum', {live: 'loud'}], + ['a string for hidden', {hidden: 'yes'}], + ])('rejects accessibility attributes with %s', (_case, value) => { + expect(() => coerce(param.accessibility(), value)).toThrow(A2uiValidationError); + }); }); diff --git a/typescript/agents/a2ui_agent/tests/unit/macros/expander-catalogs.test.ts b/typescript/agents/a2ui_agent/tests/unit/macros/expander-catalogs.test.ts index 2fdb39c54f..6edca1d0ce 100644 --- a/typescript/agents/a2ui_agent/tests/unit/macros/expander-catalogs.test.ts +++ b/typescript/agents/a2ui_agent/tests/unit/macros/expander-catalogs.test.ts @@ -128,4 +128,10 @@ describe('MacroExpander catalogs', () => { A2uiValidationError, ); }); + + it('rejects two macros with the same name', () => { + const OtherBadge = defineMacro({name: 'Badge', render: () => ({component: 'Card'})}); + + expect(() => new MacroExpander([Badge, OtherBadge])).toThrow(A2uiValidationError); + }); }); diff --git a/typescript/agents/a2ui_agent/tests/unit/macros/expander-transport.test.ts b/typescript/agents/a2ui_agent/tests/unit/macros/expander-transport.test.ts index c34bf3206b..3fa4cdcf9e 100644 --- a/typescript/agents/a2ui_agent/tests/unit/macros/expander-transport.test.ts +++ b/typescript/agents/a2ui_agent/tests/unit/macros/expander-transport.test.ts @@ -136,6 +136,21 @@ describe('MacroExpander.transformToTransport', () => { ); }); + it("throws A2uiRecursionError for SpiderMonkey's InternalError on a stack overflow", () => { + const Loop = defineMacro({ + name: 'Loop', + render: (): ComponentNode => { + const error = new Error('too much recursion'); + error.name = 'InternalError'; + throw error; + }, + }); + + expect(() => lowerComponents([Loop], [{component: 'Loop', id: 'x'}])).toThrow( + A2uiRecursionError, + ); + }); + it('throws A2uiRecursionError for a macro whose tree uses it again', () => { const Loop = defineMacro({ name: 'Loop', diff --git a/typescript/agents/a2ui_agent/tests/unit/macros/invocation-envelope.test.ts b/typescript/agents/a2ui_agent/tests/unit/macros/invocation-envelope.test.ts index e35b64bc8f..66e956482c 100644 --- a/typescript/agents/a2ui_agent/tests/unit/macros/invocation-envelope.test.ts +++ b/typescript/agents/a2ui_agent/tests/unit/macros/invocation-envelope.test.ts @@ -105,6 +105,31 @@ describe('macro invocation envelope', () => { }); }); + it('merges the envelope fields onto the root of an invocation without an ID', () => { + const messages = [ + { + version: 'v1.0', + updateComponents: { + surfaceId: 's', + components: [{component: 'Panel', title: 'T', '@accessibility': {label: 'L'}}], + }, + }, + ] as unknown as AgentToRendererMessage[]; + + const [message] = new MacroExpander([Panel], {onError: 'raise'}).transformToTransport( + messages, + ) as unknown as Array<{updateComponents: {components: Array>}}>; + + expect(message.updateComponents.components).toEqual([ + {component: 'Text', id: 'root__text_1', text: 'T'}, + expect.objectContaining({ + component: 'Card', + id: 'root__card_1', + '@accessibility': {description: 'Panel', label: 'L'}, + }), + ]); + }); + it('reads arguments nested under parameters', () => { expect( lowerRoot(Panel, {parameters: {title: 'Nested'}, '@accessibility': {label: 'L'}}),