Skip to content

feat(ts_agent): port macros (MacroExpander) to @a2ui/agent - #4413

Closed
manfredsteyer wants to merge 9 commits into
a2ui-project:mainfrom
manfredsteyer:feat/ts-agent-macros
Closed

manfredsteyer wants to merge 9 commits into
a2ui-project:mainfrom
manfredsteyer:feat/ts-agent-macros

Conversation

@manfredsteyer

Copy link
Copy Markdown

Problem

Macros are only available in the Python SDK, so a TypeScript agent can't give the model high-level components that are lowered to catalog components before the messages reach the renderer.

Solution

This PR ports MacroExpander to @a2ui/agent for v1.0. The API follows Python's in camelCase (transformCatalogs, transformToInferenceCatalog, toCatalog, transformToTransport):

const FlightCard = defineMacro({
  name: 'FlightCard',
  parameters: {from: param.string(), to: param.string(), onBook: param.action()},
  render: ({from, to, onBook}) => ({
    component: 'Card',
    child: {component: 'Button', child: {component: 'Text', text: `Book ${from} to ${to}`}, action: onBook},
  }),
});

const expander = new MacroExpander([FlightCard], {onError: 'raise'});
const transportMessages = expander.transformToTransport(messages);
  1. render returns nested component objects, and the expander allocates and namespaces their IDs.
  2. Parameters use a small param.* vocabulary taken from the macro suite instead of Zod, and the arguments of render are typed from it.
  3. The API is synchronous, as in Python.

The tree layer is deliberately light, while the expander matches Python for v1.0. Follow-up PRs can build on it: a typed builder with CLI code generation, v0.9, a TypeScript section in the docs/site guide, and data model hydration with load() once a cross-SDK RFC has settled it.

Verification

  1. macros.yaml: 47 of 70 cases pass, including 42 of the 44 v1.0 cases. The skipped cases need v0.9 macros.
  2. yarn workspace @a2ui/agent test, lint and format:check pass after every commit. The commits are ordered for review one at a time.

Open questions

  1. Is a light tree layer the right start, rather than a typed builder with CLI code generation? A builder could emit the same trees later.
  2. MacroExpander doesn't implement CatalogTransformer, because transformCatalogs returns more catalogs than it gets. Does that fit the direction of [RFC] Unifying Catalog Transformations and Message Translation via CatalogMessageTransformer & TransformerPipeline #2865?
  3. Primitive and enum arguments are checked more strictly than in Python, so the types render sees hold at runtime. KNOWN_GAPS.md records this. Is the difference OK, or should it match Python?

Demo

My dashboard demo uses this branch: manfredsteyer/dashboard-demo, branch macro-impl. Its tiles are macros, and the server lowers the model's Express program with MacroExpander (compile-dashboard.ts).

🤖 Generated with Claude Code

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request implements composite macros and component tree flattening in the TypeScript A2UI agent SDK, aligning it with the Python SDK. It introduces the 'defineMacro' API, the 'param' parameter vocabulary, the 'MacroExpander' class for lowering macro invocations, and the 'flattenComponentTree' utility for deterministic ID allocation. The reviewer provided valuable feedback to enhance robustness, including addressing a potential memory leak/state accumulation in 'transformCatalogs', fixing a bug in 'mergeEnvelopeFields' where an undefined 'instanceId' could merge envelope fields onto the wrong component, strictly validating accessibility attribute value types, throwing an error on duplicate macro definitions, and broadening the recursion check to support Firefox's 'InternalError'.

