# 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. """Unit tests for `ToolPointerBinder`.""" from __future__ import annotations from collections.abc import Collection, Mapping, Sequence from typing import Any, Literal import warnings from pydantic import BaseModel import pytest from a2ui.builder.v1_0 import ( Action, Button, Card, CheckRule, Column, ComponentBuilderNode, DynamicString, DynamicStringList, Text, ) from a2ui.core import A2uiCatalogError, A2uiValidationError, Catalog, CatalogApi from a2ui.core.basic_catalog import BasicCatalog from a2ui.core.schema import AgentToRendererMessage, ProtocolVersion from a2ui.inference_formats import to_message_models from a2ui.experimental.decision import ( ActionSpec, ConversationTurn, DecisionAnswer, DecisionBatch, DecisionDistribution, DecisionModelError, ExpressSurfaceSpec, MockDecisionModel, PointerSummary, QuestionKind, ) from a2ui.experimental.decision.binder import ( BindingState, ExpressSurfaceTemplate, ToolPointerBinder, ) from a2ui.experimental.decision.cascade import DecisionCascadeRouter from a2ui.transformers.macros import macro def _basic() -> CatalogApi: return BasicCatalog("v1.0") def _express(spec: ExpressSurfaceSpec) -> ExpressSurfaceTemplate: return ExpressSurfaceTemplate(spec, catalogs=[_basic()]) class _ScriptedBackend(MockDecisionModel): """Deterministic model returning explicit scripted answers by question ID.""" def __init__( self, answers: dict[str, DecisionAnswer | tuple[str, float] | float], *, fail_with: DecisionModelError | None = None, ) -> None: super().__init__() self._answers = answers self._fail_with = fail_with async def __call__( self, batch: DecisionBatch, ) -> list[DecisionAnswer]: self.batches.append(batch) if self._fail_with is not None: raise self._fail_with out: list[DecisionAnswer] = [] for q in batch.questions: spec = self._answers.get(q.id) if isinstance(spec, DecisionAnswer): out.append(spec) continue if q.kind is QuestionKind.BOOLEAN: yes_p = float(spec) if isinstance(spec, (int, float)) else 0.9 out.append( DecisionAnswer( question_id=q.id, distribution=DecisionDistribution( {"yes": yes_p, "no": 1.0 - yes_p} ), ) ) continue if isinstance(spec, tuple): opt, prob = spec cands = q.candidates() rest = (1.0 - prob) / max(1, len(cands) - 1) if len(cands) > 1 else 0.0 probs = {c: prob if c == opt else rest for c in cands} out.append( DecisionAnswer( question_id=q.id, distribution=DecisionDistribution(probs), ) ) continue out.append( self._answer_question( q, {"state": batch.state} if batch.state is not None else batch.shared_context, ) ) return tuple(out) @macro() def ProductCard( title: DynamicString, sku: str, stock_count: int, in_stock: bool = True, variant: Literal["compact", "detailed"] = "detailed", on_buy: Action | None = None, ) -> Card: """Renders a product card with title, SKU, stock badge, and optional buy button.""" badge = f"{sku} ({stock_count} left)" if in_stock else f"{sku} (out of stock)" children: list[ComponentBuilderNode] = [ Text(text=title), Text(text=badge, variant="caption" if variant == "compact" else "body"), ] if on_buy is not None: children.append(Button(child=Text(text="Buy"), action=on_buy)) return Card(child=Column(children=children)) @pytest.mark.asyncio async def test_bind_express_surface_and_root_sequence_wrapping() -> None: basic = _basic() weather_spec = ExpressSurfaceSpec( id="weather_card", description="Shows weather forecast for a city.", dsl=""" root = Card(Column([ Text($/city, variant="caption"), Text($/summary) ])) """, required_paths=("/city", "/summary"), ) list_spec = ExpressSurfaceSpec( id="items_list", description="Shows a list of search results.", dsl=""" root = Column(children=[item_row]) item_row = Text($/items/0/name) """, required_paths=("/items",), ) backend = _ScriptedBackend({"select:target": ("template:weather_card", 0.92)}) binder = ToolPointerBinder( backend, transport_catalogs=[basic], surface_templates=[_express(weather_spec), _express(list_spec)], ) result = await binder.bind_tool_output( "Show Seattle weather", "get_weather", {"city": "Seattle", "summary": "Sunny 72F"}, surface_id="weather_s1", ) assert not result.abstained assert result.target_id == "template:weather_card" assert result.decision_calls == 1 assert result.confidence == pytest.approx(0.92) dumped = [m.model_dump(by_alias=True, exclude_none=True) for m in result.messages] assert dumped[0]["createSurface"]["surfaceId"] == "weather_s1" assert dumped[-1]["updateDataModel"]["value"] == { "city": "Seattle", "summary": "Sunny 72F", } # Root sequence is wrapped as {"items": tool_output} and matches /items. seq_backend = _ScriptedBackend({"select:target": ("template:items_list", 0.88)}) seq_binder = ToolPointerBinder( seq_backend, transport_catalogs=[basic], surface_templates=[_express(weather_spec), _express(list_spec)], ) seq_result = await seq_binder.bind_tool_output( "List matching products", "list_items", [{"name": "Alpha"}, {"name": "Beta"}], surface_id="list_s1", ) assert not seq_result.abstained assert seq_result.target_id == "template:items_list" seq_dumped = [ m.model_dump(by_alias=True, exclude_none=True) for m in seq_result.messages ] assert seq_dumped[-1]["updateDataModel"]["value"] == { "items": [{"name": "Alpha"}, {"name": "Beta"}] } @pytest.mark.asyncio async def test_bind_product_card_macro_all_slot_kinds_and_lowering() -> None: basic = _basic() macro_cid = "urn:test:macros" tkey = f"{macro_cid}:ProductCard" backend = _ScriptedBackend({ "select:target": (tkey, 0.94), f"bind:{tkey}:title": ("/title", 0.95), f"bind:{tkey}:sku": ("/sku", 0.95), f"bind:{tkey}:stock_count": ("/inventory", 0.92), f"bind:{tkey}:in_stock": 0.91, f"bind:{tkey}:variant": ("compact", 0.85), f"bind:{tkey}:on_buy": ("add_to_cart", 0.90), }) binder = ToolPointerBinder( backend, transport_catalogs=[basic], macros=[ProductCard], macro_catalog_id=macro_cid, ) result = await binder.bind_tool_output( "Show running shoes product card", "get_product", {"title": "Trail Runner", "sku": "SKU-42", "inventory": 7}, actions=[ ActionSpec(id="add_to_cart", label="Add to Cart", context={"sku": "/sku"}) ], surface_id="prod_s1", ) assert not result.abstained assert result.target_id == tkey assert result.decision_calls == 1 assert result.bindings["title"] == {"@path": "/title"} assert result.bindings["sku"] == "SKU-42" assert result.bindings["stock_count"] == 7 assert result.bindings["in_stock"] is True assert result.bindings["variant"] == "compact" assert result.bindings["on_buy"] == { "event": {"name": "add_to_cart", "context": {"sku": {"@path": "/sku"}}} } # Verify macro was lowered to BasicCatalog primitives via lower_for_transport. dumped = [m.model_dump(by_alias=True, exclude_none=True) for m in result.messages] comp_types = [c["component"] for c in dumped[1]["updateComponents"]["components"]] assert "ProductCard" not in comp_types assert "Card" in comp_types assert "Button" in comp_types # Verify explicit state string was sent on DecisionBatch (not shared_context). assert backend.batches[0].state is not None assert backend.batches[0].shared_context == {} @pytest.mark.asyncio async def test_client_side_template_passthrough_and_macro_shadowing_parity() -> None: basic = _basic() cst_catalog = Catalog.from_json( { "catalogId": "urn:test:cst", "components": { "ProductCard": { "type": "object", "description": "Renders a product card.", "properties": { "title": {"$ref": "common_types.json#/$defs/DynamicString"}, "sku": {"type": "string"}, "stock_count": {"type": "integer"}, "in_stock": {"type": "boolean"}, "variant": { "type": "string", "enum": ["compact", "detailed"], }, "on_buy": {"$ref": "common_types.json#/$defs/Action"}, }, "required": ["title", "sku", "stock_count"], } }, }, protocol_version=ProtocolVersion.V1_0, ) cst_key = "urn:test:cst:ProductCard" backend = _ScriptedBackend({ "select:target": (cst_key, 0.91), f"bind:{cst_key}:title": ("/title", 0.95), f"bind:{cst_key}:sku": ("/sku", 0.95), f"bind:{cst_key}:stock_count": ("/inventory", 0.95), f"bind:{cst_key}:in_stock": 0.2, f"bind:{cst_key}:variant": ("detailed", 0.9), f"bind:{cst_key}:on_buy": ("none", 0.8), }) # Pass both macros=[ProductCard] and cst_catalog: CST shadows the macro. binder = ToolPointerBinder( backend, transport_catalogs=[basic, cst_catalog], macros=[ProductCard], macro_catalog_id="urn:test:macros", ) assert binder.target_keys() == (cst_key,) result = await binder.bind_tool_output( "Show product", "get_product", {"title": "Boots", "sku": "SKU-99", "inventory": 3}, actions=["buy_now"], surface_id="cst_s1", ) assert not result.abstained assert result.target_id == cst_key assert result.bindings["in_stock"] is False assert "on_buy" not in result.bindings # Optional Action chose "none" # CST passes through unexpanded on the wire. dumped = [m.model_dump(by_alias=True, exclude_none=True) for m in result.messages] assert dumped[0]["createSurface"]["catalogId"] == "urn:test:cst" root_comp = dumped[1]["updateComponents"]["components"][0] assert root_comp["component"] == "ProductCard" assert root_comp["title"] == {"@path": "/title"} assert root_comp["sku"] == "SKU-99" assert root_comp["stock_count"] == 3 assert root_comp["in_stock"] is False def test_macro_registration_rejects_unsupported_parameters() -> None: basic = _basic() backend = MockDecisionModel() class _NestedItem(BaseModel): code: str @macro() def WithChild(title: DynamicString, body: Text) -> Card: return Card(child=Column(children=[Text(text=title), body])) @macro() def WithChildList(title: DynamicString, items: list[Text]) -> Column: return Column(children=[Text(text=title), *items]) @macro() def WithCheckRule(title: DynamicString, rule: CheckRule) -> Card: del rule return Card(child=Text(text=title)) @macro() def WithNestedModel(title: DynamicString, meta: _NestedItem) -> Card: return Card(child=Column(children=[Text(text=title), Text(text=meta.code)])) @macro() def ZeroBindableSlots(flag: bool = True) -> Text: return Text(text="yes" if flag else "no") def not_a_macro(title: str) -> str: return title for bad_macro in ( WithChild, WithChildList, WithCheckRule, WithNestedModel, ZeroBindableSlots, not_a_macro, ): with pytest.raises(A2uiCatalogError): ToolPointerBinder( backend, transport_catalogs=[basic], macros=[bad_macro], ) @pytest.mark.asyncio async def test_splits_into_two_calls_when_pairs_exceed_400() -> None: basic = _basic() # Create 10 CST components each with 3 DynamicString slots + 15 string pointers: # 10 * 3 * 15 = 450 slot pairs + 11 target candidates = 461 > 400 -> 2 calls! components: dict[str, Any] = {} for idx in range(10): components[f"Card{idx}"] = { "type": "object", "description": f"Card variant {idx}", "properties": { "a": {"$ref": "common_types.json#/$defs/DynamicString"}, "b": {"$ref": "common_types.json#/$defs/DynamicString"}, "c": {"$ref": "common_types.json#/$defs/DynamicString"}, }, "required": ["a", "b", "c"], } large_cst = Catalog.from_json( {"catalogId": "urn:test:large", "components": components}, protocol_version=ProtocolVersion.V1_0, ) winner_key = "urn:test:large:Card3" backend = _ScriptedBackend({ "select:target": (winner_key, 0.90), f"bind:{winner_key}:a": ("/f0", 0.9), f"bind:{winner_key}:b": ("/f1", 0.9), f"bind:{winner_key}:c": ("/f2", 0.9), }) binder = ToolPointerBinder( backend, transport_catalogs=[basic, large_cst], template_catalogs=["urn:test:large"], ) payload = {f"f{i}": f"val_{i}" for i in range(15)} result = await binder.bind_tool_output("Show card 3", "fetch_data", payload) assert not result.abstained assert result.decision_calls == 2 assert len(backend.batches) == 2 assert [q.id for q in backend.batches[0].questions] == ["select:target"] assert {q.id for q in backend.batches[1].questions} == { f"bind:{winner_key}:a", f"bind:{winner_key}:b", f"bind:{winner_key}:c", } # Early abstention on call 1 avoids call 2. abstain_backend = _ScriptedBackend({"select:target": ("none", 0.85)}) abstain_binder = ToolPointerBinder( abstain_backend, transport_catalogs=[basic, large_cst], template_catalogs=["urn:test:large"], ) abstain_res = await abstain_binder.bind_tool_output( "Unrelated text", "fetch_data", payload ) assert abstain_res.abstained assert abstain_res.decision_calls == 1 assert len(abstain_backend.batches) == 1 @pytest.mark.asyncio async def test_abstention_conditions_and_backend_error_propagation() -> None: basic = _basic() macro_cid = "urn:test:macros" tkey = f"{macro_cid}:ProductCard" # 1. Empty payload / empty sequence / scalar -> abstain with 0 calls. zero_backend = _ScriptedBackend({}) binder = ToolPointerBinder( zero_backend, transport_catalogs=[basic], macros=[ProductCard], macro_catalog_id=macro_cid, ) for empty_payload in ({}, [], "not json", 123): res = await binder.bind_tool_output("Show", "tool", empty_payload) assert res.abstained assert res.messages == [] assert res.decision_calls == 0 assert len(zero_backend.batches) == 0 # 2. Target selection returns "none". none_binder = ToolPointerBinder( _ScriptedBackend({"select:target": ("none", 0.9)}), transport_catalogs=[basic], macros=[ProductCard], macro_catalog_id=macro_cid, ) none_res = await none_binder.bind_tool_output( "Show", "tool", {"title": "A", "sku": "S", "inventory": 1} ) assert none_res.abstained assert "none" in none_res.reason # 3. Target confidence below min_confidence (0.65). low_conf_binder = ToolPointerBinder( _ScriptedBackend({"select:target": (tkey, 0.52)}), transport_catalogs=[basic], macros=[ProductCard], macro_catalog_id=macro_cid, min_confidence=0.65, ) low_res = await low_conf_binder.bind_tool_output( "Show", "tool", {"title": "A", "sku": "S", "inventory": 1} ) assert low_res.abstained assert "min_confidence" in low_res.reason # 4. Missing required slot (backend returns zero-prob / none for required slot). missing_slot_binder = ToolPointerBinder( _ScriptedBackend({ "select:target": (tkey, 0.95), f"bind:{tkey}:title": DecisionAnswer( question_id=f"bind:{tkey}:title", distribution=DecisionDistribution({"/title": 0.0}), ), f"bind:{tkey}:sku": ("/sku", 0.9), f"bind:{tkey}:stock_count": ("/inventory", 0.9), }), transport_catalogs=[basic], macros=[ProductCard], macro_catalog_id=macro_cid, ) missing_res = await missing_slot_binder.bind_tool_output( "Show", "tool", {"title": "A", "sku": "S", "inventory": 1} ) assert missing_res.abstained assert "required slot" in missing_res.reason # 5. DecisionModelError propagates without silent fallback. err_binder = ToolPointerBinder( _ScriptedBackend( {}, fail_with=DecisionModelError("safety blocked"), ), transport_catalogs=[basic], macros=[ProductCard], macro_catalog_id=macro_cid, ) with pytest.raises(DecisionModelError, match="safety blocked"): await err_binder.bind_tool_output( "Show", "tool", {"title": "A", "sku": "S", "inventory": 1} ) def test_tool_pointer_binder_emits_experimental_warning( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.delenv("A2UI_SUPPRESS_EXPERIMENTAL_FEATURE_WARNINGS", raising=False) with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") ToolPointerBinder( MockDecisionModel(), transport_catalogs=[_basic()], ) assert any("[EXPERIMENTAL] ToolPointerBinder" in str(w.message) for w in caught) @pytest.mark.asyncio async def test_update_data_model_redacts_secrets_and_excluded_paths() -> None: basic = _basic() spec = ExpressSurfaceSpec( id="profile", description="User profile card", dsl="root = Text($/name)", required_paths=("/name",), ) backend = MockDecisionModel( scripted_answers={"select:target": ("template:profile", 0.95)} ) binder = ToolPointerBinder( backend, transport_catalogs=[basic], surface_templates=[_express(spec)], ) result = await binder.bind_tool_output( "Show profile", "get_profile", { "name": "Ada", "apiKey": "sk_live_" + ("x" * 72), "internal_note": "private", "nested": {"password": "pw", "role": "engineer"}, }, exclude=("/internal_note",), ) assert not result.abstained data_msgs = [ m.model_dump(by_alias=True, exclude_none=True)["updateDataModel"]["value"] for m in result.messages if "updateDataModel" in m.model_dump(by_alias=True, exclude_none=True) ] assert len(data_msgs) == 1 assert data_msgs[0] == {"name": "Ada", "nested": {"role": "engineer"}} @pytest.mark.asyncio async def test_omitted_select_target_answer_raises_decision_backend_error() -> None: class _EmptyModel(MockDecisionModel): async def __call__(self, batch: DecisionBatch) -> list[DecisionAnswer]: del batch return [] basic = _basic() spec = ExpressSurfaceSpec( id="profile", description="User profile card", dsl="root = Text($/name)", required_paths=("/name",), ) binder = ToolPointerBinder( _EmptyModel(), transport_catalogs=[basic], surface_templates=[_express(spec)], ) with pytest.raises(DecisionModelError, match="select:target"): await binder.bind_tool_output("Show profile", "get_profile", {"name": "Ada"}) @pytest.mark.asyncio async def test_plain_primitive_only_macro_binds_literals_and_lowers() -> None: basic = _basic() macro_cid = "urn:test:macros" @macro() def StatusBanner( headline: str, count: int, severity: Literal["info", "warning", "error"] = "info", dismissible: bool = False, ) -> Card: """Displays a status banner using only plain primitive parameters.""" suffix = " (dismissible)" if dismissible else "" return Card( child=Column( children=[ Text(text=f"[{severity.upper()}] {headline}{suffix}"), Text(text=f"Affected: {count}"), ] ) ) tkey = f"{macro_cid}:StatusBanner" backend = _ScriptedBackend({ "select:target": (tkey, 0.93), f"bind:{tkey}:headline": ("/message", 0.96), f"bind:{tkey}:count": ("/hosts", 0.94), f"bind:{tkey}:severity": ("warning", 0.91), f"bind:{tkey}:dismissible": 0.88, }) binder = ToolPointerBinder( backend, transport_catalogs=[basic], macros=[StatusBanner], macro_catalog_id=macro_cid, ) result = await binder.bind_tool_output( "Show degraded status banner", "check_status", {"message": "High latency in us-west", "hosts": 3}, surface_id="banner_s1", ) assert not result.abstained assert result.target_id == tkey assert result.bindings == { "headline": "High latency in us-west", "count": 3, "severity": "warning", "dismissible": True, } dumped = [m.model_dump(by_alias=True, exclude_none=True) for m in result.messages] comp_types = [c["component"] for c in dumped[1]["updateComponents"]["components"]] assert "StatusBanner" not in comp_types assert "Card" in comp_types @pytest.mark.asyncio async def test_optional_nullable_macro_parameters_bind_and_omit() -> None: basic = _basic() macro_cid = "urn:test:macros" @macro() def NullableNoteCard( title: DynamicString, subtitle: str | None = None, retries: int | None = None, tone: Literal["neutral", "alert"] | None = None, ) -> Card: """Displays a note card with optional nullable parameters.""" children: list[Any] = [Text(text=title)] if subtitle is not None: children.append(Text(text=subtitle)) if retries is not None: children.append(Text(text=f"Retries: {retries}")) if tone is not None: children.append(Text(text=f"Tone: {tone}")) return Card(child=Column(children=children)) tkey = f"{macro_cid}:NullableNoteCard" # Case 1: optional nullable slots bound backend_bound = _ScriptedBackend({ f"bind:{tkey}:title": ("/title", 0.95), f"bind:{tkey}:subtitle": ("/detail", 0.91), f"bind:{tkey}:retries": ("/attempts", 0.90), f"bind:{tkey}:tone": ("alert", 0.89), }) binder_bound = ToolPointerBinder( backend_bound, transport_catalogs=[basic], macros=[NullableNoteCard], macro_catalog_id=macro_cid, ) bound_res = await binder_bound.fill_macro( "Show full note", {"title": "Job failed", "detail": "Timeout after 30s", "attempts": 2}, macro_name="NullableNoteCard", surface_id="note_bound", ) assert not bound_res.abstained assert bound_res.decision_calls == 1 assert bound_res.bindings == { "title": {"@path": "/title"}, "subtitle": "Timeout after 30s", "retries": 2, "tone": "alert", } # Case 2: optional nullable slots omitted ("none") backend_omit = _ScriptedBackend({ f"bind:{tkey}:title": ("/title", 0.95), f"bind:{tkey}:subtitle": ("none", 0.85), f"bind:{tkey}:retries": ("none", 0.85), f"bind:{tkey}:tone": ("none", 0.85), }) binder_omit = ToolPointerBinder( backend_omit, transport_catalogs=[basic], macros=[NullableNoteCard], macro_catalog_id=macro_cid, ) omit_res = await binder_omit.fill_macro( "Show minimal note", {"title": "Job started"}, macro_name=tkey, surface_id="note_omit", ) assert not omit_res.abstained assert omit_res.bindings == {"title": {"@path": "/title"}} @pytest.mark.asyncio async def test_fill_macro_targeted_shadowed_and_auto_selected() -> None: basic = _basic() macro_cid = "urn:test:macros" tkey = f"{macro_cid}:ProductCard" express_spec = ExpressSurfaceSpec( id="fallback_text", description="Fallback text", dsl="root = Text($/title)", required_paths=("/title",), ) # Auto-select among registered macros only (excludes Express targets). backend = _ScriptedBackend({ "select:target": (tkey, 0.96), f"bind:{tkey}:title": ("/title", 0.95), f"bind:{tkey}:sku": ("/sku", 0.95), f"bind:{tkey}:stock_count": ("/inventory", 0.92), f"bind:{tkey}:in_stock": 0.91, f"bind:{tkey}:variant": ("detailed", 0.88), f"bind:{tkey}:on_buy": ("none", 0.80), }) binder = ToolPointerBinder( backend, transport_catalogs=[basic], macros=[ProductCard], surface_templates=[_express(express_spec)], macro_catalog_id=macro_cid, ) auto_res = await binder.fill_macro( "Show product card", {"title": "Trail Runner", "sku": "SKU-7", "inventory": 4}, surface_id="auto_macro", ) assert not auto_res.abstained assert auto_res.target_id == tkey select_q = backend.batches[0].questions[0] assert select_q.id == "select:target" assert select_q.options == (tkey,) # Unknown macro name raises A2uiCatalogError. with pytest.raises(A2uiCatalogError, match="Unknown macro target"): await binder.fill_macro( "Show missing", {"title": "X"}, macro_name="DoesNotExist", ) # Binder with no macros raises A2uiCatalogError. no_macro_binder = ToolPointerBinder( backend, transport_catalogs=[basic], surface_templates=[_express(express_spec)], ) with pytest.raises(A2uiCatalogError, match="No @macro targets"): await no_macro_binder.fill_macro("Show product", {"title": "X"}) # CST-shadowed macro resolves to the shadowing CST when targeted by bare name. cst_catalog = Catalog.from_json( { "catalogId": "urn:test:cst", "components": { "ProductCard": { "type": "object", "description": "CST ProductCard", "properties": { "title": {"$ref": "common_types.json#/$defs/DynamicString"}, "sku": {"type": "string"}, "stock_count": {"type": "integer"}, }, "required": ["title", "sku", "stock_count"], } }, }, protocol_version=ProtocolVersion.V1_0, ) cst_key = "urn:test:cst:ProductCard" cst_backend = _ScriptedBackend({ f"bind:{cst_key}:title": ("/title", 0.95), f"bind:{cst_key}:sku": ("/sku", 0.95), f"bind:{cst_key}:stock_count": ("/inventory", 0.95), }) shadow_binder = ToolPointerBinder( cst_backend, transport_catalogs=[basic, cst_catalog], macros=[ProductCard], macro_catalog_id=macro_cid, ) shadow_res = await shadow_binder.fill_macro( "Show product", {"title": "Boots", "sku": "SKU-9", "inventory": 2}, macro_name="ProductCard", surface_id="shadow_s1", ) assert not shadow_res.abstained assert shadow_res.target_id == cst_key assert shadow_res.decision_calls == 1 assert shadow_res.confidence == 1.0 def _dump(messages: Sequence[AgentToRendererMessage]) -> list[dict[str, Any]]: return [m.model_dump(by_alias=True, exclude_none=True) for m in messages] def _data_model(messages: Sequence[AgentToRendererMessage]) -> Any: values = [ d["updateDataModel"]["value"] for d in _dump(messages) if "updateDataModel" in d ] assert len(values) == 1 return values[0] def _cst_catalog(catalog_id: str, components: dict[str, Any]) -> Catalog: return Catalog.from_json( {"catalogId": catalog_id, "components": components}, protocol_version=ProtocolVersion.V1_0, ) _SUMMARY_CARD = { "type": "object", "description": "Shows a one-line summary.", "properties": {"title": {"$ref": "common_types.json#/$defs/DynamicString"}}, "required": ["title"], } @pytest.mark.asyncio async def test_data_model_redaction_matches_the_pointers_offered() -> None: profile = _express( ExpressSurfaceSpec( id="profile", description="User profile card", dsl="root = Text($/name)", required_paths=("/name",), ) ) binder = ToolPointerBinder( MockDecisionModel( scripted_answers={"select:target": ("template:profile", 0.95)} ), transport_catalogs=[_basic()], surface_templates=[profile], is_secret=lambda ptr: ptr.key in ("password", "dob"), ) result = await binder.bind_tool_output( "Show profile", "get_profile", { "name": "Ada", "dob": "1815-12-10", # A tuple is a sequence the inspector walks, so it is redacted too. "users": ( {"name": "Ada", "password": "pw", "email": "ada@example.com"}, {"name": "Bob", "password": "pw", "email": "bob@example.com"}, ), "rows": [{"id": 1}, {"id": 2}], "constructor": {"polluted": True}, # The custom predicate replaces the default, so this key stays. "total_tokens": 12, }, exclude=("/users/email", "/rows/0"), ) assert not result.abstained assert _data_model(result.messages) == { "name": "Ada", "users": [{"name": "Ada"}, {"name": "Bob"}], # An excluded element is blanked, so `/rows/1` still addresses id 2. "rows": [None, {"id": 2}], "total_tokens": 12, } @pytest.mark.asyncio async def test_enum_slot_with_none_value_binds_none_and_can_stay_unset() -> None: macro_cid = "urn:test:macros" @macro() def FramedImage( url: DynamicString, fit: Literal["contain", "cover", "none"], border: Literal["none", "thin", "thick"] = "thin", ) -> Card: """Shows an image URL with a fit and a border.""" return Card(child=Text(text=f"{fit}/{border}")) tkey = f"{macro_cid}:FramedImage" async def fill(border_choice: str) -> tuple[Any, _ScriptedBackend]: backend = _ScriptedBackend({ f"bind:{tkey}:url": ("/url", 0.95), f"bind:{tkey}:fit": ("none", 0.9), f"bind:{tkey}:border": (border_choice, 0.9), }) binder = ToolPointerBinder( backend, transport_catalogs=[_basic()], macros=[FramedImage], macro_catalog_id=macro_cid, ) result = await binder.fill_macro( "Show the image", {"url": "https://example.com/a.png"}, macro_name=tkey ) return result, backend # "none" is a value of both enums, so choosing it binds it. bound, backend = await fill("none") assert not bound.abstained assert bound.bindings["fit"] == "none" assert bound.bindings["border"] == "none" questions = {q.id: q for q in backend.batches[0].questions} # The required slot offers only its enum values. assert questions[f"bind:{tkey}:fit"].candidates() == ("contain", "cover", "none") # The optional slot offers a separate way to leave it unset. border_candidates = questions[f"bind:{tkey}:border"].candidates() assert border_candidates == ("none", "thin", "thick", "(unset)") unset, _ = await fill("(unset)") assert not unset.abstained assert "border" not in unset.bindings def test_express_template_rejects_unknown_catalog_and_several_surfaces() -> None: with pytest.raises(A2uiCatalogError, match="unknown catalog_id"): ExpressSurfaceTemplate( ExpressSurfaceSpec( id="bad_catalog", description="Names a catalog that is not registered.", dsl="root = Text($/name)", catalog_id="urn:test:missing", ), catalogs=[_basic()], ) with pytest.raises(A2uiCatalogError, match="must define one surface"): ExpressSurfaceTemplate( ExpressSurfaceSpec( id="two_surfaces", description="Defines two surfaces.", dsl='surface("a")\nroot = Text("x")\nsurface("b")\nroot = Text("y")', ), catalogs=[_basic()], ) @pytest.mark.asyncio async def test_express_template_uses_bound_surface_id_defaults_and_macros() -> None: basic = _basic() macro_cid = "urn:test:macros" @macro() def Badge(label: DynamicString) -> Text: """Shows a short label.""" return Text(text=label, variant="caption") weather = ExpressSurfaceTemplate( ExpressSurfaceSpec( id="weather", description="Shows the weather for a city.", # The header names a fixed surface, and the template sets a default. dsl='surface("weather")\n$/ui/tab = "overview"\nroot = Badge($/city)', # Naming a catalog must not hide the macro catalog. catalog_id=basic.catalog_id, required_paths=("/city",), ), catalogs=[basic], macros=[Badge], macro_catalog_id=macro_cid, ) binder = ToolPointerBinder( MockDecisionModel( scripted_answers={"select:target": ("template:weather", 0.95)} ), transport_catalogs=[basic], macros=[Badge], macro_catalog_id=macro_cid, surface_templates=[weather], ) surface_ids = [] for surface_id in ("tool_surface_1", "tool_surface_2"): result = await binder.bind_tool_output( "Weather", "get_weather", {"city": "Seattle"}, surface_id=surface_id ) assert not result.abstained dumped = _dump(result.messages) surface_ids.append(dumped[0]["createSurface"]["surfaceId"]) assert _data_model(result.messages) == { "ui": {"tab": "overview"}, "city": "Seattle", } components = dumped[0]["createSurface"]["components"] assert [c["component"] for c in components] == ["Text"] # Each call gets its own surface, so a session can show the tool twice. assert surface_ids == ["tool_surface_1", "tool_surface_2"] class _BuilderTemplate: """A surface template that builds its messages without Express.""" id = "plain" description = "Shows the name as text." required_paths = ("/name",) def __init__(self, catalog_id: str, *, fixed_surface_id: str | None = None) -> None: self._catalog_id = catalog_id self._fixed_surface_id = fixed_surface_id def render( self, surface_id: str, data_model: Mapping[str, Any] ) -> list[AgentToRendererMessage]: sid = self._fixed_surface_id or surface_id return list( to_message_models([{ "version": "1.0", "createSurface": { "surfaceId": sid, "catalogId": self._catalog_id, "components": [{ "id": "root", "component": "Text", "text": {"@path": "/name"}, }], "dataModel": dict(data_model), }, }]) ) @pytest.mark.asyncio async def test_binds_a_surface_template_that_is_not_express() -> None: basic = _basic() model = MockDecisionModel( scripted_answers={"select:target": ("template:plain", 0.9)} ) binder = ToolPointerBinder( model, transport_catalogs=[basic], surface_templates=[_BuilderTemplate(basic.catalog_id)], ) result = await binder.bind_tool_output( "Show", "get_user", {"name": "Ada"}, surface_id="s1" ) assert result.target_id == "template:plain" assert _dump(result.messages)[0]["createSurface"]["dataModel"] == {"name": "Ada"} stray = ToolPointerBinder( model, transport_catalogs=[basic], surface_templates=[_BuilderTemplate(basic.catalog_id, fixed_surface_id="x")], ) with pytest.raises(A2uiValidationError, match="instead of 's1'"): await stray.bind_tool_output( "Show", "get_user", {"name": "Ada"}, surface_id="s1" ) def test_rejects_reserved_macro_parameters_and_pre_v1_catalogs() -> None: @macro() def OrderCard(id: str, title: DynamicString) -> Card: return Card(child=Text(text=title)) with pytest.raises(A2uiCatalogError, match="reserved parameter"): ToolPointerBinder( MockDecisionModel(), transport_catalogs=[_basic()], macros=[OrderCard] ) with pytest.raises(A2uiCatalogError, match="emits v1.0 messages"): ToolPointerBinder( MockDecisionModel(), transport_catalogs=[BasicCatalog(ProtocolVersion.V0_9_1)], ) @pytest.mark.asyncio @pytest.mark.parametrize("pointer", ["/items/\u00b2", "/items/01"]) async def test_pointer_with_an_invalid_array_index_does_not_resolve( pointer: str, ) -> None: macro_cid = "urn:test:macros" @macro() def Note(body: str) -> Text: """Shows a note.""" return Text(text=body) def inspector( data: Mapping[str, Any], *, exclude: Collection[str], mutable_paths: Collection[str], labels: Mapping[str, str] | None, ) -> list[PointerSummary]: return [PointerSummary(path=pointer, value_type="string")] tkey = f"{macro_cid}:Note" binder = ToolPointerBinder( _ScriptedBackend({f"bind:{tkey}:body": (pointer, 0.9)}), transport_catalogs=[_basic()], macros=[Note], macro_catalog_id=macro_cid, pointer_inspector=inspector, ) result = await binder.fill_macro( "Show", {"items": ["zero", "one", "two"]}, macro_name="Note" ) # "\u00b2" is a digit to `str.isdigit` but not an array index, and an index # has no leading zero, so neither pointer reads an element. assert result.abstained assert result.reason == "missing required slot 'body'" @pytest.mark.asyncio async def test_string_list_slot_only_offers_arrays_of_strings() -> None: macro_cid = "urn:test:macros" @macro() def TagList(tags: DynamicStringList) -> Text: """Shows tags.""" return Text(text="tags") tkey = f"{macro_cid}:TagList" backend = _ScriptedBackend({f"bind:{tkey}:tags": ("/tags", 0.9)}) binder = ToolPointerBinder( backend, transport_catalogs=[_basic()], macros=[TagList], macro_catalog_id=macro_cid, ) result = await binder.fill_macro( "Show tags", {"tags": ["a", "b"], "users": [{"name": "Ada"}], "counts": [1, 2]}, macro_name="TagList", ) assert result.bindings == {"tags": {"@path": "/tags"}} assert backend.batches[0].questions[0].options == ("/tags",) no_strings = await binder.fill_macro( "Show tags", {"users": [{"name": "Ada"}], "counts": [1, 2]}, macro_name="TagList", ) assert no_strings.abstained assert "no compatible payload pointers" in no_strings.reason @pytest.mark.asyncio async def test_state_formatter_context_conversation_and_array_wrapper_key() -> None: seen: list[BindingState] = [] def formatter(state: BindingState) -> str: seen.append(state) return f"Intention: {state.intent} ({state.context['locale']})" rows = _express( ExpressSurfaceSpec( id="rows", description="Lists rows.", dsl="root = Text($/rows/0/name)", required_paths=("/rows",), ) ) backend = _ScriptedBackend({"select:target": ("template:rows", 0.9)}) binder = ToolPointerBinder( backend, transport_catalogs=[_basic()], surface_templates=[rows], state_formatter=formatter, array_wrapper_key="rows", ) history = (ConversationTurn(role="user", content="Liste des produits"),) result = await binder.bind_tool_output( "Montrer", "list_items", [{"name": "Alpha"}], context={"locale": "fr"}, conversation=history, ) assert not result.abstained assert _data_model(result.messages) == {"rows": [{"name": "Alpha"}]} assert seen[0].source_name == "list_items" assert [p.path for p in seen[0].pointers] == ["/rows"] batch = backend.batches[0] assert batch.state == "Intention: Montrer (fr)" assert batch.shared_context == {"locale": "fr"} assert batch.conversation == history def test_ambiguous_bare_component_target_is_rejected() -> None: first = _cst_catalog("urn:test:first", {"SummaryCard": _SUMMARY_CARD}) second = _cst_catalog("urn:test:second", {"SummaryCard": _SUMMARY_CARD}) catalogs = [_basic(), first, second] with pytest.raises(A2uiCatalogError, match="ambiguous.*urn:test:first"): ToolPointerBinder( MockDecisionModel(), transport_catalogs=catalogs, component_targets=["SummaryCard"], ) qualified = ToolPointerBinder( MockDecisionModel(), transport_catalogs=catalogs, component_targets=[("urn:test:second", "SummaryCard")], ) assert qualified.target_keys() == ("urn:test:second:SummaryCard",) @pytest.mark.asyncio async def test_fill_macro_rejects_bare_name_shared_by_several_targets() -> None: @macro() def SummaryCard(title: DynamicString) -> Card: """Shows a one-line summary.""" return Card(child=Text(text=title)) first = _cst_catalog("urn:test:first", {"SummaryCard": _SUMMARY_CARD}) second = _cst_catalog("urn:test:second", {"SummaryCard": _SUMMARY_CARD}) binder = ToolPointerBinder( _ScriptedBackend({"bind:urn:test:second:SummaryCard:title": ("/title", 0.9)}), transport_catalogs=[_basic(), first, second], macros=[SummaryCard], ) assert binder.target_keys() == ( "urn:test:first:SummaryCard", "urn:test:second:SummaryCard", ) with pytest.raises(A2uiCatalogError, match="ambiguous"): await binder.fill_macro("Show", {"title": "Hi"}, macro_name="SummaryCard") result = await binder.fill_macro( "Show", {"title": "Hi"}, macro_name="urn:test:second:SummaryCard" ) assert result.target_id == "urn:test:second:SummaryCard" def test_template_catalogs_opt_in_to_component_discovery() -> None: design_system = _cst_catalog( "urn:test:design", {"Badge": _SUMMARY_CARD, "Avatar": _SUMMARY_CARD}, ) catalogs = [_basic(), design_system] # A catalog of primitives is not a set of whole-surface targets by default. assert ( ToolPointerBinder( MockDecisionModel(), transport_catalogs=catalogs ).target_keys() == () ) opted_in = ToolPointerBinder( MockDecisionModel(), transport_catalogs=catalogs, template_catalogs=["urn:test:design"], ) assert opted_in.target_keys() == ("urn:test:design:Badge", "urn:test:design:Avatar") with pytest.raises(A2uiCatalogError, match="not in transport_catalogs"): ToolPointerBinder( MockDecisionModel(), transport_catalogs=catalogs, template_catalogs=["urn:test:missing"], ) with pytest.raises(ValueError, match="not both"): ToolPointerBinder( MockDecisionModel(), transport_catalogs=catalogs, component_targets=[("urn:test:design", "Badge")], template_catalogs=["urn:test:design"], ) def _answer(question_id: str, probabilities: dict[str, float]) -> DecisionAnswer: return DecisionAnswer( question_id=question_id, distribution=DecisionDistribution(probabilities) ) @pytest.mark.asyncio async def test_model_cannot_pick_a_target_that_was_not_offered() -> None: needs_city = _express( ExpressSurfaceSpec( id="weather", description="Weather", dsl="root = Text($/city)", required_paths=("/city",), ) ) macro_cid = "urn:test:macros" tkey = f"{macro_cid}:ProductCard" # The payload has no "/city", so the template is registered but not offered. backend = _ScriptedBackend( {"select:target": _answer("select:target", {"template:weather": 0.99})} ) binder = ToolPointerBinder( backend, transport_catalogs=[_basic()], macros=[ProductCard], macro_catalog_id=macro_cid, surface_templates=[needs_city], ) with pytest.raises(DecisionModelError, match="unknown candidate") as exc_info: await binder.bind_tool_output( "Show", "get_product", {"title": "A", "sku": "S", "inventory": 1} ) assert exc_info.value.code == "DECISION_INVALID_OPTION" select_question = backend.batches[0].questions[0] assert select_question.id == "select:target" assert select_question.options == (tkey,) @pytest.mark.asyncio async def test_rejects_answers_that_do_not_fit_their_question() -> None: macro_cid = "urn:test:macros" tkey = f"{macro_cid}:ProductCard" payload = {"title": "A", "sku": "S", "inventory": 1, "api_key": "k"} good = { f"bind:{tkey}:title": ("/title", 0.95), f"bind:{tkey}:sku": ("/sku", 0.95), f"bind:{tkey}:stock_count": ("/inventory", 0.95), f"bind:{tkey}:variant": ("compact", 0.9), } def binder_for(overrides: dict[str, Any], **kwargs: Any) -> ToolPointerBinder: return ToolPointerBinder( _ScriptedBackend({**good, **overrides}), transport_catalogs=[_basic()], macros=[ProductCard], macro_catalog_id=macro_cid, **kwargs, ) # A pointer that was hidden from the model cannot be bound. hidden = binder_for( {f"bind:{tkey}:title": _answer(f"bind:{tkey}:title", {"/api_key": 0.9})} ) with pytest.raises(DecisionModelError, match="unknown candidate"): await hidden.fill_macro("Show", payload, macro_name="ProductCard") # Nor can an enum value the slot does not have. bad_enum = binder_for( {f"bind:{tkey}:variant": _answer(f"bind:{tkey}:variant", {"huge": 0.9})} ) with pytest.raises(DecisionModelError, match="unknown candidate"): await bad_enum.fill_macro("Show", payload, macro_name="ProductCard") # A boolean answer with no probability mass is not read as "no". empty_boolean = binder_for( {f"bind:{tkey}:in_stock": _answer(f"bind:{tkey}:in_stock", {})} ) with pytest.raises(DecisionModelError, match="boolean distribution"): await empty_boolean.fill_macro("Show", payload, macro_name="ProductCard") only_no = binder_for( {f"bind:{tkey}:in_stock": _answer(f"bind:{tkey}:in_stock", {"no": 0.7})} ) result = await only_no.fill_macro("Show", payload, macro_name="ProductCard") assert result.bindings["in_stock"] is False for threshold, expected in ((0.5, True), (0.8, False)): thresholded = binder_for( {f"bind:{tkey}:in_stock": 0.6}, boolean_threshold=threshold ) result = await thresholded.fill_macro("Show", payload, macro_name="ProductCard") assert result.bindings["in_stock"] is expected @pytest.mark.asyncio async def test_slot_questions_are_split_to_fit_max_pairs() -> None: wide = _cst_catalog( "urn:test:wide", { "Wide": { "type": "object", "description": "Three text fields.", "properties": { name: {"$ref": "common_types.json#/$defs/DynamicString"} for name in ("a", "b", "c") }, "required": ["a", "b", "c"], } }, ) key = "urn:test:wide:Wide" backend = _ScriptedBackend({ "select:target": (key, 0.9), f"bind:{key}:a": ("/f0", 0.9), f"bind:{key}:b": ("/f1", 0.9), f"bind:{key}:c": ("/f2", 0.9), }) # Each slot question has 4 candidate pointers, so two fit in 8 pairs. binder = ToolPointerBinder( backend, transport_catalogs=[_basic(), wide], template_catalogs=["urn:test:wide"], max_pairs=8, ) result = await binder.bind_tool_output( "Show", "fetch", {f"f{i}": f"v{i}" for i in range(4)} ) assert not result.abstained assert result.decision_calls == 3 assert [ sum(len(q.candidates()) for q in batch.questions) for batch in backend.batches ] == [ 2, 8, 4, ] @pytest.mark.asyncio async def test_nan_target_probability_raises_contract_error_in_single_and_split_batches() -> ( None ): basic = _basic() spec = ExpressSurfaceSpec( id="weather", description="Weather summary", dsl="root = Text($/city)", required_paths=("/city",), ) class _NanTargetModel(MockDecisionModel): async def __call__(self, batch: DecisionBatch) -> list[DecisionAnswer]: self.batches.append(batch) out: list[DecisionAnswer] = [] for q in batch.questions: if q.id == "select:target": out.append( DecisionAnswer( q.id, DecisionDistribution( {"template:weather": float("nan"), "none": 0.1} ), ) ) else: out.append( DecisionAnswer( q.id, DecisionDistribution({"yes": 0.9, "no": 0.1}) ) ) return out for max_pairs in (100, 1): binder = ToolPointerBinder( _NanTargetModel(), transport_catalogs=[basic], surface_templates=[ExpressSurfaceTemplate(spec, catalogs=[basic])], max_pairs=max_pairs, ) with pytest.raises(DecisionModelError) as exc_info: await binder.bind_tool_output("Weather", "get_weather", {"city": "NYC"}) assert exc_info.value.code == "DECISION_CONTRACT_ERROR" @pytest.mark.asyncio async def test_express_template_catalog_id_and_cross_catalog_macro_shadowing() -> None: basic = _basic() cst_catalog = _cst_catalog( "urn:test:cst", { "ShadowCard": { "type": "object", "description": "Client-side card.", "properties": { "badge_text": {"$ref": "common_types.json#/$defs/DynamicString"}, }, "required": ["badge_text"], } }, ) @macro() def ShadowCard(different_prop: DynamicString) -> Text: """Macro with the same name as a CST component.""" return Text(text=different_prop) default_tmpl = ExpressSurfaceTemplate( ExpressSurfaceSpec( id="plain", description="No explicit catalog_id.", dsl="root = Text($/title)", ), catalogs=[basic], ) assert default_tmpl.catalog_id is None shadowed_tmpl = ExpressSurfaceTemplate( ExpressSurfaceSpec( id="shadowed", description="Uses the CST ShadowCard rather than the shadowed macro.", dsl="root = ShadowCard(badge_text=$/badge)", catalog_id=cst_catalog.catalog_id, required_paths=("/badge",), ), catalogs=[basic, cst_catalog], macros=[ShadowCard], macro_catalog_id="urn:test:macros", ) assert shadowed_tmpl.catalog_id == cst_catalog.catalog_id cascade_model = MockDecisionModel( scripted_answers={ "gate:needs_ui": 0.95, "route:tier": ("template", 0.95), "route:template": ("plain", 0.95), } ) router = DecisionCascadeRouter( cascade_model, templates=[default_tmpl, shadowed_tmpl], ) decision = await router.route("Show title", catalogs=[basic]) assert decision.template is default_tmpl messages = shadowed_tmpl.render("s1", {"badge": "VIP"}) dumped = _dump(messages) comp = dumped[0]["createSurface"]["components"][0] assert comp["component"] == "ShadowCard" assert "@catalogId" not in comp assert comp["badge_text"] == {"@path": "/badge"}