Skip to content

feat(ts_agent): add macros - #4541

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

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

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 (#3455).

Changes

This PR ports Python's MacroExpander to @a2ui/agent for v1.0. The macro API is exported as the Macros namespace:

import {ComponentBuilderNode, Macros} from '@a2ui/agent';

const {defineMacro, MacroExpander, param} = Macros;

const Greeting = defineMacro({
  name: 'Greeting',
  parameters: {name: param.string({description: 'Who to greet'})},
  render: ({name}) =>
    new ComponentBuilderNode({
      component: 'Card',
      child: new ComponentBuilderNode({component: 'Text', text: `Hello, ${name}!`}),
    }),
});

const expander = new MacroExpander([Greeting], {onError: 'raise'});
const inferenceCatalog = expander.transformToInferenceCatalog(basicCatalog);
const transportMessages = expander.transformToTransport(messages);
  1. defineMacro and param define a macro. param has the parameter types of the shared macro conformance suite instead of Zod, and the arguments of render are typed from it. Component IDs arrive as ComponentRefs, as in Python.
  2. MacroExpander follows Python's API in camelCase: transformCatalogs, transformToInferenceCatalog, toCatalog, transformToTransport and transformToInference. It checks and coerces the arguments, merges an invocation's @accessibility, @metadata and @checks onto the root, resolves macros on surfaces that mix catalogs, tracks surfaces and applies an onError policy.
  3. The macro API is a namespace because its value types, such as Action and DynamicString, have the names of @a2ui/web_core types. ComponentBuilderNode and ComponentRef stay root exports, since generated builder classes will extend them outside macros.
  4. Some checks are stricter than Python's: primitive, enum and accessibility arguments are checked against their parameters, an Action has only event or only functionCall, a function call has only @call, args and catalogId, an argument set to null counts as left out, and two macros with the same name throw.

Verification

  1. The unit tests under tests/unit/macros/ cover the parameters and their types, argument coercion, the envelope fields, catalog resolution, surface tracking and a round trip through A2uiGenerator.
  2. yarn workspace @a2ui/agent test, lint and format:check pass. typecheck reports the same 20 errors as main, all in test files this PR doesn't touch.

@manfredsteyer

manfredsteyer commented Dec 2, 2026 •

Copy link
Copy Markdown
Author

This PR builds on #4540, and since both come from a fork, the diff includes its commits until it merges. The commit to review here is 8287dbe.

@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 introduces a macro expansion and component tree flattening system for the TypeScript A2UI Agent SDK. It adds utilities to define high-level macro components, expand them into standard catalog components, and flatten component trees into flat lists with deterministic ID allocation. The feedback highlights two important improvements: addressing potential duplicate component IDs when flattening an array of roots without a specified root ID, and preventing a potential TypeError in the macro expander by using optional chaining when retrieving custom envelope properties.

Comment on lines +61 to +63
return root.flatMap((item, index) =>
flattenComponentTree(item, {rootId: rootId ? `${rootId}_${index}` : undefined}),
);

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

When root is an array and rootId is not provided, each root component will be flattened with rootId as undefined. This causes all roots to default to the same prefix (e.g., 'root'), leading to duplicate component IDs in the flattened list. To prevent ID collisions, a unique prefix should be provided for each root in the array even when rootId is omitted.

Suggested change
return root.flatMap((item, index) =>
flattenComponentTree(item, {rootId: rootId ? `${rootId}_${index}` : undefined}),
);
return root.flatMap((item, index) =>
flattenComponentTree(item, {rootId: rootId ? rootId + "_" + index : "root_" + index}),
);

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.

Good catch. The collision is real, and Python's flatten_component_tree has it too. The suggested fallback would replace a root's own id with root_<index>, though, and break any reference to that root. So without a rootId, a root now keeps its own id, and only a root without one gets root_<index>. Two roots that still end up with the same ID throw A2uiValidationError, as two components with the same id in one tree already do.

The fix is in 288010b, which belongs to #4540, and KNOWN_GAPS notes the difference from Python.

Comment on lines +685 to +687
owners.every(id =>
this.schemaHelpers.get(id)?.getCustomEnvelopeProperties(name).has('catalogId'),
);

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 this.schemaHelpers.get(id) is defined but getCustomEnvelopeProperties(name) returns undefined (e.g., if the component is not found in the catalog), calling .has('catalogId') on it will throw a TypeError. Using optional chaining and a nullish coalescing fallback ensures defensive programming and prevents potential runtime crashes.

Suggested change
owners.every(id =>
this.schemaHelpers.get(id)?.getCustomEnvelopeProperties(name).has('catalogId'),
);
owners.every(id =>
this.schemaHelpers.get(id)?.getCustomEnvelopeProperties(name)?.has('catalogId') ?? false,
);
References
  1. In TypeScript, when handling partial objects that may not fully implement an interface, defensively default their properties (e.g., using nullish coalescing or logical OR) to prevent runtime TypeErrors.

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.

getCustomEnvelopeProperties never returns undefined: it's typed ReadonlySet<string> and falls back to an empty set (src/utils/schema-helper.ts). When get(id) is undefined, ?. short-circuits the rest of the chain, the callback returns undefined, and every treats that as false. There's no TypeError to guard against, so I'm leaving it as is.

@github-actions github-actions Bot added the status: needs-triage auto-managed: https://github.com/a2ui-project/a2ui/blob/main/scripts/triage.mjs label Dec 2, 2026
@polina-c

polina-c commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

From triage bot, analysis:

For humans

TL;DR
Case: ditman already started reviewing this change in #4413 and asked for this split. This PR is its second part, on top of #4540.
Suggestion: assign polina-c, who owns the review.

Summary:
Second of the three PRs that split #4413. It adds src/macros/ to @a2ui/agent, with defineMacro, param and MacroExpander ported from Python, so that a TypeScript agent can give the model high-level components that are lowered to catalog components before transport.

Why flagged for triage:
This PR has no assignee.

Suggestion:

  • ditman reviewed #4413 and asked to split it into three PRs, which #4540, #4541 and #4542 follow. ditman said that polina-c owns the review after that first round, so assign polina-c to all three.
  • The diff includes the commits of #4540 until it merges. The author says to review 871efcd3c. No merge conflicts.
  1. Add labels: type: feature/enhancement, component: agent sdk, lang: typescript
  2. Assign: polina-c
  3. Related items: feat(ts_agent): add ComponentBuilderNode and flattenComponentTree #4540, test(ts_agent): run the macros conformance suite and document macros #4542, feat(ts_agent): port macros (MacroExpander) to @a2ui/agent #4413

Reply:

From triage:

Assigning this PR to polina-c, who owns the review that ditman started on #4413.

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/4541
For software
<a2ui>
root = TriageAnalysis(
  tldr="""Case: `ditman` already started reviewing this change in [#4413](https://github.com/a2ui-project/a2ui/pull/4413) and asked for this split. This PR is its second part, on top of [#4540](https://github.com/a2ui-project/a2ui/pull/4540).
Suggestion: assign `polina-c`, who owns the review.""",
  summary="""Second of the three PRs that split [#4413](https://github.com/a2ui-project/a2ui/pull/4413). It adds `src/macros/` to `@a2ui/agent`, with `defineMacro`, `param` and `MacroExpander` ported from Python, so that a TypeScript agent can give the model high-level components that are lowered to catalog components before transport.""",
  reason="This PR has no assignee.",
  suggestion="""- `ditman` [reviewed](https://github.com/a2ui-project/a2ui/pull/4413#pullrequestreview-6141583583) [#4413](https://github.com/a2ui-project/a2ui/pull/4413) and [asked](https://github.com/a2ui-project/a2ui/pull/4413#pullrequestreview-6141583583) to split it into three PRs, which [#4540](https://github.com/a2ui-project/a2ui/pull/4540), [#4541](https://github.com/a2ui-project/a2ui/pull/4541) and [#4542](https://github.com/a2ui-project/a2ui/pull/4542) follow. `ditman` [said](https://github.com/a2ui-project/a2ui/pull/4413#issuecomment-7320083978) that `polina-c` owns the review after that first round, so assign `polina-c` to all three.
- The diff includes the commits of [#4540](https://github.com/a2ui-project/a2ui/pull/4540) until it merges. The author [says](https://github.com/a2ui-project/a2ui/pull/4541#issuecomment-7353215315) to review [871efcd3c](https://github.com/a2ui-project/a2ui/pull/4541/commits/871efcd3c0d9ce1881818ce46e3eae329e434d93). No merge conflicts.""",
  reply="""Assigning this PR to `polina-c`, who owns the review that `ditman` started on [#4413](https://github.com/a2ui-project/a2ui/pull/4413).""",
  added_labels=["type: feature/enhancement", "component: agent sdk", "lang: typescript"],
  new_assignees=["polina-c"],
  related_items=[4540, 4542, 4413]
)
</a2ui>

This analysis does not change after taking the later submitted comments into account: review from manfredsteyer, review from manfredsteyer, and the force-push of the PR branch, after which the author's comment names 66f5b04cd as the commit to review.

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

CatalogSchemaHelper and the component envelope helpers are not specific
to Express: macros need them too. Move schema-helper.ts and its test from
inference-formats/express/ to utils/ without changing them.
Port the component tree of the Python builder: ComponentBuilderNode and
ComponentRef, and flattenComponentTree, which turns a tree of nodes into
the flat component list of updateComponents with deterministic IDs
namespaced under the root.

Nodes are recognized by class, so a plain data object with a component
property stays a value. Two components with the same explicit ID throw
A2uiValidationError instead of producing duplicate IDs.

An array of roots flattened without a rootId keeps each root's own ID
and gives a root without one the ID root_<index>. Python flattens all of
those roots under the prefix root, so their IDs collide.
Port the macros of the Python SDK to @a2ui/agent for v1.0, exported as
the Macros namespace so that their value types, such as Action, don't
clash with @a2ui/web_core.

- defineMacro and the param vocabulary define a macro; the arguments of
  render are typed from its parameters, and component IDs arrive as
  ComponentRefs.
- MacroExpander adds the macros to the inference catalogs and lowers the
  model's messages to the transport catalogs: it checks and coerces the
  arguments, merges the invocation's envelope fields onto the root,
  resolves macros on surfaces that mix catalogs, tracks surfaces and
  applies an onError policy. transformToInference passes messages
  through, as in Python.
@Varun-S10

Copy link
Copy Markdown
Collaborator

Hi @manfredsteyer, thank you for raising this PR. We verified the macro implementation and tests and they work well, but the branch is behind main with a merge conflict in schema-helper.ts and three @returns JSDoc tags in coercion.ts and expander.ts that need to use @return for the new lint rule. Could you please rebase on latest main after #4540 and update those three @returns tags so we can review it again?

@Varun-S10 Varun-S10 self-assigned this Dec 3, 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 Dec 3, 2026
@manfredsteyer
manfredsteyer force-pushed the feat/ts-agent-macros-expander branch from 66f5b04 to 8287dbe Compare December 3, 2026 12:28
@manfredsteyer

Copy link
Copy Markdown
Author

Thanks, @Varun-S10. This PR is rebased onto main together with #4540, and the three @returns tags are @return now. The new rules also flagged mergeEnvelopeFields in invocation-envelope.ts, whose @param named only one of its four parameters, so that text moved into the function's description. The commit to review is now 8287dbe.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants