diff --git a/AGENTS.md b/AGENTS.md index c724e45..924d21f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,8 +36,9 @@ Config reference: `.env.example`. - **Never** `isinstance(state, dict)` on ADK `CallbackContext.state` / `ToolContext.state` — it is a custom proxy, not a dict. Duck-type on `.get` (see `src/arema/runtime/services.py:_state_value`). -- A `ToolDescriptor.id` **must equal** the tool function's `__name__`, or its - `OutputPolicy` will not bind at compose time. +- A `ToolDescriptor.id` **must equal** the tool function's `__name__`. Compose + time rejects a mismatch (`InvalidToolDescriptorError`), which would otherwise + silently unbind the `OutputPolicy` and record tool events under the wrong id. - Tool callbacks needing `RuntimeServices`/sandbox use a `ToolDescriptor(factory=…)` that closes over `ToolBuildContext`; a tool taking `tool_context: ToolContext` must import `ToolContext` at runtime diff --git a/src/arema/runtime/agent_factory.py b/src/arema/runtime/agent_factory.py index dc6541d..302b780 100644 --- a/src/arema/runtime/agent_factory.py +++ b/src/arema/runtime/agent_factory.py @@ -22,6 +22,7 @@ from google.adk.agents import BaseAgent, LlmAgent, LoopAgent, ParallelAgent, SequentialAgent from google.adk.events import Event, EventActions +from google.adk.tools.base_toolset import BaseToolset from google.genai.types import Content, Part from pydantic import ValidationError @@ -31,7 +32,7 @@ from arema.prompts.loader import load_prompt from arema.registry.descriptors import AfterAgentCallback as DescriptorAfterAgentCallback from arema.registry.descriptors import ContextMode -from arema.registry.errors import InvalidCapabilityDescriptorError +from arema.registry.errors import InvalidCapabilityDescriptorError, InvalidToolDescriptorError from arema.registry.mcp import build_mcp_toolset from arema.runtime.callbacks.chain import CallbackChain, build_callback_chain, compose_after_tool from arema.runtime.services import make_checkpoint_recorder @@ -403,11 +404,26 @@ def build_loop_agent(context: AgentBuildContext) -> LoopAgent: def _resolve_tool(descriptor: ToolDescriptor, tool_context: ToolBuildContext) -> ToolLike: """Return a concrete tool for one descriptor, building it lazily if deferred.""" if descriptor.tool is not None: - return descriptor.tool - if descriptor.factory is not None: - return descriptor.factory(tool_context) - # Catalog validation guarantees exactly one of tool/factory; defensive only. - raise ValueError(f"tool '{descriptor.id}' has neither a concrete tool nor a factory") + tool = descriptor.tool + elif descriptor.factory is not None: + tool = descriptor.factory(tool_context) + else: + # Catalog validation guarantees exactly one of tool/factory; defensive only. + raise ValueError(f"tool '{descriptor.id}' has neither a concrete tool nor a factory") + + # The compactor binds an OutputPolicy by runtime tool name and the metrics + # callback records a ToolEvent under it, while the catalog keys both by + # descriptor id. A divergence is silent -- the default policy applies and the + # event is recorded under the wrong id -- so reject it here, the one point + # where both are known. A toolset supplies many names, so it has none to match. + if not isinstance(tool, BaseToolset): + name = getattr(tool, "name", None) or getattr(tool, "__name__", None) + if isinstance(name, str) and name != descriptor.id: + raise InvalidToolDescriptorError( + f"tool descriptor '{descriptor.id}' resolves to a tool named '{name}'; " + "a ToolDescriptor id must equal its runtime tool name" + ) + return tool def _build_agent( diff --git a/tests/unit/runtime/test_agent_factory.py b/tests/unit/runtime/test_agent_factory.py index 8d1aa61..f127f38 100644 --- a/tests/unit/runtime/test_agent_factory.py +++ b/tests/unit/runtime/test_agent_factory.py @@ -18,11 +18,13 @@ from google.adk.agents.invocation_context import InvocationContext from google.adk.sessions import InMemorySessionService -from arema.registry.descriptors import AgentDescriptor, AgentKind, RuntimeProfile -from arema.registry.errors import InvalidCapabilityDescriptorError +from arema.registry.descriptors import AgentDescriptor, AgentKind, RuntimeProfile, ToolDescriptor +from arema.registry.errors import InvalidCapabilityDescriptorError, InvalidToolDescriptorError from arema.runtime.agent_factory import ( AgentBuildContext, EscalationDecision, + ToolBuildContext, + _resolve_tool, build_escalation_gate, build_loop_agent, build_parallel_agent, @@ -847,3 +849,70 @@ def normalize(_context: object) -> None: ) assert built["llm"].after_agent_callback == [normalize] + + +# --------------------------------------------------------------------------- +# _resolve_tool: descriptor id must equal the runtime tool name +# --------------------------------------------------------------------------- + + +def _tool_ctx() -> ToolBuildContext: + """A build context for tools that never read it.""" + from arema.core.config import Settings + from arema.runtime.services import RuntimeServices + + return ToolBuildContext( + settings=Settings(_env_file=None, llm_provider="ollama"), + services=RuntimeServices.default(), + catalog=SimpleNamespace(), # type: ignore[arg-type] + ) + + +def test_resolve_tool_accepts_a_matching_id_and_name() -> None: + def clock_now() -> str: + return "now" + + descriptor = ToolDescriptor(id="clock_now", description="Return UTC time.", tool=clock_now) + assert _resolve_tool(descriptor, _tool_ctx()) is clock_now + + +def test_resolve_tool_rejects_an_id_that_differs_from_the_tool_name() -> None: + """A mismatch would silently unbind the OutputPolicy and misattribute events.""" + + def clock_now() -> str: + return "now" + + descriptor = ToolDescriptor(id="current_time", description="Return UTC time.", tool=clock_now) + with pytest.raises(InvalidToolDescriptorError, match="clock_now"): + _resolve_tool(descriptor, _tool_ctx()) + + +def test_resolve_tool_rejects_a_factory_built_name_mismatch() -> None: + """Deferred tools are the common case, and only resolve at build time.""" + + def clock_now() -> str: + return "now" + + descriptor = ToolDescriptor( + id="current_time", + description="Return UTC time.", + factory=lambda _ctx: clock_now, + ) + with pytest.raises(InvalidToolDescriptorError, match="current_time"): + _resolve_tool(descriptor, _tool_ctx()) + + +def test_resolve_tool_exempts_a_toolset_which_supplies_many_names() -> None: + from google.adk.tools.base_toolset import BaseToolset + + class _Toolset(BaseToolset): + async def get_tools(self, readonly_context: object = None) -> list[object]: + del readonly_context + return [] + + async def close(self) -> None: + return None + + toolset = _Toolset() + descriptor = ToolDescriptor(id="many_tools", description="A toolset.", tool=toolset) + assert _resolve_tool(descriptor, _tool_ctx()) is toolset