Comment on lines +200 to +203
transformCatalogs(catalogs: readonly CatalogApi[]): CatalogApi[] {
for (const catalog of catalogs) {
this.registerCatalog(catalog);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

transformCatalogs registers the passed catalogs by calling this.registerCatalog(catalog), which appends them to this.baseCatalogIds and this.catalogComponents permanently.

If the same MacroExpander instance is reused across multiple requests or sessions with different catalogs, these arrays/maps will accumulate catalogs indefinitely. This can lead to memory leaks and false-positive ambiguity errors (A2uiCatalogError) in stampOwningCatalogs if a component name is defined in catalogs from different requests.

Consider separating permanently registered base catalogs (passed to the constructor) from transient catalogs passed to transformCatalogs, or avoid mutating the global expander state during transformCatalogs.

  transformCatalogs(catalogs: readonly CatalogApi[]): CatalogApi[] {
    // Note: Registering catalogs here mutates the global expander state.
    // Consider refactoring to keep transient catalogs request-scoped.
    for (const catalog of catalogs) {
      this.registerCatalog(catalog);
    }

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.

This is by design and matches Python's transform_catalogs: the expander has to remember the base catalogs so that transformToTransport can tell a macro from a catalog component of the same name and stamp the owning @catalogId. Registering a catalog again replaces its entry, so the state grows only with distinct catalog IDs. The expander is meant to be used per session or per set of transport catalogs, as the README says; the transformCatalogs doc comment now says so too (3f487a4).

lowered: JsonObject[],
instanceId: string | undefined,
): void {
const root = lowered.findLast(component => component['id'] === instanceId) ?? lowered.at(-1);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

If instanceId is undefined, the expression component['id'] === instanceId becomes component['id'] === undefined. This will evaluate to true for any component in the lowered array that does not have an id property.

As a result, lowered.findLast will incorrectly select the last component without an id (which might be a child/descendant component like Text) instead of the actual root component (which is always the last element lowered.at(-1)). This causes envelope fields (such as @accessibility, @metadata, and @checks) to be merged onto the wrong component.

To fix this, only search by instanceId if it is explicitly defined.

Suggested change
const root = lowered.findLast(component => component['id'] === instanceId) ?? lowered.at(-1);
const root =
instanceId !== undefined
? (lowered.findLast(component => component['id'] === instanceId) ?? lowered.at(-1))
: lowered.at(-1);
References
  1. Avoid using the non-null assertion operator on lookup results that may fail. Instead, allow the variable to be nullable and handle the undefined case downstream using optional chaining or nullish coalescing.

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.

In practice this lookup couldn't pick the wrong component: lowered always comes from flattenComponentTree, which gives every component an ID, the root included, so component['id'] === undefined never matched and the lookup fell back to the last component, the root. I've made the check explicit anyway, as Python's if instance_id is not None does, and added a test for an invocation without an ID (3f487a4).

Comment on lines +119 to +127
case 'accessibility':
if (!isJsonObject(value) || !Object.keys(value).every(key => ACCESSIBILITY_KEYS.has(key))) {
throw mismatch('accessibility attributes');
}
return value;
}
}

const ACCESSIBILITY_KEYS: ReadonlySet<string> = new Set(['label', 'description', 'live', 'hidden']);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The validation for the accessibility parameter type only checks that the keys of the object are valid accessibility attributes, but it does not validate that the values of those keys match their expected types (e.g., label and description as DynamicString, live as 'off' | 'polite' | 'assertive', and hidden as DynamicBoolean). This can lead to runtime type mismatches in the macro's render function.

Consider implementing a helper function isAccessibilityAttributes to strictly validate both the keys and their values at runtime.

    case 'accessibility':
      if (!isAccessibilityAttributes(value)) {
        throw mismatch('accessibility attributes');
      }
      return value;
  }
}

function isAccessibilityAttributes(value: unknown): boolean {
  if (!isJsonObject(value)) return false;
  for (const [key, val] of Object.entries(value)) {
    if (key === 'label' || key === 'description') {
      if (typeof val !== 'string' && !isBindingOrCall(val)) return false;
    } else if (key === 'live') {
      if (val !== 'off' && val !== 'polite' && val !== 'assertive') return false;
    } else if (key === 'hidden') {
      if (typeof val !== 'boolean' && !isBindingOrCall(val)) return false;
    } else {
      return false;
    }
  }
  return true;
}

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.

Agreed, done in 3f487a4: each attribute's value is checked against its type in common_types.json, with a test for each case.

Comment on lines +153 to +156
for (const macro of macros) {
validateMacroName(macro.name);
}
this.macros = new Map(macros.map(macro => [macro.name, macro]));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

If the macros array contains duplicate macro definitions with the same name, the Map constructor will silently overwrite the earlier definition with the later one. This can lead to hard-to-debug behavior where a macro is unexpectedly overridden.

Consider throwing an A2uiValidationError if a duplicate macro name is detected during initialization.

Suggested change
for (const macro of macros) {
validateMacroName(macro.name);
}
this.macros = new Map(macros.map(macro => [macro.name, macro]));
const names = new Set<string>();
for (const macro of macros) {
validateMacroName(macro.name);
if (names.has(macro.name)) {
throw new A2uiValidationError(`Duplicate macro definition for '${macro.name}'.`);
}
names.add(macro.name);
}
this.macros = new Map(macros.map(macro => [macro.name, macro]));
References
  1. When validating input or configuration data (such as few-shot examples), do not silently skip invalid or malformed entries if the specification expects validation to fail. Instead, throw an appropriate validation error.

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.

Agreed, done in 3f487a4: the constructor throws A2uiValidationError for two macros with the same name. Python keeps the last one, so KNOWN_GAPS.md notes the difference.

try {
tree = macro.render(args as never);
} catch (e) {
if (e instanceof RangeError && /call stack/i.test(e.message)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The check e instanceof RangeError && /call stack/i.test(e.message) might fail to detect stack overflow errors in some JavaScript engines. For example, Firefox (SpiderMonkey) throws an InternalError with the message "too much recursion", which does not match "call stack" and is not an instance of RangeError.

To ensure cross-engine compatibility (especially since this SDK can run in browser environments), consider broadening the check to also match "recursion" and handle InternalError.

    if (
      (e instanceof RangeError || (e as Error).name === 'InternalError') &&
      /call stack|recursion/i.test((e as Error).message)
    )

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 3f487a4, since the package also runs in browsers: an InternalError with "too much recursion" is recognized too, with a test.

@github-actions github-actions Bot added the status: needs-triage auto-managed: https://github.com/a2ui-project/a2ui/blob/main/scripts/triage.mjs label Nov 25, 2026
@manfredsteyer

Copy link
Copy Markdown
Author

Some context for triage: I opened this PR after an email exchange with @ditman, to start a discussion about macros in the TypeScript Agent SDK (#3455). If we decide to go ahead, I'm happy to split it into smaller PRs, for example along the commits.

@polina-c

Copy link
Copy Markdown
Collaborator

From triage bot, analysis:

For humans

TL;DR
Case: this out-of-team PR ports macros to @a2ui/agent, a large change that the author opened after an email exchange with ditman.
Suggestion: add status: needs-team-input to decide whether the team takes it.

Summary:
The PR ports the Python MacroExpander to the TypeScript agent SDK @a2ui/agent, so that a TypeScript agent can give the model high-level components that are lowered to catalog components before transport. The description asks the team three design questions.

Why flagged for triage:
This PR has no assignee.

Suggestion:

  • It is not a minor change (4,196 added lines in 28 files), and #3455, which asked for it, was closed for lack of capacity around the v1.0 launch.
  • The author says they opened it after an email exchange with ditman, to start a discussion. ditman wrote the catalog transformers, and gspencergoog wrote 10 of the last 20 commits to @a2ui/agent.
  • Question for the team: take macros into @a2ui/agent now, and in one PR or split along the commits?
  1. Add labels: status: needs-team-input, type: feature/enhancement, component: agent sdk, lang: typescript, feature: macros
  2. Related items: [v1.0][TypeScript] MacroExpander, MacroProcessor, and IdAllocator are completely unimplemented in @a2ui/agent and @a2ui/web_core (macros.yaml skipped) #3455

Reply:

Requires team input. Note for the discussion:

Adding status: needs-team-input, because the team needs to decide whether to add macros to @a2ui/agent now: #3455 was closed in October because the team could not prioritize it around the v1.0 launch. Thanks for offering to split the PR along its commits if the team goes ahead.

To adjust the analysis and apply its suggestion, open it in the hosted triage UI, or run in your a2ui checkout:

tools/internal/triage/triage_ui.sh https://github.com/a2ui-project/a2ui/pull/4413
For software
<a2ui>
root = TriageAnalysis(
  tldr="""Case: this out-of-team PR ports macros to `@a2ui/agent`, a large change that the author opened after an email exchange with `ditman`.
Suggestion: add `status: needs-team-input` to decide whether the team takes it.""",
  summary="""The PR ports the Python `MacroExpander` to the TypeScript agent SDK `@a2ui/agent`, so that a TypeScript agent can give the model high-level components that are lowered to catalog components before transport. The description asks the team three design questions.""",
  reason="""This PR has no assignee.""",
  suggestion="""- It is not a minor change (4,196 added lines in 28 files), and [#3455](https://github.com/a2ui-project/a2ui/issues/3455), which asked for it, was [closed](https://github.com/a2ui-project/a2ui/issues/3455#issuecomment-6354765779) for lack of capacity around the v1.0 launch.
- The author [says](https://github.com/a2ui-project/a2ui/pull/4413#issuecomment-7162823915) they opened it after an email exchange with `ditman`, to start a discussion. `ditman` wrote the [catalog transformers](https://github.com/a2ui-project/a2ui/commits/main/typescript/agents/a2ui_agent/src/catalog-transformers), and `gspencergoog` wrote [10 of the last 20 commits](https://github.com/a2ui-project/a2ui/commits/main/typescript/agents/a2ui_agent) to `@a2ui/agent`.
- Question for the team: take macros into `@a2ui/agent` now, and in one PR or split along the commits?""",
  reply="""Adding `status: needs-team-input`, because the team needs to decide whether to add macros to `@a2ui/agent` now: [#3455](https://github.com/a2ui-project/a2ui/issues/3455) was closed in October because the team could not prioritize it around the v1.0 launch. Thanks for offering to split the PR along its commits if the team goes ahead.""",
  added_labels=["status: needs-team-input", "type: feature/enhancement", "component: agent sdk", "lang: typescript", "feature: macros"],
  related_items=[3455]
)
</a2ui>

This analysis is auto-created to help humans to triage this item. Please, do not treat it as a team decision.

@Varun-S10

Copy link
Copy Markdown
Collaborator

Hi @manfredsteyer, thank you for putting this PR together. We verified the macro implementation locally and all tests pass, though the branch is 6 commits behind main and there are open review comments including the undefined instanceId bug in invocation-envelope.ts.
Could you please sync with latest main and address the review comments?

@Varun-S10 Varun-S10 self-assigned this Nov 26, 2026
@Varun-S10 Varun-S10 added status: waiting-for-author-response and removed status: needs-triage auto-managed: https://github.com/a2ui-project/a2ui/blob/main/scripts/triage.mjs labels Nov 26, 2026
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 `<prefix>__<component>_<n>`, 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.
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 a2ui-project#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.
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.
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.
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.
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.
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.
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.
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.
@manfredsteyer

Copy link
Copy Markdown
Author

Thanks for checking, @Varun-S10. I've rebased the branch onto the latest main (no conflicts) and added 3f487a4 for the review comments: the root lookup in mergeEnvelopeFields is explicit now, accessibility arguments are checked value by value, duplicate macro names are rejected, and Firefox's InternalError counts as a stack overflow. The comment on transformCatalogs describes intended behavior that matches Python; I've replied there and documented it. On instanceId: the lowered components always have IDs, so the old lookup couldn't pick the wrong root, but the explicit check is clearer. Tests, lint and format pass.

@Varun-S10

Copy link
Copy Markdown
Collaborator

Hi @manfredsteyer, thank you for updating the PR and addressing all the review comments. We have verified the updated PR and all local tests, lint, and formatting checks pass cleanly. I will escalate this to the team to review and look into your open questions. Thank you for your patience and understanding.
Hi @gspencergoog, Could you please take a look?

@ditman

ditman commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

@polina-c and I will take a look at this one! (Polina will actually own this after I publish the first round of reviews from my agent!)

@ditman ditman left a comment

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.

🤖 Thanks for putting this together, @manfredsteyer. TypeScript macros is a high priority for us, and this is a solid start (v1.0-first, no Zod dependency, synchronous, 42 of 44 v1.0 conformance cases passing).

Could you split this into a 3-PR stack along your commits so it is easier to review and revert if needed?

  1. PR 1: move the shared envelope/schema helpers out of src/inference-formats/express/schema-helper.ts into src/utils/, and add src/component-tree/ (ComponentBuilderNode, ComponentRef, flattenComponentTree) with unit tests.
  2. PR 2: add src/macros/ (defineMacro, param, coercion, envelope merging, MacroExpander) with unit tests.
  3. PR 3: add the macros.yaml conformance harness and update README.md, KNOWN_GAPS.md, CHANGELOG.md, and blueprints/codebases/typescript/agents/a2ui_agent/codebase.blueprint.md.

Answers to your open questions

  1. Starting with a light tree layer is fine, as long as we use nominal classes matching Python (ComponentBuilderNode and ComponentRef) instead of duck-typing plain objects on a component key (see the inline comment with a failing test), and leave agent/builder/builder.yaml in UNSUPPORTED_SUITES until a typed builder exists.
  2. Not implementing CatalogTransformer matches Python and fits #2865, since transformCatalogs returns more catalogs than it receives and MacroExpander also lowers messages.
  3. Keeping stricter checks on primitives, enums, and accessibility than Python is fine and matches the rest of @a2ui/agent.

Follow-up work (not blocking this stack)

Once this stack lands, the remaining gaps compared to Python (plus shared cross-SDK work) can go in separate follow-up PRs:

  1. Typesafe builders and a TypeScript emitter in dart/a2ui_cli/lib/src/emitters/typescript/ to generate Basic Catalog and custom-catalog classes extending ComponentBuilderNode, then enable conformance/agent/builder/builder.yaml.
  2. Richer parameter types beyond the 15 conformance types (typed arrays, typed maps, Extensions, single CheckRule/DataBinding/FunctionCall/DynamicChildList, catalog sub-models, and oneOf unions).
  3. Protocol v0.9 / v0.9.1 support for the 23 skipped v0.9 cases in macros.yaml, if needed.
  4. TypeScript examples in docs/site/src/content/docs/guides/macros.mdx and a shared blueprints/features/macros.blueprint.md derived from Python and TypeScript.
  5. Async macro expansion and data-model hydration as a cross-SDK RFC.

Note on CI: the ci-renderers failure (@a2ui/angular ColumnComponent flow-start vs flex-start) is unrelated to your changes—your branch is slightly behind main, where #4447 fixed it. Rebasing onto latest main will clear that check. Also please make sure yarn workspace @a2ui/agent typecheck passes alongside test, lint, and format:check.

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.

SkillSet,
} from './skill/index.js';

// Component trees

@ditman ditman Dec 1, 2026 •

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.

MacroArgs and MacroInput expose types from parameter-values.ts (Action, DynamicString, CheckRule, AccessibilityAttributes, ChildList, etc.), so callers need a way to import them without deep imports.

Because we want to keep parameter-values.ts free of Zod-backed web_core types, several of those names overlap with @a2ui/web_core/v1_0. What do you think about exporting the macro API under a namespace from the root entrypoint?

export * as Macros from './macros/index.js';

That avoids collisions (Macros.Action, Macros.defineMacro, Macros.MacroExpander), while macro-only files can still destructure values (const {defineMacro, param, ComponentBuilderNode, MacroExpander} = Macros;).

(We could also add an @a2ui/agent/macros entrypoint or similar, but that wouldn't solve the name clashing)

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 #4541: export * as Macros from './macros/index.js', with explicit named exports in src/macros/index.ts. I kept ComponentBuilderNode and ComponentRef as root exports (#4540) instead of putting them in Macros, since generated builder classes will extend them outside macros.

@@ -0,0 +1,114 @@
/*

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.

Please drop this file and keep agent/builder/builder.yaml in UNSUPPORTED_SUITES.

21 of the 22 cases are skipped, and the one passing case (01_primitive_components_v1_0) is a flat list of 3 sibling components with explicit IDs and defaults. Your tests/unit/component-tree/flatten.test.ts already tests flattenComponentTree much more thoroughly, and keeping builder.yaml in UNSUPPORTED_SUITES avoids reporting the builder API as supported before a typed builder exists.

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.

Dropped. builder.yaml stays in UNSUPPORTED_SUITES (#4542), and KNOWN_GAPS.md has an entry for the missing typed builder.

returnType?: string;
}

export type DynamicString = string | DataBinding | FunctionCall;

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.

Two small v1.0 gaps in these types:

  1. FunctionCall is missing catalogId?: string.
  2. DynamicValue is missing | null.

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.

  1. Added catalogId to FunctionCall in feat(ts_agent): add macros #4541. I also removed returnType, which v1.0 declares on the function definition in the catalog, not on the call.
  2. I left null out of DynamicValue, because v1.0's DynamicValue in common_types.json doesn't include it (string, number, boolean, array, object, binding or call), and neither does the DynamicValue alias in Python's a2ui.builder.v1_0. If you'd rather accept null anyway, I can add it.

}
coerced[name] = parameter.default;
continue;
}

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.

Three small coercion edge cases:

  1. Line 51: treating value === null like undefined rejects an explicit JSON null on a required param.dynamicValue().
  2. Line 104: case 'dynamicNumber' should check Number.isFinite(value) like case 'number', so NaN and Infinity are rejected.
  3. Line 176: toAction lets extra sibling keys through on {event: {name: 'save'}, extra: 1} and {functionCall: {'@call': 'fn'}, extra: 1}, and isFunctionCall accepts an empty '' for @call or non-object args.

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.

2 and 3 are done in #4541. dynamicNumber rejects NaN and Infinity. A full Action must have only event or only functionCall, an event only name, context and userMessage, and a function call a non-empty @call, object args, and no keys besides @call, args and catalogId.

On 1, I kept null as a left-out argument: an optional parameter gets its default and a required one rejects it. Since v1.0's DynamicValue doesn't include null (see the thread on parameter-values.ts), a required param.dynamicValue() has no valid null to accept. Python passes None on to the macro instead, and no conformance case pins either, so KNOWN_GAPS.md lists the difference (#4542) and a unit test pins it. Happy to change it if you see it differently.

A2uiRecursionError,
A2uiValidationError,
AgentToRendererMessage,
Catalog,

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.

src/macros/ should not import internal helpers from ../inference-formats/express/schema-helper.js (same in invocation-envelope.ts). In PR 1 of the stack, please move the shared envelope helpers and CatalogSchemaHelper into src/utils/.

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: schema-helper.ts moved to src/utils/ unchanged, in a commit of its own, and src/macros/ imports it from there.

const surfaces =
options.surfaceCatalogs === undefined
? this.surfaceCatalogs
: new Map(Object.entries(options.surfaceCatalogs));

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.

Two small parity items:

  1. Please add transformToInference(messages) (identity pass-through) to match Python's MacroExpander and wire action === 'transform_to_inference' in macros-conformance.test.ts (case 16_reverse_passthrough only avoided failing because it defaults to v0.9).
  2. Line 341: returning early when this.macros.size === 0 skips deleteSurface and trackCreatedSurface, so an empty MacroExpander([], {baseCatalogs}) will not rewrite a createSurface whose catalogId is macroCatalogId (or throw A2uiCatalogError when baseCatalogs is empty).

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.

Both done in #4541.

  1. transformToInference passes the messages through, and test(ts_agent): run the macros conformance suite and document macros #4542 runs 16_reverse_passthrough. It doesn't depend on the version of the macros, so it runs despite its v0.9 envelope.
  2. The early return now happens only without macros and without base catalogs, like Python's if not self.macros and self._target_family is None, so MacroExpander([], {baseCatalogs}) rewrites a createSurface whose catalogId is the macro catalog. Without base catalogs, both SDKs pass the messages through, so that case doesn't throw A2uiCatalogError.

this.taken.add(namespaced);
return namespaced;
}
const name = componentName.toLowerCase();

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.

If two distinct descendant nodes in the same tree set the same explicit id (for example id: 'item'), allocate returns ${this.prefix}__item for both, emitting duplicate component IDs. Please either throw A2uiValidationError on duplicate explicit IDs or disambiguate them.

@ditman ditman Dec 1, 2026 •

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.

Wow, I just noticed this is also an issue in Python! Throwing A2uiValidationError here (and noting it in KNOWN_GAPS.md alongside the other stricter-than-Python checks so we can fix Python too) is the cleaner behavior IMO.

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: a second component with the same explicit id throws A2uiValidationError, and KNOWN_GAPS.md lists it with the other checks that are stricter than Python's (#4542).

@jacobsimionato

Copy link
Copy Markdown
Collaborator

@manfredsteyer @ditman @polina-c Quick heads-up on Python macro alignment so this PR does not hit surprises as we land the #2865 stack on Python:

  1. Open question 1 (light tree layer vs. typed builder): Keeping the light nested-object tree layer here is a great start. A CLI-generated typed builder can emit the same tree shape later without changing defineMacro or param.*.
  2. Open question 2 (CatalogTransformer and #2865): We are landing #2865 in Python by adding transform_catalogs(catalogs) -> list[Catalog] on CatalogTransformer, MessageTransformer, CatalogMessageTransformer, and TransformerPipeline on A2uiGenerator / A2uiRequestProcessor, with a per-session bind(transport_catalogs) seam so shared MacroExpander instances do not mutate state across concurrent requests. Making MacroExpander implement CatalogMessageTransformer cleanly resolves the 1-to-N catalog mismatch you flagged.
  3. Open question 3 (strict validation, duplicates, and defaults): We are updating Python to match your duplicate-macro-name rejection (A2uiValidationError), switching Python's default on_error from "passthrough" to "raise" (#2748, updating macros.yaml Case 33 explicitly), and reconciling dart/a2ui_cli so optional builder fields default to None rather than materializing schema defaults onto wire payloads (which will update shared builder and macro goldens in a dedicated PR). No need to block this PR on those Python follow-ups — just flagging them ahead of time for visibility.

🤖 Agent-generated

@manfredsteyer

Copy link
Copy Markdown
Author

Thanks for the review, @ditman. I've split this into #4540, #4541 and #4542 as you suggested and answered the inline comments here. The two places where I kept the current behavior are null for DynamicValue and for a required param.dynamicValue(), since v1.0's DynamicValue doesn't include null; details are in those threads.

On typecheck: yarn workspace @a2ui/agent typecheck reports 20 errors on main itself, in conformance.test.ts, specification-round-trip.test.ts, renderer-function-call-validation.test.ts and a few other test files. The three PRs add none.

Since the PRs come from a fork, #4541 and #4542 include the commits of the PRs before them until those merge. I'm closing this PR in favor of the three.

@manfredsteyer

Copy link
Copy Markdown
Author

Thanks for the heads-up, @jacobsimionato. In the split (#4540, #4541, #4542) the tree is made of ComponentBuilderNodes, so a generated builder can extend that class without changing defineMacro or param. CatalogMessageTransformer, the per-session bind(transport_catalogs) and the on_error default can follow in TypeScript once they've landed in Python.

@ditman

ditman commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Thanks for all the work; see you on the split PR @manfredsteyer!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants