Repository navigation
feat(ts_agent): port macros (MacroExpander) to @a2ui/agent - #4413
manfredsteyer wants to merge 9 commits into
Conversation
a8a0708 to
e06af57
Compare
There was a problem hiding this comment.
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'.
| transformCatalogs(catalogs: readonly CatalogApi[]): CatalogApi[] { | ||
| for (const catalog of catalogs) { | ||
| this.registerCatalog(catalog); | ||
| } |
There was a problem hiding this comment.
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);
}There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
| 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
- 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.
There was a problem hiding this comment.
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).
| 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']); |
There was a problem hiding this comment.
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;
}There was a problem hiding this comment.
Agreed, done in 3f487a4: each attribute's value is checked against its type in common_types.json, with a test for each case.
| for (const macro of macros) { | ||
| validateMacroName(macro.name); | ||
| } | ||
| this.macros = new Map(macros.map(macro => [macro.name, macro])); |
There was a problem hiding this comment.
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.
| 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
- 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.
There was a problem hiding this comment.
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)) { |
There was a problem hiding this comment.
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)
)There was a problem hiding this comment.
Done in 3f487a4, since the package also runs in browsers: an InternalError with "too much recursion" is recognized too, with a test.
|
From triage bot, analysis: For humansTL;DR Summary: Why flagged for triage: Suggestion:
Reply:
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/4413For softwareThis analysis is auto-created to help humans to triage this item. Please, do not treat it as a team decision. |
|
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. |
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.
e06af57 to
3f487a4
Compare
|
Thanks for checking, @Varun-S10. I've rebased the branch onto the latest |
|
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. |
|
@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
left a comment
There was a problem hiding this comment.
🤖 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?
- PR 1: move the shared envelope/schema helpers out of
src/inference-formats/express/schema-helper.tsintosrc/utils/, and addsrc/component-tree/(ComponentBuilderNode,ComponentRef,flattenComponentTree) with unit tests. - PR 2: add
src/macros/(defineMacro,param, coercion, envelope merging,MacroExpander) with unit tests. - PR 3: add the
macros.yamlconformance harness and updateREADME.md,KNOWN_GAPS.md,CHANGELOG.md, andblueprints/codebases/typescript/agents/a2ui_agent/codebase.blueprint.md.
Answers to your open questions
- Starting with a light tree layer is fine, as long as we use nominal classes matching Python (
ComponentBuilderNodeandComponentRef) instead of duck-typing plain objects on acomponentkey (see the inline comment with a failing test), and leaveagent/builder/builder.yamlinUNSUPPORTED_SUITESuntil a typed builder exists. - Not implementing
CatalogTransformermatches Python and fits #2865, sincetransformCatalogsreturns more catalogs than it receives andMacroExpanderalso lowers messages. - 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:
- Typesafe builders and a TypeScript emitter in
dart/a2ui_cli/lib/src/emitters/typescript/to generate Basic Catalog and custom-catalog classes extendingComponentBuilderNode, then enableconformance/agent/builder/builder.yaml. - Richer parameter types beyond the 15 conformance types (typed arrays, typed maps,
Extensions, singleCheckRule/DataBinding/FunctionCall/DynamicChildList, catalog sub-models, andoneOfunions). - Protocol v0.9 / v0.9.1 support for the 23 skipped v0.9 cases in
macros.yaml, if needed. - TypeScript examples in
docs/site/src/content/docs/guides/macros.mdxand a sharedblueprints/features/macros.blueprint.mdderived from Python and TypeScript. - 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' | ||
| ); |
There was a problem hiding this comment.
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'}},
},
},
},
],
},
},
]);
});There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
| @@ -0,0 +1,114 @@ | |||
| /* | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
Two small v1.0 gaps in these types:
FunctionCallis missingcatalogId?: string.DynamicValueis missing| null.
There was a problem hiding this comment.
- Added
catalogIdtoFunctionCallin feat(ts_agent): add macros #4541. I also removedreturnType, which v1.0 declares on the function definition in the catalog, not on the call. - I left
nullout ofDynamicValue, because v1.0'sDynamicValueincommon_types.jsondoesn't include it (string, number, boolean, array, object, binding or call), and neither does theDynamicValuealias in Python'sa2ui.builder.v1_0. If you'd rather acceptnullanyway, I can add it.
| } | ||
| coerced[name] = parameter.default; | ||
| continue; | ||
| } |
There was a problem hiding this comment.
Three small coercion edge cases:
- Line 51: treating
value === nulllikeundefinedrejects an explicit JSONnullon a requiredparam.dynamicValue(). - Line 104:
case 'dynamicNumber'should checkNumber.isFinite(value)likecase 'number', soNaNandInfinityare rejected. - Line 176:
toActionlets extra sibling keys through on{event: {name: 'save'}, extra: 1}and{functionCall: {'@call': 'fn'}, extra: 1}, andisFunctionCallaccepts an empty''for@callor non-objectargs.
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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/.
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
Two small parity items:
- Please add
transformToInference(messages)(identity pass-through) to match Python'sMacroExpanderand wireaction === 'transform_to_inference'inmacros-conformance.test.ts(case16_reverse_passthroughonly avoided failing because it defaults to v0.9). - Line 341: returning early when
this.macros.size === 0skipsdeleteSurfaceandtrackCreatedSurface, so an emptyMacroExpander([], {baseCatalogs})will not rewrite acreateSurfacewhosecatalogIdismacroCatalogId(or throwA2uiCatalogErrorwhenbaseCatalogsis empty).
There was a problem hiding this comment.
Both done in #4541.
transformToInferencepasses the messages through, and test(ts_agent): run the macros conformance suite and document macros #4542 runs16_reverse_passthrough. It doesn't depend on the version of the macros, so it runs despite its v0.9 envelope.- 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, soMacroExpander([], {baseCatalogs})rewrites acreateSurfacewhosecatalogIdis the macro catalog. Without base catalogs, both SDKs pass the messages through, so that case doesn't throwA2uiCatalogError.
| this.taken.add(namespaced); | ||
| return namespaced; | ||
| } | ||
| const name = componentName.toLowerCase(); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
@manfredsteyer @ditman @polina-c Quick heads-up on Python macro alignment so this PR does not hit surprises as we land the
🤖 Agent-generated |
|
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 On 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. |
|
Thanks for the heads-up, @jacobsimionato. In the split (#4540, #4541, #4542) the tree is made of |
|
Thanks for all the work; see you on the split PR @manfredsteyer! |
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
MacroExpanderto@a2ui/agentfor v1.0. The API follows Python's in camelCase (transformCatalogs,transformToInferenceCatalog,toCatalog,transformToTransport):renderreturns nested component objects, and the expander allocates and namespaces their IDs.param.*vocabulary taken from the macro suite instead of Zod, and the arguments ofrenderare typed from it.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/siteguide, and data model hydration withload()once a cross-SDK RFC has settled it.Verification
macros.yaml: 47 of 70 cases pass, including 42 of the 44 v1.0 cases. The skipped cases need v0.9 macros.yarn workspace @a2ui/agent test,lintandformat:checkpass after every commit. The commits are ordered for review one at a time.Open questions
MacroExpanderdoesn't implementCatalogTransformer, becausetransformCatalogsreturns more catalogs than it gets. Does that fit the direction of [RFC] Unifying Catalog Transformations and Message Translation via CatalogMessageTransformer & TransformerPipeline #2865?rendersees hold at runtime.KNOWN_GAPS.mdrecords 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 withMacroExpander(compile-dashboard.ts).🤖 Generated with Claude Code