Skip to content
Closed
4 changes: 4 additions & 0 deletions typescript/agents/a2ui_agent/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)).

Expand Down
18 changes: 16 additions & 2 deletions typescript/agents/a2ui_agent/KNOWN_GAPS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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, 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.
Expand Down
63 changes: 63 additions & 0 deletions typescript/agents/a2ui_agent/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
45 changes: 45 additions & 0 deletions typescript/agents/a2ui_agent/src/component-tree/component-node.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>)['component'] === 'string'
);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Duck-typing any object with a string component key breaks when a plain data object happens to have a component property (for example inside param.dynamicValue(), action.event.context, FunctionCall.args, or @metadata.extensions). flattenComponentTree hoists that data object into the top-level components array and replaces it with an ID string.

Please match Python's nominal classes (ComponentBuilderNode and ComponentRef in python/a2ui_agent/src/a2ui/builder/core/base_node.py and blueprints/features/typesafe_builder_api.blueprint.md) and check instanceof ComponentBuilderNode instead. That also avoids colliding with @a2ui/web_core/v1_0's ComponentNode, and lets future generated builder classes extend ComponentBuilderNode directly.

Here is a failing test to verify the fix:

it('does not treat a plain data object with a string component key as a component node', () => {
  const PayloadAction = defineMacro({
    name: 'PayloadAction',
    parameters: {payload: param.dynamicValue()},
    render: ({payload}) => ({
      component: 'Button',
      child: {component: 'Text', text: 'Inspect'},
      action: {event: {name: 'inspect', context: {payload}}},
    }),
  });

  const expander = new MacroExpander([PayloadAction], {onError: 'raise'});
  const lowered = expander.transformToTransport([
    {
      version: '1.0',
      updateComponents: {
        surfaceId: 's',
        components: [
          {
            component: 'PayloadAction',
            id: 'btn',
            payload: {component: 'auth-service', status: 'ok'},
          },
        ],
      },
    },
  ]);

  // Expected: 2 components (Text + Button), with context.payload untouched.
  // Today: hoists {component: 'auth-service', id: 'btn__auth-service_1'} as a 3rd component
  // and replaces context.payload with 'btn__auth-service_1'.
  expect(lowered).toEqual([
    {
      version: '1.0',
      updateComponents: {
        surfaceId: 's',
        components: [
          {component: 'Text', id: 'btn__text_1', text: 'Inspect'},
          {
            component: 'Button',
            id: 'btn',
            child: 'btn__text_1',
            action: {
              event: {
                name: 'inspect',
                context: {payload: {component: 'auth-service', status: 'ok'}},
              },
            },
          },
        ],
      },
    },
  ]);
});

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in #4540: nodes are instances of ComponentBuilderNode now, with ComponentRef for components already on the surface, and the flattener checks instanceof. Your case is a test in #4541 (expander-transport.test.ts), and #4540 has a flattener-level version of it. A component argument arrives as a ComponentRef, as in Python.

}
141 changes: 141 additions & 0 deletions typescript/agents/a2ui_agent/src/component-tree/flatten.ts
Original file line number Diff line number Diff line change
@@ -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 `<prefix>__<component>_<n>`; one with an `id` gets `<prefix>__<id>`, 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 `<rootId>_<index>`
* 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<string> {
const reserved = new Set<string>();
const visited = new Set<object>();
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<ComponentNode, string>();

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<string, unknown> = {};
for (const [key, nested] of Object.entries(value)) {
if (nested !== undefined) {
wire[key] = this.toWireValue(nested);
}
}
return wire;
}
return value;
}
}
Loading
Loading