From a649b02eb199b36c64b0ca50c962611c3cc8f221 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:19:53 -0500 Subject: [PATCH 01/11] Sub-agents: a type's model choices AgentConfig.model_choices (the agent YAML's model_choices: [fast]) names the models a delegation may run a sub-agent type on instead of its own: references, bare ids or roles. validate_agent_graph refuses them on the root, one that is no tuple or list of texts and a choice named twice; validate_settings parses each and checks its provider's key; the catalog lists their providers at startup and computes a role choice no setting maps. --- src/agentic_cli/config.py | 48 +++++++++++-------- src/agentic_cli/workflow/agent_loader.py | 4 ++ src/agentic_cli/workflow/config.py | 44 +++++++++++++++-- src/agentic_cli/workflow/model_services.py | 36 +++++++++++--- tests/test_config.py | 54 +++++++++++++++++++++ tests/workflow/test_agent_loader.py | 29 +++++++++++ tests/workflow/test_model_services.py | 30 ++++++++++++ tests/workflow/test_subagent_config.py | 56 ++++++++++++++++++++-- 8 files changed, 267 insertions(+), 34 deletions(-) diff --git a/src/agentic_cli/config.py b/src/agentic_cli/config.py index 36f27604..615dcbd0 100644 --- a/src/agentic_cli/config.py +++ b/src/agentic_cli/config.py @@ -339,12 +339,13 @@ def validate_settings( The static half of model validation: - every reference parses: ``default_model``, ``model_roles`` and each - agent's ``model`` (a role must map to a model, never another role); + agent's ``model`` and each of its ``model_choices`` (a role must map to a model, never another role); ``models`` keys are checked when the settings load; - every provider a reference names is built in or defined in ``model_providers``; - every provider a model will run on can be called: the default model's, - each agent's, and that of each role an agent names (a built-in has its + each agent's and each of its model choices', and that of each role an + agent names (a built-in has its key; a configured provider's ``api_key_env`` is set, in the environment or the app's user-level env files, or it names none); - a built-in role that is computed, not mapped (``default`` without a @@ -363,7 +364,8 @@ def validate_settings( Args: settings: Settings to validate. - agent_configs: Optional agent configs whose ``model`` is checked too. + agent_configs: Optional agent configs whose ``model`` and + ``model_choices`` are checked too. Raises: SettingsValidationError: Listing every problem, one per line. @@ -461,24 +463,28 @@ def setting(who: str, spec: str | None) -> ModelRef | None: errors.append(str(exc)) for config in agent_configs or []: - spec = getattr(config, "model", None) - if not spec: - continue - who = f"Agent {getattr(config, 'name', '?')!r}" - try: - parsed = parse_spec(spec) - except ModelSpecError as exc: - errors.append(f"{who}: {exc}") - continue - if isinstance(parsed, RoleRef): - # A mapped role runs on its model; an unmapped one is computed - # from the catalog at startup. - mapped = roles.spec_for(parsed.role) if roles is not None else None - if mapped is not None and parsed.role != "default": - runs.append((f"{who} (role {parsed.role!r})", mapped)) - continue - named.append((who, parsed)) - runs.append((who, parsed)) + name = getattr(config, "name", "?") + choices = getattr(config, "model_choices", None) or () + for who, spec, own in ( + (f"Agent {name!r}", getattr(config, "model", None), True), + *((f"Agent {name!r} (model choice {choice!r})", choice, False) for choice in choices), + ): + if not spec: + continue + try: + parsed = parse_spec(spec) + except ModelSpecError as exc: + errors.append(f"{who}: {exc}") + continue + if isinstance(parsed, RoleRef): + # A mapped role runs on its model; an unmapped one is computed + # from the catalog at startup. + mapped = roles.spec_for(parsed.role) if roles is not None else None + if mapped is not None and parsed.role != "default": + runs.append((f"{who} (role {parsed.role!r})" if own else who, mapped)) + continue + named.append((who, parsed)) + runs.append((who, parsed)) for who, ref in named: if ref.provider not in providers: diff --git a/src/agentic_cli/workflow/agent_loader.py b/src/agentic_cli/workflow/agent_loader.py index af95408e..03358657 100644 --- a/src/agentic_cli/workflow/agent_loader.py +++ b/src/agentic_cli/workflow/agent_loader.py @@ -23,6 +23,7 @@ brief_required: [objective, deliverable] # what a delegation must fill limits: {max_model_calls: 30, timeout: 600} # over the policy's, per field continuable: true # false: one-shot, closed when its run ends + model_choices: [fast] # what a delegation may run it on instead of its model - name: fact_checker instruction: Check one claim. spawnable_by: [agent] # in no sub_agents: a type agents start at run time @@ -100,6 +101,8 @@ class AgentSpec(BaseModel): continuable: bool = True # None: only its parent starts it. spawnable_by: list[str] | None = None + # Empty: only its own model. + model_choices: list[str] = Field(default_factory=list) class AgentsFile(BaseModel): @@ -192,6 +195,7 @@ def load_agents_from_yaml(path: str | Path) -> list[AgentConfig]: include_state_tools=spec.include_state_tools, inherit_context=spec.inherit_context, continuable=spec.continuable, + model_choices=tuple(spec.model_choices), **delegation, ) ) diff --git a/src/agentic_cli/workflow/config.py b/src/agentic_cli/workflow/config.py index 9cd43c4d..d399f794 100644 --- a/src/agentic_cli/workflow/config.py +++ b/src/agentic_cli/workflow/config.py @@ -1,6 +1,7 @@ """Configuration classes for workflow management.""" import inspect +from collections import Counter from dataclasses import dataclass, field from typing import Callable, Any, TYPE_CHECKING @@ -87,6 +88,12 @@ class AgentConfig: ``sub_agents`` starts it. A type that sets it and is in no ``sub_agents`` list is a free type: no root, started at run time only. Only on sub-agents. + model_choices: The models a delegation may run this type on instead + of its own, as ``model`` takes them: references, bare ids or + roles (a list is read as a tuple). Each is resolved with the + agent's ``model_settings`` and given its own context numbers + at initialization. Empty (the default): its own model alone. + Only on sub-agents. """ name: str @@ -104,6 +111,7 @@ class AgentConfig: limits: AgentLimits | None = None continuable: bool = True spawnable_by: frozenset[str] | None = None + model_choices: tuple[str, ...] = () def get_prompt(self, settings: "BaseSettings | None" = None) -> str: """Get the prompt string, calling the factory if the prompt is callable. @@ -247,8 +255,10 @@ def validate_agent_graph( 12. each agent's ``limits`` is None or an ``AgentLimits``; 13. each agent's ``continuable`` is True or False; 14. the root sets none of ``brief_required`` (beyond its default, the - objective), ``limits`` and ``continuable`` (beyond True): it is never - delegated to. + objective), ``limits``, ``continuable`` (beyond True) and + ``model_choices``: it is never delegated to; + 15. each agent's ``model_choices`` is a tuple (or list) of texts, none + blank and none named twice. A free type that no source ``policy`` enables can start is warned of (``subagent_type_unreachable``), once for each validation. @@ -449,7 +459,7 @@ def _check_inherit_context(config_map: dict[str, AgentConfig], root: str) -> Non def _check_delegation_fields(config_map: dict[str, AgentConfig], root: str) -> None: - """Each agent's ``brief_required``, ``limits`` and ``continuable`` are what they say, and the root sets none. + """Each agent's ``brief_required``, ``limits``, ``continuable`` and ``model_choices`` are what they say, and the root sets none. Raises: AgentGraphError: Naming the agent(s), the value and what to change. @@ -495,6 +505,7 @@ def _check_delegation_fields(config_map: dict[str, AgentConfig], root: str) -> N ("brief_required", tuple(config.brief_required) != _DEFAULT_BRIEF_REQUIRED), ("limits", config.limits is not None), ("continuable", config.continuable is False), + ("model_choices", bool(config.model_choices)), ) if is_set ] @@ -505,6 +516,26 @@ def _check_delegation_fields(config_map: dict[str, AgentConfig], root: str) -> N "Remove them from the root." ) + not_texts = [ + f"{name!r} ({config.model_choices!r})" + for name, config in config_map.items() + if not _are_texts(config.model_choices) + ] + if not_texts: + raise AgentGraphError( + "model_choices must be a tuple or list of models or roles, each as " + f"text: {', '.join(not_texts)}." + ) + + twice = sorted( + f"{name!r} ({choice!r})" + for name, config in config_map.items() + for choice, count in Counter(config.model_choices).items() + if count > 1 + ) + if twice: + raise AgentGraphError(f"model_choices names a model twice: {', '.join(twice)}.") + def _names_brief_fields(value: object) -> bool: """Whether ``value`` is a tuple or list of brief field names (a string is neither).""" @@ -513,6 +544,13 @@ def _names_brief_fields(value: object) -> bool: ) +def _are_texts(value: object) -> bool: + """Whether ``value`` is a tuple or list of non-blank texts (a string is neither).""" + return isinstance(value, (tuple, list)) and all( + isinstance(item, str) and item.strip() for item in value + ) + + def _topological_order(config_map: dict[str, AgentConfig]) -> tuple[str, ...]: """Order agent names so each follows its sub-agents. diff --git a/src/agentic_cli/workflow/model_services.py b/src/agentic_cli/workflow/model_services.py index 89eb0e34..dc66cb59 100644 --- a/src/agentic_cli/workflow/model_services.py +++ b/src/agentic_cli/workflow/model_services.py @@ -145,8 +145,8 @@ def model_references( In order: the manager's own model (``manager_model``), ``default_model``, each ``model_roles`` value (so the model of each mapped role an agent - names), then each agent's model that is a reference or a bare model id. - One that does not parse is left out: validation reports it. + names), then each agent's model that is a reference or a bare model id, + and each of its model choices that is one. One that does not parse is left out: validation reports it. """ return tuple(_named_references(settings, agent_configs, manager_model)) @@ -158,7 +158,8 @@ def reference_settings( ) -> dict[ModelRef, str]: """Where each model ``model_references`` gives is named, in its order: ``the manager's model``, ``default_model``, ``model_roles['fast']``, ``agent - 'writer'``, those that name one model joined with "and". The catalog's + 'writer'``, ``agent 'writer' model_choices``, those that name one model + joined with "and". The catalog's warning that a provider does not serve a model says which setting to change. """ named = _named_references(settings, agent_configs, manager_model) @@ -188,6 +189,10 @@ def _named_references( parsed = _agent_model(config) if isinstance(parsed, ModelRef): named.setdefault(parsed, []).append(f"agent {config.name!r}") + where = f"agent {config.name!r} model_choices" + for choice in _agent_choices(config): + if isinstance(choice, ModelRef) and where not in named.setdefault(choice, []): + named[choice].append(where) return named @@ -200,7 +205,8 @@ def computed_roles( ``default`` when neither the manager's own model nor ``default_model`` is set, and each other built-in role an agent names that ``model_roles`` - does not map. (An app's own role nobody maps runs on the default model.) + does not map, as a model or as a model choice. (An app's own role nobody + maps runs on the default model.) """ computed: set[str] = set() if not manager_model and not settings.default_model: @@ -217,9 +223,25 @@ def computed_roles( def _agent_models(agent_configs: Iterable["AgentConfig"]) -> list[ModelRef | RoleRef]: - """Each agent's model that names one (None runs on the default) and parses.""" - parsed = (_agent_model(config) for config in agent_configs) - return [model for model in parsed if model is not None] + """Each agent's model that names one (None runs on the default), then its choices; those that parse.""" + models: list[ModelRef | RoleRef] = [] + for config in agent_configs: + model = _agent_model(config) + if model is not None: + models.append(model) + models.extend(_agent_choices(config)) + return models + + +def _agent_choices(config: "AgentConfig") -> list[ModelRef | RoleRef]: + """The agent's model choices that parse (validation reports the others).""" + parsed: list[ModelRef | RoleRef] = [] + for choice in getattr(config, "model_choices", None) or (): + try: + parsed.append(parse_spec(choice)) + except (ModelSpecError, TypeError, AttributeError): + continue + return parsed def _agent_model(config: "AgentConfig") -> ModelRef | RoleRef | None: diff --git a/tests/test_config.py b/tests/test_config.py index 106f1ad3..94766413 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -628,6 +628,60 @@ def test_a_role_an_agent_uses_needs_its_provider_s_key(self, temp_workspace: Pat # A mapping no agent uses costs nothing. validate_settings(settings, [AgentConfig(name="w", prompt="p")]) + def test_a_model_choice_needs_its_provider_s_key(self, temp_workspace: Path): + """Each of an agent's model choices runs as its model does: checked alike.""" + settings = self._settings(temp_workspace, {"GOOGLE_API_KEY": "test-key"}) + agents = [AgentConfig(name="writer", prompt="p", model="gemini-2.5-pro", + model_choices=("gemini-2.5-flash", "claude-haiku-4-5"))] + + assert self._problems(settings, agents) == [ + "Agent 'writer' (model choice 'claude-haiku-4-5'): model " + "'anthropic:claude-haiku-4-5' needs the anthropic API key; set ANTHROPIC_API_KEY." + ] + + def test_a_role_choice_needs_its_mapped_model_s_key(self, temp_workspace: Path): + settings = self._settings( + temp_workspace, {"GOOGLE_API_KEY": "test-key"}, + model_roles={"fast": "anthropic:claude-haiku-4-5"}, + ) + agents = [AgentConfig(name="writer", prompt="p", model_choices=("fast",))] + + assert self._problems(settings, agents) == [ + "Agent 'writer' (model choice 'fast'): model 'anthropic:claude-haiku-4-5' needs " + "the anthropic API key; set ANTHROPIC_API_KEY." + ] + + def test_a_malformed_model_choice_is_an_error(self, temp_workspace: Path): + settings = self._settings(temp_workspace, {"GOOGLE_API_KEY": "test-key"}) + agents = [AgentConfig(name="writer", prompt="p", model_choices=("fast", "gemini"))] + + (problem,) = self._problems(settings, agents) + assert problem.startswith("Agent 'writer' (model choice 'gemini'): ") + + def test_a_model_choice_on_an_undefined_provider_is_an_error(self, temp_workspace: Path): + settings = self._settings(temp_workspace, {"GOOGLE_API_KEY": "test-key"}) + agents = [AgentConfig(name="writer", prompt="p", model_choices=("third-box:mistral",))] + + (problem,) = self._problems(settings, agents) + assert problem.startswith( + "Agent 'writer' (model choice 'third-box:mistral'): model 'third-box:mistral' " + "names provider 'third-box'" + ) + + def test_a_computed_role_choice_needs_a_tier(self, temp_workspace: Path, monkeypatch): + monkeypatch.setenv("OPENROUTER_API_KEY", "test-key") + settings = self._settings( + temp_workspace, + model_providers=self.OPENROUTER, + default_model="openrouter:qwen/qwen3.7-plus", + ) + agents = [AgentConfig(name="writer", prompt="p", model_choices=("fast",))] + + assert self._problems(settings, agents) == [ + "No model for role 'fast': map it in model_roles['fast'], or set a Google, " + "Anthropic or OpenAI key (GOOGLE_API_KEY, ANTHROPIC_API_KEY, OPENAI_API_KEY) so " + "the newest fast-tier model is used.", + ] def test_a_malformed_agent_model_is_an_error(self, temp_workspace: Path): settings = self._settings(temp_workspace, {"GOOGLE_API_KEY": "test-key"}) agents = [AgentConfig(name="writer", prompt="p", model="gemini")] diff --git a/tests/workflow/test_agent_loader.py b/tests/workflow/test_agent_loader.py index 9543ac33..f6e06aab 100644 --- a/tests/workflow/test_agent_loader.py +++ b/tests/workflow/test_agent_loader.py @@ -135,6 +135,7 @@ def test_defaults(self, tmp_path): assert cfg.limits is None assert cfg.continuable is True assert cfg.spawnable_by is None + assert cfg.model_choices == () def test_a_sub_agents_inherit_context(self, tmp_path): path = _write( @@ -290,6 +291,34 @@ def test_a_source_spawnable_by_does_not_name_is_the_graphs_to_refuse(self, tmp_p with pytest.raises(AgentGraphError, match="'researcher' has spawnable_by frozenset"): validate_agent_graph(configs) + def test_model_choices(self, tmp_path): + path = _write( + tmp_path, + """ + agents: + - name: coordinator + instruction: Lead. + sub_agents: [researcher] + - name: researcher + instruction: Find facts. + model: strong + model_choices: [fast, anthropic:claude-haiku-4-5] + """, + ) + configs = load_agents_from_yaml(path) + assert [c.model_choices for c in configs] == [ + (), ("fast", "anthropic:claude-haiku-4-5"), + ] + assert validate_agent_graph(configs).root_name == "coordinator" + + def test_model_choices_is_a_list(self, tmp_path): + path = _write( + tmp_path, "agents:\n - name: a\n instruction: hi\n model_choices: fast\n" + ) + with pytest.raises(ValidationError) as exc: + load_agents_from_yaml(path) + message = str(exc.value) + assert "agents.0.model_choices" in message and "valid list" in message def test_brief_required_is_a_list(self, tmp_path): path = _write( tmp_path, diff --git a/tests/workflow/test_model_services.py b/tests/workflow/test_model_services.py index 3ed54962..3f92f7db 100644 --- a/tests/workflow/test_model_services.py +++ b/tests/workflow/test_model_services.py @@ -460,6 +460,36 @@ def test_reference_settings_say_where_each_reference_is_named(): ) +def test_model_choices_are_named_references_too(): + """Each agent's model choices, after its model: the catalog lists their + providers at startup, and its warning names the agent's model_choices.""" + settings = BaseSettings(default_model="gemini-2.5-flash") + agents = [AgentConfig( + name="writer", prompt="p", model="google:gemini-2.5-pro", + model_choices=("anthropic:claude-haiku-4-5", "fast", "gemini-2.5-flash", "x y"), + )] + + assert model_services.model_references(settings, agents) == ( + ModelRef("google", "gemini-2.5-flash"), + ModelRef("google", "gemini-2.5-pro"), + ModelRef("anthropic", "claude-haiku-4-5"), + ) + assert model_services.reference_settings(settings, agents) == { + ModelRef("google", "gemini-2.5-flash"): "default_model and agent 'writer' model_choices", + ModelRef("google", "gemini-2.5-pro"): "agent 'writer'", + ModelRef("anthropic", "claude-haiku-4-5"): "agent 'writer' model_choices", + } + + +def test_a_role_choice_is_computed(): + settings = BaseSettings(default_model="gemini-2.5-flash", model_roles={"strong": "o3"}) + agents = [ + AgentConfig(name="writer", prompt="p", model_choices=("fast", "strong")), + AgentConfig(name="critic", prompt="p", model_choices=("vision",)), # an app's role + ] + + assert model_services.computed_roles(settings, agents) == ("fast",) + def test_model_references_skip_what_does_not_parse(): """Validation reports each of them, before any catalog is built.""" agents = _agents("x y", "Lab:qwen3", "lab:", "") diff --git a/tests/workflow/test_subagent_config.py b/tests/workflow/test_subagent_config.py index 732ea54e..258432e9 100644 --- a/tests/workflow/test_subagent_config.py +++ b/tests/workflow/test_subagent_config.py @@ -1,4 +1,4 @@ -"""A sub-agent type's delegation fields: ``brief_required``, ``limits``, ``continuable`` and ``spawnable_by``. +"""A sub-agent type's delegation fields: ``brief_required``, ``limits``, ``continuable``, ``spawnable_by`` and ``model_choices``. ``brief_required`` names the brief fields a delegation to the type must fill (the title and the objective are always needed); ``limits`` are the type's @@ -13,6 +13,10 @@ it and is in no ``sub_agents`` list is a free type, never the root, and ``validate_agent_graph`` checks its sources, refuses it on the root and warns of a free type the policy lets no source start. + +``model_choices`` are the models (or roles) a delegation may run the type on +instead of its own: a tuple or list of texts, none named twice, and none on +the root. """ from __future__ import annotations @@ -54,9 +58,11 @@ def test_an_instance_takes_follow_ups_by_default(self): def test_they_follow_inherit_context(self): # Appended: a positional AgentConfig(...) written before them still binds. names = [f.name for f in dataclasses.fields(AgentConfig)] - assert names[-5:] == ["inherit_context", "brief_required", "limits", "continuable", - "spawnable_by"] + assert names[-6:] == ["inherit_context", "brief_required", "limits", "continuable", + "spawnable_by", "model_choices"] + def test_no_model_choices_by_default(self): + assert AgentConfig(name="a", prompt="p").model_choices == () def test_only_its_parent_starts_it_by_default(self): assert AgentConfig(name="a", prompt="p").spawnable_by is None @@ -382,3 +388,47 @@ def test_a_sub_agent_its_parent_starts_is_not(self, logged): def test_the_policy_must_be_a_policy(self): with pytest.raises(TypeError, match="subagents must be a SubAgentPolicy or None"): validate_agent_graph(team(), policy={"spawn_sources": {"agent"}}) + + +class TestModelChoices: + """``model_choices``: the models a delegation may pick instead of the type's own.""" + + @pytest.mark.parametrize("value", [("fast",), ["fast", "anthropic:claude-haiku-4-5"], + ("claude-opus-4-7",)]) + def test_a_tuple_or_list_of_models_or_roles(self, value): + assert validate_agent_graph(team(writer={"model_choices": value})).root_name == "lead" + + @pytest.mark.parametrize("value", ["fast", ("fast", ""), ("fast", " "), (1,), None, + {"fast"}]) + def test_each_is_text(self, value): + # A string would be read letter by letter. + with pytest.raises(AgentGraphError) as exc: + validate_agent_graph(team(writer={"model_choices": value})) + assert str(exc.value) == ( + "model_choices must be a tuple or list of models or roles, each as text: " + f"'writer' ({value!r})." + ) + + def test_none_is_named_twice(self): + with pytest.raises(AgentGraphError) as exc: + validate_agent_graph(team( + writer={"model_choices": ("fast", "strong", "fast")}, + researcher={"model_choices": ["strong", "strong"]}, + )) + assert str(exc.value) == ( + "model_choices names a model twice: 'researcher' ('strong'), 'writer' ('fast')." + ) + + def test_the_root_sets_none(self): + with pytest.raises(AgentGraphError) as exc: + validate_agent_graph(team(lead={"model_choices": ("fast",)})) + assert str(exc.value) == ( + "Agent 'lead' is the root agent, but sets model_choices: they apply to a " + "delegation, and the root is never delegated to. Remove them from the root." + ) + + def test_a_free_type_may_set_them(self): + configs = with_free(AgentConfig( + name="helper", prompt="p", spawnable_by={"agent"}, model_choices=("fast",), + )) + assert validate_agent_graph(configs, policy=AGENTS).free_types == ("helper",) From e1ec7940a0d7db021e6818cc65f09a3e6b3b6937 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:20:34 -0500 Subject: [PATCH 02/11] Sub-agents: model choices resolved and budgeted at initialization Each agent's model_choices resolve as its model would (its name, its model_settings), all or nothing with the rest of the models, and get their own context numbers before any service is built: a window too small to work in fails startup as an agent's own does. The manager gives them as choice_models[(agent, choice)] and context_budget(agent, model=choice). --- src/agentic_cli/workflow/base_manager.py | 62 +++++++++++- .../workflow/test_budgets_before_services.py | 49 ++++++++++ tests/workflow/test_manager_models.py | 97 +++++++++++++++++++ 3 files changed, 205 insertions(+), 3 deletions(-) diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index db4e7eef..ac436fb8 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -23,6 +23,7 @@ import asyncio import contextlib import contextvars +import dataclasses import functools import inspect import warnings @@ -490,6 +491,10 @@ def __init__( # no context. self._root_agent_name: str | None = None self._budgets: dict[str, "ContextBudget"] = {} + # Each agent's model choices, resolved with its model and given their + # own numbers, by (agent, choice as written). + self._choice_models: dict[tuple[str, str], ResolvedModel] = {} + self._choice_budgets: dict[tuple[str, str], "ContextBudget"] = {} # User input handling (callback-only), context-local — see # set_input_callback(). One ContextVar per manager; there are only ever @@ -2291,6 +2296,12 @@ def agent_models(self) -> Mapping[str, ResolvedModel]: """Each agent's model, by agent name; empty before initialization.""" return MappingProxyType(self._resolved_models) + @property + def choice_models(self) -> Mapping[tuple[str, str], ResolvedModel]: + """Each agent's model choices' models, by ``(agent, choice)``, the choice + as ``AgentConfig.model_choices`` writes it; empty before initialization.""" + return MappingProxyType(self._choice_models) + @property def root_agent_name(self) -> str | None: """The root agent's name, from the validated agent graph. @@ -2300,7 +2311,9 @@ def root_agent_name(self) -> str | None: """ return self._root_agent_name if self._initialized else None - def context_budget(self, agent_name: str | None = None) -> "ContextBudget": + def context_budget( + self, agent_name: str | None = None, *, model: str | None = None + ) -> "ContextBudget": """An agent's context numbers, as its backend summarizes and trims by them. Its window (or the 128k floor), input budget, summary trigger and the @@ -2310,13 +2323,16 @@ def context_budget(self, agent_name: str | None = None) -> "ContextBudget": Args: agent_name: The agent; None for the root agent (``root_agent_name``). + model: One of the agent's model choices, as ``AgentConfig.model_choices`` + writes it: its numbers instead of the agent's own model's. Raises: RuntimeError: Before initialization, or after cleanup. KeyError: ``agent_name`` names no agent whose context this manager manages: one whose model did not resolve (a native ADK YAML - app's). LangGraph manages none: every name is unknown there, - the root's included. + app's), or a ``model`` that is none of its choices. + LangGraph manages none: every name is unknown there, the + root's included. """ if not self._initialized: raise RuntimeError( @@ -2324,6 +2340,13 @@ def context_budget(self, agent_name: str | None = None) -> "ContextBudget": "budgets are computed when it initializes." ) name = self.root_agent_name if agent_name is None else agent_name + if model is not None: + if (name, model) not in self._choice_budgets: + raise KeyError( + f"No context budget for agent {name!r}'s model choice {model!r}: " + "this manager does not manage it." + ) + return self._choice_budgets[(name, model)] if name is None or name not in self._budgets: who = "the root agent" if name is None else f"agent {name!r}" raise KeyError(f"No context budget for {who}: this manager does not manage it.") @@ -2480,6 +2503,7 @@ async def _initialize_locked( # small to work in (ContextBudgetError) fails here too, before a # service or a session store is built. self._budgets = self._compute_budgets() + self._choice_budgets = self._compute_choice_budgets() if services is not None: # Another manager's, published as its: only what they lack # is built, and the rollback below drops them unclosed. @@ -2539,6 +2563,24 @@ def _compute_budgets(self) -> "dict[str, ContextBudget]": for name, model in self._resolved_models.items() } + def _compute_choice_budgets(self) -> "dict[tuple[str, str], ContextBudget]": + """Each model choice's context numbers, by ``(agent, choice)``; none for a backend that manages none. + + Called right after ``_compute_budgets``, with the same failure: a + choice whose model leaves too small an input budget to work in. + + Raises: + ContextBudgetError: Naming the agent and the model. + """ + if not self._manages_context(): + return {} + from agentic_cli.workflow.context import context_budget + + return { + key: context_budget(model, self._settings) + for key, model in self._choice_models.items() + } + def _validate_model_settings(self) -> None: """The static model checks (``validate_settings``), with this manager's override. @@ -2608,15 +2650,27 @@ def _resolve_models(self, providers: Mapping[str, Provider]) -> None: default = model else: resolved[config.name] = model + # A choice runs as the agent's model would: its name, its settings. + choices: dict[tuple[str, str], ResolvedModel] = {} + for config in self._agent_configs: + for choice in config.model_choices: + try: + choices[(config.name, choice)] = self._resolve_for( + dataclasses.replace(config, model=choice), roles, self._catalog, providers + ) + except ModelResolutionError as exc: + errors.append(str(exc)) if errors: raise SettingsValidationError("\n".join(dict.fromkeys(errors))) resolved.update(self._resolve_extra_models(roles, providers)) self._default_model, self._resolved_models = default, resolved + self._choice_models = choices logger.info( "models_resolved", default=str(default.ref), agents={name: str(model.ref) for name, model in resolved.items()}, + choices={f"{name}/{choice}": str(model.ref) for (name, choice), model in choices.items()}, ) def _resolve_extra_models( @@ -2914,6 +2968,7 @@ async def _release_resources( self._initialized = False self._budgets = {} + self._choice_budgets = {} self._memory_index.clear() self._rosters.clear() catalog, self._catalog = self._catalog, None @@ -3046,6 +3101,7 @@ def _reset_model(self, model: str | None) -> None: self._model_override = model self._default_model = None self._resolved_models = {} + self._choice_models = {} @abstractmethod async def process( diff --git a/tests/workflow/test_budgets_before_services.py b/tests/workflow/test_budgets_before_services.py index 554b685a..171a68b4 100644 --- a/tests/workflow/test_budgets_before_services.py +++ b/tests/workflow/test_budgets_before_services.py @@ -157,6 +157,55 @@ async def test_a_window_that_works_builds_services_and_keeps_its_budgets( await manager.cleanup() +def _choosing(choice: str) -> list[AgentConfig]: + """A lead, and an agent whose tool needs a service (the jobs) with ``choice`` as its model choice.""" + from agentic_cli.tools.jobs.tools import job_status + + return [ + AgentConfig(name="lead", prompt="p", sub_agents=["a"]), + AgentConfig(name="a", prompt="p", tools=[job_status], model_choices=(choice,)), + ] + + +class TestAModelChoicesBudget: + """A model choice gets its own context numbers when the models resolve: one + too small to work in fails the start as an agent's own model does.""" + + @pytest.mark.parametrize(("path", "store_opener"), BACKENDS) + async def test_a_choice_too_small_to_work_in_builds_no_service( + self, ctx, monkeypatch, path, store_opener + ): + cls = _backend(path) + spy = _Spy(monkeypatch, cls, store_opener) + manager = cls(_choosing(SMALL), settings=ctx.settings) + + with pytest.raises(ContextBudgetError, match=r"'a'.*gemini-3\.8-flash"): + await manager.initialize_services() + + assert (spy.built, spy.stores) == ([], []) + assert not manager.is_initialized + assert (manager._budgets, manager._choice_budgets) == ({}, {}) + + @pytest.mark.parametrize(("path", "store_opener"), BACKENDS) + async def test_a_choice_s_numbers_are_its_model_s(self, ctx, path, store_opener): + cls = _backend(path) + manager = cls(_choosing("google:gemini-2.5-flash"), settings=ctx.settings) + try: + await manager.initialize_services() + + choice = manager.choice_models[("a", "google:gemini-2.5-flash")] + assert manager.context_budget("a", model="google:gemini-2.5-flash") == ( + context_budget(choice, ctx.settings) + ) + assert manager.context_budget("a") == context_budget( + manager.agent_models["a"], ctx.settings + ) + with pytest.raises(KeyError, match="model choice 'fast'"): + manager.context_budget("a", model="fast") + finally: + await manager.cleanup() + assert manager._choice_budgets == {} + class TestANativeAdkApp: async def test_the_configs_the_factory_passes_through_are_ignored(self, ctx, tmp_path): # ``create_workflow_manager_from_settings`` hands a native app's configs to diff --git a/tests/workflow/test_manager_models.py b/tests/workflow/test_manager_models.py index 8857db61..589272e2 100644 --- a/tests/workflow/test_manager_models.py +++ b/tests/workflow/test_manager_models.py @@ -388,6 +388,103 @@ async def test_an_unmapped_app_role_runs_on_the_default_model(self, providers, m await manager.cleanup() +class TestModelChoices: + """Each agent's ``model_choices`` resolve with the agents' models, all or + nothing, each with the agent's own generation settings: what a + delegation may run the agent on instead (``choice_models``).""" + + async def test_each_choice_resolves_as_a_model_would(self, providers, monkeypatch): + keys(monkeypatch, "google") + manager = adk( + team("gemini-2.5-pro", model_choices=("fast", "google:gemini-2.5-flash")), + settings(model_roles={"fast": "google:gemini-2.5-flash-lite"}), + ) + + assert manager.choice_models == {} + await manager.initialize_services() + try: + assert {key: str(m.ref) for key, m in manager.choice_models.items()} == { + ("writer", "fast"): "google:gemini-2.5-flash-lite", + ("writer", "google:gemini-2.5-flash"): "google:gemini-2.5-flash", + } + # Each is the agent's, under its name; its own model is unchanged. + assert {m.agent for m in manager.choice_models.values()} == {"writer"} + assert str(manager.agent_models["writer"].ref) == "google:gemini-2.5-pro" + assert set(manager.agent_models) == {"coordinator", "writer"} + finally: + await manager.cleanup() + + async def test_a_role_no_setting_maps_is_computed_and_its_provider_listed( + self, providers, monkeypatch + ): + """``fast`` as a choice is what ``fast`` as a model is: the start lists the + provider whose newest fast-tier model it takes, as it does for an agent + on that role.""" + keys(monkeypatch, "anthropic") + manager = adk(team(model_choices=("fast",)), settings(default_model="claude-opus-4-7")) + + await manager.initialize_services() + try: + assert providers.calls == ["anthropic"] + assert str(manager.choice_models[("writer", "fast")].ref) == ( + "anthropic:claude-haiku-4-5" + ) + finally: + await manager.cleanup() + + async def test_a_choice_that_cannot_run_is_reported_with_the_rest_and_nothing_kept( + self, providers, monkeypatch + ): + keys(monkeypatch, "google") + configs = [ + AgentConfig(name="coordinator", prompt="p", sub_agents=["a", "b"]), + AgentConfig(name="a", prompt="p", model="anthropic:claude-sonnet-4-5"), + AgentConfig(name="b", prompt="p", model_choices=("anthropic:claude-haiku-4-5",)), + ] + manager = adk(configs, settings()) + + with pytest.raises(SettingsValidationError) as caught: + await manager.initialize_services(validate=False) # past the static check + + message = str(caught.value) + assert "Agent 'a': model 'anthropic:claude-sonnet-4-5' needs the anthropic" in message + assert "Agent 'b': model 'anthropic:claude-haiku-4-5' needs the anthropic" in message + assert (manager.choice_models, manager._resolved_models) == ({}, {}) + assert not manager.is_initialized + + async def test_a_choice_takes_the_agent_s_generation_settings( + self, providers, monkeypatch + ): + """A thinking level the choice's model lacks fails the start, as on the agent's own.""" + keys(monkeypatch, "anthropic") + writer = ModelSettings(thinking=ThinkingSettings(mode="xhigh")) + manager = adk( + team("anthropic:claude-opus-4-7", model_settings=writer, + model_choices=("anthropic:claude-haiku-4-5",)), + settings(), + ) + + with pytest.raises(SettingsValidationError) as caught: + await manager.initialize_services(validate=False) + + assert str(caught.value).startswith( + "Agent 'writer': thinking mode 'xhigh' is not available on " + "anthropic:claude-haiku-4-5" + ) + + async def test_a_model_switch_resolves_them_again(self, providers, monkeypatch): + keys(monkeypatch, "google") + manager = adk(team(model_choices=("default",)), settings(default_model="gemini-2.5-pro")) + + await manager.initialize_services() + try: + await manager.reinitialize(model="gemini-2.5-flash", preserve_sessions=True) + assert str(manager.choice_models[("writer", "default")].ref) == ( + "google:gemini-2.5-flash" + ) + finally: + await manager.cleanup() + # --- the manager's own model (R4) ------------------------------------------------------ From 8b25f5de47b6d5ca8c2a86d2762c6702275389ae Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:22:52 -0500 Subject: [PATCH 03/11] Sub-agents: task's tools and model arguments Every task call may give tools, some of the type's own tools, and, when a type it offers has model choices, model, one of them; the type's line in task's description names its choices. read_choices reads both after the brief: anything else is a BriefError naming what it may be. With the default policy task is what it was but for the tools argument. --- src/agentic_cli/workflow/agents/brief.py | 95 ++++++++++++++- .../workflow/deepagents/test_agent_builder.py | 2 +- tests/workflow/test_agent_brief.py | 111 +++++++++++++++++- tests/workflow/test_subagents_contract.py | 13 +- 4 files changed, 210 insertions(+), 11 deletions(-) diff --git a/src/agentic_cli/workflow/agents/brief.py b/src/agentic_cli/workflow/agents/brief.py index e87270a5..a13bbd2d 100644 --- a/src/agentic_cli/workflow/agents/brief.py +++ b/src/agentic_cli/workflow/agents/brief.py @@ -12,13 +12,15 @@ ``task``'s schema and description, the same for both backends, made for the types one run may start (``task_offer``, ``Delegations.offered``); ``follow_up_parameters`` and ``follow_up_description`` are the parent's other -tools' (``message_agent``, ``stop_agent``, ``check_agents``). +tools' (``message_agent``, ``stop_agent``, ``check_agents``). Every call may +narrow its run's tools (``tools``), and one to a type with model choices may +pick one (``model``), which ``read_choices`` checks. """ from __future__ import annotations import copy -from collections.abc import Mapping +from collections.abc import Collection, Mapping from dataclasses import dataclass from typing import TYPE_CHECKING, Any @@ -33,8 +35,33 @@ #: A brief's fields besides its title, in the order a task message lays them out. BRIEF_FIELDS = ("objective", "deliverable", "constraints", "known", "done_when") -#: ``task``'s arguments, in the order its schema lists them. -_ARGUMENTS = ("agent_type", "title", *BRIEF_FIELDS) +#: ``task``'s arguments, in the order its schema lists them (``model`` only for +#: types with model choices). +_ARGUMENTS = ("agent_type", "title", *BRIEF_FIELDS, "tools", "model") + +#: What ``task``'s schema tells the model of ``tools``. +TOOLS_DESCRIPTION = ( + "Optional: names of the agent's own tools to give this task, to narrow it; " + "leave it out for all of them." +) + +#: What ``task``'s schema tells the model of ``model``, when a type has choices. +MODEL_DESCRIPTION = ( + "Optional: one of the agent's model choices (named with it below) to run this " + "task on; leave it out for its own model." +) + +#: What a call is told whose ``tools`` are not some of the type's own. +TOOLS_ERROR = "The tools for '{agent_type}' must be some of its own: {names}." + +#: What a call is told that narrows the tools of a type that has none of its own. +NO_TOOLS_ERROR = "'{agent_type}' has no tools of its own; leave tools out." + +#: What a call is told whose ``model`` is none of the type's choices. +MODEL_ERROR = "The model for '{agent_type}' must be one of its model choices: {names}." + +#: What a call is told that names a model for a type with no choices. +NO_MODEL_CHOICES_ERROR = "'{agent_type}' has no model choices; leave model out." #: What ``task``'s schema tells the model of each field of the brief. _FIELD_DESCRIPTIONS = { @@ -257,6 +284,51 @@ def read_brief( return config, Brief(**texts) +def read_choices( + arguments: Mapping[str, Any], + config: AgentConfig, + own_tools: Collection[str] = (), +) -> tuple[frozenset[str] | None, str | None]: + """The tools and the model a ``task`` call gives its run: None each when left out (or null). + + ``tools`` are some of the type's own: ``own_tools`` are the names its + backend gives it (the state and delegation tools left out), and none at + all is a narrowing too. ``model`` is one of the type's ``model_choices``, + as written (stripped). Read after ``read_brief``, before the run counts; + the tools are read first. + + Raises: + BriefError: ``tools`` are not a list of the names of the type's own + tools (the message lists them), or the type has none; ``model`` is not + one of its choices (the message lists them), or it has none. + """ + agent_type = config.name + tools: frozenset[str] | None = None + given = arguments.get("tools") + if given is not None: + if not own_tools and given != []: + raise BriefError(NO_TOOLS_ERROR.format(agent_type=agent_type)) + if not isinstance(given, list) or not all( + isinstance(name, str) and name in own_tools for name in given + ): + raise BriefError( + TOOLS_ERROR.format(agent_type=agent_type, names=", ".join(sorted(own_tools))) + ) + tools = frozenset(given) + + model: str | None = None + chosen = arguments.get("model") + if chosen is not None: + if not config.model_choices: + raise BriefError(NO_MODEL_CHOICES_ERROR.format(agent_type=agent_type)) + if not isinstance(chosen, str) or chosen.strip() not in config.model_choices: + raise BriefError( + MODEL_ERROR.format(agent_type=agent_type, names=", ".join(config.model_choices)) + ) + model = chosen.strip() + return tools, model + + def task_parameters(types: Mapping[str, AgentConfig]) -> dict[str, Any]: """``task``'s arguments, as a JSON schema object: both backends build its schema from this. @@ -264,6 +336,8 @@ def task_parameters(types: Mapping[str, AgentConfig]) -> dict[str, Any]: named in its description with what it does; then the brief's title and fields. The type, the title and the objective are required: what else a type needs of the brief is said in its line, and ``read_brief`` checks it. + Then ``tools``, which every call may give, and ``model``, only when a type + in ``types`` has model choices (``read_choices`` checks both). """ lines = "\n".join(_type_line(name, config) for name, config in types.items()) properties: dict[str, Any] = { @@ -275,6 +349,13 @@ def task_parameters(types: Mapping[str, AgentConfig]) -> dict[str, Any]: } for name in ("title", *BRIEF_FIELDS): properties[name] = {"type": "string", "description": _FIELD_DESCRIPTIONS[name]} + properties["tools"] = { + "type": "array", + "items": {"type": "string"}, + "description": TOOLS_DESCRIPTION, + } + if any(config.model_choices for config in types.values()): + properties["model"] = {"type": "string", "description": MODEL_DESCRIPTION} return { "type": "object", "properties": properties, @@ -378,8 +459,8 @@ def _type_line(name: str, config: AgentConfig, *, warn: bool = False) -> str: """How ``task`` offers ``config``: ``- (): ``. The notes say that an inheriting type sees the caller's conversation and - which brief fields the type needs beyond the title and the objective. A - type without a description is "The agent.", logged when ``warn``. + which brief fields the type needs beyond the title and the objective, and + names its model choices, last. A type without a description is "The agent.", logged when ``warn``. """ description = config.description.strip() if not description: @@ -392,5 +473,7 @@ def _type_line(name: str, config: AgentConfig, *, warn: bool = False) -> str: more = [field for field in BRIEF_FIELDS[1:] if field in config.brief_required] if more: notes.append(f"its brief also needs: {', '.join(more)}") + if config.model_choices: + notes.append(f"model choices: {', '.join(config.model_choices)}") head = f"- {name} ({'; '.join(notes)})" if notes else f"- {name}" return f"{head}: {description}" diff --git a/tests/workflow/deepagents/test_agent_builder.py b/tests/workflow/deepagents/test_agent_builder.py index 589057fc..539757f6 100644 --- a/tests/workflow/deepagents/test_agent_builder.py +++ b/tests/workflow/deepagents/test_agent_builder.py @@ -320,7 +320,7 @@ async def test_the_coordinator_is_offered_task_and_nothing_of_deep_agents_else(s schema = coordinator.tool_schema("task") assert set(schema["parameters"]["properties"]) == { "agent_type", "title", "objective", "deliverable", "constraints", "known", - "done_when", + "done_when", "tools", } assert schema["parameters"]["required"] == ["agent_type", "title", "objective"] diff --git a/tests/workflow/test_agent_brief.py b/tests/workflow/test_agent_brief.py index 864bfbbc..006fad86 100644 --- a/tests/workflow/test_agent_brief.py +++ b/tests/workflow/test_agent_brief.py @@ -9,7 +9,8 @@ ``INHERITED_CONTEXT_NOTE``. ``task_parameters`` and ``task_description`` are the tool's schema and description, which both backends build ``task`` from; ``follow_up_parameters`` and ``follow_up_description`` are the parent's other -tools'. +tools'. Every call may narrow its run's tools (``tools``), and one to a type +with model choices may pick one (``model``), which ``read_choices`` checks. """ from __future__ import annotations @@ -24,12 +25,15 @@ BRIEF_FIELDS, DEPTH_SENTENCE, INHERITED_CONTEXT_NOTE, + MODEL_DESCRIPTION, + TOOLS_DESCRIPTION, Brief, BriefError, TaskOffer, follow_up_description, follow_up_parameters, read_brief, + read_choices, task_description, task_message, task_offer, @@ -45,6 +49,18 @@ ) NOTES = AgentConfig(name="notes", prompt="p", inherit_context=True) TYPES = {"researcher": RESEARCHER, "writer": WRITER} +#: A type a delegation may run on a cheaper model. +CHOOSING = AgentConfig(name="checker", prompt="p", description="Checks a claim.", + model_choices=("fast", "anthropic:claude-haiku-4-5")) +#: The ``tools`` argument, as every ``task`` declares it. +TOOLS_ARGUMENT = { + "type": "array", + "items": {"type": "string"}, + "description": ( + "Optional: names of the agent's own tools to give this task, to narrow it; " + "leave it out for all of them." + ), +} @pytest.fixture @@ -257,17 +273,35 @@ def test_the_schema(self): ), }, "done_when": {"type": "string", "description": "The criteria for the task to be done."}, + "tools": TOOLS_ARGUMENT, }, "required": ["agent_type", "title", "objective"], } + def test_the_tools_and_model_arguments_texts(self): + assert TOOLS_DESCRIPTION == TOOLS_ARGUMENT["description"] + assert MODEL_DESCRIPTION == ( + "Optional: one of the agent's model choices (named with it below) to run this " + "task on; leave it out for its own model." + ) + + def test_a_model_argument_once_a_type_has_model_choices(self): + schema = task_parameters({"researcher": RESEARCHER, "checker": CHOOSING}) + properties = schema["properties"] + assert list(properties) == ["agent_type", "title", *BRIEF_FIELDS, "tools", "model"] + assert properties["model"] == {"type": "string", "description": MODEL_DESCRIPTION} + assert properties["agent_type"]["description"].endswith( + "- checker (model choices: fast, anthropic:claude-haiku-4-5): Checks a claim." + ) + assert schema["required"] == ["agent_type", "title", "objective"] + def test_it_is_json(self): schema = task_parameters(TYPES) assert json.loads(json.dumps(schema)) == schema def test_its_arguments_are_the_ones_read_brief_reads(self): properties = task_parameters(TYPES)["properties"] - assert list(properties) == ["agent_type", "title", *BRIEF_FIELDS] + assert list(properties) == ["agent_type", "title", *BRIEF_FIELDS, "tools"] def test_it_warns_of_nothing(self, logged): task_parameters({"notes": NOTES}) @@ -292,6 +326,13 @@ def test_the_description(self, logged): ) assert logged == [] + def test_a_types_model_choices_are_named_last_in_its_notes(self): + both = dataclasses.replace(CHOOSING, brief_required=("objective", "known")) + text = task_description({"checker": both}, SubAgentPolicy()) + assert text.endswith( + "- checker (its brief also needs: known; model choices: fast, " + "anthropic:claude-haiku-4-5): Checks a claim." + ) def test_an_inheriting_type_says_so(self): text = task_description({"notes": NOTES, "researcher": RESEARCHER}, SubAgentPolicy()) assert "- notes (sees this conversation, so the brief need not repeat it): " in text @@ -376,6 +417,72 @@ def test_with_the_depth_sentence_and_the_warning(self, logged): assert [e["event"] for e in logged] == ["subagent_without_description"] +#: What a type's own tools are called, as its backend lists them. +OWN = frozenset({"lookup", "fetch_page", "mcp_search"}) + + +class TestReadChoices: + """``read_choices``: the tools and the model a ``task`` call gives its run, + each None when left out; anything but some of the type's own tools, or + one of its model choices, is a ``BriefError`` naming what it may be.""" + + def test_both_left_out(self): + assert read_choices({"agent_type": "checker"}, CHOOSING) == (None, None) + + def test_null_is_left_out(self): + assert read_choices({"tools": None, "model": None}, CHOOSING, OWN) == (None, None) + + def test_some_of_its_own_tools(self): + tools, model = read_choices({"tools": ["lookup", "mcp_search", "lookup"]}, CHOOSING, OWN) + assert (tools, model) == (frozenset({"lookup", "mcp_search"}), None) + + def test_none_of_them_is_a_narrowing_too(self): + assert read_choices({"tools": []}, CHOOSING, OWN) == (frozenset(), None) + + @pytest.mark.parametrize("tools", [["lookup", "write_file"], "lookup", [3], {"lookup": 1}]) + def test_anything_else_names_its_own(self, tools): + with pytest.raises(BriefError) as exc: + read_choices({"tools": tools}, CHOOSING, OWN) + assert str(exc.value) == ( + "The tools for 'checker' must be some of its own: fetch_page, lookup, mcp_search." + ) + + def test_a_type_with_no_tools_of_its_own(self): + with pytest.raises(BriefError) as exc: + read_choices({"tools": ["lookup"]}, CHOOSING, frozenset()) + assert str(exc.value) == "'checker' has no tools of its own; leave tools out." + assert read_choices({"tools": []}, CHOOSING, frozenset()) == (frozenset(), None) + + @pytest.mark.parametrize("given, chosen", [ + ("fast", "fast"), (" anthropic:claude-haiku-4-5 ", "anthropic:claude-haiku-4-5"), + ]) + def test_one_of_its_model_choices_as_written(self, given, chosen): + assert read_choices({"model": given}, CHOOSING) == (None, chosen) + + @pytest.mark.parametrize("model", ["strong", "claude-haiku-4-5", "", 3]) + def test_any_other_model_names_its_choices(self, model): + with pytest.raises(BriefError) as exc: + read_choices({"model": model}, CHOOSING) + assert str(exc.value) == ( + "The model for 'checker' must be one of its model choices: fast, " + "anthropic:claude-haiku-4-5." + ) + + def test_a_type_with_no_model_choices(self): + with pytest.raises(BriefError) as exc: + read_choices({"model": "fast"}, RESEARCHER) + assert str(exc.value) == "'researcher' has no model choices; leave model out." + + def test_the_tools_are_read_first(self): + with pytest.raises(BriefError, match="The tools for 'checker'"): + read_choices({"tools": ["nope"], "model": "nope"}, CHOOSING, OWN) + + def test_read_brief_takes_both_arguments(self): + arguments = {"agent_type": "checker", "title": "T", "objective": "O", + "tools": ["lookup"], "model": "fast"} + config, brief = read_brief(arguments, {"checker": CHOOSING}) + assert (config, brief) == (CHOOSING, Brief(title="T", objective="O")) + AGENT_ID = "The sub-agent's id, such as researcher-2." diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 21dbeff2..11d2896d 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -6317,7 +6317,8 @@ async def test_in_agent_yaml(self, make_crew, project): #: ``task``'s declaration for ``team()``'s coordinator, as both backends send it -#: with the default policy: what an app that starts no type at run time keeps. +#: with the default policy: what an app that starts no type at run time keeps, +#: and the ``tools`` every call may narrow its run to. TEAM_TASK = { "description": ( "Hand a task to a sub-agent. The sub-agent works on it on its own, with its own " @@ -6352,6 +6353,13 @@ async def test_in_agent_yaml(self, make_crew, project): ), }, "done_when": {"type": "string", "description": "The criteria for the task to be done."}, + "tools": { + "type": "array", "items": {"type": "string"}, + "description": ( + "Optional: names of the agent's own tools to give this task, to narrow " + "it; leave it out for all of them." + ), + }, }, "required": ["agent_type", "title", "objective"], }, @@ -6370,7 +6378,8 @@ def agent_types(declared: dict[str, Any] | None) -> list[str]: class TestTheDefaultPolicyKeepsTask: - """With nothing started at run time, ``task`` is what it was, byte for byte.""" + """With nothing started at run time, ``task`` is what it was, byte for byte, + but for the ``tools`` argument every call has.""" async def test_its_schema_and_description(self, make_crew): crew = make_crew(team(), coordinator=[says("Hi.")]) From 2bf8a7d3fd561692604bd13ac31d4f5a9896105d Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:23:41 -0500 Subject: [PATCH 04/11] Sub-agents: an instance's records keep its tools and model A first run's AGENT_RUN start may carry the tools and the model choice its delegation gave it (WorkflowEvent.agent_run(tools=, model=)); its instance keeps them (InstanceRecord.tools, .model), exported with the records and read back, records written before them reading as all its tools and its type's own model. --- src/agentic_cli/workflow/agents/runs.py | 41 ++++++++++++++- src/agentic_cli/workflow/events.py | 14 ++++- tests/workflow/test_agent_run_event.py | 17 ++++++ tests/workflow/test_agent_runs.py | 69 ++++++++++++++++++++++++- 4 files changed, 137 insertions(+), 4 deletions(-) diff --git a/src/agentic_cli/workflow/agents/runs.py b/src/agentic_cli/workflow/agents/runs.py index 529f90e9..48c119a8 100644 --- a/src/agentic_cli/workflow/agents/runs.py +++ b/src/agentic_cli/workflow/agents/runs.py @@ -199,6 +199,12 @@ class InstanceRecord: status: One of ``INSTANCE_STATUSES``. runs: Its run ids, oldest first. continuable: Whether its type takes follow-ups, as it was when it started. + tools: The type's own tools its first run's delegation narrowed it to + (``task``'s ``tools``; empty for none of them); None for all of + them. Every run of it keeps them. + model: The model choice its first run's delegation ran it on, as the + type writes it (``task``'s ``model``); None for the type's own + model. Every run of it keeps it. """ instance: str @@ -210,6 +216,8 @@ class InstanceRecord: status: str runs: list[str] = field(default_factory=list) continuable: bool = True + tools: tuple[str, ...] | None = None + model: str | None = None def own_plan_and_tasks(state: Mapping[str, Any]) -> tuple[str, list[dict[str, Any]]]: @@ -490,7 +498,7 @@ def export(self, conversation: SessionRef | None) -> dict[str, Any]: ``{"v": RECORDS_VERSION, "saved": , "numbered": {type: n}, "instances": [...], "runs": [...]}``: each instance's fields - (``InstanceRecord``) and each run's (``RunRecord``, its ``ref``'s + (``InstanceRecord``, its ``tools`` a list) and each run's (``RunRecord``, its ``ref``'s fields first, its times as ISO text, and ``end``: where its end was recorded, 0 for none yet), in the order they started, and the highest instance number of each type. ``saved`` is when this was @@ -503,7 +511,7 @@ def export(self, conversation: SessionRef | None) -> dict[str, Any]: agent: count for (owner, agent), count in self._numbered.items() if owner == conversation }, - "instances": [asdict(one) for one in self.instances(conversation)], + "instances": [_instance_value(one) for one in self.instances(conversation)], "runs": [ _run_value(record, self.end_order(conversation, record.ref.run or "")) for record in self.records(conversation) @@ -603,6 +611,7 @@ def _instance_of( instances = self._instances.setdefault(conversation, {}) record = instances.get(ref.instance) if record is None: + tools = metadata.get("tools") record = instances[ref.instance] = InstanceRecord( instance=ref.instance, agent=ref.agent, @@ -612,6 +621,8 @@ def _instance_of( title=metadata.get("title") or "", status=INSTANCE_RUNNING, continuable=bool(metadata.get("continuable", True)), + tools=tuple(tools) if tools is not None else None, + model=metadata.get("model"), ) return record @@ -640,6 +651,14 @@ def stored_instance_ids(data: Any) -> list[str] | None: ] +def _instance_value(instance: InstanceRecord) -> dict[str, Any]: + """An instance's record as ``export`` writes it: JSON-safe, its tools a list.""" + value = asdict(instance) + if instance.tools is not None: + value["tools"] = list(instance.tools) + return value + + def _run_value(record: RunRecord, end: int) -> dict[str, Any]: """A run's record as ``export`` writes it: JSON-safe, ``end`` where its end was recorded.""" ref = record.ref @@ -721,9 +740,27 @@ def _instance_from(value: Any) -> InstanceRecord: status=status, runs=list(runs), continuable=_get(value, "continuable", bool), + # Written since records first kept them: missing in older ones (all + # of the type's tools, its own model). + tools=_tools(value.get("tools")), + model=_get_new(value, "model", str, _NONE), ) +def _tools(value: Any) -> tuple[str, ...] | None: + if value is None: + return None + if type(value) is not list or not all(type(name) is str for name in value): + raise TypeError("tools that are not a list of names") + return tuple(value) + + +def _get_new(value: Mapping[str, Any], name: str, *kinds: type) -> Any: + """``value[name]`` as ``_get`` reads it, None when it is missing (a field + added since a version's first records).""" + return _get(value, name, *kinds) if name in value else None + + def _run_from(value: Any) -> RunRecord: if not isinstance(value, Mapping): raise TypeError("a run that is not an object") diff --git a/src/agentic_cli/workflow/events.py b/src/agentic_cli/workflow/events.py index a81b6a84..9d2cfd33 100644 --- a/src/agentic_cli/workflow/events.py +++ b/src/agentic_cli/workflow/events.py @@ -22,6 +22,7 @@ print(f"Result: {event.metadata['result']}") """ +from collections.abc import Sequence from dataclasses import dataclass, field from datetime import datetime from enum import Enum @@ -214,6 +215,8 @@ def agent_run( input: str | None = None, inherit_context: bool | None = None, continuable: bool | None = None, + tools: Sequence[str] | None = None, + model: str | None = None, ) -> "WorkflowEvent": """Create a sub-agent run's event: its start, or how it ended (``AGENT_RUN``). @@ -221,7 +224,7 @@ def agent_run( ``started`` (with its ``title``, its ``brief``, who it was ``started_by`` and its ``mode``; a first run of an instance also says whether the instance ``inherit_context`` and is ``continuable``, - and a follow-up's start carries its ``input``, the message as + and the ``tools`` and ``model`` its delegation gave it; a follow-up's start carries its ``input``, the message as written), then one end status (``completed``, ``failed``, ``refused``, ``cancelled``, ``interrupted``: the constants of ``workflow/agents/runs.py``) with the first of its ``result``, its @@ -254,6 +257,11 @@ def agent_run( its parent's conversation. continuable: A first run's start: whether its instance takes follow-ups. + tools: A first run's start: the type's own tools its delegation + narrowed it to (``metadata["tools"]``, a list, empty for none + of them); None for all of them. + model: A first run's start: the model choice it runs on, as the + type writes it; None for the type's own model. """ metadata: dict[str, Any] = {"status": status, "agent": ref.agent, "partial": partial} if title is not None: @@ -286,6 +294,10 @@ def agent_run( metadata["inherit_context"] = inherit_context if continuable is not None: metadata["continuable"] = continuable + if tools is not None: + metadata["tools"] = list(tools) + if model is not None: + metadata["model"] = model return cls( type=EventType.AGENT_RUN, content=f"{ref.instance} {status}", diff --git a/tests/workflow/test_agent_run_event.py b/tests/workflow/test_agent_run_event.py index 2ce794ba..b5c5e077 100644 --- a/tests/workflow/test_agent_run_event.py +++ b/tests/workflow/test_agent_run_event.py @@ -90,6 +90,23 @@ def test_a_first_runs_start_carries_what_its_instance_keeps(self): assert (event.metadata["inherit_context"], event.metadata["continuable"]) == (True, False) + def test_a_first_runs_start_carries_the_tools_and_model_it_was_given(self): + event = WorkflowEvent.agent_run( + RESEARCHER, "started", title="Find X.", tools=("lookup", "fetch"), model="fast" + ) + + assert (event.metadata["tools"], event.metadata["model"]) == (["lookup", "fetch"], "fast") + + def test_none_of_its_own_tools_is_said_too(self): + event = WorkflowEvent.agent_run(RESEARCHER, "started", title="Find X.", tools=[]) + + assert event.metadata["tools"] == [] + assert "model" not in event.metadata + + def test_no_tools_or_model_unless_given(self): + event = WorkflowEvent.agent_run(RESEARCHER, "started", title="Find X.") + + assert "tools" not in event.metadata and "model" not in event.metadata def test_a_follow_ups_start_carries_its_input(self): second = RunRef("researcher", "researcher-1", "researcher-1#2", None, 1) diff --git a/tests/workflow/test_agent_runs.py b/tests/workflow/test_agent_runs.py index e81e2b41..e9ac23fe 100644 --- a/tests/workflow/test_agent_runs.py +++ b/tests/workflow/test_agent_runs.py @@ -442,7 +442,35 @@ def test_a_start_without_them_keeps_the_defaults(self): record = runs.instance(ONE, "researcher-1") assert (record.inherit_context, record.continuable) == (False, True) + assert (record.tools, record.model) == (None, None) + def test_a_first_runs_start_keeps_the_tools_and_model_it_was_given(self): + runs = AgentRuns() + ref = runs.run_for(ONE, None, "c1", "researcher") + + in_turn(ONE, lambda: runs.observe(WorkflowEvent.agent_run( + ref, RUN_STARTED, title="Find X.", call_id="c1", tools=["lookup", "fetch"], + model="fast", + ))) + + record = runs.instance(ONE, "researcher-1") + assert (record.tools, record.model) == (("lookup", "fetch"), "fast") + + def test_a_follow_ups_start_changes_neither(self): + runs = AgentRuns() + ref = runs.run_for(ONE, None, "c1", "researcher") + in_turn(ONE, lambda: runs.observe(WorkflowEvent.agent_run( + ref, RUN_STARTED, title="Find X.", call_id="c1", tools=[], model="fast", + ))) + ended(runs, ONE, ref) + second = runs.next_run(ONE, "researcher-1", parent_run=None) + + in_turn(ONE, lambda: runs.observe(WorkflowEvent.agent_run( + second, RUN_STARTED, title="Go on.", call_id="c2", input="Go on.", + ))) + + record = runs.instance(ONE, "researcher-1") + assert (record.tools, record.model) == ((), "fast") def test_a_childs_parent_is_its_parent_runs_instance(self): runs = AgentRuns() middle = started(runs, ONE, "c1", "middle") @@ -691,7 +719,7 @@ def a_conversation(runs: AgentRuns) -> None: in_turn(ONE, lambda: runs.observe(WorkflowEvent.agent_run( first, RUN_STARTED, title="Find X.", call_id="c1", brief={"title": "Find X.", "objective": "Find X."}, started_by="agent:root", mode="blocking", - inherit_context=False, continuable=True, + inherit_context=False, continuable=True, tools=["lookup"], model="fast", ))) ended(runs, ONE, first, usage={"m": {"input": 120, "output": 30}}, instance_status="idle") second = runs.next_run(ONE, "researcher-1", parent_run=None) @@ -754,6 +782,7 @@ def test_its_shape(self): "instance": "researcher-1", "agent": "researcher", "parent": "root", "depth": 1, "inherit_context": False, "title": "researcher work", "status": INSTANCE_IDLE, "runs": ["researcher-1#1"], "continuable": True, + "tools": None, "model": None, }], "runs": [{ "run": "researcher-1#1", "agent": "researcher", "instance": "researcher-1", @@ -848,6 +877,44 @@ def test_records_it_cannot_read_change_nothing(self, data): assert (runs.records(ONE), runs.instances(ONE)) == before + def test_an_instances_tools_are_a_list_and_read_back_as_given(self): + runs = AgentRuns() + a_conversation(runs) + + data = json.loads(json.dumps(runs.export(ONE))) + + assert (data["instances"][0]["tools"], data["instances"][0]["model"]) == ( + ["lookup"], "fast" + ) + again = AgentRuns() + again.restore(ONE, data) + assert (again.instance(ONE, "researcher-1").tools, + again.instance(ONE, "researcher-1").model) == (("lookup",), "fast") + + def test_records_written_before_tools_and_model_read_them_as_none(self): + runs = AgentRuns() + a_conversation(runs) + data = json.loads(json.dumps(runs.export(ONE))) + for instance in data["instances"]: + del instance["tools"], instance["model"] + again = AgentRuns() + + assert again.restore(ONE, data) == ["writer-1#1"] + + assert {(i.tools, i.model) for i in again.instances(ONE)} == {(None, None)} + + @pytest.mark.parametrize("field, value", [ + ("tools", "lookup"), ("tools", [1]), ("tools", {"lookup": True}), ("model", 3), + ("model", ["fast"]), + ]) + def test_tools_or_a_model_that_do_not_read_are_records_it_cannot_read(self, field, value): + runs = AgentRuns() + a_conversation(runs) + data = json.loads(json.dumps(runs.export(ONE))) + data["instances"][0][field] = value + + with pytest.raises(ValueError, match="do not read"): + AgentRuns().restore(ONE, data) def test_the_instances_records_name(self): runs = AgentRuns() a_conversation(runs) From a2c791ccf9d0afb6bb31345c96a234c1b5a3984f Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:26:15 -0500 Subject: [PATCH 05/11] Sub-agents: a delegation's tools and model, checked and kept Delegations.delegate reads task's tools against the type's own (its backend's names, tool_names=, asked only for a call that names some) and its model against the type's choices, after the brief: anything else is the call's error result, no run started and none counted. The run, its control (RunControl.tools, keeps: its tools and the state and delegation tools) and its instance get them; every follow-up runs with them, and one whose type no longer has them is refused. --- src/agentic_cli/workflow/agents/control.py | 21 ++ src/agentic_cli/workflow/agents/delegate.py | 145 ++++++++++++-- tests/workflow/test_agent_control.py | 28 +++ tests/workflow/test_agent_delegate.py | 211 ++++++++++++++++++++ tests/workflow/test_subagents_contract.py | 44 ++++ 5 files changed, 434 insertions(+), 15 deletions(-) diff --git a/src/agentic_cli/workflow/agents/control.py b/src/agentic_cli/workflow/agents/control.py index 1bd2f046..66accceb 100644 --- a/src/agentic_cli/workflow/agents/control.py +++ b/src/agentic_cli/workflow/agents/control.py @@ -32,6 +32,9 @@ stays unstored until its backend says the run's transcript holds it (``stored``); ``Delegations`` gives the unstored ones (``unstored``) to the instance's next run, so a message is never lost. +- ``tools`` narrows the run: the backend offers the model only those (and + ``KEPT_TOOLS``), and answers a call of any other as one of a tool the + agent does not have; ``keeps(tool)`` says whether the run may use it. - ``stop_cause`` is what a call the run left at its permission prompt, or running, is told stopped the run: its parent, its time limit or its token limit (None for the user's stop). @@ -61,6 +64,14 @@ "You have reached the most model calls this task may make. Answer now with your best " "result from what you have; no tools are available for this answer." ) +#: The tools a narrowed run keeps whatever its ``tools``: its plan's (the state +#: tools, ``tools/_core/state_tools.py``) and the delegation tools +#: (``tools/_core/delegation.py``), which follow what the run may start. Named +#: here, not imported: this module imports no tool. +KEPT_TOOLS = frozenset({ + "save_plan", "get_plan", "save_tasks", "get_tasks", + "task", "message_agent", "stop_agent", "check_agents", +}) #: Who cancels a run at one of its limits. LIMIT = "limit" #: What stopped a run, as a call it left at its prompt is told. @@ -79,10 +90,13 @@ class RunControl: tools' side calls, its summaries; not its own steps, which ``used`` counts), input plus output tokens, as its usage record counts them: counted with its own at each check. None: none. + tools: The type's own tools this run may use, by name; None: all of + them. ``KEPT_TOOLS`` are kept whatever it says. Attributes: ref: The run. limits: Its limits. + tools: The names it narrowed the run's tools to, or None. cancelled: ``(by, error)`` once it is cancelled: who cancelled it (``parent``, ``user`` or ``limit``) and why, one line. """ @@ -93,9 +107,11 @@ def __init__( limits: AgentLimits, *, side_tokens: Callable[[], int] | None = None, + tools: frozenset[str] | None = None, ) -> None: self.ref = ref self.limits = limits + self.tools = tools self._side_tokens = side_tokens self.cancelled: tuple[str, str] | None = None self._steering: list[str] = [] @@ -111,6 +127,11 @@ def __init__( # Whether the hook said the run's work has ended (finish()). self._finished = False + def keeps(self, tool: str) -> bool: + """Whether the run may use ``tool``: all of them unless narrowed, then its + ``tools`` and ``KEPT_TOOLS``.""" + return self.tools is None or tool in self.tools or tool in KEPT_TOOLS + # -- the run's task -------------------------------------------------------- def bind(self, task: asyncio.Task[Any]) -> None: diff --git a/src/agentic_cli/workflow/agents/delegate.py b/src/agentic_cli/workflow/agents/delegate.py index 8477d4f7..d94c7c1c 100644 --- a/src/agentic_cli/workflow/agents/delegate.py +++ b/src/agentic_cli/workflow/agents/delegate.py @@ -8,8 +8,11 @@ - reads the brief against what the calling run may start (``brief.read_brief``; ``offered``: its own sub-agents, then, while the run's depth is below ``max_spawn_depth``, the types agents start at run time, - ``agents/spawn.py``): a brief that cannot start a run is the call's error - result, and nothing else happens (no run, no record, no event); + ``agents/spawn.py``), then its tools against the type's own and its model + against the type's choices (``brief.read_choices``): a brief that cannot + start a run, tools that are not some of the type's own and a model that is + none of its choices are the call's error result, and nothing else happens + (no run, no record, no event, no count); Then ``start``, the one entry for an instance's first run, whoever starts it (a ``StartRequest``: the type, the brief, who starts it): @@ -54,6 +57,11 @@ hold when the run ends (``RunControl.unstored``) is kept for the instance's next run, which starts with it steered: a message is never lost. +Every run of an instance has the tools and the model its first run's +delegation gave it (``AgentRun.tools``, ``AgentRun.model``, kept in its +``InstanceRecord``); a follow-up to an instance whose type no longer has +them is refused (``CHOICE_GONE_ERROR``). + Each run works under its ``RunControl`` (``agents/control.py``, ``AgentRun.control``): its limits (its type's over the policy's), the time limit running while the hook does, and a cancel of the run alone @@ -108,7 +116,15 @@ from __future__ import annotations import asyncio -from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mapping, Sequence +from collections.abc import ( + AsyncIterator, + Awaitable, + Callable, + Collection, + Iterator, + Mapping, + Sequence, +) from contextlib import asynccontextmanager, contextmanager from contextvars import ContextVar from dataclasses import dataclass, field @@ -122,10 +138,11 @@ BriefError, TaskOffer, read_brief, + read_choices, task_message, task_offer, ) -from agentic_cli.workflow.agents.control import PARENT_CAUSE, RunControl +from agentic_cli.workflow.agents.control import KEPT_TOOLS, PARENT_CAUSE, RunControl from agentic_cli.workflow.agents.envelope import ( CANCELLED_BY, INTERRUPTED_ERROR, @@ -207,6 +224,12 @@ STOPPED_ERROR = "{instance} was stopped by the user; only the user can continue it." RUNNING_ERROR = "{instance} is running: an instance runs one run at a time." TYPE_GONE_ERROR = "{instance}'s type '{agent}' is not one of this app's agents." +#: A follow-up to an instance started with a model or tools its type no longer has +#: (``what``: ``the model `` or ``the tools , ``). +CHOICE_GONE_ERROR = ( + "{instance} was started with {what}, which '{agent}' no longer has; " + "start a new one with task." +) NO_MESSAGE_ERROR = "A follow-up needs a message." #: A message that is not text, or is blank. MESSAGE_NEEDED_ERROR = "message_agent needs a message." @@ -303,6 +326,11 @@ class StartRequest: counted: Whether the run counts toward its turn's runs (``SubAgentPolicy.max_runs_per_turn``); False for a run the user starts. + tools: The type's own tools the run may use (the asker checked them + against the type's: ``read_choices``); None: all of them. Every + later run of the instance keeps them. + model: One of the type's ``model_choices``, as written, to run it on; + None: the type's own model. Every later run keeps it. """ agent_type: str @@ -314,6 +342,8 @@ class StartRequest: state: Mapping[str, Any] = field(default_factory=dict) history: Callable[[], Any] | None = None counted: bool = True + tools: frozenset[str] | None = None + model: str | None = None @dataclass(frozen=True) @@ -336,6 +366,10 @@ class AgentRun: exists, ``message`` is the follow-up as written (no task message), ``history`` is None, and ``state`` is the caller's shared state (the outside-content mark). + tools: The type's own tools it may use (``control.tools``); None: all. + model: The type's model choice it runs on, as ``model_choices`` + writes it; the backend runs the type's agent built on it. None: + the type's own model. """ ref: RunRef @@ -346,10 +380,14 @@ class AgentRun: history: Any = None control: RunControl = None # type: ignore[assignment] # filled below when None follow_up: bool = False + tools: frozenset[str] | None = None + model: str | None = None def __post_init__(self) -> None: if self.control is None: - object.__setattr__(self, "control", RunControl(self.ref, AgentLimits())) + object.__setattr__( + self, "control", RunControl(self.ref, AgentLimits(), tools=self.tools) + ) @dataclass(frozen=True) @@ -430,6 +468,8 @@ class Delegated: #: How many instances of each type a conversation's store already keeps, by #: type: the highest instance number (``BaseWorkflowManager._stored_instances``). StoredInstances = Callable[[SessionRef], Awaitable[Mapping[str, int]]] +#: A backend's names for an agent type's own tools (``_agent_tool_names``). +ToolNames = Callable[[str], Awaitable[Collection[str]]] @dataclass @@ -562,6 +602,10 @@ class Delegations: named, so what another manager ran there (before a restart, or in another process between two turns) is numbered past. None: every conversation is numbered from 1. + tool_names: The names of an agent type's own tools, as its backend + gives them (``BaseWorkflowManager._agent_tool_names``), asked + only for a call that names ``tools`` and for a follow-up of a + narrowed instance. None: the names of the type's configured tools. """ def __init__( @@ -574,6 +618,7 @@ def __init__( ledgers: UsageLedgers | None = None, stored: StoredInstances | None = None, open_calls: OpenCalls | None = None, + tool_names: ToolNames | None = None, ) -> None: self._runs = runs self.policy = policy @@ -582,6 +627,7 @@ def __init__( self._ledgers = ledgers self._stored = stored self._open_calls = open_calls + self._tool_names = tool_names # Each conversation's turn its stored instances were last read in # (its span, ``current_turn_scope``: held here, so no later turn's # can be the same object), and each conversation's lock, which a @@ -655,21 +701,27 @@ def task_offer( async def delegate(self, request: DelegationRequest) -> Delegated: """Run the sub-agent ``request`` asks for, to its end; its envelope. - A brief that cannot start a run is the error result, and nothing - else happens; otherwise it ends in ``start``, started by the - calling run. + A brief that cannot start a run, then tools that are not some of the + type's own and a model that is none of its choices, is the error + result, and nothing else happens (no run, no count); otherwise it ends + in ``start``, started by the calling run. """ depth = request.caller.depth if request.caller is not None else 0 try: config, brief = read_brief( request.arguments, self.offered(request.caller_agent, depth) ) + own = ( + await self._own_tools(config) + if request.arguments.get("tools") is not None else () + ) + tools, model = read_choices(request.arguments, config, own) except BriefError as error: return _refused(str(error)) return await self.start(StartRequest( agent_type=config.name, brief=brief, started_by=started_by(request.caller), caller=request.caller, call_id=request.call_id, state=request.state, - history=request.history, + history=request.history, tools=tools, model=model, )) async def start(self, request: StartRequest) -> Delegated: @@ -704,12 +756,15 @@ async def start(self, request: StartRequest) -> Delegated: ref, RUN_STARTED, call_id=request.call_id, title=run_title(brief.title), brief=brief.fields(), started_by=request.started_by, mode=BLOCKING, inherit_context=config.inherit_context, continuable=config.continuable, + tools=sorted(request.tools) if request.tools is not None else None, + model=request.model, )) return await self._run( ref, config, conversation, request.call_id, message=task_message(brief, inherit=config.inherit_context), state=request.state, history=request.history if config.inherit_context else None, + tools=request.tools, model=request.model, ) async def follow_up( @@ -726,14 +781,20 @@ async def follow_up( the user continues it), a running one (one run per instance at a time) and a blank message. An agent's follow-up counts toward its turn's runs (``SubAgentPolicy.max_runs_per_turn``), the user's does - not. Everything up to the run's start event is one synchronous step, - so two follow-ups of one instance cannot both start. + not. The run has the tools and the model its instance's first run + had; an instance whose type no longer has its model or some of its + tools is refused (``CHOICE_GONE_ERROR``). Everything up to the run's + start event is one synchronous step, so two follow-ups of one + instance cannot both start: the type's tool names a narrowed instance + is checked against are awaited before it, which suspends only where + a backend lists them for the first time. """ conversation = ( request.conversation if request.conversation is not None else get_active_turn() ) + own = await self._instance_tools(conversation, request.instance) with _as_turn(conversation): - error = self._follow_up_refused(conversation, request) + error = self._follow_up_refused(conversation, request, own_tools=own) if error is not None: return Delegated(result={"success": False, "error": error}, state={}, run=None) instance = self._runs.instance(conversation, request.instance) @@ -759,6 +820,8 @@ async def follow_up( return await self._run( ref, config, conversation, request.call_id, message=request.message, state=request.state, history=None, follow_up=True, + tools=frozenset(instance.tools) if instance.tools is not None else None, + model=instance.model, ) def close(self, conversation: SessionRef | None, instance: str, *, reason: str) -> list[str]: @@ -826,6 +889,7 @@ async def message( conversation = ( request.conversation if request.conversation is not None else get_active_turn() ) + own = await self._instance_tools(conversation, request.instance) with _as_turn(conversation): if not isinstance(request.message, str) or not request.message.strip(): return _refused(MESSAGE_NEEDED_ERROR) @@ -847,7 +911,9 @@ async def message( ended = self._ends[(conversation, ref.run or "")] made_here = False if interrupt and not stopping: - error = self._follow_up_refused(conversation, request, running_ok=True) + error = self._follow_up_refused( + conversation, request, running_ok=True, own_tools=own + ) if error is None and request.started_by != USER: refused = self._past_runs_per_turn(ref.agent) error = refused.result["error"] if refused is not None else None @@ -1213,11 +1279,15 @@ def _follow_up_refused( request: FollowUpRequest, *, running_ok: bool = False, + own_tools: Collection[str] | None = None, ) -> str | None: """Why ``request`` cannot start a run, else None. ``running_ok``: a running instance is no reason (an interrupt asks whether the message could start a run once the instance's run ends). + ``own_tools``: the names of the instance's type's own tools now + (``_instance_tools``), which a narrowed instance's must still be + among; None: not checked. """ message = request.message if not isinstance(message, str) or not message.strip(): @@ -1238,8 +1308,45 @@ def _follow_up_refused( return RUNNING_ERROR.format(instance=found.instance) if found.agent not in self._types: return TYPE_GONE_ERROR.format(instance=found.instance, agent=found.agent) + config = self._types[found.agent] + what = None + if found.model is not None and found.model not in config.model_choices: + what = f"the model {found.model}" + elif found.tools is not None and own_tools is not None: + gone = sorted(set(found.tools) - set(own_tools)) + if gone: + what = f"the tools {', '.join(gone)}" + if what is not None: + return CHOICE_GONE_ERROR.format(instance=found.instance, what=what, agent=found.agent) return None + async def _own_tools(self, config: AgentConfig) -> Collection[str]: + """The names of ``config``'s own tools: its backend's, else its configured tools'.""" + if self._tool_names is not None: + return await self._tool_names(config.name) + names = ( + tool if isinstance(tool, str) else getattr(tool, "__name__", "") + for tool in config.tools + ) + return frozenset(name for name in names if name and name not in KEPT_TOOLS) + + async def _instance_tools( + self, conversation: SessionRef | None, instance: str + ) -> frozenset[str] | None: + """The names of the own tools of ``instance``'s type, when it is a narrowed one; else None. + + What a follow-up checks the instance's tools against. Awaited before + the follow-up's synchronous step, and only for an instance that has + tools to check, so any other never waits. + """ + record = self._runs.instance(conversation, instance) + if record is None or record.tools is None: + return None + config = self._types.get(record.agent) + if config is None: + return None + return frozenset(await self._own_tools(config)) + async def _run( self, ref: RunRef, @@ -1251,14 +1358,18 @@ async def _run( state: Mapping[str, Any], history: Callable[[], Any] | None, follow_up: bool = False, + tools: frozenset[str] | None = None, + model: str | None = None, ) -> Delegated: """Run ``ref``'s run, started and reported already, to its end; its envelope. What a first run and a follow-up share: the run's control, its task, - the caller's slot lent while it waits. + the caller's slot lent while it waits. ``tools`` and ``model`` are + the instance's. """ control = RunControl( - ref, self._limits(config), side_tokens=self._side_tokens(conversation, ref) + ref, self._limits(config), side_tokens=self._side_tokens(conversation, ref), + tools=tools, ) # What an earlier run was steered and did not store: this run's, after its own message. for unread in self._unread.pop((conversation, ref.instance), ()): @@ -1267,6 +1378,7 @@ async def _run( self._in_run( ref, config, conversation, call_id, control, message=message, state=state, history=history, follow_up=follow_up, + model=model, ), name=f"agent run {ref.run}", ) @@ -1452,6 +1564,7 @@ async def _in_run( state: Mapping[str, Any], history: Callable[[], Any] | None, follow_up: bool, + model: str | None = None, ) -> RunAnswer: """The run, in its own task: the active run, and no tool call active. @@ -1475,6 +1588,8 @@ async def _in_run( history=history() if history is not None else None, control=control, follow_up=follow_up, + tools=control.tools, + model=model, ) pool = self.slots(conversation) queued = pool.free == 0 diff --git a/tests/workflow/test_agent_control.py b/tests/workflow/test_agent_control.py index 338f204d..8bd6bae5 100644 --- a/tests/workflow/test_agent_control.py +++ b/tests/workflow/test_agent_control.py @@ -14,6 +14,7 @@ import pytest from agentic_cli.workflow.agents.control import ( + KEPT_TOOLS, PARENT_CAUSE, STEP_LIMIT_NOTE, TIME_LIMIT_CAUSE, @@ -416,3 +417,30 @@ def test_one_whose_work_has_ended_is(self): made.finish() assert made.stopping is True + + +class TestTheToolsItKeeps: + """A narrowed run's tools: its own ``tools``, and those every run keeps.""" + + def test_a_run_not_narrowed_keeps_every_tool(self): + control = RunControl(REF, AgentLimits()) + + assert control.tools is None + assert control.keeps("lookup") and control.keeps("anything") + + def test_a_narrowed_run_keeps_its_tools_its_plan_and_its_delegation_tools(self): + control = RunControl(REF, AgentLimits(), tools=frozenset({"lookup"})) + + names = ["lookup", "fetch_page", "save_plan", "get_tasks", "task", "check_agents"] + assert [name for name in names if control.keeps(name)] == [ + "lookup", "save_plan", "get_tasks", "task", "check_agents", + ] + assert not RunControl(REF, AgentLimits(), tools=frozenset()).keeps("lookup") + + def test_every_run_keeps_the_state_tools_and_the_delegation_tools(self): + from agentic_cli.tools._core import state_tools + from agentic_cli.tools._core.delegation import FOLLOW_UP_TOOLS, TASK_TOOL + + assert KEPT_TOOLS == { + *(name for name, _ in state_tools._STATE_TOOLS), TASK_TOOL, *FOLLOW_UP_TOOLS, + } diff --git a/tests/workflow/test_agent_delegate.py b/tests/workflow/test_agent_delegate.py index e67df250..dc21208d 100644 --- a/tests/workflow/test_agent_delegate.py +++ b/tests/workflow/test_agent_delegate.py @@ -4096,3 +4096,214 @@ async def test_a_start_blocks_no_event_loop(): out, events = await started(delegations(hook), start_request()) assert out["result"].result["status"] == RUN_COMPLETED + + +# -- a delegation's tools and model: narrowed tools, a model choice -------------------- + +#: A type a delegation may narrow and run on a cheaper model. +CHOOSY = AgentConfig(name="choosy", prompt="p", description="Chooses.", + model_choices=("fast", "anthropic:claude-haiku-4-5")) +CHOOSING = {**TYPES, "coordinator": AgentConfig( + name="coordinator", prompt="p", sub_agents=["researcher", "choosy"]), "choosy": CHOOSY} +NARROW = {"agent_type": "choosy", "title": "Look", "objective": "Look X up.", + "tools": ["lookup"], "model": "fast"} + + +def own_tools(names: dict[str, set[str]], asked: list[str] | None = None): + """A backend's hook for each type's own tools (``_agent_tool_names``), recording who asked.""" + async def tool_names(agent: str) -> frozenset[str]: + if asked is not None: + asked.append(agent) + return frozenset(names.get(agent, ())) + + return tool_names + + +OWN = {"choosy": {"lookup", "fetch_page"}, "researcher": {"lookup"}} + + +class TestADelegationsToolsAndModel: + """``task``'s ``tools`` and ``model``: some of the type's own tools, one of its + model choices; the run, its control, its start and its instance keep them.""" + + async def test_the_run_gets_them_and_its_start_says_them(self): + hook, asked = answering() + runs = AgentRuns() + made = delegations(hook, runs=runs, types=CHOOSING, tool_names=own_tools(OWN)) + + result, events = await delegated(made, request(NARROW)) + + assert result.result["status"] == RUN_COMPLETED + (run,) = asked + assert (run.tools, run.model) == (frozenset({"lookup"}), "fast") + assert run.control.tools == frozenset({"lookup"}) + start = runs_of_status(events, RUN_STARTED)[0] + assert (start.metadata["tools"], start.metadata["model"]) == (["lookup"], "fast") + instance = runs.instance(CONVERSATION, "choosy-1") + assert (instance.tools, instance.model) == (("lookup",), "fast") + + async def test_left_out_the_run_has_all_its_tools_and_its_own_model(self): + hook, asked = answering() + tools_asked: list[str] = [] + made = delegations(hook, types=CHOOSING, tool_names=own_tools(OWN, tools_asked)) + + _, events = await delegated(made, request( + {"agent_type": "choosy", "title": "Look", "objective": "Look X up."} + )) + + (run,) = asked + assert (run.tools, run.model, run.control.tools) == (None, None, None) + start = runs_of_status(events, RUN_STARTED)[0] + assert "tools" not in start.metadata and "model" not in start.metadata + assert tools_asked == [] # nothing to check + + async def test_a_static_sub_agent_may_be_narrowed_too(self): + hook, asked = answering() + made = delegations(hook, types=CHOOSING, tool_names=own_tools(OWN)) + + await delegated(made, request({**BRIEF, "tools": []})) + + assert asked[0].tools == frozenset() + + @pytest.mark.parametrize("arguments, error", [ + ({**NARROW, "tools": ["lookup", "write_file"]}, + "The tools for 'choosy' must be some of its own: fetch_page, lookup."), + ({**NARROW, "model": "strong"}, + "The model for 'choosy' must be one of its model choices: fast, " + "anthropic:claude-haiku-4-5."), + ({**BRIEF, "model": "fast"}, "'researcher' has no model choices; leave model out."), + ({**NARROW, "objective": " "}, "The brief for 'choosy' is missing: objective."), + ]) + async def test_what_the_type_cannot_take_starts_no_run_and_counts_none( + self, arguments, error + ): + hook, asked = answering() + runs = AgentRuns() + made = delegations(hook, runs=runs, types=CHOOSING, tool_names=own_tools(OWN)) + + async def work(): + refused = await made.delegate(request(arguments)) + return refused, runs_this_turn() + + (result, counted), events = await turned(work) + + assert result.result == {"success": False, "error": error} + assert (counted, events, asked, runs.records(CONVERSATION)) == (0, [], [], []) + + async def test_without_a_backends_names_its_configured_tools_are_its_own(self): + hook, asked = answering() + typed = AgentConfig(name="choosy", prompt="p", tools=[contract_tool, "web_fetch"]) + made = delegations(hook, types={**CHOOSING, "choosy": typed}) + + result, _ = await delegated(made, request({**NARROW, "model": None, + "tools": ["contract_tool"]})) + + assert result.result["status"] == RUN_COMPLETED + assert asked[0].tools == frozenset({"contract_tool"}) + + async def test_a_start_request_carries_them_to_the_run(self): + hook, asked = answering() + made = delegations(hook, types=CHOOSING) + + await started(made, start_request("choosy", tools=frozenset({"lookup"}), model="fast")) + + (run,) = asked + assert (run.tools, run.model, run.control.tools) == ( + frozenset({"lookup"}), "fast", frozenset({"lookup"}) + ) + + def test_the_fields_default_to_none(self): + made = StartRequest(agent_type="researcher", brief=Brief(title="T", objective="O"), + started_by="user") + assert (made.tools, made.model) == (None, None) + run = AgentRun(ref=RESEARCHER, config=TYPES["researcher"], message="m", + conversation=None, state={}) + assert (run.tools, run.model, run.control.tools) == (None, None, None) + + +def contract_tool() -> dict: + """A plain tool of a type's own.""" + return {"success": True} + + +class TestAFollowUpKeepsThem: + """Every run of an instance runs with the tools and the model its first + run's delegation gave it; one the type no longer has is refused.""" + + @staticmethod + async def narrowed(made: Delegations) -> None: + await turned(lambda: made.delegate(request(NARROW))) + + async def test_its_next_run_has_them(self): + hook, asked = answering() + made = delegations(hook, types=CHOOSING, tool_names=own_tools(OWN)) + await self.narrowed(made) + + result, events = await turned(lambda: made.follow_up(follow("choosy-1"))) + + assert result.result["status"] == RUN_COMPLETED + assert [(run.tools, run.model) for run in asked] == [ + (frozenset({"lookup"}), "fast"), (frozenset({"lookup"}), "fast"), + ] + assert asked[1].control.tools == frozenset({"lookup"}) + # Its start says nothing of them: they are the instance's. + assert "tools" not in runs_of_status(events, RUN_STARTED)[0].metadata + + async def test_the_users_follow_up_and_a_restored_instance_too(self): + hook, asked = answering() + runs = AgentRuns() + made = delegations(hook, runs=runs, types=CHOOSING, tool_names=own_tools(OWN)) + await self.narrowed(made) + again = AgentRuns() + again.restore(CONVERSATION, runs.export(CONVERSATION)) + restarted = delegations(hook, runs=again, types=CHOOSING, tool_names=own_tools(OWN)) + + result, _ = await turned(lambda: restarted.follow_up(users("choosy-1"))) + + assert result.result["run"] == "choosy-1#2" + assert (asked[-1].tools, asked[-1].model) == (frozenset({"lookup"}), "fast") + + async def test_a_model_the_type_no_longer_has_is_refused(self): + hook, asked = answering() + runs = AgentRuns() + made = delegations(hook, runs=runs, types=CHOOSING, tool_names=own_tools(OWN)) + await self.narrowed(made) + made._types["choosy"] = AgentConfig(name="choosy", prompt="p", + model_choices=("anthropic:claude-haiku-4-5",)) + + result, events = await turned(lambda: made.follow_up(follow("choosy-1"))) + + assert result.result == { + "success": False, + "error": "choosy-1 was started with the model fast, which 'choosy' no longer has; " + "start a new one with task.", + } + assert (events, len(asked)) == ([], 1) + + async def test_tools_the_type_no_longer_has_are_refused(self): + hook, asked = answering() + names = {"choosy": {"lookup", "fetch_page"}} + made = delegations(hook, types=CHOOSING, tool_names=own_tools(names)) + await turned(lambda: made.delegate(request({**NARROW, "model": None, + "tools": ["lookup", "fetch_page"]}))) + names["choosy"] = {"fetch_page"} + + result, events = await turned(lambda: made.message(users("choosy-1"))) + + assert result.result == { + "success": False, + "error": "choosy-1 was started with the tools lookup, which 'choosy' no longer has; " + "start a new one with task.", + } + assert (events, len(asked)) == ([], 1) + + async def test_an_instance_not_narrowed_never_asks_for_the_tools(self): + hook, asked = answering() + tools_asked: list[str] = [] + made = delegations(hook, types=CHOOSING, tool_names=own_tools(OWN, tools_asked)) + await turned(lambda: made.delegate(request({**NARROW, "tools": None}))) + + await turned(lambda: made.follow_up(follow("choosy-1"))) + + assert tools_asked == [] + assert [run.model for run in asked] == ["fast", "fast"] diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 11d2896d..c9d9cc4c 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -6469,3 +6469,47 @@ async def test_with_follow_ups_it_gets_the_parents_tools_and_the_roster(self, ma assert crew.opening("coordinator", -1) == [ roster("- helper-1 (helper, idle): Help with X. — Helped."), "Go.", ] + + +# -- a delegation's tools and model ------------------------------------------------------ + + +def narrow_team(**researcher: Any) -> list[AgentConfig]: + """A coordinator, and a researcher with two tools of its own and its plan's tools.""" + return [ + agent("coordinator", sub_agents=("researcher",)), + agent("researcher", tools=(contract_lookup, contract_whoami), include_state_tools=True, + **researcher), + ] + + +class TestWhatATypeCannotTake: + """A ``task`` call whose ``tools`` are not some of the type's own, or whose + ``model`` is none of its choices, is its error result naming what it may + be: no run starts, and the turn's runs are not counted.""" + + @pytest.mark.parametrize("researcher, fields, error", [ + ({}, {"tools": ["contract_lookup", "write_file"]}, + "The tools for 'researcher' must be some of its own: contract_lookup, contract_whoami."), + ({}, {"model": "fast"}, "'researcher' has no model choices; leave model out."), + ({"model_choices": ("anthropic:claude-haiku-4-5",)}, {"model": "fast"}, + "The model for 'researcher' must be one of its model choices: " + "anthropic:claude-haiku-4-5."), + ], ids=["tools", "no-choices", "model"]) + async def test_starts_no_run_and_takes_no_count(self, make_crew, researcher, fields, error): + crew = make_crew( + narrow_team(**researcher), subagents=SubAgentPolicy(max_runs_per_turn=1), + coordinator=[calls(delegate("researcher", "Find X.", "c1", **fields)), + calls(delegate("researcher", "Find Y.", "c2")), says("Done.")], + researcher=[says("Y is 7.")], + ) + + events = await crew.turn() + + assert json.loads(crew.results_read("coordinator", 1)["c1"]) == { + "success": False, "error": error, + } + # The turn's one run is still its to start. + assert envelope_read(crew.results_read("coordinator", 2)["c2"])["result"] == "Y is 7." + assert [r.ref.run for r in crew.records()] == ["researcher-1#1"] + assert [e.metadata["status"] for e in runs_of(events)] == [RUN_STARTED, RUN_COMPLETED] From c9cf397123f82bc2b668e5e0f020627e9357fbfb Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:29:53 -0500 Subject: [PATCH 06/11] Sub-agents: a narrowed run is offered its tools alone, on both backends A run whose task call gave tools is offered only those of its type's tools and the ones every run keeps (its plan's, the delegation tools): ADK's RunControlPlugin leaves the others out of the request and its tools_dict, Deep Agents' RunControlMiddleware out of the model request, and a call of one is answered as one of a tool the agent does not have. _agent_tool_names says what tools may name: the agent's own tools, its skill and MCP tools (ADK lists an MCP toolset when first asked). --- src/agentic_cli/workflow/adk/manager.py | 34 ++++++++ .../workflow/adk/run_control_plugin.py | 34 +++++++- src/agentic_cli/workflow/base_manager.py | 24 +++++- .../workflow/deepagents/manager.py | 15 ++++ .../workflow/deepagents/middleware.py | 32 +++++++- tests/workflow/adk/test_run_control_plugin.py | 63 ++++++++++++++- .../deepagents/test_run_control_middleware.py | 81 ++++++++++++++++++- tests/workflow/deepagents/test_skills.py | 28 +++++++ tests/workflow/test_adk_mcp_lifecycle.py | 35 ++++++++ tests/workflow/test_skills.py | 24 ++++++ tests/workflow/test_subagents_contract.py | 81 +++++++++++++++++++ 11 files changed, 444 insertions(+), 7 deletions(-) diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index 4aeb19e6..aecf507e 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -83,6 +83,7 @@ ) from agentic_cli.workflow.adk.task_tool import SHARED_KEYS, TaskTool, follow_up_tools from agentic_cli.workflow.adk.tool_result_cap_plugin import ToolResultCapPlugin +from agentic_cli.workflow.agents.control import KEPT_TOOLS from agentic_cli.workflow.agents.delegate import AgentRun, RunAnswer, RunFailed, failure_reason from agentic_cli.workflow.agents.runs import own_plan_and_tasks from agentic_cli.workflow.agents.spawn import can_have_children @@ -348,6 +349,38 @@ async def generate_simple(self, prompt: str, max_tokens: int = 500) -> str: )) return text + async def _agent_tool_names(self, agent: str) -> frozenset[str]: + """The names a ``task`` call's ``tools`` may give for ``agent``: its built agent's. + + Its tools as its model sees them (callables, ADK tools, a skill + toolset's tools) and each MCP toolset's, which ADK lists by connecting: + done when first asked, once a build (the toolset stays connected for the + agent's runs, and its runner stops it). A listing that fails is logged + and asked again next time. The state and delegation tools are left out. + """ + built = self._agents.get(agent) + if built is None: + return await super()._agent_tool_names(agent) + from google.adk.tools.mcp_tool.mcp_toolset import McpToolset + + tools = list(built.tools) + names = _tool_names(tools) + listed = self.__dict__.setdefault("_mcp_tool_names", {}) + for tool in tools: + if not isinstance(tool, McpToolset): + continue + kept = listed.get(id(tool)) + if kept is None: + try: + found = {t.name for t in await tool.get_tools_with_prefix()} + except Exception as exc: # noqa: BLE001 - a server that will not list + logger.warning("mcp_tools_unlisted", agent=agent, error=str(exc)) + continue + # The toolset is kept with its names: its id is only its own while it lives. + kept = listed[id(tool)] = (tool, found) + names |= kept[1] + return frozenset(names - KEPT_TOOLS) + def _detach_backend(self) -> list[Closer]: """The runners and the agents, and the LLM logging plugin. @@ -357,6 +390,7 @@ def _detach_backend(self) -> list[Closer]: keeps stays open. They close before the session service (the base runs the backend's closers before the store's). """ + self.__dict__.pop("_mcp_tool_names", None) runner, self._runner = self._runner, None runners, self._agent_runners = self._agent_runners, MappingProxyType({}) self._agents = MappingProxyType({}) diff --git a/src/agentic_cli/workflow/adk/run_control_plugin.py b/src/agentic_cli/workflow/adk/run_control_plugin.py index 78e1705c..0a622c3e 100644 --- a/src/agentic_cli/workflow/adk/run_control_plugin.py +++ b/src/agentic_cli/workflow/adk/run_control_plugin.py @@ -4,7 +4,13 @@ for the run in progress (``get_active_run``: the run's own task, ``agents/delegate.py``), whose control the manager's ``Delegations`` holds: -- before each model call, the messages steered to the run since its last +- before each model call, a run narrowed to some of its type's tools + (``RunControl.tools``) has the others left out of the request and of + its ``tools_dict``, which ADK resolves a call from, so a call of one is + answered as one of a tool the agent does not have (``narrow``: before + the fit guard, which measures the narrowed request; a skill toolset's + instruction text stays in the system prompt, only its calls are refused); +- before each, the messages steered to the run since its last (``RunControl.take_steering``) go after its last message, each a user event appended to the run's child session (through the callback context's session service: the invocation's own session, which a session @@ -94,6 +100,8 @@ async def before_model_callback( control = self._control() if control is None: return None + if control.tools is not None: + narrow(llm_request, control.keeps) steered = control.take_steering() if steered: self._stamped[callback_context.invocation_id] = await _steer( @@ -171,6 +179,30 @@ async def _steer( return stamped +def narrow(llm_request: LlmRequest, keeps: Callable[[str], bool]) -> None: + """Leave the function tools ``keeps`` refuses out of ``llm_request``, in place. + + Out of ``tools_dict`` (what ADK resolves a call from: a call of a name + left out gets ADK's answer for a tool that is not there) and out of the + declarations the model is sent. A tool left with no declaration and + nothing else (a built-in's field) goes; the others stay as they are. + """ + for name in [name for name in llm_request.tools_dict if not keeps(name)]: + del llm_request.tools_dict[name] + kept: list[types.Tool] = [] + for tool in llm_request.config.tools or (): + declarations = tool.function_declarations + if declarations is None: + kept.append(tool) + continue + left = [d for d in declarations if d.name is None or keeps(d.name)] + if len(left) == len(declarations): + kept.append(tool) + elif left or tool.model_dump(exclude={"function_declarations"}, exclude_none=True): + kept.append(tool.model_copy(update={"function_declarations": left or None})) + llm_request.config.tools = kept or None + + def with_note(contents: list[types.Content], note: str) -> list[types.Content]: """``contents`` with ``note`` after their last message, as the user's. diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index ac436fb8..3f68199e 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -51,6 +51,7 @@ ) from agentic_cli.workflow import live_events from agentic_cli.workflow.config import AgentConfig +from agentic_cli.workflow.agents.control import KEPT_TOOLS from agentic_cli.workflow.agents.delegate import ( STOPPED_BY_USER_ERROR, USER, @@ -668,6 +669,7 @@ def _delegations(self) -> Delegations: ledgers=self._usage_ledgers, stored=self._stored_instances, open_calls=getattr(self, "_open_calls", None), + tool_names=self._agent_tool_names, ) return delegations @@ -1222,13 +1224,33 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: has ended, before anything it awaits to read what the run did, it calls ``run.control.finish()``, so a cancel of the run alone then loses nothing. ``run.control`` keeps its limits at its model calls - (each backend's in its sub-agents' stacks). + (each backend's in its sub-agents' stacks). A run narrowed to some of + its type's tools (``run.control.tools``) is offered only those and the + tools every run keeps (``KEPT_TOOLS``), and a call of another is + answered as one of a tool the agent does not have + (``unknown_tool_result``). Raises: NotImplementedError: This backend runs no sub-agent. """ raise NotImplementedError(f"{type(self).__name__} runs no sub-agent") + async def _agent_tool_names(self, agent: str) -> frozenset[str]: + """The names a ``task`` call's ``tools`` may give for ``agent`` (a backend hook). + + Asked for a call that names tools and for a narrowed instance's + follow-up: the agent's own tools by the names its model sees (a + backend adds its skill and MCP tools), the state and delegation tools + (``KEPT_TOOLS``) left out. The base's are the agent's configured tools + as ``_build_tools`` assembles them, each by its callable's name; an + agent that is not configured has none. + """ + config = next((c for c in self._agent_configs if c.name == agent), None) + if config is None: + return frozenset() + names = (getattr(tool, "__name__", "") for tool in self._build_tools(config, {})) + return frozenset(name for name in names if name and name not in KEPT_TOOLS) + @property def settings(self) -> "BaseSettings": """Get the settings instance.""" diff --git a/src/agentic_cli/workflow/deepagents/manager.py b/src/agentic_cli/workflow/deepagents/manager.py index b1726877..4a2c9790 100644 --- a/src/agentic_cli/workflow/deepagents/manager.py +++ b/src/agentic_cli/workflow/deepagents/manager.py @@ -67,6 +67,7 @@ validate_agent_graph, ) from agentic_cli.workflow import live_events +from agentic_cli.workflow.agents.control import KEPT_TOOLS from agentic_cli.workflow.agents.delegate import AgentRun, RunAnswer, RunFailed, failure_reason from agentic_cli.workflow.agents.runs import own_plan_and_tasks from agentic_cli.workflow.context import ( @@ -193,6 +194,10 @@ def __init__( self._root: CompiledStateGraph | None = None # Every agent's graph, by name: what a sub-agent run runs on. self._agent_graphs: dict[str, CompiledStateGraph] = {} + # Each agent's own tools' names as its model sees them (its tools, skill + # tools and MCP tools), the framework's state and delegation tools left + # out: what a task call's `tools` may name. + self._own_tool_names: dict[str, frozenset[str]] = {} # The root agent's summarization middleware, which compact() uses. self._root_summarization: ReportingSummarizationMiddleware | None = None @@ -281,6 +286,10 @@ async def _do_initialize(self) -> None: if config.mcp_servers: own = await self._with_mcp_tools(config, own) tools[config.name] = own + self._own_tool_names = { + name: frozenset(t.name for t in own if t.name not in KEPT_TOOLS) + for name, own in tools.items() + } summarizers: dict[str, ReportingSummarizationMiddleware] = {} root = self._root_agent_name # from the graph the base validated index_wanted = self._memory_index_wanted(root) @@ -428,6 +437,7 @@ def _detach_backend(self) -> list[Closer]: self._root = None self._agent_graphs = {} self._root_summarization = None + self._own_tool_names = {} self._pending_notices = [] sessions, self._mcp = self._mcp, MCPSessions() return [("mcp_sessions", sessions.aclose)] @@ -445,6 +455,11 @@ def _detach_store(self) -> list[Closer]: self._sessions = None return [("checkpointer", functools.partial(self._close_connection, connection))] + async def _agent_tool_names(self, agent: str) -> frozenset[str]: + """The names a ``task`` call's ``tools`` may give for ``agent``: its built tools'.""" + names = self._own_tool_names.get(agent) + return names if names is not None else await super()._agent_tool_names(agent) + async def _close_connection(self, connection: "AbstractAsyncContextManager | None") -> None: """Exit what owns the checkpointer's and the index's connections. diff --git a/src/agentic_cli/workflow/deepagents/middleware.py b/src/agentic_cli/workflow/deepagents/middleware.py index 8a68f8f0..caca0b9d 100644 --- a/src/agentic_cli/workflow/deepagents/middleware.py +++ b/src/agentic_cli/workflow/deepagents/middleware.py @@ -1143,7 +1143,12 @@ class RunControlMiddleware(AgentMiddleware): app's own tool of that name) is the run's: its description and schema are what the run may start (``Delegations.task_offer``, by the run's depth), or the tool is left out when it may start nothing, as ADK - declares one per request. + declares one per request; + - a run narrowed to some of its type's tools (``RunControl.tools``) is + offered only those and the tools every run keeps (``KEPT_TOOLS``), and a + call of any other (``awrap_tool_call``) is answered as one of a tool the + agent does not have, as the permission gate answers one, and run + nowhere. The summarization inside it counts the note and the rewritten tools; the outcome middleware outside it reads an answer whose calls were dropped as @@ -1180,6 +1185,11 @@ async def awrap_model_call( control = self._control() if control is None: return await handler(request) + if control.tools is not None: + request = request.override(tools=[ + tool for tool in request.tools or () + if not isinstance(tool, BaseTool) or control.keeps(tool.name) + ]) # What abefore_model added is in this request, and its step is checkpointed. control.stored() if control.model_call(): @@ -1195,6 +1205,26 @@ async def awrap_model_call( response = _mapped(response, without_calls) return response + async def awrap_tool_call( + self, + request: ToolCallRequest, + handler: Callable[[ToolCallRequest], Awaitable[_ToolResult]], + ) -> _ToolResult: + control = self._control() + call = request.tool_call + if control is None or control.keeps(call["name"]): + return await handler(request) + run = control.ref + # What the agent was not offered this run: the unknown-tool answer, listing + # what it was (``task`` only when this run may start something). + task_offered = self._delegations().task_offer(run.agent, run.depth) is not None + available = [ + tool.name for tool in getattr(request.runtime, "tools", None) or () + if control.keeps(tool.name) and (tool.name != TASK_TOOL or task_offered) + ] + logger.info("tool_not_found", tool=call["name"], agent=run.agent) + return error_tool_message(unknown_tool_result(call["name"], available), call) + def _with_task_offered(self, request: ModelRequest, run: RunRef) -> ModelRequest: """``request`` with the framework's ``task`` as ``run`` is offered it. diff --git a/tests/workflow/adk/test_run_control_plugin.py b/tests/workflow/adk/test_run_control_plugin.py index d342c9e6..8854fc26 100644 --- a/tests/workflow/adk/test_run_control_plugin.py +++ b/tests/workflow/adk/test_run_control_plugin.py @@ -1,8 +1,8 @@ -"""ADK: a sub-agent run's limits at its model calls (``workflow/adk/run_control_plugin.py``). +"""ADK: a sub-agent run's limits, and the tools a narrowed run is offered, at its model calls (``workflow/adk/run_control_plugin.py``). What the plugin does to a request and an answer, alone. Whole turns, on both backends, are in the contract suite (``TestTheStepLimit``, -``TestTheTokenLimit``). +``TestTheTokenLimit``, ``TestANarrowedRun``). """ from __future__ import annotations @@ -16,11 +16,13 @@ from google.adk.models.llm_request import LlmRequest # noqa: E402 from google.adk.models.llm_response import LlmResponse # noqa: E402 +from google.adk.tools import BaseTool # noqa: E402 from google.genai import types # noqa: E402 from agentic_cli.workflow.adk.run_control_plugin import ( # noqa: E402 RunControlPlugin, drop_calls, + narrow, with_note, ) from agentic_cli.workflow.agents.control import STEP_LIMIT_NOTE, RunControl # noqa: E402 @@ -232,3 +234,60 @@ async def test_a_run_stopped_while_storing_keeps_the_rest_unstored(self): assert service.stored == ["Also Z."] assert control.unstored() == ["In metric units."] + + +def offering(*names: str) -> LlmRequest: + """A request that offers a function tool of each of ``names``, and Google search.""" + request = LlmRequest(contents=[user(text("# Task: Find X."))]) + request.config.tools = [ + types.Tool(function_declarations=[ + types.FunctionDeclaration(name=name, description=name) for name in names + ]), + types.Tool(google_search=types.GoogleSearch()), + ] + request.tools_dict = {name: BaseTool(name=name, description=name) for name in names} + return request + + +def declared(request: LlmRequest) -> list[str]: + return [d.name for tool in request.config.tools or () for d in tool.function_declarations or ()] + + +class TestANarrowedRunsTools: + """A run narrowed to some of its type's tools (``RunControl.tools``) is + offered those and the tools every run keeps, in ``tools_dict`` (what ADK + resolves a call from) and in what the model is sent.""" + + async def test_its_tools_and_those_every_run_keeps_and_no_other(self): + control = RunControl(REF, AgentLimits(), tools=frozenset({"lookup"})) + plugin = RunControlPlugin(lambda: control, "anthropic") + request = offering("lookup", "fetch_page", "save_plan", "task", "check_agents") + + await plugin.before_model_callback(callback_context=None, llm_request=request) + + assert list(request.tools_dict) == ["lookup", "save_plan", "task", "check_agents"] + assert declared(request) == ["lookup", "save_plan", "task", "check_agents"] + # What is no function declaration stays. + assert request.config.tools[1].google_search is not None + + def test_a_tool_left_with_no_declaration_goes(self): + request = LlmRequest(contents=[user(text("Go."))]) + request.config.tools = [types.Tool(function_declarations=[ + types.FunctionDeclaration(name="fetch_page", description="Fetch."), + ])] + request.tools_dict = {"fetch_page": BaseTool(name="fetch_page", description="Fetch.")} + + narrow(request, lambda name: False) + + assert (request.tools_dict, request.config.tools) == ({}, None) + + async def test_a_run_not_narrowed_keeps_them_all(self): + control = RunControl(REF, AgentLimits()) + plugin = RunControlPlugin(lambda: control, "anthropic") + request = offering("lookup", "fetch_page") + + await plugin.before_model_callback(callback_context=None, llm_request=request) + + assert (list(request.tools_dict), declared(request)) == ( + ["lookup", "fetch_page"], ["lookup", "fetch_page"] + ) diff --git a/tests/workflow/deepagents/test_run_control_middleware.py b/tests/workflow/deepagents/test_run_control_middleware.py index bdb8e7b7..f559ae7f 100644 --- a/tests/workflow/deepagents/test_run_control_middleware.py +++ b/tests/workflow/deepagents/test_run_control_middleware.py @@ -1,7 +1,8 @@ """Deep Agents: a sub-agent run's limits at its model calls (``RunControlMiddleware``). What the middleware does to a request and an answer, alone: a run's limits, and the -``task`` its request offers (what the run may start). Whole turns, on +``task`` its request offers (what the run may start), and the tools a narrowed +run is offered and may call. Whole turns, on both backends, are in the contract suite (``TestTheStepLimit``, ``TestTheTokenLimit``). """ @@ -16,7 +17,7 @@ pytest.importorskip("deepagents") -from langchain.agents.middleware import ModelRequest # noqa: E402 +from langchain.agents.middleware import ModelRequest, ToolCallRequest # noqa: E402 from langchain_core.messages import AIMessage, HumanMessage, ToolMessage # noqa: E402 from langchain_core.tools import StructuredTool # noqa: E402 @@ -278,3 +279,79 @@ async def test_a_task_call_by_a_run_offered_nothing_is_logged_at_info(): assert message.status == "error" assert json.loads(message.content) == unknown_tool_result("task", ["lookup"]) assert [(log["log_level"], log["event"]) for log in logs] == [("info", "tool_not_found")] + + +# -- a narrowed run: its tools, and a call of one it was not given --------------------- + + +def _named(name: str) -> StructuredTool: + return StructuredTool.from_function(lambda q="": name, name=name, description=name) + + +def _narrowing(tools: frozenset[str] | None, *, task_offered: bool = False): + """The middleware, over delegations whose run has ``tools`` (and offers ``task`` or not).""" + control = RunControl(REF, AgentLimits(), tools=tools) + delegations = SimpleNamespace( + control=lambda run: control, + task_offer=lambda agent, depth: object() if task_offered else None, + ) + return RunControlMiddleware(lambda: delegations) + + +TOOLS = [_named(name) for name in ("lookup", "fetch_page", "save_plan", "task", "check_agents")] + + +async def test_a_narrowed_runs_request_offers_its_tools_and_those_every_run_keeps(): + sent: list[list[str]] = [] + + async def handler(request): + sent.append([tool.name for tool in request.tools]) + return AIMessage("Done.") + + await _narrowing(frozenset({"lookup"})).awrap_model_call(_request(list(TOOLS)), handler) + + assert sent == [["lookup", "save_plan", "task", "check_agents"]] + + +async def _called(middleware, name: str) -> tuple[object, list[str]]: + """A call of the tool ``name`` through ``middleware``: its answer, and what ran.""" + ran: list[str] = [] + + async def handler(request): + ran.append(request.tool_call["name"]) + return ToolMessage("ran", tool_call_id="r2") + + tool = next(t for t in TOOLS if t.name == name) + request = ToolCallRequest( + tool_call={"name": name, "args": {}, "id": "r2", "type": "tool_call"}, + tool=tool, state={}, runtime=SimpleNamespace(tools=list(TOOLS)), + ) + return await middleware.awrap_tool_call(request, handler), ran + + +@pytest.mark.parametrize("task_offered, available", [ + (False, "check_agents, lookup, save_plan"), + (True, "check_agents, lookup, save_plan, task"), +]) +async def test_a_call_of_a_tool_it_was_not_given_is_one_it_does_not_have( + task_offered, available +): + answer, ran = await _called( + _narrowing(frozenset({"lookup"}), task_offered=task_offered), "fetch_page" + ) + + assert ran == [] + assert (answer.status, json.loads(answer.content)) == ("error", { + "success": False, + "error": "fetch_page failed: ValueError: Tool 'fetch_page' not found.\n" + f"Available tools: {available}", + }) + + +@pytest.mark.parametrize("tools, name", [ + (frozenset({"lookup"}), "lookup"), (frozenset({"lookup"}), "save_plan"), (None, "fetch_page"), +]) +async def test_a_call_of_a_tool_it_has_runs(tools, name): + answer, ran = await _called(_narrowing(tools), name) + + assert (ran, answer.content) == ([name], "ran") diff --git a/tests/workflow/deepagents/test_skills.py b/tests/workflow/deepagents/test_skills.py index 7c7a7212..edbcc8a9 100644 --- a/tests/workflow/deepagents/test_skills.py +++ b/tests/workflow/deepagents/test_skills.py @@ -723,6 +723,34 @@ async def call_tool(**arguments): (result,) = of(events, EventType.TOOL_RESULT) assert result.metadata["result"]["skill_name"] == "pdf-tools" + async def test_a_task_may_narrow_a_sub_agent_to_its_skill_mcp_and_own_tools( + self, ctx, monkeypatch + ): + """What ``task``'s ``tools`` may name, as on ADK: the agent's own tools, + its skill tools and its MCP tools, never the state or delegation tools.""" + from agentic_cli.tools import read_file + + async def call_tool(**arguments): + return [{"type": "text", "text": "found"}], None + + _fake_mcp(monkeypatch, StructuredTool( + name="search", description="A server's tool.", args_schema={"type": "object"}, + coroutine=call_tool, response_format="content_and_artifact", + )) + scripted(monkeypatch, lead=[], writer=[]) + manager = _manager(ctx.settings, [ + AgentConfig(name="lead", prompt="Lead.", sub_agents=["writer"]), + _writer(tools=[read_file], include_state_tools=True, + mcp_servers=[MCPServerConfig(name="atlas", command="srv")]), + ]) + try: + await manager.initialize_services() + assert await manager._agent_tool_names("writer") == { + "read_file", *SKILL_TOOL_NAMES, "search", + } + finally: + await manager.cleanup() + assert manager._own_tool_names == {} async def test_a_model_switch_rebuilds_them(self, ctx, monkeypatch): models = scripted(monkeypatch, writer=_steps(("load_skill", {"skill_name": "pdf-tools"}))) manager = _manager(ctx.settings, [_writer()]) diff --git a/tests/workflow/test_adk_mcp_lifecycle.py b/tests/workflow/test_adk_mcp_lifecycle.py index 6e3d861f..2a7c3611 100644 --- a/tests/workflow/test_adk_mcp_lifecycle.py +++ b/tests/workflow/test_adk_mcp_lifecycle.py @@ -25,6 +25,7 @@ from agentic_cli.workflow.adk.manager import GoogleADKWorkflowManager # noqa: E402 from agentic_cli.workflow.config import AgentConfig # noqa: E402 from agentic_cli.workflow.mcp import MCPServerConfig # noqa: E402 +from tests.loop_guard import no_blocking_calls # noqa: E402 from tests.workflow.adk.fakes import FakeAPI, anthropic_message # noqa: E402 from tests.workflow.test_manager_models import route # noqa: E402 @@ -97,6 +98,40 @@ async def test_cleanup_stops_the_servers_and_a_model_switch_leaves_one( assert alive(pid_dir) == [], "a server outlived cleanup()" +async def test_a_sub_agents_mcp_tools_are_listed_when_first_asked_and_stop_with_it( + project, pid_dir, monkeypatch +): + """What ``task``'s ``tools`` may name includes a sub-agent's MCP tools, by + their prefixed names: ADK connects its toolset to list them, once a + build, and the toolset's runner stops the server.""" + route(monkeypatch, anthropic, "AsyncAnthropic", + FakeAPI(anthropic_message({"type": "text", "text": "ok"}))) + server = MCPServerConfig( + name="atlas", command=sys.executable, args=[str(SERVER)], timeout=30, + env={"MCP_TEST_PID_DIR": str(pid_dir)}, tool_name_prefix="atlas", + ) + manager = GoogleADKWorkflowManager( + agent_configs=[ + AgentConfig(name="lead", prompt="Lead.", sub_agents=["researcher"]), + AgentConfig(name="researcher", prompt="Find.", mcp_servers=[server]), + ], + settings=BaseSettings(session_store="memory", default_model="claude-sonnet-4-6"), + ) + try: + await manager.initialize_services() + assert list(pid_dir.iterdir()) == [] # ADK connects when it is asked + + with no_blocking_calls(): + names = await manager._agent_tool_names("researcher") + again = await manager._agent_tool_names("researcher") + + assert names == again == {"atlas_add", "atlas_lookup"} + assert len(list(pid_dir.iterdir())) == 1 # listed once + finally: + await manager.cleanup() + + assert alive(pid_dir) == [], "a server outlived cleanup()" + async def test_a_native_apps_toolset_outlives_its_runner_and_serves_the_next( project, pid_dir, monkeypatch ): diff --git a/tests/workflow/test_skills.py b/tests/workflow/test_skills.py index c218ef25..05c73b13 100644 --- a/tests/workflow/test_skills.py +++ b/tests/workflow/test_skills.py @@ -192,6 +192,30 @@ def test_manager_attaches_skill_toolset(self, tmp_path, mock_context): # Scripts disabled by default -> run_skill_script not exposed. assert "run_skill_script" not in {t.name for t in skill_toolsets[0]._tools} + async def test_a_task_may_narrow_a_sub_agent_to_its_skill_tools_and_its_own(self, tmp_path): + """What ``task``'s ``tools`` may name: the agent's own tools by their names, + its skill toolset's tools, never the state or delegation tools.""" + from agentic_cli.tools import read_file + from agentic_cli.workflow.adk.manager import GoogleADKWorkflowManager + from tests.conftest import MockContext + + configs = [ + AgentConfig(name="lead", prompt="p", sub_agents=["a"]), + AgentConfig(name="a", prompt="p", tools=[read_file], + skills=[str(_make_skill(tmp_path))]), + ] + with MockContext(google_api_key="test-key", session_store="memory") as context: + mgr = GoogleADKWorkflowManager( + agent_configs=configs, settings=context.settings, model="gemini-2.5-flash" + ) + await mgr.initialize_services() + try: + assert await mgr._agent_tool_names("a") == { + "read_file", "list_skills", "load_skill", "load_skill_resource", + } + assert await mgr._agent_tool_names("nobody") == frozenset() + finally: + await mgr.cleanup() def test_yaml_loader_parses_skills(self, tmp_path): from agentic_cli.workflow.agent_loader import load_agents_from_yaml diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index c9d9cc4c..c15103ef 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -6483,6 +6483,87 @@ def narrow_team(**researcher: Any) -> list[AgentConfig]: ] +#: The researcher's own tool it was not given, called anyway: what its call reads. +WHOAMI_NOT_FOUND = { + "success": False, + "error": "contract_whoami failed: ValueError: Tool 'contract_whoami' not found.\n" + "Available tools: contract_lookup, get_plan, get_tasks, save_plan, save_tasks", +} +#: The researcher's requests, narrowed to ``contract_lookup``: it and its plan's tools. +NARROWED = ["contract_lookup", "save_plan", "get_plan", "save_tasks", "get_tasks"] + + +class TestANarrowedRun: + """``task``'s ``tools``: the run is offered only those of its type's tools and + the tools every run keeps (its plan's, the delegation tools); a call of + any other is answered as one of a tool it does not have, and the run goes + on. A static sub-agent as a type started at run time.""" + + async def test_its_requests_offer_only_its_tools_and_a_call_of_another_is_unknown( + self, make_crew + ): + crew = make_crew( + narrow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1", + tools=["contract_lookup"])), says("Done.")], + researcher=[calls(use("contract_whoami", "r1")), + calls(use("contract_lookup", "r2", q="x")), says("X is 42.")], + ) + + with no_blocking_calls(): + await crew.turn() + + assert [crew.tool_names("researcher", n) for n in range(3)] == [NARROWED] * 3 + assert json.loads(crew.results_read("researcher", 1)["r1"]) == WHOAMI_NOT_FOUND + assert json.loads(crew.results_read("researcher", 2)["r2"]) == { + "success": True, "value": 42, + } + assert SEEN == [] # contract_whoami never ran + assert envelope_read(crew.results_read("coordinator")["c1"])["result"] == "X is 42." + (instance,) = crew.manager.agent_runs.instances(crew.conversation) + assert (instance.tools, instance.model) == (("contract_lookup",), None) + + async def test_left_out_it_has_them_all(self, make_crew): + crew = make_crew( + narrow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[says("X is 42.")], + ) + + await crew.turn() + + assert crew.tool_names("researcher") == [ + "contract_lookup", "contract_whoami", "save_plan", "get_plan", "save_tasks", + "get_tasks", + ] + + async def test_a_type_started_at_run_time_is_narrowed_alike(self, make_crew): + crew = make_crew( + [*team(), helper(tools=(contract_lookup, contract_whoami))], subagents=SPAWNING, + coordinator=[calls(delegate("helper", "Help.", "c1", tools=["contract_whoami"])), + says("Done.")], + helper=[says("Helped.")], + ) + + await crew.turn() + + assert crew.tool_names("helper") == ["contract_whoami"] + + async def test_a_follow_up_keeps_them(self, make_crew): + crew = make_crew( + narrow_team(), subagents=FOLLOWING, + coordinator=[calls(delegate("researcher", "Find X.", "c1", + tools=["contract_lookup"])), says("Asked."), + calls(message("researcher-1", "Now find Y.", "c2")), says("Done.")], + researcher=[says("X is 42."), says("Y is 7.")], + ) + + await crew.turn() + await crew.turn("Find Y too.") + + assert crew.tool_names("researcher", 1) == NARROWED + assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Y is 7." + class TestWhatATypeCannotTake: """A ``task`` call whose ``tools`` are not some of the type's own, or whose ``model`` is none of its choices, is its error result naming what it may From 5ea843df02fab43754eb525a9f35b491a04c90bb Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:34:49 -0500 Subject: [PATCH 07/11] Sub-agents: a run on a model choice runs on its type built on that model Each sub-agent type is built once more at initialization for each of its model choices, through the backend's builder: on ADK an agent and a runner of its own, its plugin chain reading the choice's model, kind and context numbers under the type's name; on Deep Agents a graph of its own (build_agent, Variant), summarized by the choice's numbers. A run on a choice runs there, its usage and context the choice's; a model switch builds them again and the release closes them. ADK's raw log names the choice's model too. --- src/agentic_cli/workflow/adk/manager.py | 145 ++++++++++++-- src/agentic_cli/workflow/adk/plugins.py | 29 ++- src/agentic_cli/workflow/base_manager.py | 22 +++ .../workflow/deepagents/agent_builder.py | 179 ++++++++++++----- .../workflow/deepagents/manager.py | 46 ++++- tests/workflow/adk/test_plugin_chain.py | 35 ++++ .../workflow/deepagents/test_agent_builder.py | 41 +++- tests/workflow/test_subagents_contract.py | 185 +++++++++++++++++- 8 files changed, 604 insertions(+), 78 deletions(-) diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index aecf507e..4446ff75 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -120,6 +120,7 @@ from collections.abc import Mapping from agentic_cli.models import Provider, ResolvedModel, RoleMap + from agentic_cli.workflow.context import ContextBudget from agentic_cli.workflow.adk.build import ADKBuild from agentic_cli.workflow.agents.policy import SubAgentPolicy from agentic_cli.workflow.sessions import SessionRef @@ -240,6 +241,10 @@ class GoogleADKWorkflowManager(BaseWorkflowManager): #: is no app; class defaults, as above (read-only: each build sets its own). _agents: "Mapping[str, LlmAgent]" = MappingProxyType({}) _agent_runners: "Mapping[str, Runner]" = MappingProxyType({}) + #: Each sub-agent type built once more on each of its model choices, and the + #: runner of each, by (type, choice): what a run on a choice runs on. + _variant_agents: "Mapping[tuple[str, str], LlmAgent]" = MappingProxyType({}) + _variant_runners: "Mapping[tuple[str, str], Runner]" = MappingProxyType({}) def __init__( self, @@ -308,6 +313,10 @@ def __init__( # turn drains: the reference exists before process() is called. self._llm_logging_plugin: LLMLoggingPlugin | None = None + # The model choice each working run on one is on, by (conversation, + # run id): what the raw log names the run's calls by (``_chosen_model``). + self._chosen_runs: dict[tuple["SessionRef | None", str], "ResolvedModel"] = {} + logger.debug( "workflow_manager_created", app_name=self.app_name, @@ -384,7 +393,8 @@ async def _agent_tool_names(self, agent: str) -> frozenset[str]: def _detach_backend(self) -> list[Closer]: """The runners and the agents, and the LLM logging plugin. - The conversation's runner and each sub-agent type's: a runner closes + The conversation's runner and each sub-agent type's, and each of a + type's model choices': a runner closes its agent's toolsets (an MCP server stops with its toolset) and plugins; the session service it only flushes, so one a model switch keeps stays open. They close before the session service (the base @@ -393,6 +403,8 @@ def _detach_backend(self) -> list[Closer]: self.__dict__.pop("_mcp_tool_names", None) runner, self._runner = self._runner, None runners, self._agent_runners = self._agent_runners, MappingProxyType({}) + chosen_runners, self._variant_runners = self._variant_runners, MappingProxyType({}) + self._variant_agents = MappingProxyType({}) self._agents = MappingProxyType({}) self._root_agent = None self._build = None @@ -409,6 +421,13 @@ def _detach_backend(self) -> list[Closer]: (f"runner {name}", functools.partial(self._aclose_owned, owned, f"runner {name}")) for name, owned in runners.items() ), + *( + ( + f"runner {name} on {choice}", + functools.partial(self._aclose_owned, owned, f"runner {name} on {choice}"), + ) + for (name, choice), owned in chosen_runners.items() + ), ] def _detach_store(self) -> list[Closer]: @@ -524,11 +543,15 @@ def _build_agent( *, root: bool, delegates: bool = False, + model: "ResolvedModel | None" = None, ) -> Agent: """Construct one ``LlmAgent`` from a config, on its own. Its model, generation settings and thinking come from the model - initialization resolved for it, built by the model factory. + initialization resolved for it, built by the model factory; ``model`` + is one of its model choices' instead (the agent is built whole once + more, its own MCP toolsets and delegation tools, never cloned: two + runners would close a shared toolset). No agent has ADK ``sub_agents``, so ADK offers none of them ``transfer_to_agent``. An agent that delegates (``delegates``: it has @@ -549,7 +572,8 @@ def _build_agent( known only once they connect, excepted). """ built = build_adk_model( - self._resolved_models[config.name], settings=self._settings, app_name=self.app_name + model if model is not None else self._resolved_models[config.name], + settings=self._settings, app_name=self.app_name, ) tools = self._assemble_agent_tools(config, service_map) if root: @@ -591,7 +615,9 @@ def _create_agents(self) -> Agent: shapes the framework refuses failed there with the offending agent named. Called outside an initialization, it validates the graph itself. Every agent is kept by name (``_agents``): each sub-agent - type gets a runner of its own (``_do_initialize``). + type gets a runner of its own (``_do_initialize``), and so does each + of its model choices, an agent built once more on that model + (``_variant_agents``, by (type, choice)). Prompt factories are called under this manager's settings context (see ``AgentConfig.get_prompt``), so a prompt that reads settings sees the @@ -612,6 +638,7 @@ def _create_agents(self) -> Agent: ) agents: dict[str, LlmAgent] = {} + variants: dict[tuple[str, str], LlmAgent] = {} service_map = self._get_service_tool_map() configs = list(graph.config_map.values()) @@ -626,6 +653,12 @@ def _create_agents(self) -> Agent: agents[name] = self._build_agent( config, service_map, root=root, delegates=delegates ) + if not root: + for choice in config.model_choices: + variants[(name, choice)] = self._build_agent( + config, service_map, root=False, delegates=delegates, + model=self._choice_models[(name, choice)], + ) logger.debug( "agent_created", name=name, @@ -634,6 +667,7 @@ def _create_agents(self) -> Agent: ) self._agents = agents + self._variant_agents = variants root_agent = agents[graph.root_name] logger.info("agents_created", root=root_agent.name, total=len(agents)) return root_agent @@ -686,6 +720,8 @@ def _init_plugins(self) -> list: # its usage by that model's provider kind. models=self._agent_model_refs(), kinds=self._agent_kinds(), + # A run on a model choice: its calls name that model. + chosen=self._chosen_model, ) plugins.append(self._llm_logging_plugin) logger.info("llm_logging_plugin_enabled") @@ -756,9 +792,19 @@ def _plugin_chain( roster=self._roster_wanted(root.name), ) - def _agent_plugin_chain(self, agent: LlmAgent) -> list: + def _agent_plugin_chain( + self, + agent: LlmAgent, + *, + model: "ResolvedModel | None" = None, + budget: "ContextBudget | None" = None, + ) -> list: """The plugin chain of a sub-agent type's runner: the app's, made for a sub-agent. + ``model`` and ``budget`` are a model choice's, for the runner of the + type built on it: every plugin that reads an agent's model, kind or + context numbers by name reads the choice's under the type's name. + Its own instances, in the app's order, but for what a sub-agent is: - the permission gate writes no outside-content mark at a model @@ -793,9 +839,16 @@ def _agent_plugin_chain(self, agent: LlmAgent) -> list: ] if self._llm_logging_plugin is not None: head.append(self._llm_logging_plugin) + kinds = self._agent_kinds() + models = budgets = None + if model is not None: + kinds[agent.name] = model.record.kind.value + models = {**self._resolved_models, agent.name: model} + if budget is not None: + budgets = {**self._budgets, agent.name: budget} head.append(RunControlPlugin( lambda: self._delegations.control(get_active_run()), - self._agent_kinds().get(agent.name), + kinds.get(agent.name), )) head.append(SubAgentOutcomePlugin()) return self._chain( @@ -806,6 +859,8 @@ def _agent_plugin_chain(self, agent: LlmAgent) -> list: skip_agents=frozenset(), memory_index=False, stop_cause=lambda: self._delegations.stop_cause(get_active_run()), + models=models, + budgets=budgets, ) def _chain( @@ -819,16 +874,24 @@ def _chain( memory_index: bool, stop_cause: Callable[[], str | None] | None = None, roster: bool = False, + models: "Mapping[str, ResolvedModel] | None" = None, + budgets: "Mapping[str, ContextBudget] | None" = None, ) -> list: """A plugin chain in the order ``_plugin_chain`` gives, from its ``head`` on. + ``models`` and ``budgets`` are the agents' models and context numbers + the plugins read (the manager's by default): a model choice's runner + passes its own with the choice's under its type's name. + ``stop_cause`` is what a seal tells a call at its prompt, or running, stopped the run (``InterruptedCallsPlugin``): a sub-agent chain's. """ from agentic_cli.workflow.adk.foreign_reasoning_plugin import ForeignReasoningPlugin - kinds = {name: model.record.kind for name, model in self._resolved_models.items()} + models = self._resolved_models if models is None else models + budgets = self._budgets if budgets is None else budgets + kinds = {name: model.record.kind for name, model in models.items()} clock = CallClock() plugins: list = [MainAgentPlugin(), CallLatencyPlugin(clock), *head] plugins.append(ForeignReasoningPlugin({name: kind.value for name, kind in kinds.items()})) @@ -854,13 +917,16 @@ def _chain( # A sub-agent type's chain (no main agent): a run's task message is # never trimmed, whatever was steered to it after. keep_task = root is None - fit_guard = FitGuardPlugin(self._budgets, kinds, keep_task=keep_task) + fit_guard = FitGuardPlugin(budgets, kinds, keep_task=keep_task) plugins.append(OverflowPlugin( root=root, reply_agents=replies, - budgets=self._budgets, + budgets=budgets, kinds=kinds, - models=self._agent_model_refs(), + models=( + self._agent_model_refs() if models is self._resolved_models + else {name: str(model.ref) for name, model in models.items()} + ), summarize_now=self._summarize_now, fit_guard=fit_guard, keep_task=keep_task, @@ -958,6 +1024,24 @@ async def _do_initialize(self) -> None: for name, agent in self._agents.items() if name != build.root.name } + # And of each model choice: the type built on it, the type's chain on + # the choice's numbers. + self._variant_runners = { + key: NoAfterTurnCompactionRunner( + app=App( + name=child_app(self.app_name), + root_agent=agent, + plugins=self._agent_plugin_chain( + agent, model=self._choice_models[key], + budget=self._choice_budgets.get(key), + ), + context_cache_config=build.cache, + events_compaction_config=None, + ), + session_service=self._session_service, + ) + for key, agent in self._variant_agents.items() + } # A call's usage names its agent's own model and context numbers (the # default model stands in for an agent without one); only the agents # that reply write the reply, another's text is a sub-agent's work. @@ -1086,7 +1170,7 @@ def _context_cache_config(self) -> ContextCacheConfig | None: """ if not self._settings.prompt_caching_enabled: return None - models = list(self._resolved_models.values()) + models = [*self._resolved_models.values(), *self._choice_models.values()] if not any(m is not None and m.record.cache in _CACHING for m in models): return None return ContextCacheConfig( @@ -1575,6 +1659,10 @@ async def _workflow_events( async def _run_agent(self, run: AgentRun) -> RunAnswer: """Run one sub-agent run on its type's runner, on a child session (the base's hook). + A run on a model choice (``run.model``) runs on the runner of its type + built on that model (``_variant_runners``), its usage and context the + choice's (``_run_models``). + In the run's own task (``agents/delegate.py``): the child session (``child_app``, ``child_session_id``: the conversation's id and the run's instance) is made with the state the run starts from (the @@ -1623,19 +1711,34 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: app, conversation.user_id, session_id, run ) build = self._build + # A run on a model choice runs on its type built on that model, its + # usage and context the choice's under the type's name. + _, budgets = self._run_models(run) + models, kinds = dict(build.models), self._agent_kinds() + chosen = self._choice_models[(run.ref.agent, run.model)] if run.model is not None else None + if chosen is not None: + models[run.ref.agent] = str(chosen.ref) + kinds[run.ref.agent] = chosen.record.kind.value processor = ADKEventProcessor( model=self.model, root=build.root.name, - models=build.models, - budgets=self._budgets, + models=models, + budgets=budgets, reply_agents=build.reply_agents, - kinds=self._agent_kinds(), + kinds=kinds, ledgers=self._usage_ledgers, run=run.ref, ) aborted = asyncio.Event() raised: BaseException | None = None - stream = self._agent_runners[run.ref.agent].run_async( + runner = ( + self._agent_runners[run.ref.agent] if chosen is None + else self._variant_runners[(run.ref.agent, run.model)] + ) + key = (conversation, run.ref.run or "") + if chosen is not None: + self._chosen_runs[key] = chosen + stream = runner.run_async( user_id=conversation.user_id, session_id=session_id, new_message=types.Content(role="user", parts=[types.Part.from_text(text=run.message)]), @@ -1662,6 +1765,7 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: raised = _plugin_cause(error) if isinstance(error, RuntimeError) else error logger.debug("subagent_failed", run=run.ref.run, exc_info=raised) finally: + self._chosen_runs.pop(key, None) self._report_raw_log() # Its work has ended: a limit or a stop landing during the read of # its state below must not discard the answer it made. @@ -1698,6 +1802,17 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: **own, ) + def _chosen_model(self, agent: str | None) -> "ResolvedModel | None": + """The model choice the run in progress is on, when it is ``agent``'s run; else None. + + What the raw LLM log names a call's model by (``LLMLoggingPlugin``): + the one plugin serves every runner, and names a model by agent name. + """ + run = get_active_run() + if run is None or run.agent != agent: + return None + return self._chosen_runs.get((get_active_turn(), run.run or "")) + async def _child_session( self, app: str, user_id: str, session_id: str, run: AgentRun ) -> tuple[dict[str, Any], dict[str, Any] | None]: diff --git a/src/agentic_cli/workflow/adk/plugins.py b/src/agentic_cli/workflow/adk/plugins.py index f29f7857..e1651f70 100644 --- a/src/agentic_cli/workflow/adk/plugins.py +++ b/src/agentic_cli/workflow/adk/plugins.py @@ -9,7 +9,7 @@ from __future__ import annotations from collections import deque -from collections.abc import Mapping +from collections.abc import Callable, Mapping from pathlib import Path from typing import Any, TYPE_CHECKING @@ -27,6 +27,8 @@ from google.adk.agents.invocation_context import InvocationContext from google.adk.models import LlmRequest, LlmResponse + from agentic_cli.models import ResolvedModel + logger = Loggers.workflow() @@ -41,8 +43,9 @@ class LLMLoggingPlugin(BasePlugin): call's ``LLM_USAGE``, credited to its agent, and a second copy would count every call twice (as on Deep Agents, where logging adds no usage). - Each record names the model of the agent that made the call (``models``), - else the request's own model or ``model_name``; that agent + Each record names the model of the agent that made the call (``models``; + ``chosen``: the model choice a run of that agent is on), else the + request's own model or ``model_name``; that agent (``metadata["agent"]``); and, for a sub-agent's call, its run (``WorkflowEvent.run``, the active run the framework's delegation set for the run's task, ``agents/delegate.py``, which the log writes as @@ -71,6 +74,9 @@ class LLMLoggingPlugin(BasePlugin): models: Each agent's model reference, by agent name kinds: Each agent's model's provider kind, by agent name; an agent it does not hold is an unknown kind's + chosen: The model a call's agent is running on when that is a model + choice, not its own (None: the agent's own); the manager answers + it for the run in progress app_name: Application name for log directory (~/.{app_name}/logs/) max_events: Maximum events to buffer in memory (oldest are dropped) include_messages: Whether to include full message history @@ -89,11 +95,13 @@ def __init__( log_requests: bool = True, models: Mapping[str, str] | None = None, kinds: Mapping[str, str] | None = None, + chosen: Callable[[str | None], ResolvedModel | None] | None = None, ) -> None: super().__init__(name="llm_logging") self.model_name = model_name self.models: Mapping[str, str] = models or {} self.kinds: Mapping[str, str] = kinds or {} + self.chosen = chosen self.app_name = app_name self.max_events = max_events self.include_messages = include_messages @@ -137,7 +145,7 @@ def record_request( self.clock.start(callback_context) # The calling agent's model, else the one the request names - model = self.models.get(agent) or llm_request.model or self.model_name + model = self._model_of(agent)[0] or llm_request.model or self.model_name # Extract messages if enabled messages = None @@ -193,7 +201,8 @@ async def after_model_callback( # Get author from context if available author = getattr(callback_context, "agent_name", None) - model = self.models.get(author) or self.model_name + model, kind = self._model_of(author) + model = model or self.model_name # Extract text content content = None @@ -237,7 +246,7 @@ async def after_model_callback( usage_event = adk_usage_event( model, llm_response.usage_metadata, - self.kinds.get(author), + kind, invocation_id=invocation_id, latency_ms=latency_ms, ) @@ -293,6 +302,14 @@ def clear(self) -> None: # Internal helpers # ------------------------------------------------------------------ + def _model_of(self, agent: str | None) -> tuple[str | None, str | None]: + """``agent``'s model reference and its provider kind: the model choice a run + of it is on when there is one, else its own.""" + chosen = self.chosen(agent) if self.chosen is not None else None + if chosen is not None: + return str(chosen.ref), chosen.record.kind.value + return self.models.get(agent), self.kinds.get(agent) + def _write_to_log(self, event: WorkflowEvent) -> None: """Write event to JSON Lines log file.""" self._log.write(event) diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index 3f68199e..fa1352d8 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -1235,6 +1235,28 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: """ raise NotImplementedError(f"{type(self).__name__} runs no sub-agent") + def _run_models( + self, run: AgentRun + ) -> "tuple[Mapping[str, ResolvedModel], Mapping[str, ContextBudget]]": + """The agents' models and context numbers a sub-agent ``run`` reads, by agent name. + + Those of the manager's, except that a run on a model choice + (``run.model``) has its type's entries the choice's: its backend's + event processing, usage and overflow messages then name and count + the model the run went to, under the type's name. + + Raises: + KeyError: ``run.model`` is not one of its type's model choices. + """ + if run.model is None: + return self._resolved_models, self._budgets + key = (run.ref.agent, run.model) + models = {**self._resolved_models, run.ref.agent: self._choice_models[key]} + budgets = dict(self._budgets) + if key in self._choice_budgets: + budgets[run.ref.agent] = self._choice_budgets[key] + return models, budgets + async def _agent_tool_names(self, agent: str) -> frozenset[str]: """The names a ``task`` call's ``tools`` may give for ``agent`` (a backend hook). diff --git a/src/agentic_cli/workflow/deepagents/agent_builder.py b/src/agentic_cli/workflow/deepagents/agent_builder.py index 03999d7d..3abee590 100644 --- a/src/agentic_cli/workflow/deepagents/agent_builder.py +++ b/src/agentic_cli/workflow/deepagents/agent_builder.py @@ -14,7 +14,9 @@ answers with the result envelope. Only the configured sub-agents are offered: there is no automatic general-purpose sub-agent, and none of Deep Agents' file tools. ``graphs``, when given, is filled with every agent's graph by name: -what the manager runs a sub-agent on. +what the manager runs a sub-agent on. A sub-agent type's model choices are +built once more each (``Variant``, ``variants=``): the type's graph on +another model, filled into ``variant_graphs`` by key. Every stack, outermost first: ``InterruptedCallsMiddleware`` (answers a tool call a cancelled turn or a crash left without a result, before each run, as @@ -53,7 +55,8 @@ from __future__ import annotations -from collections.abc import Callable, Mapping +from collections.abc import Callable, Hashable, Mapping +from dataclasses import dataclass from typing import TYPE_CHECKING from deepagents.middleware.patch_tool_calls import PatchToolCallsMiddleware @@ -101,6 +104,26 @@ from agentic_cli.workflow.agents.delegate import Delegations +@dataclass(frozen=True) +class Variant: + """One more graph of a sub-agent type, on another model (a model choice's). + + Built as the type's own is, with its tools and prompt, but its model + side from ``resolved`` and its summarization from ``budget``. + + Attributes: + config: The type. + chat_model: The chat model of the choice. + resolved: The choice's resolved model (None: a unit test's, with no model side). + budget: The choice's context numbers; None: computed from ``resolved``. + """ + + config: AgentConfig + chat_model: "BaseChatModel" + resolved: "ResolvedModel | None" + budget: ContextBudget | None = None + + def build_agent_tree( configs: list[AgentConfig], *, @@ -122,6 +145,8 @@ def build_agent_tree( graphs: "dict[str, CompiledStateGraph] | None" = None, roster: Callable[[], str] | None = None, root: str | None = None, + variants: "Mapping[Hashable, Variant] | None" = None, + variant_graphs: "dict[Hashable, CompiledStateGraph] | None" = None, ) -> "CompiledStateGraph": """Build every agent, each on its own, and return the root. @@ -184,6 +209,11 @@ def build_agent_tree( root: The root's name (the validated graph's ``AgentGraph.root_name``). None: the first agent nobody delegates to that sets no ``spawnable_by``. + variants: Sub-agent types on other models (a type's model choices), + by key: each is built as the type's graph is, from its own chat + model, resolved model and budget, with the type's tools and + prompt, and filled into ``variant_graphs``. + variant_graphs: Filled, when given, with each variant's graph, by key. Raises: AgentGraphError: A delegating agent's own tools include one named @@ -198,60 +228,115 @@ def build_agent_tree( ) def build(name: str) -> "CompiledStateGraph": - config = config_map[name] - model = chat_models[name] - model_side = _model_side( - model, resolved.get(name), settings, + is_root = name == root + return build_agent( + config_map[name], root=is_root, configs=configs, chat_model=chat_models[name], + resolved=resolved.get(name), tools=tools.get(name, []), prompt=prompts[name], + settings=settings, checkpointer=checkpointer, bound=bound, budget=budgets.get(name) if budgets is not None else None, - memory_index=memory_index if name == root else None, - memory_index_cached=memory_index_cached if name == root else None, - memory_index_forget=memory_index_forget if name == root else None, - roster=roster if name == root else None, - ) - if name != root: - # Inside the outcome middleware, which reads the answer whose - # calls it dropped as final; outside the summarization, which - # counts its note. - if delegations is not None: - model_side = [RunControlMiddleware(delegations), *model_side] - # Outermost: it sees the answer every other model-side - # middleware let through, as the run's answer is read. - model_side = [SubAgentOutcomeMiddleware(), *model_side] - if summarizers is not None: - summarizers.update( - (name, middleware) for middleware in model_side - if isinstance(middleware, ReportingSummarizationMiddleware) - ) - delegates = delegations is not None and can_have_children( - config, configs, delegations().policy, root=name == root - ) - follows = delegates and delegations is not None and delegations().policy.follow_ups - own = _own_tools(config, tools.get(name, []), delegates=delegates, follows=follows) - if delegates and delegations is not None: - own = [*own, build_task_tool(name, delegations, root=name == root)] - if follows: - own = [*own, *build_follow_up_tools(delegations)] - return create_agent( - model=model, - tools=own, - system_prompt=prompts[name], - middleware=[ - PatchToolCallsMiddleware() if open_calls is None - else InterruptedCallsMiddleware(open_calls, root=name == root), - *model_side, - *_tool_side(config, settings, bound=bound, open_calls=open_calls, marks=marks), - ], - state_schema=AgentCliState, - name=name, - checkpointer=checkpointer if name == root or checkpointer is not None else False, + summarizers=summarizers, open_calls=open_calls, marks=marks, + memory_index=memory_index if is_root else None, + memory_index_cached=memory_index_cached if is_root else None, + memory_index_forget=memory_index_forget if is_root else None, + delegations=delegations, roster=roster if is_root else None, ) built = {name: build(name) for name in config_map} if graphs is not None: graphs.update(built) + for key, variant in (variants or {}).items(): + name = variant.config.name + graph = build_agent( + variant.config, root=False, configs=configs, chat_model=variant.chat_model, + resolved=variant.resolved, tools=tools.get(name, []), prompt=prompts[name], + settings=settings, checkpointer=checkpointer, bound=bound, budget=variant.budget, + open_calls=open_calls, marks=marks, delegations=delegations, + ) + if variant_graphs is not None: + variant_graphs[key] = graph return built[root] +def build_agent( + config: AgentConfig, + *, + root: bool, + configs: list[AgentConfig], + chat_model: "BaseChatModel", + resolved: "ResolvedModel | None", + tools: list["BaseTool"], + prompt: str, + settings: "BaseSettings | None", + checkpointer: "BaseCheckpointSaver | None", + bound: Callable[[object], ToolDefinition | None] = identify_tool, + budget: ContextBudget | None = None, + summarizers: dict[str, ReportingSummarizationMiddleware] | None = None, + open_calls: OpenCalls | None = None, + marks: OutsideContentMarks | None = None, + memory_index: Callable[[], str] | None = None, + memory_index_cached: Callable[[], str] | None = None, + memory_index_forget: Callable[[], None] | None = None, + delegations: "Callable[[], Delegations] | None" = None, + roster: Callable[[], str] | None = None, +) -> "CompiledStateGraph": + """Build one agent's graph: ``config`` on ``chat_model``, with its tools and prompt. + + What ``build_agent_tree`` builds each agent with (its arguments, for one + agent), and builds a model choice's variant of a sub-agent type with. + ``root`` says whether this is the root: only it has the memory index and + the roster (passed only for it), and every other agent has the run + control and the outcome middleware; a sub-agent's graph has no + checkpointer of its own unless the tree has one. + + Raises: + AgentGraphError: A delegating agent's own tools include one named + ``task``, the name of its delegation tool. + """ + name = config.name + model_side = _model_side( + chat_model, resolved, settings, budget=budget, + memory_index=memory_index, memory_index_cached=memory_index_cached, + memory_index_forget=memory_index_forget, roster=roster, + ) + if not root: + # Inside the outcome middleware, which reads the answer whose + # calls it dropped as final; outside the summarization, which + # counts its note. + if delegations is not None: + model_side = [RunControlMiddleware(delegations), *model_side] + # Outermost: it sees the answer every other model-side + # middleware let through, as the run's answer is read. + model_side = [SubAgentOutcomeMiddleware(), *model_side] + if summarizers is not None: + summarizers.update( + (name, middleware) for middleware in model_side + if isinstance(middleware, ReportingSummarizationMiddleware) + ) + delegates = delegations is not None and can_have_children( + config, configs, delegations().policy, root=root + ) + follows = delegates and delegations is not None and delegations().policy.follow_ups + own = _own_tools(config, tools, delegates=delegates, follows=follows) + if delegates and delegations is not None: + own = [*own, build_task_tool(name, delegations, root=root)] + if follows: + own = [*own, *build_follow_up_tools(delegations)] + return create_agent( + model=chat_model, + tools=own, + system_prompt=prompt, + middleware=[ + PatchToolCallsMiddleware() if open_calls is None + else InterruptedCallsMiddleware(open_calls, root=root), + *model_side, + *_tool_side(config, settings, bound=bound, open_calls=open_calls, marks=marks), + ], + state_schema=AgentCliState, + name=name, + checkpointer=checkpointer if root or checkpointer is not None else False, + ) + + def _own_tools( config: AgentConfig, tools: list["BaseTool"], *, delegates: bool, follows: bool = False ) -> list["BaseTool"]: diff --git a/src/agentic_cli/workflow/deepagents/manager.py b/src/agentic_cli/workflow/deepagents/manager.py index 4a2c9790..1bf3d8fc 100644 --- a/src/agentic_cli/workflow/deepagents/manager.py +++ b/src/agentic_cli/workflow/deepagents/manager.py @@ -76,7 +76,7 @@ is_context_overflow, subagent_overflow_message, ) -from agentic_cli.workflow.deepagents.agent_builder import build_agent_tree +from agentic_cli.workflow.deepagents.agent_builder import Variant, build_agent_tree from agentic_cli.workflow.deepagents.event_processor import ( DeepAgentsEventProcessor, RunCallback, @@ -194,6 +194,9 @@ def __init__( self._root: CompiledStateGraph | None = None # Every agent's graph, by name: what a sub-agent run runs on. self._agent_graphs: dict[str, CompiledStateGraph] = {} + # Each sub-agent type's graph on each of its model choices, by (type, + # choice): what a run on a choice runs on. + self._variant_graphs: dict[tuple[str, str], CompiledStateGraph] = {} # Each agent's own tools' names as its model sees them (its tools, skill # tools and MCP tools), the framework's state and delegation tools left # out: what a task call's `tools` may name. @@ -295,6 +298,22 @@ async def _do_initialize(self) -> None: index_wanted = self._memory_index_wanted(root) roster_wanted = self._roster_wanted(root) graphs: dict[str, CompiledStateGraph] = {} + variant_graphs: dict[Any, CompiledStateGraph] = {} + variants = { + (config.name, choice): Variant( + config=config, + chat_model=build_chat_model( + self._choice_models[(config.name, choice)], + settings=self._settings, + app_name=self.app_name, + ), + resolved=self._choice_models[(config.name, choice)], + budget=self._choice_budgets.get((config.name, choice)), + ) + for config in self._agent_configs + if config.name != root + for choice in config.model_choices + } self._root = build_agent_tree( self._agent_configs, chat_models={ @@ -324,8 +343,11 @@ async def _do_initialize(self) -> None: delegations=lambda: self._delegations, graphs=graphs, root=root, + variants=variants, + variant_graphs=variant_graphs, ) self._agent_graphs = graphs + self._variant_graphs = variant_graphs self._root_summarization = summarizers.get(root) logger.info( @@ -436,6 +458,7 @@ def _detach_backend(self) -> list[Closer]: """ self._root = None self._agent_graphs = {} + self._variant_graphs = {} self._root_summarization = None self._own_tool_names = {} self._pending_notices = [] @@ -784,6 +807,10 @@ async def _run_turn( async def _run_agent(self, run: AgentRun) -> RunAnswer: """Run one sub-agent run on its agent's graph (the base's hook, ``Delegations``'s). + A run on a model choice (``run.model``) runs on its type's graph built + on that model (``_variant_graphs``), its usage and context the + choice's (``_run_models``). + In the run's own task (``agents/delegate.py``), apart from its caller's stream: the graph is streamed with the run's own config, its callbacks this run's ``RunCallback``, and LangGraph's ambient @@ -834,7 +861,12 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: conversation = run.conversation if conversation is None: raise RuntimeError("A sub-agent run runs in a conversation's turn.") - graph = self._agent_graphs[run.ref.agent] + # A run on a model choice runs on its type's graph built on that model. + graph = ( + self._agent_graphs[run.ref.agent] if run.model is None + else self._variant_graphs[(run.ref.agent, run.model)] + ) + models, budgets = self._run_models(run) task_id = f"agentic-cli-task-{uuid.uuid4().hex}" # A first run's message is its instance's brief, which its summaries keep. task = ( @@ -865,19 +897,19 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: inputs = {**run.state, "messages": [*(run.history or ()), task]} processor = DeepAgentsEventProcessor( root=self._root_agent_name, - agent_models=self._resolved_models, + agent_models=models, session_id=conversation.session_id, - budgets=self._budgets, + budgets=budgets, ledgers=self._usage_ledgers, run=run.ref, ) callback = RunCallback( root=self._root_agent_name, - agent_models=self._resolved_models, + agent_models=models, llm_log=self._raw_llm_log(), # Run outside a turn there is no one to report to. live=live_events.current() or LiveEvents(), - budgets=self._budgets, + budgets=budgets, ledgers=self._usage_ledgers, ) final: dict[str, Any] = {} @@ -913,7 +945,7 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: # The run fails with the text it wrote before it. wrote = _last_text(_answers_in(final, task.id)) if is_context_overflow(error): - model = self._resolved_models.get(run.ref.agent) + model = models.get(run.ref.agent) raise RunFailed( subagent_overflow_message( run.ref.agent, str(model.ref) if model is not None else "the model" diff --git a/tests/workflow/adk/test_plugin_chain.py b/tests/workflow/adk/test_plugin_chain.py index 8870d12c..5612a44c 100644 --- a/tests/workflow/adk/test_plugin_chain.py +++ b/tests/workflow/adk/test_plugin_chain.py @@ -186,6 +186,41 @@ async def test_a_delegating_app(project): assert logs == [shared] +async def test_a_model_choices_runner_has_its_types_chain_on_the_choices_numbers(project): + """A sub-agent type with model choices has a runner of its own for each: + its agent built on the choice's model, and the type's chain, in which + every plugin that reads an agent's numbers, kind or model by name reads + the choice's under the type's name. The release closes it.""" + choice = "claude-haiku-4-5" + manager = GoogleADKWorkflowManager( + agent_configs=[ + AgentConfig(name="lead", prompt="Lead.", sub_agents=["helper"]), + AgentConfig(name="helper", prompt="Help.", description="Helps.", + model_choices=(choice,)), + ], + settings=_settings(extras=True), + ) + + try: + await manager.initialize_services() + own = manager._agent_runners["helper"] + chosen = manager._variant_runners[("helper", choice)] + plugins = {plugin.name: plugin for plugin in chosen.app.plugins} + budget = manager.context_budget("helper", model=choice) + agent = chosen.app.root_agent + assert set(manager._variant_runners) == {("helper", choice)} + assert [p.name for p in chosen.app.plugins] == [p.name for p in own.app.plugins] + assert (agent.name, agent.model.model) == ("helper", choice) + assert own.app.root_agent.model.model == MODEL + assert plugins["fit_guard"]._budgets["helper"] == budget + assert plugins["context_overflow"]._budgets["helper"] == budget + assert plugins["context_overflow"]._models["helper"] == f"anthropic:{choice}" + assert manager.context_budget("helper") != budget + finally: + await manager.cleanup() + + assert (manager._variant_runners, manager._variant_agents) == ({}, {}) + async def test_a_main_agent_that_continues_its_sub_agents_gets_the_roster(project): """With the policy's ``follow_ups`` the main agent has ``message_agent``: its chain carries the roster, before the memory index; a sub-agent type's diff --git a/tests/workflow/deepagents/test_agent_builder.py b/tests/workflow/deepagents/test_agent_builder.py index 539757f6..1253e061 100644 --- a/tests/workflow/deepagents/test_agent_builder.py +++ b/tests/workflow/deepagents/test_agent_builder.py @@ -51,7 +51,7 @@ ) from agentic_cli.workflow.config import AgentConfig, AgentGraphError # noqa: E402 from agentic_cli.workflow.deepagents import agent_builder # noqa: E402 -from agentic_cli.workflow.deepagents.agent_builder import build_agent_tree # noqa: E402 +from agentic_cli.workflow.deepagents.agent_builder import Variant, build_agent_tree # noqa: E402 from agentic_cli.workflow.deepagents.middleware import ( # noqa: E402 ActiveToolCallMiddleware, PermissionMiddleware, @@ -675,3 +675,42 @@ def stop_agent(agent: str) -> dict: ) assert [tool.name for tool in created["coordinator"]["tools"]] == ["stop_agent", "task"] + + +class TestAVariant: + """One more graph of a sub-agent type on another model (a model choice's): + built as the type's is, its tools and prompt the type's, on its own model.""" + + async def test_it_runs_on_its_own_model_as_a_sub_agent(self, monkeypatch): + made: list[dict] = [] + real = agent_builder.create_agent + + def spy(*args, **kwargs): + made.append(kwargs) + return real(*args, **kwargs) + + monkeypatch.setattr(agent_builder, "create_agent", spy) + own = ScriptedChat(script=[ai("From its own.")]) + cheaper = ScriptedChat(script=[ai("From the choice.")]) + variant_graphs: dict = {} + tools = {"researcher": to_langchain_tools([save_plan])} + + _tree( + [COORDINATOR, RESEARCHER], + {"coordinator": ScriptedChat(), "researcher": own}, + tools=tools, checkpointer=InMemorySaver(), + variants={("researcher", "fast"): Variant(config=RESEARCHER, chat_model=cheaper, + resolved=None)}, + variant_graphs=variant_graphs, + ) + await variant_graphs[("researcher", "fast")].ainvoke( + {"messages": [HumanMessage("# Task: Find X.")]}, + {"configurable": {"thread_id": "v"}}, + ) + + assert (len(own.requests), len(cheaper.requests)) == (0, 1) + *_, variant = made + assert [m["name"] for m in made] == ["coordinator", "researcher", "researcher"] + assert (variant["model"], variant["system_prompt"]) == (cheaper, "You are researcher.") + assert [tool.name for tool in variant["tools"]] == ["save_plan"] + assert RunControlMiddleware in [type(m) for m in variant["middleware"]] diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index c15103ef..7b422aef 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -355,15 +355,22 @@ def _team_chat() -> type: Deep Agents summarizes an agent's conversation on that agent's model; the scenarios script the summaries apart, as ADK sends them apart. """ + from pydantic import Field + from tests.workflow.deepagents.fakes import ScriptedChat class TeamChat(ScriptedChat): #: The chat that answers summary requests (Any: not copied by pydantic). summaries: Any = None + #: The model id this copy was built for, and each request's, in order: + #: a copy (``model_copy``) shares the script, the requests and this list. + model_id: str = "" + sent_models: list[str] = Field(default_factory=list) def _answer(self, messages): if self.summaries is not None and SUMMARY_MARKER in (messages[-1].text or ""): return self.summaries._answer(messages) + self.sent_models.append(self.model_id) return super()._answer(messages) return TeamChat @@ -495,6 +502,7 @@ class Crew: _models: Callable[[str], list[str]] | None = None _opening: Callable[[str, int], list[str]] | None = None _declared: Callable[[str, str, int], dict[str, Any] | None] | None = None + _sent_models: Callable[[str], list[str]] | None = None #: The turns ``start`` started: one a failed test left running is stopped #: before its manager is cleaned up (the cleanup waits for its turn). started: list["asyncio.Task[Any]"] = field(default_factory=list) @@ -539,6 +547,11 @@ def models(self, agent: str) -> list[str]: assert self._models is not None return self._models(agent) + def sent_models(self, agent: str) -> list[str]: + """The model each of ``agent``'s requests went to, as a model id, in order: + ADK each request's, Deep Agents the model each request's chat was built for.""" + assert self._sent_models is not None + return self._sent_models(agent) def opening(self, agent: str, call: int = -1) -> list[str]: """The text blocks of the first user message ``agent``'s model request ``call`` held, in order: what opens its conversation (the main @@ -783,7 +796,7 @@ def opening(name: str, call: int) -> list[str]: "adk", manager, manager.session_ref(SESSION, USER), results_read, requests, result_ids, answers, last_message, bodies, tool_names, message_count, state, marked, _call_results=call_results, _instance_mark=instance_mark, _models=models, - _opening=opening, _declared=declared, + _opening=opening, _declared=declared, _sent_models=models, ) @@ -810,7 +823,14 @@ def _deepagents_crew( models.chats[name] = _team_chat()( label=chat.label, script=chat.script, summaries=summaries ) - monkeypatch.setattr(deepagents_manager, "build_chat_model", models) + def chat_for(resolved: Any, *, settings: Any, app_name: str) -> Any: + # Each agent's chat, as built for this model: what its requests went to. + chat = models(resolved, settings=settings, app_name=app_name) + if resolved.agent is None: + return chat + return chat.model_copy(update={"model_id": resolved.ref.model}) + + monkeypatch.setattr(deepagents_manager, "build_chat_model", chat_for) manager = deepagents_manager.DeepAgentsWorkflowManager( agent_configs=team, settings=_settings(store, entries), subagents=subagents ) @@ -910,6 +930,7 @@ def opening(name: str, call: int) -> list[str]: result_ids, answers, last_message, bodies, tool_names, message_count, state, marked, _call_results=call_results, _instance_mark=instance_mark, _models=built_models, _opening=opening, _declared=declared, + _sent_models=lambda name: list(models.chats[name].sent_models), ) @@ -6594,3 +6615,163 @@ async def test_starts_no_run_and_takes_no_count(self, make_crew, researcher, fie assert envelope_read(crew.results_read("coordinator", 2)["c2"])["result"] == "Y is 7." assert [r.ref.run for r in crew.records()] == ["researcher-1#1"] assert [e.metadata["status"] for e in runs_of(events)] == [RUN_STARTED, RUN_COMPLETED] + + +#: A cheaper model the researcher may be run on: a model choice. +CHOICE = "anthropic:claude-haiku-4-5" + + +class TestAModelChoice: + """``task``'s ``model``: the run goes to the choice's model (its type's agent + built on it), its usage is that model's, and its instance keeps it.""" + + async def test_task_offers_it_and_names_a_types_choices(self, make_crew): + from agentic_cli.workflow.agents.brief import MODEL_DESCRIPTION + + crew = make_crew(narrow_team(model_choices=("fast", CHOICE)), + coordinator=[says("Hi.")]) + + await crew.turn() + + parameters = crew.declared("coordinator")["parameters"] + assert list(parameters["properties"])[-2:] == ["tools", "model"] + assert parameters["properties"]["model"] == { + "type": "string", "description": MODEL_DESCRIPTION, + } + assert parameters["properties"]["agent_type"]["description"] == ( + "The agent to hand the task to:\n- researcher (model choices: fast, " + "anthropic:claude-haiku-4-5): The researcher." + ) + + async def test_its_requests_go_to_the_choices_model_and_its_usage_is_under_it( + self, make_crew + ): + crew = make_crew( + narrow_team(model_choices=(CHOICE,)), + coordinator=[calls(delegate("researcher", "Find X.", "c1", model=CHOICE), + delegate("researcher", "Find Y.", "c2")), says("Done.")], + researcher=[says("X is 42.", usage=(100, 10)), says("Y is 7.", usage=(80, 8))], + ) + + with no_blocking_calls(): + await crew.turn() + + by_run = {r.ref.run: r for r in crew.records()} + assert sorted(crew.sent_models("researcher")) == ["claude-haiku-4-5", "claude-sonnet-4-6"] + assert by_run["researcher-1#1"].usage == {CHOICE: {"input": 100, "output": 10}} + assert by_run["researcher-2#1"].usage == { + "anthropic:claude-sonnet-4-6": {"input": 80, "output": 8}, + } + assert crew.ledger().by_model(run="researcher-1#1") == { + CHOICE: UsageTotals(input=100, output=10, calls=1), + } + assert [(i.instance, i.model) for i in crew.manager.agent_runs.instances( + crew.conversation + )] == [("researcher-1", CHOICE), ("researcher-2", None)] + + async def test_a_follow_up_runs_on_it_after_a_model_switch_too(self, make_crew): + crew = make_crew( + narrow_team(model_choices=(CHOICE,)), subagents=FOLLOWING, + coordinator=[calls(delegate("researcher", "Find X.", "c1", model=CHOICE)), + says("Asked."), calls(message("researcher-1", "Now find Y.", "c2")), + says("Done.")], + researcher=[says("X is 42."), says("Y is 7.")], + ) + + await crew.turn() + await crew.manager.reinitialize(model="claude-opus-4-7", preserve_sessions=True) + await crew.turn("Find Y too.") + + assert crew.sent_models("researcher") == ["claude-haiku-4-5", "claude-haiku-4-5"] + assert crew.sent_models("coordinator")[-1] == "claude-opus-4-7" + assert "X is 42." in crew.bodies("researcher")[1] + assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Y is 7." + + +class TestAModelChoiceInTheRawLog: + async def test_its_calls_records_name_the_choices_model(self, make_crew, monkeypatch): + settings = BaseSettings( + session_store="memory", default_model="claude-sonnet-4-6", raw_llm_logging=True + ) + monkeypatch.setattr(sys.modules[__name__], "_settings", lambda store, models=None: settings) + crew = make_crew( + narrow_team(model_choices=(CHOICE,)), + coordinator=[calls(delegate("researcher", "Find X.", "c1", model=CHOICE)), + says("Done.")], + researcher=[says("X is 42.")], + ) + + await crew.turn() + + log = Path.home() / f".{settings.app_name}" / "logs" / "llm_events.jsonl" + records = [json.loads(line) for line in log.read_text().splitlines()] + assert { + (r["metadata"]["agent"], r["metadata"]["model"]) for r in records + if r["type"] in ("llm_request", "llm_response") + } == {("coordinator", "anthropic:claude-sonnet-4-6"), ("researcher", CHOICE)} + + +class TestChoicesKeptAcrossARestart: + """An instance on a model choice and narrowed tools, continued after a + restart (its records restored by a new manager): its follow-up runs on + the same model with the same tools.""" + + async def test_the_follow_up_runs_as_its_first_run_did(self, make_crew): + first = make_crew( + narrow_team(model_choices=(CHOICE,)), subagents=FOLLOWING, store="sqlite", + coordinator=[calls(delegate("researcher", "Find X.", "c1", model=CHOICE, + tools=["contract_lookup"])), says("Asked.")], + researcher=[says("X is 42.")], + ) + await first.turn() + await first.manager.cleanup() + second = make_crew( + narrow_team(model_choices=(CHOICE,)), subagents=FOLLOWING, store="sqlite", + coordinator=[calls(message("researcher-1", "Now find Y.", "c2")), says("Done.")], + researcher=[says("Y is 7.")], + ) + + await second.manager.initialize_services() + await second.manager.load_session(SESSION, user_id=USER) + (instance,) = second.manager.agent_runs.instances(second.conversation) + await second.turn("Find Y too.") + + assert (instance.tools, instance.model) == (("contract_lookup",), CHOICE) + assert second.sent_models("researcher") == ["claude-haiku-4-5"] + assert second.tool_names("researcher") == NARROWED + assert envelope_read(second.results_read("coordinator")["c2"])["result"] == "Y is 7." + + +class TestAChoicesSmallerWindow: + """A model choice whose window is smaller than its type's own: an + inheriting run on it, over a long conversation, is kept within the + choice's numbers (ADK's fit guard trims it, Deep Agents summarizes it), + where on the type's own model it is sent whole.""" + + @pytest.mark.parametrize("chosen", [SMALL_MODEL, None], ids=["the-choice", "its-own"]) + async def test_its_requests_fit_the_choices_budget(self, make_crew, chosen): + crew = make_crew( + [agent("coordinator", sub_agents=("reader",)), + agent("reader", inherit_context=True, model_choices=(SMALL_MODEL,))], + models=SMALL_ENTRY, + coordinator=[says("Noted."), says("Noted again."), + calls(delegate("reader", "Sum it up.", "c1", + **({"model": chosen} if chosen else {}))), + says("Done.")], + reader=[says("It was words.")], + summaries=[says("The user sent many words twice.")], + ) + await crew.turn("First: " + "word " * 8_000) + await crew.turn("Second: " + "word " * 8_000) + + events = await crew.turn("Have the reader sum it up.") + + sent = crew.bodies("reader")[-1] + trimmed = [e.metadata["agent"] for e in events if e.type is EventType.CONTEXT_TRIMMED] + if chosen: + assert crew.sent_models("reader") == ["claude-haiku-4-5"] + assert "First: word" not in sent and trimmed == ["reader"] + else: + assert crew.sent_models("reader") == ["claude-sonnet-4-6"] + assert "First: word" in sent and trimmed == [] + assert envelope_read(crew.results_read("coordinator")["c1"])["result"] == "It was words." From 832411bee8157e9a9831f3881f9ac7c1b489e54b Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:35:29 -0500 Subject: [PATCH 08/11] Sub-agents: /agents and the view say an instance's model and tools /agents shows the model choice and the tools an instance's delegation gave it. Its view's status bar (ctx) and /status read its model and context numbers from its model choice when it runs on one, after a restart too. --- src/agentic_cli/cli/agent_view.py | 26 +++++++++++----- src/agentic_cli/cli/agents_command.py | 24 +++++++++++--- tests/cli/test_agent_view.py | 45 +++++++++++++++++++++++++++ tests/cli/test_agents_command.py | 23 ++++++++++++-- 4 files changed, 104 insertions(+), 14 deletions(-) diff --git a/src/agentic_cli/cli/agent_view.py b/src/agentic_cli/cli/agent_view.py index a4f86fd6..f10e4952 100644 --- a/src/agentic_cli/cli/agent_view.py +++ b/src/agentic_cli/cli/agent_view.py @@ -6,7 +6,8 @@ recap of it: its brief's title and objective, its last run's status, the first lines of its result and its tokens; nothing is replayed. The prompt becomes ``researcher-2> `` and the status bar names it and its status, its -context (``ctx``: its own last prompt against its own summary trigger) and +context (``ctx``: its own last prompt against its own summary trigger, the +numbers of its model choice when it runs on one) and its tokens, the jobs segment kept. A line typed there is the user's message to the instance: while it is idle @@ -170,10 +171,10 @@ def context_rows(self) -> list[tuple[str, str]]: if record is None: return [("Sub-agent", f"{self.instance} (gone)")] rows = [("Sub-agent", f"{self.instance} ({record.agent}, {record.status})")] - model = getattr(workflow, "agent_models", {}).get(record.agent) + model = _model(workflow, record) if model is not None: rows.append(("Model", str(model.ref))) - budget = _budget(workflow, record.agent) + budget = _budget(workflow, record) if budget is not None: window = ( format_tokens(budget.window) if budget.window_known @@ -496,10 +497,19 @@ def _runs_of(workflow: Any, conversation: "SessionRef", instance: str) -> list[" ] -def _budget(workflow: Any, agent: str) -> Any: - """``agent``'s context budget; None when its manager manages none.""" +def _model(workflow: Any, record: "InstanceRecord") -> Any: + """The model the instance runs on: its model choice's when it has one, else its type's.""" + if record.model is not None: + return getattr(workflow, "choice_models", {}).get((record.agent, record.model)) + return getattr(workflow, "agent_models", {}).get(record.agent) + + +def _budget(workflow: Any, record: "InstanceRecord") -> Any: + """The instance's context budget (its model choice's, when it has one); None when its manager manages none.""" try: - return workflow.context_budget(agent) + if record.model is not None: + return workflow.context_budget(record.agent, model=record.model) + return workflow.context_budget(record.agent) except (KeyError, RuntimeError, AttributeError): return None @@ -518,8 +528,8 @@ def _last_prompt(workflow: Any, conversation: "SessionRef", record: "InstanceRec def _context(workflow: Any, conversation: "SessionRef", record: "InstanceRecord") -> str: """The status bar's ``ctx`` for the instance: its last prompt against its - own trigger, as the main agent's is shown (``UsageTracker.format_context``).""" - budget = _budget(workflow, record.agent) + own trigger (its model choice's, when it has one), as the main agent's is shown (``UsageTracker.format_context``).""" + budget = _budget(workflow, record) return UsageTracker( last_prompt_tokens=_last_prompt(workflow, conversation, record), context_trigger=budget.trigger if budget is not None else None, diff --git a/src/agentic_cli/cli/agents_command.py b/src/agentic_cli/cli/agents_command.py index 6b188edb..04a232f0 100644 --- a/src/agentic_cli/cli/agents_command.py +++ b/src/agentic_cli/cli/agents_command.py @@ -6,7 +6,8 @@ deeper. Enter opens the view of the one picked (``/agent ``), Esc nothing; ``/agents `` shows one instance (``researcher-2``) or one run (``researcher-2#1``): its type, its parent, its -title, then each run's status (while it works ``running``, ``queued`` waiting +title, the model choice it runs on and the tools its delegation narrowed it +to (when it was given any), then each run's status (while it works ``running``, ``queued`` waiting for a free working slot, or ``needs you`` waiting on the user; a completion cut at its output limit ``completed (partial)``) and how long it ran (or has been running), the fields of its brief its parent filled (its objective, @@ -60,6 +61,8 @@ #: How many lines of a run's result ``/agents `` shows. RESULT_LINES = 3 +#: What ``/agents `` says of an instance narrowed to none of its type's own tools. +NO_OWN_TOOLS = "none of its own" #: What ``/agents`` says for a conversation with no run recorded. NO_RUNS = "No sub-agent runs in this conversation yet." #: The title of ``/agents``'s picker. @@ -199,7 +202,10 @@ def show(app: Any, workflow: Any, conversation: "SessionRef", wanted: str) -> No mine = [found] if found.ref.run == wanted else [ r for r in runs.records(conversation) if r.ref.instance == found.ref.instance ] - app.session.add_rich(_one(mine, workflow.usage_of(conversation))) + app.session.add_rich(_one( + mine, workflow.usage_of(conversation), + instance=runs.instance(conversation, found.ref.instance), + )) async def _load(app: Any, workflow: Any, conversation: "SessionRef") -> bool: @@ -248,8 +254,14 @@ def _workflow(app: Any) -> Any: return workflow -def _one(records: list["RunRecord"], ledger: "UsageLedger") -> Panel: - """``/agents ``'s panel: one instance's runs (one run's, for a run id).""" +def _one( + records: list["RunRecord"], ledger: "UsageLedger", *, instance: "InstanceRecord | None" = None +) -> Panel: + """``/agents ``'s panel: one instance's runs (one run's, for a run id). + + After its title it names the model choice and the tools of ``instance`` + (its record) when its delegation gave it any. + """ first = records[0] table = Table(show_header=False, box=None, padding=(0, 2, 0, 0)) table.add_column("Key", style="bold cyan", no_wrap=True) @@ -257,6 +269,10 @@ def _one(records: list["RunRecord"], ledger: "UsageLedger") -> Panel: table.add_row("Type", Text(first.ref.agent)) table.add_row("Parent", Text(first.ref.parent_run or "root")) table.add_row("Title", Text(first.title or "—")) + if instance is not None and instance.model is not None: + table.add_row("Model", Text(instance.model)) + if instance is not None and instance.tools is not None: + table.add_row("Tools", Text(", ".join(instance.tools) or NO_OWN_TOOLS)) now = _now() for record in records: table.add_row(f"Run {_run_number(record)}", f"{_status(record)} · {_duration(record, now)}") diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index f78668ff..f41fe33e 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -59,6 +59,8 @@ FOLLOWING, HELD, SESSION, + SMALL_ENTRY, + SMALL_MODEL, USER, Crew, agent, @@ -530,6 +532,49 @@ async def test_status_has_one_model_row_the_instances(self, make_crew): assert models == [str(crew.manager.agent_models["researcher"].ref)] +class TestAnInstanceOnAModelChoice: + """An instance on a model choice with narrowed tools, continued after a + restart (its records restored in a new manager): ``/agents `` and its + view say its model and tools, its view's context is its choice's, and + its next run is on that model with those tools.""" + + async def test_after_a_restart_its_view_and_panel_say_so(self, make_crew): + first = make_crew( + follow_team(model_choices=(SMALL_MODEL,)), store="sqlite", models=SMALL_ENTRY, + coordinator=[calls(delegate("researcher", "Find X.", "c1", model=SMALL_MODEL, + tools=["contract_lookup"])), says("Done.")], + researcher=[says("X is 42.", usage=(1_200, 40))], + ) + await first.turn() + await first.manager.cleanup() + second = make_crew( + follow_team(model_choices=(SMALL_MODEL,)), store="sqlite", models=SMALL_ENTRY, + researcher=[says("Y is 7.", usage=(900, 30))], + ) + app = await app_on(second) + + await typed(app, "/agents researcher-1") + (panel,) = app.session.add_rich.call_args.args + rows = dict(rows_of(panel.renderable)) + await typed(app, "/agent researcher-1", "Now find Y.") + bar = status(app) + await typed(app, "/status") + (shown,) = app.session.add_rich.call_args.args + + assert (rows["Model"], rows["Tools"]) == (SMALL_MODEL, "contract_lookup") + assert second.sent_models("researcher") == ["claude-haiku-4-5"] + assert second.tool_names("researcher") == ["contract_lookup"] + budget = second.manager.context_budget("researcher", model=SMALL_MODEL) + assert budget != second.manager.context_budget("researcher") + assert UsageTracker( + last_prompt_tokens=900, context_trigger=budget.trigger, + window_known=budget.window_known, + ).format_context() in bar + context = dict(rows_of(shown.renderable)) + assert (context["Model"], context["Summarize At"]) == ( + SMALL_MODEL, format_tokens(budget.trigger) + ) + class TestOffTheLoop: async def test_it_blocks_no_event_loop(self, make_crew): crew = make_crew( diff --git a/tests/cli/test_agents_command.py b/tests/cli/test_agents_command.py index c58aec36..29b851dd 100644 --- a/tests/cli/test_agents_command.py +++ b/tests/cli/test_agents_command.py @@ -82,11 +82,12 @@ def __init__(self, manager: GoogleADKWorkflowManager, conversation: SessionRef) self.conversation = conversation def start(self, agent: str, call_id: str, request: str, *, at: int, - parent: RunRef | None = None, brief: dict[str, str] | None = None) -> RunRef: + parent: RunRef | None = None, brief: dict[str, str] | None = None, + tools: list[str] | None = None, model: str | None = None) -> RunRef: ref = self.manager.agent_runs.run_for(self.conversation, parent, call_id, agent) title = request.splitlines()[0] self._observe(WorkflowEvent.agent_run( - ref, "started", title=title, call_id=call_id, brief=brief, + ref, "started", title=title, call_id=call_id, brief=brief, tools=tools, model=model, ), at) return ref @@ -250,6 +251,24 @@ async def test_an_instance_its_parent_title_run_result_and_tokens_by_model(self, ("", f"{HAIKU}: 100 in / 10 out · 1 call"), ] + @pytest.mark.parametrize("tools, model, shown", [ + (["lookup", "fetch_page"], "fast", [("Model", "fast"), ("Tools", "lookup, fetch_page")]), + ([], None, [("Tools", "none of its own")]), + (None, HAIKU, [("Model", HAIKU)]), + ]) + async def test_an_instances_model_choice_and_narrowed_tools_after_its_title( + self, manager, tools, model, shown + ): + runs = Runs(manager, manager.session_ref("s1")) + ref = runs.start("researcher", "c1", "Find X.", at=0, tools=tools, model=model) + runs.end(ref, "completed", at=5, result="X is 42.") + + session = await agents(manager, "researcher-1") + + (panel,) = session.add_rich.call_args.args + assert rows_of(panel.renderable)[:3 + len(shown)] == [ + ("Type", "researcher"), ("Parent", "root"), ("Title", "Find X."), *shown, + ] async def test_a_runs_own_plan_and_tasks_after_its_result(self, manager): runs = Runs(manager, manager.session_ref("s1")) ref = runs.start("researcher", "c1", "Find X.", at=0) From f0c5d0db955e4dd528c67016ece0ef5edfe087c4 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:43:15 -0500 Subject: [PATCH 09/11] Sub-agents: document model choices and a delegation's tools and model The CHANGELOG adds AgentConfig.model_choices and task's tools and model, and says task keeps its schema with the default policy but for the tools argument. The README's AgentConfig and YAML tables, graph checks and sub-agent section, and CLAUDE.md's structure lines and sub-agent paragraph, say the same. --- CHANGELOG.md | 55 +++++++++++++++++++++++++++++++++++++++++++++++++--- CLAUDE.md | 30 ++++++++++++++-------------- README.md | 27 +++++++++++++++++++++++++- 3 files changed, 93 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bde3e9bd..fba21bac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -575,6 +575,53 @@ the start of the entry's title. ### Added +- **`AgentConfig.model_choices`: the models a delegation may run a type on + instead of its own, on both backends.** References, bare model ids or + roles (`model_choices=("fast",)`; the agent YAML's `model_choices: + [fast]`; empty by default), each resolved with the type's + `model_settings` when the manager initializes, all or nothing with the + agents' models (`validate_settings` parses them and checks their + providers' keys first; a built-in role no setting maps, such as `fast`, + is computed from the model list, its provider listed at startup), and + given its own context numbers: a window too small to work in fails + startup (`ContextBudgetError`), as a type's own model does. Each choice + is its type built once more at initialization, on that model: on ADK an + agent and a runner of its own, whose plugin chain reads the choice's + model, provider kind and context numbers under the type's name, so the + fit guard and the overflow handler keep a run within them; on Deep + Agents a graph of its own, summarized by the choice's numbers. A model + switch builds them again, and the release closes them with the type's. A + run on a choice keeps its type's name in its events and records; its + usage is the choice's model's (`RunRecord.usage`, the ledger's + `by_model`, the raw LLM log). The manager gives each choice's model and + numbers: `choice_models[(agent, choice)]` and `context_budget(agent, + model=choice)`. `validate_agent_graph` raises `AgentGraphError` for + `model_choices` on the root, for one that is no tuple or list of texts, + and for a choice named twice. +- **`task`'s `tools` and `model`: a delegation may narrow its run's tools and + pick a cheaper model, never widen, on both backends.** Every `task` call + may give `tools`, some of the type's own tools (its registered, skill and + MCP tools, by the names its model is offered them; the plan's tools and + the delegation tools are always kept): the run's model is offered only + those, and a call of any other is answered as one of a tool the agent + does not have (" failed: ValueError: Tool '' not found.", then + the tools it has), and the run goes on. A call to a type with model + choices may give `model`, one of them: the run is on that model. Anything + else is the call's error result, and no run starts nor counts toward the + turn's ("The tools for 'researcher' must be some of its own: lookup.", + "The model for 'researcher' must be one of its model choices: fast.", + "'researcher' has no model choices; leave model out."). `task`'s schema + always has `tools` (with the default policy it is otherwise as it was), + and `model` when a type it offers has choices, which its line names + (`- researcher (model choices: fast): …`). The instance keeps them + (`InstanceRecord.tools`, `.model`, in the records beside the + conversation; records written before them read as all the tools and the + type's own model): its follow-ups, the user's and after a restart, run + with them, and one whose type no longer has them is refused + ("researcher-1 was started with the model fast, which 'researcher' no + longer has; start a new one with task."). `/agents ` shows `Model` + and `Tools`, and the instance's view its model and its context against + the choice's numbers (the status bar's `ctx`, `/status`). - **Agent types started at run time: `AgentConfig.spawnable_by`, free types and `SubAgentPolicy.spawn_sources`, on both backends.** A type may be started while the app runs, besides by its parent in the configured tree, @@ -582,8 +629,8 @@ the start of the entry's title. `"skill"`, `"user"`; the agent YAML's `spawnable_by: [agent]`; None, the default, for a type only its parent starts) and the policy's `spawn_sources` (the same three, `frozenset()` by default: nothing is - started at run time, and an app keeps its `task` as it was, byte for - byte). An agent's `task` call is the `"agent"` source: `task` lists, after + started at run time, and an app keeps its `task` as it was, but for the + `tools` argument every call has: see **`task`'s `tools` and `model`…**). An agent's `task` call is the `"agent"` source: `task` lists, after the caller's own sub-agents, the types agents may start, each with its description (`agentic_cli.workflow.agents.spawn`, provisional: `spawnable`, `may_spawn`, `can_have_children`; the manager's delegations' @@ -1953,7 +2000,9 @@ the start of the entry's title. may start (its own sub-agents first), each listed in the tool's description with what it does and the brief fields it requires, then the brief, `title` and `objective` (required), - `deliverable`, `constraints`, `known` and `done_when`. The run's first + `deliverable`, `constraints`, `known` and `done_when`, then `tools` (and, for + a type with model choices, `model`: see Added: **`task`'s `tools` and + `model`…**). The run's first message is the task message, `# Task: ` and a section per filled field (`## Objective`, `## Deliverable`, `## Constraints`, `## What is already known`, `## Done when`). A call whose brief misses a field its diff --git a/CLAUDE.md b/CLAUDE.md index 26d5fc0a..9400f507 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,9 +36,9 @@ agentic-cli/ │ │ ├── conversation.py # ConversationCore: the conversation the turns run in (its id, turned, its lock at its Place: the backend and store, the store the run's for its whole life (Place.kept: not the memory store, where the CLI keeps one conversation at a time and NOT_KEPT says why nothing else opens), the backend recorded as the app starts, for a new conversation on another backend, and on a /settings change of the orchestrator while the workflow is down, its next start builds afresh and nothing of the conversation is stored (SettingsUI._move_here, WorkflowController.next_start_builds), never read from the settings in between; deferred: an id this run made (the start's, /new's, an orchestrator change's) is in no store, so it is held from its first write, hold_to_write under the turn lock before a turn, a job's notice or /compact (_held_to_write; a run in which no turn runs makes no lock file: a line typed while the workflow is down takes the hold before its retried start; a lock that cannot be taken, an OSError, leaves it unheld, said once, and the write goes on); fresh: nothing of it stored, opened_empty (an id this run made, or one a load found empty) and not written (no turn of it ran on a ready workflow), the one condition for another backend); switch: the one protocol (/new on any backend, /resume, startup, the same id in another place while the workflow is down): the target's lock taken (another process's refused), memories proposed, the workflow loads it (a stored one gone: not made, or, made already in another place, opened empty: gone), then made at once (lock, id, task list, usage counters) or let go, a workflow that took it given the old one back; made before the load when there is no other conversation to stay in (the same id, or another place: a new or stored conversation on another backend); a Ctrl+C at any await leaves one conversation held; switch_now: the deprecated session_id setter's part; turn_lock: what writes to the conversation and every switch take it; run_turn, compact and run_job_resume: a turn (echoed, held to write, turned, written once it reached a ready workflow; run_turn says whether it ran, whatever the processor returns), /compact and a finished job's notice under it, on TurnParts (the app's parts as they are); run_instance and tell_root (_write): a line typed in a sub-agent's view as its next run (process_instance; written, not turned) and the main agent's notice after a view (process_notice; turned), under it too; deliver_finished_jobs: each job that waits here (cli/waiting_jobs.py's rule, which waiting_jobs names them by, the other backends' look through TurnParts.kept_elsewhere), every JobManager call on a worker thread, a delivery claimed only once it can reach the agent (process_resume(claim=), after the readiness check and can_resume; _claim_delivery: a claim a Ctrl+C stopped is handed back, JobManager.release_resume), a failure before the claim said once per job and conversation when the CLI tells jobs on its own (telling_on_its_own); to_drop/drop_left: the conversations /new left on the memory store that the store may still hold (the workflow down, a lookup or delete that raised), dropped through TurnParts.drop under the turn lock once a workflow is ready, before a turn, /compact or a delivery uses it (after a turn or /compact that started it), one try per point, done once the store has it no more (a workflow without supports_sessions has none), the open one skipped; a delivery with none to drop takes no turn lock │ │ ├── conversation_lock.py # ConversationLock: one process per stored conversation (flock under <sessions_dir>/locks/; ConversationCore holds it and refuses one held elsewhere; /sessions --delete too, through conversation_held) │ │ ├── builtin_commands.py # /help (by category; /help <command>: its usage and examples), /status (the main agent's context rows: context_budget, in a sub-agent's view the instance's, AgentView.context_rows; why the workflow did not start: app.workflow_error; tokens by agent: the main agent, each sub-agent with its runs, the side calls by purpose, from the manager's usage ledger), /models (ModelsCommand: the list, each model's facts and sources, Status for an entry left out, the providers in use; /models <text> searches the full listings; refresh), /sessions (every installed backend's, a Backend column; --delete=<id> on the backend that keeps it, --backend=<name> for an id two keep; on the memory store NOT_KEPT, no table, --delete refused), /resume [<id>] (sessions; refused on the memory store), /jobs (resume: finished jobs; in a sub-agent's view JOBS_WAIT: they wait for /back), /compact [focus] (refused in a sub-agent's view: COMPACT_IN_VIEW), /new [backend] (an unknown backend or a missing extra refused: check_backend), ... -│ │ ├── agents_command.py # /agents: the open conversation's sub-agent instances (agent_runs.instances under workflow.session_ref(app.session_id)) in a picker (a Dialog with one ChoiceField, as /resume's: `picker`), each followed by the ones it started (id · type · status · title), Enter opening the view of the one picked (app.open_agent_view); /agent <id> opens its view (open_agent_view: cli/agent_view.py), /agent stop <id> and /agent close <id> are the user's stop and close (stop_instance, close_instance, the app's conversation named), each saying what it did or why not (NO_SUCH_AGENT, ALREADY_TEXT), nothing tried on records not read; /agents <id> (its panel: tokens in/out from the usage ledger, usage_of, live for a running run; time): one instance (every run of it) or run (type, parent, title; each run's status and time, its brief's other fields (a follow-up's message in their place), its result's first lines, its own last plan and tasks, its error, its tokens by model); the records are the conversation's, kept beside it in its store and loaded with it (`workflow.load_agents`, asked by /agents too: a conversation resumed after a restart lists its runs before its first turn; a store that cannot be read is said, and the runs held shown), a run from before a restart showing its record's tokens by model (its usage, no call count); a module of its own, as /memory's +│ │ ├── agents_command.py # /agents: the open conversation's sub-agent instances (agent_runs.instances under workflow.session_ref(app.session_id)) in a picker (a Dialog with one ChoiceField, as /resume's: `picker`), each followed by the ones it started (id · type · status · title), Enter opening the view of the one picked (app.open_agent_view); /agent <id> opens its view (open_agent_view: cli/agent_view.py), /agent stop <id> and /agent close <id> are the user's stop and close (stop_instance, close_instance, the app's conversation named), each saying what it did or why not (NO_SUCH_AGENT, ALREADY_TEXT), nothing tried on records not read; /agents <id> (its panel: tokens in/out from the usage ledger, usage_of, live for a running run; time): one instance (every run of it) or run (type, parent, title, the instance's Model and Tools when its delegation gave them, NO_OWN_TOOLS for none; each run's status and time, its brief's other fields (a follow-up's message in their place), its result's first lines, its own last plan and tasks, its error, its tokens by model); the records are the conversation's, kept beside it in its store and loaded with it (`workflow.load_agents`, asked by /agents too: a conversation resumed after a restart lists its runs before its first turn; a store that cannot be read is said, and the runs held shown), a run from before a restart showing its record's tokens by model (its usage, no call count); a module of its own, as /memory's │ │ ├── dialogs.py # One dialog at a time on a session: serialize_dialogs (BaseCLIApp.session's setter wraps a real session's six dialog methods, whoever calls them: the framework's commands, an app's own, a question's dialog) and dialog_lock(ui) (the message processor holds it around a question's dialog; a task may take it again) make a sub-agent view's run (outside the input handler) asking while a command's dialog is open, or the reverse, wait instead of raising (thinking-prompt raises on a second dialog: a permission prompt would be a denial the user never saw); a stand-in whose methods are mocks is left as it is -│ │ ├── agent_view.py # A sub-agent's view (provisional; open_view/leave_view behind BaseCLIApp.open_agent_view/leave_agent_view, /back: BackCommand): entering prints VIEW_RULE ("── researcher-2 · researcher · idle ──") and a recap (title, its first brief's objective, its last run's status, its result's first lines, its tokens: instance_tokens, each run's from the usage ledger or its record), the prompt "<id>> " (none for a closed one: read-only, READ_ONLY) and WorkflowController.view_segment (its status, its ctx: its last own step's prompt against its own trigger, its tokens); AgentView.take: a line steers the run that works (steer_instance, STEERED) or starts the instance's next run in a task of its own (ConversationCore.run_instance on the view's own MessageProcessor), outside the input handler, so the prompt takes the lines that steer it (thinking-prompt takes none while a handler runs); bind_ctrl_c: Ctrl+C stops that run (AgentView.stop: the user's stop) through a prompt_toolkit binding on the session's application, active only while it works; AgentView.interrupt (at exit): the manager's interrupt_instance, then the view's tasks cancelled; a line typed before the run ends waits for it inside the view (a stop says the cancel once), and one typed while the workflow is down is the next run all the same (its start retries); leave_view (/back): waits for the run, retries a workflow that is down, BACK_RULE, the prompt and bar back, then one notice turn (ConversationCore.tell_root, view_notice, TELLING) when a run the user started there ended since the main agent last heard, then the finished jobs that waited (job_auto_resume); in a view /compact is refused (COMPACT_IN_VIEW), /jobs resume waits (JOBS_WAIT), /status shows its context_rows, /new and /resume leave it first +│ │ ├── agent_view.py # A sub-agent's view (provisional; open_view/leave_view behind BaseCLIApp.open_agent_view/leave_agent_view, /back: BackCommand): entering prints VIEW_RULE ("── researcher-2 · researcher · idle ──") and a recap (title, its first brief's objective, its last run's status, its result's first lines, its tokens: instance_tokens, each run's from the usage ledger or its record), the prompt "<id>> " (none for a closed one: read-only, READ_ONLY) and WorkflowController.view_segment (its status, its ctx: its last own step's prompt against its own trigger, its model choice's for an instance on one, its tokens); AgentView.take: a line steers the run that works (steer_instance, STEERED) or starts the instance's next run in a task of its own (ConversationCore.run_instance on the view's own MessageProcessor), outside the input handler, so the prompt takes the lines that steer it (thinking-prompt takes none while a handler runs); bind_ctrl_c: Ctrl+C stops that run (AgentView.stop: the user's stop) through a prompt_toolkit binding on the session's application, active only while it works; AgentView.interrupt (at exit): the manager's interrupt_instance, then the view's tasks cancelled; a line typed before the run ends waits for it inside the view (a stop says the cancel once), and one typed while the workflow is down is the next run all the same (its start retries); leave_view (/back): waits for the run, retries a workflow that is down, BACK_RULE, the prompt and bar back, then one notice turn (ConversationCore.tell_root, view_notice, TELLING) when a run the user started there ended since the main agent last heard, then the finished jobs that waited (job_auto_resume); in a view /compact is refused (COMPACT_IN_VIEW), /jobs resume waits (JOBS_WAIT), /status shows its context_rows, /new and /resume leave it first │ │ ├── memory_command.py # /memory: the list (a picker like /resume's), one memory (Delete, History), /memory <id>, history (Restore), inbox (Accept/Discard/Skip), stale; proposals_line; Enter's button is Close or Skip, and Delete acts only on the memory as shown │ │ ├── workflow_controller.py # WorkflowController (lazy/background init; subagents=: the SubAgentPolicy every manager it builds gets, a switch_backend's too; the session store of every manager of the run, store, fixed at its first start; the backend it runs, backend: the settings' orchestrator at its first start, then switch_backend's (a conversation on another backend, new or opened: the new manager started first on the run's services lent, given over by the old one and published at once, the old one released in the controller's task, a cancel stops only the wait; a failed start or give leaves the old one with its services; while down, a manager a failed reinitialization kept lends its services to the next build, _lender, and is released once they are given); reinitialize, a model switch, always in place; the status bar names the main agent's model, or in a sub-agent's view what view_segment says of the instance, the jobs segment kept) │ │ ├── session_resume.py # What /resume shows: the picker (picker: each row's backend once one is another's; PickedConversation, the id a str naming its backend), the "Resumed:" line ("Resumed on <backend>:" on another backend), the replay of the last 10 messages @@ -51,25 +51,25 @@ agentic-cli/ │ │ ├── waiting_jobs.py # Which finished jobs wait to be told in the open conversation: one rule (JobRecord.awaiting_resume, then its own, no conversation's, or a gone conversation's: can_resume, then the other installed backends' readers, opens_anywhere: one another backend keeps is not gone, its job waits for it) for the deliveries, ↻N and the startup line │ │ └── usage_tracker.py # Token usage / status bar: ctx = the main agent's last prompt over its context_trigger (a call with a purpose, a sub-agent's, a summary's or a side call's, never moves it); the token segment the open conversation's total, every call of its turns; format_usage: /status's rows by agent and /agents <id>'s tokens by model │ ├── workflow/ -│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none); the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built: each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) +│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none), and _agent_tool_names, what a task call's tools may name (the agent's own tools by the names its model sees, KEPT_TOOLS left out; the base's: its configured tools; ADK and Deep Agents add MCP and skill tools); _run_models: a run's maps of each agent's model and numbers, its type's its model choice's when it runs on one; the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', each config's model_choices as its model would be, with its model_settings, into _choice_models by (agent, choice), choice_models, then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built, and _compute_choice_budgets (each model choice's, context_budget(agent, model=choice)): each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) │ │ ├── factory.py # create_workflow_manager_from_settings (_BACKENDS: orchestrator → "module:Class" + extra, imported when chosen; orchestrator=: another backend than the settings'; session_store=: the store a manager is built for, BaseWorkflowManager.session_store, the settings' by default; subagents=: the SubAgentPolicy the manager gets, checked before a backend is imported); orchestrator_of; check_backend (an unknown name, a missing extra) │ │ ├── session_readers.py # SessionReader: a backend's stored conversations read without its manager (list/info/exists/delete/aclose, rows naming the backend; delete deletes what the manager's does, ADK's sub-agent transcripts and records with the conversation), opened from the settings and a store (open_session_reader: the backend's own session code, adk/sessions.py::open_sessions and deepagents/sessions.py::open_sessions, imported on a worker thread; no agents, models or services; a sqlite store not made yet reads empty and is not made, Deep Agents not even imported for it; a database without its backend's tables, looked at read-only, reads empty, nothing written to it: no table, no journal mode); none for the memory store or LangGraph; ImportError (the install hint) for a missing extra; reader_backends │ │ ├── service_registry.py # get_service/require_service + ContextVar registry; the registry keys and KNOWN_SERVICE_KEYS, read from services.py's table │ │ ├── services.py # The services a manager builds: SERVICES, one ServiceSpec each (key, build, close, tools, declarable, always, built_with, rebind; builders import lazily); ServiceSet: one manager's (build_into, publish, carried, release, tool_map, not_owned: borrowed or given away, never closed there); ServiceLoan: a hand-over between managers (rebind: the engine's workflow/per_call, the KB's summarizer) │ │ ├── memory_index.py # MemoryIndex: the memory index the root's requests carry, one snapshot per conversation (now: taken once, off the event loop; cached: never reading; forget: /resume, a summary and /compact; clear: the release; cap: memory_index_max_bytes, or a tenth of the root's budget: MEMORY_INDEX_BUDGET_SHARE, MEMORY_INDEX_MIN_BYTES); reads the manager's settings, memory store, the root's memory tools (_root_memory_tools) and its room live, through callables, and takes a snapshot at the manager's _memory_index_cap (limit=), so a subclass's cap is the one asked; imports no backend │ │ ├── outside_content.py # OutsideContentMarks (per conversation, first tool wins), brings_outside_content, the note -│ │ ├── events.py # WorkflowEvent, EventType; WorkflowEvent.turn_failed: a failed turn's one ERROR (rate_limited, error_type); WorkflowEvent.run: the agent run that wrote it (RunRef; None: the manager's own); AGENT_RUN (WorkflowEvent.agent_run): a sub-agent run's start (brief=, started_by=, mode=; a first run's inherit_context=, continuable=; a follow-up's input=), how it works meanwhile (queued, running, input_required) and end (an end with what the run used, by model: usage=; cancelled_by= for a cancelled run; instance_status=: the status it leaves its instance in); AGENT_INSTANCE (WorkflowEvent.agent_instance): an instance's status changing without a run (a close); UserInputRequest.run: the sub-agent run that asks (request_user_input fills it from get_active_run()) +│ │ ├── events.py # WorkflowEvent, EventType; WorkflowEvent.turn_failed: a failed turn's one ERROR (rate_limited, error_type); WorkflowEvent.run: the agent run that wrote it (RunRef; None: the manager's own); AGENT_RUN (WorkflowEvent.agent_run): a sub-agent run's start (brief=, started_by=, mode=; a first run's inherit_context=, continuable=, and the tools=, model= its delegation gave it; a follow-up's input=), how it works meanwhile (queued, running, input_required) and end (an end with what the run used, by model: usage=; cancelled_by= for a cancelled run; instance_status=: the status it leaves its instance in); AGENT_INSTANCE (WorkflowEvent.agent_instance): an instance's status changing without a run (a close); UserInputRequest.run: the sub-agent run that asks (request_user_input fills it from get_active_run()) │ │ ├── live_events.py # LiveEvents, merged: events reported inside a turn (reporting/report) reach its stream as they happen; on_stop: a consumer that stops early, before the source is cancelled; emit gives an event that names no run the active one (get_active_run) │ │ ├── usage.py # Token usage: normalized_tokens, the one place a provider's report becomes the counts every LLM_USAGE carries (prompt_tokens every input token, cache included; completion_tokens every output token, thinking included): adk_tokens (ADK's, by provider kind: Gemini's and ADK's Claude adapter's thinking apart from the candidates, OpenAI's inside; an unknown kind's apart), adk_usage_event (the one place ADK's usage becomes an LLM_USAGE: the event processor, the summarizer, generate_simple, the raw log), langchain_tokens (every partner package's, langchain-openai's priority and flex tiers' parts too), llm_usage_event; PURPOSE_* (none: the root's step; subagent, summarization, tool, memory_extraction, side_call) and side_call (what a caller's side calls are for); UsageLedger (a conversation's calls, a row each, each with its latency_ms: totals by run, agent, model, purpose and turn; a row's turn its conversation's while a turn of it runs, as the manager counts them, None in another conversation's turn or a task its turn outlived; by_agent, by_purpose, by_model, run_usage), UsageLedgers (a manager's, by conversation, filed under the turn a call is made in; for the manager's life: a backend switch's new manager starts afresh, a run's totals by model kept with its record; forget: a deleted conversation's) │ │ ├── interrupts.py # What a call a cancel or a crash left open is answered with; OpenCalls (each manager's record, kept by conversation: only that conversation's turns clear it; within it by the instance whose run made each call, run=, the active run by default, so an instance's next run reads what an earlier one recorded; cancelled/take_cancel with instance=: a stopped run of an instance, whose calls a conversation's clear keeps until its next run takes the stop); forget(ref): everything of a deleted conversation, a failed turn's calls and every stop with its cause; unrecorded: a call no record holds; job_for_call: a job of the turn's conversation and of the run whose call it answers (started_by) only; fresh_call_id: the id a call whose provider reused one gets (the old one and a short suffix, `[A-Za-z0-9_-]`, at most 40 characters); `cancelled(cause=)`/`answer(cause=)`: what a call left at its prompt, or running, in a sub-agent run stopped by its parent or a limit is told stopped it (`not_run(cause)`: `Not run: its parent stopped the run before this call ran.`, `its time limit`, `its token limit`; `interrupted_by(cause)`, `INTERRUPTED_BY`: `Interrupted: its parent stopped the run before this call finished; …`), kept with the instance's stop until its next run takes it -│ │ ├── config.py # AgentConfig (brief_required: the brief fields it asks a delegation to fill; limits: its own AgentLimits, over the policy's; continuable: False makes a type one-shot, closed when its run ends; spawnable_by: who may start it at run time, of SPAWN_SOURCES), AgentGraph (free_types: spawnable_by set, in no sub_agents list, never the root), validate_agent_graph (policy=: the managers pass theirs; rules 1-14, the first failure the most fundamental; 7: one root among the agents that are not free types, spawnable_by checked first, the root setting none; 11-14: brief_required names brief fields, limits is an AgentLimits, continuable is True or False, the root sets none of the three; a free type no enabled source can start warned of, subagent_type_unreachable) -│ │ ├── agent_loader.py # load_agents_from_yaml: the framework's agent YAML → AgentConfig (unknown keys refused; brief_required, continuable, limits: {max_model_calls, timeout, max_tokens} read strictly, AgentLimits checking them; spawnable_by: a list, read as a frozenset); create_workflow_manager_from_yaml +│ │ ├── config.py # AgentConfig (brief_required: the brief fields it asks a delegation to fill; limits: its own AgentLimits, over the policy's; continuable: False makes a type one-shot, closed when its run ends; spawnable_by: who may start it at run time, of SPAWN_SOURCES; model_choices: what a delegation may run it on instead of its model, checked by rule 15 and none on the root), AgentGraph (free_types: spawnable_by set, in no sub_agents list, never the root), validate_agent_graph (policy=: the managers pass theirs; rules 1-15, the first failure the most fundamental; 7: one root among the agents that are not free types, spawnable_by checked first, the root setting none; 11-14: brief_required names brief fields, limits is an AgentLimits, continuable is True or False, the root sets none of the three; a free type no enabled source can start warned of, subagent_type_unreachable) +│ │ ├── agent_loader.py # load_agents_from_yaml: the framework's agent YAML → AgentConfig (unknown keys refused; model_choices a list read as a tuple; brief_required, continuable, limits: {max_model_calls, timeout, max_tokens} read strictly, AgentLimits checking them; spawnable_by: a list, read as a frozenset); create_workflow_manager_from_yaml │ │ ├── settings.py # Workflow/tool settings schema; models, model_providers, model_roles and permissions in Annotated form (an app's override warns nothing); _merge_shipped_entries: the app's models and model_providers, then the sources', field by field, and the app's permissions before the sources' (at load only); permissions: the union of every trusted source's rules, each list concatenated, a duplicate once (_source_sections reads each source's value as the sources hook filed it) │ │ ├── context.py # ContextBudget/context_budget: when to summarize (window or the 128k floor, budget, trigger, keep; both backends, the CLI); FailedSummaries: a range whose summary failed is skipped for the rest of its turn (keyed by its live events, weakly) until it grows by MIN_SAVING of the trigger; SUMMARY_FAILED: the one warning a failed summary gives, on both backends; is_context_overflow, overflow_message, subagent_overflow_message (a sub-agent's overflow warning, both backends); prompt_room/cut_middle/MIN_PROMPT_ROOM: a side call's prompt in characters its model takes │ │ ├── retry.py # is_rate_limit_error: a provider's 429 told from other failures (a failed turn's ERROR says so: rate_limited, which the CLI reports); no retry logic, the provider clients retry (retry_max_attempts, retry_initial_delay) │ │ ├── tool_summaries.py # One-line summaries of tool results; delegation_summary: a delegation's result, the same on both backends (the answer's first line, Failed: <reason>) │ │ ├── memory_services.py # Settings → agentic_cli.memory arguments (KBs, memory store: the user scope and the project scope keyed by the cwd, project_key; a scope that cannot open never stops the app: the project scope is left out, else no store is published, memory_project_scope_unavailable / memory_store_unavailable); the project KB opened within=Path.cwd() -│ │ ├── model_services.py # Settings → agentic_cli.models arguments (keys, model_providers, entries, roles); a configured provider's key: the environment, then user_env_files (absolute env_file entries; provider_env); build_catalog (with model_references and computed_roles: the settings', the agents' and the manager's; reference_settings: where each is named, for the catalog's warnings); role_models (the roles' models the list offers, for the pickers and /models) +│ │ ├── model_services.py # Settings → agentic_cli.models arguments (keys, model_providers, entries, roles); a configured provider's key: the environment, then user_env_files (absolute env_file entries; provider_env); build_catalog (with model_references and computed_roles: the settings', the agents' (their model_choices too: a role choice is computed) and the manager's; reference_settings: where each is named, "agent 'x' model_choices" for a choice, for the catalog's warnings); role_models (the roles' models the list offers, for the pickers and /models) │ │ ├── model_wire.py # What both adapters send: timeouts, placeholder key, an openrouter-kind provider's headers, reasoning_body (by the provider's kind and the model's thinking) │ │ ├── langchain_models.py # build_chat_model: ResolvedModel → LangChain chat model (profile=); OpenAICompatibleChat │ │ ├── checkpointers.py # open_checkpointer (memory/sqlite/postgres) for the LangChain backends; open_store: the LangGraph store of the same kind beside it (sqlite: the same file, its own connection; a setup that lost a migration race to another process run again), Deep Agents' session index; deepagents_sqlite_path (deepagents_sqlite_location: where, without making it); private_sqlite_file: ADK's sessions.db and Deep Agents' checkpoints.db made owner-only before they open (an older one at the default location tightened, with the -journal/-wal/-shm beside it; an existing file sqlite_uri names left as it is) @@ -84,9 +84,9 @@ agentic-cli/ │ │ │ ├── capabilities.py # Capability, EXEMPT │ │ │ ├── matchers.py # PathMatcher, URLMatcher, ShellMatcher, StringGlobMatcher │ │ │ └── rules.py, store.py, prompt.py (build_request(run=): a sub-agent's prompt opens with its run; is_permission_request: by its perm- id) -│ │ ├── agents/ # Sub-agents: runs.py: the RUN_* statuses (a working run's: RUN_QUEUED, RUN_RUNNING, RUN_INPUT_REQUIRED, RUN_WORKING_STATUSES; a record says running from its start), INSTANCE_RUNNING/IDLE/STOPPED/CLOSED and INSTANCE_STATUSES, InstanceRecord (an instance: parent, depth, title, status, runs, continuable), RunRecord (input: a follow-up's message as written, "" for a first run), AgentRuns (a manager's runs and instances by conversation: run_for names <agent>-<n> and its first run #1 per (conversation, parent run, call id), a new one once it ended; next_run: an instance's next run; instances/instance, kept from the events: a start makes or reopens the instance running, an end sets its status from instance_status, AGENT_INSTANCE a change without a run; number_from: past the instances a conversation's store keeps, a count never lowered; observe records AGENT_RUN under the turn it is reported in; interrupt_open; a record's usage: what the run used, by model, from its end event or the ledger; its plan and tasks: the run's own last, from its end event; RECORDS_VERSION, export (a conversation's records as JSON-safe data: v, saved, numbered, instances, runs) and restore (replaces them; a run found working ends interrupted, INTERRUPTED_ERROR, at the later of its start and saved, its instance idle, closed for a type that is not continuable; each run's end order stored (end), any time or field that does not read ValueError; counters never below an instance kept; ValueError for another version or records that do not read, nothing changed), stored_instance_ids (the instances stored records name; None for none), AgentRuns(on_change=): told each change, never by restore), run_title, result_head, run_instance and run_number (the one reader of a run id: researcher-2#1's instance and number), run_label (how a dialog names a run: researcher-2 (researcher, run 1)), SUBAGENT_ERROR_PREFIX (ADK's old words for a failed delegation, kept for callers), show_as_delegation(result, envelope) (a delegation's TOOL_RESULT shown alike on both backends: the result's first line, or Failed: <error>; metadata["result"] the envelope); a record's brief, started_by, mode and cancelled_by; delegate.py: Delegations (delegate(DelegationRequest) → Delegated and follow_up(FollowUpRequest) → Delegated: the one place a run starts and ends, on both backends (a follow-up is the instance's next run through the same hook, AgentRun.follow_up: refused as an error result, no run, for an unknown or not-yours instance (NOT_YOURS_ERROR, YOURS, NO_SUB_AGENTS), a closed one (CLOSED_ERROR), one the user stopped when an agent sends it (STOPPED_ERROR), a running one (RUNNING_ERROR), one whose type the app no longer has (TYPE_GONE_ERROR) and a blank message (NO_MESSAGE_ERROR); an agent's counts toward max_runs_per_turn, the user's (started_by USER) does not; a run's end carries the status it leaves its instance in: stopped for the user's cancel, closed for a type that is not continuable or the oldest idle one past max_open, else idle; close(conversation, instance, reason=): an idle or stopped instance and its descendants, AGENT_INSTANCE closed; open_calls=: the manager's OpenCalls, whose stop recorded for an instance is taken when the instance is left closed (its end, close, max_open, or a turn that stops a one-shot run), so its calls are freed; max_open ranks by AgentRuns.end_order, the order ends were recorded in, never the clock): the brief read against what the calling run may start (offered(agent, depth): its own sub-agents, then, while may_spawn, the types agents may start at run time, an inheriting one for the root alone; task_offer: task's TaskOffer for that run, None for nothing), then start(StartRequest), the one entry for a first run (counted unless the user's, started_by as given; who may start the type is the asker's to check), the run named (a turn's first run past the instances its conversation's store keeps: stored=, asked once per conversation per turn, again after a failed or stopped ask), its AGENT_RUN start and end observed and reported, the backend's hook (RunHook: AgentRun → RunAnswer) run in a task of its own with the run active and no tool call, the end by the answer (completed, partial for a cut or the step limit, refused, failed for an error or a raise, with one recoverable ERROR <instance> failed: <reason>, or RunFailed's own words, its result the text the run wrote before it failed (RunFailed(text=); a failed model call the hook's RunAnswer.error, failure_reason, with error_code its type, the warning's code), cancelled by its control with what the hook had), interrupted on its turn's cancel, which wins; the envelope as the result; each run under its RunControl, the type's limits over the policy's, kept while it works: control(run), cancel(run_id, by=, error=), the run alone; a call past max_runs_per_turn the error result RUNS_PER_TURN_ERROR, no run; the stored instances asked under a lock per conversation; forget(conversation): a deleted one's slots, unread messages, waiting closes and asks; each run in a working slot of its conversation's SlotPool, slots(conversation): policy.max_active slots, made on first use and kept, the root taking none: taken right before its hook and its time limit, queued then running while it waits for one, given back at its end, straight back to a caller that waits on it alone; a caller that delegates lends its slot while it waits for its children), DelegationRequest, StartRequest, FollowUpRequest, AgentRun (control, follow_up), RunAnswer, RunFailed, started_by, waiting_on_user (a sub-agent run waiting on the user: input_required, its slot lent, queued while its take-back waits for a slot, then running; nested waits once; request_user_input and the permission engine); records.py: RecordsWriter (each conversation's records written to its store as they change: changed, one write at a time per conversation taking the records as it starts, so changes made meanwhile go together in the next; flush, flush_all, discard (a delete's: what waits dropped, the write under way waited for); a failed write warned once per conversation, subagent_records_not_saved, never raised); slots.py: SlotPool (acquire(priority): a free slot, else a future in a heap by priority, RETURNING before NEW, then arrival; release; lent(slot, on_wait=): the slot lent while its run waits, nested lends once, taken back at RETURNING after (on_wait called when that has to wait), at most one take-back waiting for a slot and none once it is held (a wait that starts while one is queued takes it over, and one handed the slot withdraws any queued since), nothing taken back after a cancel, so a tool's caught timeout around a question leaves its run working without a slot, input_required until its next question is answered (running again, still without a slot) or its end; hand_back(slot, to): a child's slot to its parent waiting on it alone; free, waiting; a cancelled waiter leaves the heap, one handed a slot as it is cancelled hands it on; not asyncio.Semaphore), Slot (held, lent), RETURNING, NEW; control.py: RunControl (one run's: cancel(by=, error=) its task, the first cancel winning, own_cancel for the hook that takes it and returns, finish: the hook's work ended, no cancel after it (ADK's state read loses no answer), timing: the time limit while the hook runs; model_call/at_step_limit/final_call: the step limit, STEP_LIMIT_NOTE on the last allowed call; used: the token limit, against its own calls and side_tokens (its side calls and summaries, from the ledger), an answer past it that makes calls the run's last, cancelled by it, one that makes none its result (calls=); model_call once final stays final; a cancel leaves a task its turn is cancelling alone; steer/take_steering), STEP_LIMIT_NOTE; outcome.py: a sub-agent's refused or cut answer (outcome_of, the refusal notice as Deep Agents 0.7.34 words it, cut_off, cut_off_warning, OPENAI_REFUSAL_PREFIX: how ADK's OpenAI adapters word a refusal); policy.py: SubAgentPolicy (max_active, max_runs_per_turn, limits, max_open, follow_ups, spawn_sources: of SPAWN_SOURCES, kept as a frozenset, max_spawn_depth) and AgentLimits (max_model_calls, timeout, max_tokens; over: a type's limits over the policy's, field by field, None taking the base's), DEFAULT_LIMITS (100 model calls), frozen and checked as they are made (a ValueError naming the field), as_policy (the one reading of a subagents= argument: a TypeError for anything but a policy or None); brief.py: BRIEF_FIELDS, Brief, BriefError, read_brief (a task call's agent type and brief, against the types its caller may start: the error texts), task_message (a run's first message, a section per filled field; an inheriting type's ends with INHERITED_CONTEXT_NOTE), task_parameters and task_description (task's schema and description, the same for both backends; limit_sentences: the limits it states, "At most <max_active> sub-agents work at once; more calls in one response wait for a free slot. At most <max_runs_per_turn> runs per turn.", then DEPTH_SENTENCE, "Sub-agents cannot start sub-agents.", when no run the call starts may start one; warn=False for a description made per run), TaskOffer and task_offer (both, for the types one run may start); envelope.py: envelope (a delegation run's result: success only for completed, a one-line error, cancelled_by for a cancelled run), read_envelope (a dict or its JSON text, else None; never raises), view_notice (`VIEW_NOTICE`: what the root is told once the user worked with an instance), the limit and interrupted error texts; `Delegations.message` (an idle instance's follow-up; a running one's run steered, or with `interrupt` cancelled by its parent and followed up; one run per instance, so of two messages to one idle instance in one answer the first runs and the second is steered into it), `stop` (a running instance's run cancelled by its parent, the instance idle; `close` closes it and its descendants, a running one's at its run's end), `check`, `steer(conversation, run, message)`, `stop_by_user`/`close_by_user` (`STOPPED_BY_USER_ERROR`, `CLOSED_BY_USER`: a running run cancelled by the user and waited for), `stop_cause(run)` and `cancel(..., conversation=)`; a message steered to a run that its transcript does not hold when it ends (`RunControl.unstored`) is kept for the instance's next run; a run whose parent's run its control stopped ends `cancelled` by its parent (`its parent's run was stopped`); a run that did not complete fully names its open tasks in its envelope (`envelope(open_tasks=)`, `open_task_descriptions`) and a cancelled run keeps its plan and tasks; `SubAgentPolicy.follow_ups`; brief.py: `follow_up_description`/`follow_up_parameters` (the parent's tools' texts); follow_ups.py: `call_follow_up_tool` (a message_agent, stop_agent or check_agents call as the run in progress); spawn.py: spawnable (the types a source may start at run time: the policy's spawn_sources and the type's spawnable_by), may_spawn (depth below max_spawn_depth), can_have_children (who is built with task, and with follow_ups the parent's tools and the roster: sub-agents, or a type agents may start while the root or runs below it may), depth_sentence_applies, AGENT_SOURCE/SKILL_SOURCE/USER_SOURCE; no backend imports; roster.py: roster_text (the main agent's open sub-agents, newest first, one line each, ROSTER_OPEN/ROSTER_HEADER/ROSTER_CLOSE, at most ROSTER_MAX characters in whole lines, "" for none open), Rosters (a snapshot per conversation, as MemoryIndex: now, forget, clear; the root's own instances, parent root) +│ │ ├── agents/ # Sub-agents: runs.py: the RUN_* statuses (a working run's: RUN_QUEUED, RUN_RUNNING, RUN_INPUT_REQUIRED, RUN_WORKING_STATUSES; a record says running from its start), INSTANCE_RUNNING/IDLE/STOPPED/CLOSED and INSTANCE_STATUSES, InstanceRecord (an instance: parent, depth, title, status, runs, continuable, and the tools and model its first run's start gave it, read as None from records without them), RunRecord (input: a follow-up's message as written, "" for a first run), AgentRuns (a manager's runs and instances by conversation: run_for names <agent>-<n> and its first run #1 per (conversation, parent run, call id), a new one once it ended; next_run: an instance's next run; instances/instance, kept from the events: a start makes or reopens the instance running, an end sets its status from instance_status, AGENT_INSTANCE a change without a run; number_from: past the instances a conversation's store keeps, a count never lowered; observe records AGENT_RUN under the turn it is reported in; interrupt_open; a record's usage: what the run used, by model, from its end event or the ledger; its plan and tasks: the run's own last, from its end event; RECORDS_VERSION, export (a conversation's records as JSON-safe data: v, saved, numbered, instances, runs) and restore (replaces them; a run found working ends interrupted, INTERRUPTED_ERROR, at the later of its start and saved, its instance idle, closed for a type that is not continuable; each run's end order stored (end), any time or field that does not read ValueError; counters never below an instance kept; ValueError for another version or records that do not read, nothing changed), stored_instance_ids (the instances stored records name; None for none), AgentRuns(on_change=): told each change, never by restore), run_title, result_head, run_instance and run_number (the one reader of a run id: researcher-2#1's instance and number), run_label (how a dialog names a run: researcher-2 (researcher, run 1)), SUBAGENT_ERROR_PREFIX (ADK's old words for a failed delegation, kept for callers), show_as_delegation(result, envelope) (a delegation's TOOL_RESULT shown alike on both backends: the result's first line, or Failed: <error>; metadata["result"] the envelope); a record's brief, started_by, mode and cancelled_by; delegate.py: Delegations (delegate(DelegationRequest) → Delegated and follow_up(FollowUpRequest) → Delegated: the one place a run starts and ends, on both backends (a follow-up is the instance's next run through the same hook, AgentRun.follow_up: refused as an error result, no run, for an unknown or not-yours instance (NOT_YOURS_ERROR, YOURS, NO_SUB_AGENTS), a closed one (CLOSED_ERROR), one the user stopped when an agent sends it (STOPPED_ERROR), a running one (RUNNING_ERROR), one whose type the app no longer has (TYPE_GONE_ERROR) and a blank message (NO_MESSAGE_ERROR); an agent's counts toward max_runs_per_turn, the user's (started_by USER) does not; a run's end carries the status it leaves its instance in: stopped for the user's cancel, closed for a type that is not continuable or the oldest idle one past max_open, else idle; close(conversation, instance, reason=): an idle or stopped instance and its descendants, AGENT_INSTANCE closed; open_calls=: the manager's OpenCalls, whose stop recorded for an instance is taken when the instance is left closed (its end, close, max_open, or a turn that stops a one-shot run), so its calls are freed; max_open ranks by AgentRuns.end_order, the order ends were recorded in, never the clock): the brief read against what the calling run may start (offered(agent, depth): its own sub-agents, then, while may_spawn, the types agents may start at run time, an inheriting one for the root alone; task_offer: task's TaskOffer for that run, None for nothing), its tools and model against the type's own (read_choices, tool_names= asked only for a call naming tools), then start(StartRequest, its tools= and model= carried to AgentRun.tools/.model and RunControl.tools, and said by its start: every run of the instance keeps them, a follow-up one whose type lost them refused, CHOICE_GONE_ERROR), the one entry for a first run (counted unless the user's, started_by as given; who may start the type is the asker's to check), the run named (a turn's first run past the instances its conversation's store keeps: stored=, asked once per conversation per turn, again after a failed or stopped ask), its AGENT_RUN start and end observed and reported, the backend's hook (RunHook: AgentRun → RunAnswer) run in a task of its own with the run active and no tool call, the end by the answer (completed, partial for a cut or the step limit, refused, failed for an error or a raise, with one recoverable ERROR <instance> failed: <reason>, or RunFailed's own words, its result the text the run wrote before it failed (RunFailed(text=); a failed model call the hook's RunAnswer.error, failure_reason, with error_code its type, the warning's code), cancelled by its control with what the hook had), interrupted on its turn's cancel, which wins; the envelope as the result; each run under its RunControl, the type's limits over the policy's, kept while it works: control(run), cancel(run_id, by=, error=), the run alone; a call past max_runs_per_turn the error result RUNS_PER_TURN_ERROR, no run; the stored instances asked under a lock per conversation; forget(conversation): a deleted one's slots, unread messages, waiting closes and asks; each run in a working slot of its conversation's SlotPool, slots(conversation): policy.max_active slots, made on first use and kept, the root taking none: taken right before its hook and its time limit, queued then running while it waits for one, given back at its end, straight back to a caller that waits on it alone; a caller that delegates lends its slot while it waits for its children), DelegationRequest, StartRequest, FollowUpRequest, AgentRun (control, follow_up), RunAnswer, RunFailed, started_by, waiting_on_user (a sub-agent run waiting on the user: input_required, its slot lent, queued while its take-back waits for a slot, then running; nested waits once; request_user_input and the permission engine); records.py: RecordsWriter (each conversation's records written to its store as they change: changed, one write at a time per conversation taking the records as it starts, so changes made meanwhile go together in the next; flush, flush_all, discard (a delete's: what waits dropped, the write under way waited for); a failed write warned once per conversation, subagent_records_not_saved, never raised); slots.py: SlotPool (acquire(priority): a free slot, else a future in a heap by priority, RETURNING before NEW, then arrival; release; lent(slot, on_wait=): the slot lent while its run waits, nested lends once, taken back at RETURNING after (on_wait called when that has to wait), at most one take-back waiting for a slot and none once it is held (a wait that starts while one is queued takes it over, and one handed the slot withdraws any queued since), nothing taken back after a cancel, so a tool's caught timeout around a question leaves its run working without a slot, input_required until its next question is answered (running again, still without a slot) or its end; hand_back(slot, to): a child's slot to its parent waiting on it alone; free, waiting; a cancelled waiter leaves the heap, one handed a slot as it is cancelled hands it on; not asyncio.Semaphore), Slot (held, lent), RETURNING, NEW; control.py: RunControl (one run's: tools, the type's own tools it may use, and keeps(name): one of them or of KEPT_TOOLS, the state and delegation tools, what both backends filter by; cancel(by=, error=) its task, the first cancel winning, own_cancel for the hook that takes it and returns, finish: the hook's work ended, no cancel after it (ADK's state read loses no answer), timing: the time limit while the hook runs; model_call/at_step_limit/final_call: the step limit, STEP_LIMIT_NOTE on the last allowed call; used: the token limit, against its own calls and side_tokens (its side calls and summaries, from the ledger), an answer past it that makes calls the run's last, cancelled by it, one that makes none its result (calls=); model_call once final stays final; a cancel leaves a task its turn is cancelling alone; steer/take_steering), STEP_LIMIT_NOTE; outcome.py: a sub-agent's refused or cut answer (outcome_of, the refusal notice as Deep Agents 0.7.34 words it, cut_off, cut_off_warning, OPENAI_REFUSAL_PREFIX: how ADK's OpenAI adapters word a refusal); policy.py: SubAgentPolicy (max_active, max_runs_per_turn, limits, max_open, follow_ups, spawn_sources: of SPAWN_SOURCES, kept as a frozenset, max_spawn_depth) and AgentLimits (max_model_calls, timeout, max_tokens; over: a type's limits over the policy's, field by field, None taking the base's), DEFAULT_LIMITS (100 model calls), frozen and checked as they are made (a ValueError naming the field), as_policy (the one reading of a subagents= argument: a TypeError for anything but a policy or None); brief.py: BRIEF_FIELDS, Brief, BriefError, read_brief (a task call's agent type and brief, against the types its caller may start: the error texts), read_choices (its tools, some of the type's own, and its model, one of its model_choices: TOOLS_ERROR, NO_TOOLS_ERROR, MODEL_ERROR, NO_MODEL_CHOICES_ERROR), task_message (a run's first message, a section per filled field; an inheriting type's ends with INHERITED_CONTEXT_NOTE), task_parameters and task_description (task's schema and description, the same for both backends: tools always, TOOLS_DESCRIPTION, model when a type offered has choices, MODEL_DESCRIPTION, and a type's line its "model choices: <a>, <b>"; limit_sentences: the limits it states, "At most <max_active> sub-agents work at once; more calls in one response wait for a free slot. At most <max_runs_per_turn> runs per turn.", then DEPTH_SENTENCE, "Sub-agents cannot start sub-agents.", when no run the call starts may start one; warn=False for a description made per run), TaskOffer and task_offer (both, for the types one run may start); envelope.py: envelope (a delegation run's result: success only for completed, a one-line error, cancelled_by for a cancelled run), read_envelope (a dict or its JSON text, else None; never raises), view_notice (`VIEW_NOTICE`: what the root is told once the user worked with an instance), the limit and interrupted error texts; `Delegations.message` (an idle instance's follow-up; a running one's run steered, or with `interrupt` cancelled by its parent and followed up; one run per instance, so of two messages to one idle instance in one answer the first runs and the second is steered into it), `stop` (a running instance's run cancelled by its parent, the instance idle; `close` closes it and its descendants, a running one's at its run's end), `check`, `steer(conversation, run, message)`, `stop_by_user`/`close_by_user` (`STOPPED_BY_USER_ERROR`, `CLOSED_BY_USER`: a running run cancelled by the user and waited for), `stop_cause(run)` and `cancel(..., conversation=)`; a message steered to a run that its transcript does not hold when it ends (`RunControl.unstored`) is kept for the instance's next run; a run whose parent's run its control stopped ends `cancelled` by its parent (`its parent's run was stopped`); a run that did not complete fully names its open tasks in its envelope (`envelope(open_tasks=)`, `open_task_descriptions`) and a cancelled run keeps its plan and tasks; `SubAgentPolicy.follow_ups`; brief.py: `follow_up_description`/`follow_up_parameters` (the parent's tools' texts); follow_ups.py: `call_follow_up_tool` (a message_agent, stop_agent or check_agents call as the run in progress); spawn.py: spawnable (the types a source may start at run time: the policy's spawn_sources and the type's spawnable_by), may_spawn (depth below max_spawn_depth), can_have_children (who is built with task, and with follow_ups the parent's tools and the roster: sub-agents, or a type agents may start while the root or runs below it may), depth_sentence_applies, AGENT_SOURCE/SKILL_SOURCE/USER_SOURCE; no backend imports; roster.py: roster_text (the main agent's open sub-agents, newest first, one line each, ROSTER_OPEN/ROSTER_HEADER/ROSTER_CLOSE, at most ROSTER_MAX characters in whole lines, "" for none open), Rosters (a snapshot per conversation, as MemoryIndex: now, forget, clear; the root's own instances, parent root) │ │ ├── adk/ # ADK orchestrator -│ │ │ ├── manager.py # GoogleADKWorkflowManager (the agents built from configs or, adk_config_path, by ADK from a native YAML (library-only: no BaseCLIApp starts one; loaded once per manager at the first _validate_agent_graph (_native_root: the settings' keys exported first; a retry, a model switch and a start after cleanup build on the same tree, whose toolsets the closed runner left reusable), its agents' models resolved leniently in _resolve_extra_models, the base's hook, its registered tools' services detected; configs passed with it ignored, adk_native_configs_ignored): the only difference; _do_initialize builds the app from the tree alone, _build_app → ADKBuild, through the hooks _plugin_chain (the whole chain, top to bottom, its head _init_plugins), _compaction_config (None for a root without a budget), _context_cache_config, _agent_model_refs; the event processor built from the build; a config-built agent's prompt as an instruction provider, sent as written: no `{name}` state injection; _compact_turn: ADK's compaction once, in the base's compact turn; supports_compact False once built for a root without a budget (_no_compact_support says why); the job resume hooks: _conversation_exists (the session read without its events, num_recent_events=0), _deliver_job_notice (the notice, for every app); _run_config: the agents' synchronous tools run in ADK's tool thread pool, 8 workers; _run_and_stream: a run that fails yields the turn's one ERROR, last, none after an ERROR already yielded, and keeps the record of its calls that returned for the next turn (OpenCalls.failed; _answer_left_open forgets it once its answers are stored); the agents: _create_agents builds each config's agent on its own (_agents, by name; no ADK sub_agents), a delegating one with a TaskTool (its own tool named task: AgentGraphError); a runner per sub-agent type (_agent_runners: NoAfterTurnCompactionRunner on App(name=child_app(app_name), root_agent=the type's agent, plugins=_agent_plugin_chain(agent), the app's context cache, no compaction) over the session service, closed with the main runner by _detach_backend, rebuilt by every initialization); _run_agent, the base's hook: the instance's child session (_child_session: a first run makes it from run.state and an inheriting instance's copied events, once; never one the store keeps, whose instance numbering goes past: ADK's create_session refuses it, and the run fails; a follow-up takes the stored session, answers the calls an earlier run left open there (left_open_by) and passes the caller's mark when it holds none; one the store lost is made as a first run's), _stored_instances (the base's hook: the highest instance number of each type the conversation's child sessions keep), the type's runner on the task message (a follow-up's own message) with an abort signal set before it is closed, a run-mode ADKEventProcessor, the raw log's records reported as they come (_report_raw_log); a model's failure raised as the provider's (_plugin_cause), an overflow RunFailed, a reply that is no answer RunAnswer(error=), the shared keys it changed read back) +│ │ │ ├── manager.py # GoogleADKWorkflowManager (the agents built from configs or, adk_config_path, by ADK from a native YAML (library-only: no BaseCLIApp starts one; loaded once per manager at the first _validate_agent_graph (_native_root: the settings' keys exported first; a retry, a model switch and a start after cleanup build on the same tree, whose toolsets the closed runner left reusable), its agents' models resolved leniently in _resolve_extra_models, the base's hook, its registered tools' services detected; configs passed with it ignored, adk_native_configs_ignored): the only difference; _do_initialize builds the app from the tree alone, _build_app → ADKBuild, through the hooks _plugin_chain (the whole chain, top to bottom, its head _init_plugins), _compaction_config (None for a root without a budget), _context_cache_config, _agent_model_refs; the event processor built from the build; a config-built agent's prompt as an instruction provider, sent as written: no `{name}` state injection; _compact_turn: ADK's compaction once, in the base's compact turn; supports_compact False once built for a root without a budget (_no_compact_support says why); the job resume hooks: _conversation_exists (the session read without its events, num_recent_events=0), _deliver_job_notice (the notice, for every app); _run_config: the agents' synchronous tools run in ADK's tool thread pool, 8 workers; _run_and_stream: a run that fails yields the turn's one ERROR, last, none after an ERROR already yielded, and keeps the record of its calls that returned for the next turn (OpenCalls.failed; _answer_left_open forgets it once its answers are stored); the agents: _create_agents builds each config's agent on its own (_agents, by name; no ADK sub_agents), a delegating one with a TaskTool (its own tool named task: AgentGraphError); a runner per sub-agent type (_agent_runners: NoAfterTurnCompactionRunner on App(name=child_app(app_name), root_agent=the type's agent, plugins=_agent_plugin_chain(agent), the app's context cache, no compaction) over the session service, closed with the main runner by _detach_backend, rebuilt by every initialization); a runner per (type, model choice) too (_variant_runners over _variant_agents: the type's agent built on the choice, _build_agent(model=), its chain _agent_plugin_chain(agent, model=, budget=), every plugin reading the choice's model, kind and numbers under the type's name), closed and rebuilt alike; _agent_tool_names: the built agent's tools by name, an MCP toolset's listed when first asked and kept for the build; _run_agent, the base's hook: the runner of run.model's choice or the type's, its processor on _run_models' maps, the raw log told the choice (_chosen_model); the instance's child session (_child_session: a first run makes it from run.state and an inheriting instance's copied events, once; never one the store keeps, whose instance numbering goes past: ADK's create_session refuses it, and the run fails; a follow-up takes the stored session, answers the calls an earlier run left open there (left_open_by) and passes the caller's mark when it holds none; one the store lost is made as a first run's), _stored_instances (the base's hook: the highest instance number of each type the conversation's child sessions keep), the type's runner on the task message (a follow-up's own message) with an abort signal set before it is closed, a run-mode ADKEventProcessor, the raw log's records reported as they come (_report_raw_log); a model's failure raised as the provider's (_plugin_cause), an overflow RunFailed, a reply that is no answer RunAnswer(error=), the shared keys it changed read back) │ │ │ ├── build.py # ADKBuild (root, reply_agents, plugins, compaction, cache, models); load_native_root (from_config at validation; what ADK cannot load, wrapped as AgentGraphError naming the file, ADK's error the cause; a root that is not an LlmAgent, a name used twice in the tree and a task-mode agent refused, AgentGraphError naming it; ensure_direct_anthropic); what the run reads of any tree: reply_agents (the root and the chat-mode agents it can transfer to), own_after_tool_agents (left out by the cap) │ │ │ ├── task_tool.py # TaskTool: the framework's task on ADK (a BaseTool; declared for each request what the run that asks may start, Delegations.task_offer by get_active_run's depth, the root's own requests 0: task_parameters' JSON schema, parameters_json_schema, and task_description; None, no task declared, for a run offered nothing; its description attribute the offer at its first depth, warned of once; bound to the task declaration, an exact TaskTool only): a call → Delegations.delegate, the run's shared-key changes written to the caller's state, the envelope returned as JSON text (ADK's OpenAI Responses adapter sends only a dict's result); SHARED_KEYS (the outside-content mark alone); inherited_events (an inheriting run's history: the session's root-visible events, copied); FollowUpTool (with follow_ups: message_agent, stop_agent, check_agents, each an exact FollowUpTool bound to its declaration, the result as JSON text; an own tool of one of their names fails the build) │ │ │ ├── compaction.py # AgentCliSummarizer (main agent only; summary_range, render_events; its usage normalized, timed and recorded in the conversation's ledger, ledgers, as soon as the call answers: an empty summary's too; on_written: a summary written drops the conversation's memory index snapshot), MainAgentPlugin (the running agent, first in every chain), NoAfterTurnCompactionRunner, compact_session @@ -107,14 +107,14 @@ agentic-cli/ │ │ │ ├── context_cache_plugin.py # One Gemini cache attempt a turn │ │ │ ├── foreign_reasoning_plugin.py # No model is sent another provider's thoughts │ │ │ ├── subagent_outcome_plugin.py # SubAgentOutcomePlugin: a sub-agent's final answer a model refused or cut, rewritten in place (the refusal notice; the text and the cut-off note) and marked (custom_metadata agentic_cli_outcome), which the run's event processor ends it by; what it reads: finish_reason, error_code, an OTHER stop's JSON reason, the text "OpenAI refusal: <text>"; in each sub-agent type's runner's chain (_agent_plugin_chain), after the raw log and RunControlPlugin; the root's answers untouched -│ │ │ ├── run_control_plugin.py # RunControlPlugin: a sub-agent run's control at its model calls (Delegations.control of the active run): the messages steered to it appended to its child session and the request before each call (the run's events from then on stamped after them, on_event_callback: ADK stamps an answer before its call's callbacks, and a durable store reads events back by time), the call counted and the last allowed one given STEP_LIMIT_NOTE (with_note: a part of the last user content; its tools stay declared), each answer's usage (adk_tokens) to used, with whether it makes calls, the run's last answer's function calls dropped (drop_calls: an empty text for calls alone); in each sub-agent type's chain, after the raw log, before SubAgentOutcomePlugin +│ │ │ ├── run_control_plugin.py # RunControlPlugin: a sub-agent run's control at its model calls (Delegations.control of the active run): a narrowed run's other tools left out of the request, its tools_dict and declarations (narrow: a call of one finds ADK's stand-in, unknown_tool_result), before the fit guard; the messages steered to it appended to its child session and the request before each call (the run's events from then on stamped after them, on_event_callback: ADK stamps an answer before its call's callbacks, and a durable store reads events back by time), the call counted and the last allowed one given STEP_LIMIT_NOTE (with_note: a part of the last user content; its tools stay declared), each answer's usage (adk_tokens) to used, with whether it makes calls, the run's last answer's function calls dropped (drop_calls: an empty text for calls alone); in each sub-agent type's chain, after the raw log, before SubAgentOutcomePlugin │ │ │ ├── log_filters.py # install_log_filters: what ADK would print over the CLI logged at debug instead (the warnings hook, filters by logger name: see Console Output); imports no ADK (the package loads LLMLoggingPlugin on first use); the plugin-manager filter reads overflow_plugin.OVERFLOW_PLUGIN_FAILED as a record comes; BaseCLIApp.run() installs them, once │ │ │ ├── call_clock.py # Every model call timed: CallClock (a clock per call, under its EventActions, held through an error until the answer a later plugin gives; the raw log keeps one too), CallSentPlugin (last: starts it as the request goes out), CallLatencyPlugin (second, after MainAgentPlugin: marks the answer, custom_metadata[LATENCY_KEY], which the event processor reads, call_latency; an answer already marked keeps its mark: mark_latency, the overflow retry's); no adapter sends it -│ │ │ └── plugins.py # LLM traffic logging (raw_llm_logging): requests as sent (SentRequestLoggingPlugin, after the fit guard); each record names its agent's model, the agent and its sub-agent run (the active run); latency per model call (call_clock.CallClock: a clock under the call's EventActions, as the fit guard keeps its copies); usage records go to the file only (the stream's LLM_USAGE is the event processor's), counted as the stream's (adk_usage_event, by the agent's kind: kinds); the summary call and the overflow retry are not logged on ADK (a follow-up) +│ │ │ └── plugins.py # LLM traffic logging (raw_llm_logging): requests as sent (SentRequestLoggingPlugin, after the fit guard); each record names its agent's model (chosen=: a run's model choice's), the agent and its sub-agent run (the active run); latency per model call (call_clock.CallClock: a clock under the call's EventActions, as the fit guard keeps its copies); usage records go to the file only (the stream's LLM_USAGE is the event processor's), counted as the stream's (adk_usage_event, by the agent's kind: kinds); the summary call and the overflow retry are not logged on ADK (a follow-up) │ │ ├── deepagents/ # Deep Agents orchestrator (deepagents extra); imports neither adk/ nor langgraph/ -│ │ │ ├── manager.py # DeepAgentsWorkflowManager (turns, sessions, the release hooks: the agents and MCP sessions, the checkpointer and index; MCP, skills, the job resume hooks (_conversation_exists, _deliver_job_notice), _compact_turn; _run_agent, the base's hook: the type's graph (_agent_graphs) astreamed in the run's task with var_child_runnable_config cleared, so its chunks reach its own loop alone, through a run-mode processor and a RunCallback of its own; the answer the last AIMessage with text, its outcome mark, the shared keys it changed by Deep Agents' _is_unchanged rule (copied), an overflow RunFailed) -│ │ │ ├── agent_builder.py # build_agent_tree: one create_agent per AgentConfig, each on its own (graphs=: kept by name for _run_agent; every agent compiled on the manager's checkpointer, a tree built without one compiling its sub-agents with none); root=: the graph's root (a free type listed first is no root); each agent can_have_children says gets task from task_tool.build_task_tool (delegations=), its own tool named task an AgentGraphError; every sub-agent's RunControlMiddleware (delegations=), inside its SubAgentOutcomeMiddleware -│ │ │ ├── middleware.py # InterruptedCallsMiddleware (each call recorded and answered as the active run's; a call id the agent's state holds renamed as the answer arrives, awrap_model_call outside the model side, fresh_call_id; a call answered by a result of its id between its answer and the next), PermissionMiddleware, ToolResultCapMiddleware, ToolCallErrorMiddleware, ActiveToolCallMiddleware (each call the active tool call around its tool), ForeignReasoningMiddleware, ContextOverflowMiddleware, MemoryIndexMiddleware (the root's memory index first in the first human message of each request), RosterMiddleware (outside it: the root's roster of its open sub-agents, after the index), SubAgentOutcomeMiddleware (outermost on every sub-agent's model side: a refused or cut final answer rewritten, its reasoning kept, and marked, response_metadata["agentic_cli"]["outcome"], beside the other marks; a call that raises passes), RunControlMiddleware (inside it: a sub-agent run's control at its model calls, Delegations.control of the active run: the messages steered to it added to its state before each call, abefore_model; the call counted and the last allowed one given STEP_LIMIT_NOTE, with_note, its tools still bound; each answer's usage, langchain_tokens, to used; the run's last answer's tool calls dropped, without_calls; the framework's task among the request's tools, by identity, given the schema and description the run is offered, Delegations.task_offer by its depth, or left out when it is offered nothing); mark_latency/answer_latency: the run callback's mark of how long a call took, response_metadata["agentic_cli"]["latency_ms"]; only the gate has a synchronous tool or model wrapper (it denies the sync tool call), the rest wrap with the async ones (`InterruptedCallsMiddleware.before_agent` is a node hook, synchronous, run on async turns too): turns run through `astream`, and a synchronous run of a graph fails at the first without a sync wrapper, LangChain's NotImplementedError +│ │ │ ├── manager.py # DeepAgentsWorkflowManager (turns, sessions, the release hooks: the agents and MCP sessions, the checkpointer and index; _agent_tool_names: each agent's own tools as built, _own_tool_names; MCP, skills, the job resume hooks (_conversation_exists, _deliver_job_notice), _compact_turn; _run_agent, the base's hook: the type's graph (_agent_graphs), or its model choice's (_variant_graphs, built from Variant(config, chat_model, resolved, budget) per (type, choice)), its processor and RunCallback on _run_models' maps, astreamed in the run's task with var_child_runnable_config cleared, so its chunks reach its own loop alone, through a run-mode processor and a RunCallback of its own; the answer the last AIMessage with text, its outcome mark, the shared keys it changed by Deep Agents' _is_unchanged rule (copied), an overflow RunFailed) +│ │ │ ├── agent_builder.py # build_agent_tree: one create_agent per AgentConfig, each on its own, through build_agent (one agent's graph, root= explicit; variants=: Variant, a sub-agent type on another model and its numbers, its graphs in variant_graphs=) (graphs=: kept by name for _run_agent; every agent compiled on the manager's checkpointer, a tree built without one compiling its sub-agents with none); root=: the graph's root (a free type listed first is no root); each agent can_have_children says gets task from task_tool.build_task_tool (delegations=), its own tool named task an AgentGraphError; every sub-agent's RunControlMiddleware (delegations=), inside its SubAgentOutcomeMiddleware +│ │ │ ├── middleware.py # InterruptedCallsMiddleware (each call recorded and answered as the active run's; a call id the agent's state holds renamed as the answer arrives, awrap_model_call outside the model side, fresh_call_id; a call answered by a result of its id between its answer and the next), PermissionMiddleware, ToolResultCapMiddleware, ToolCallErrorMiddleware, ActiveToolCallMiddleware (each call the active tool call around its tool), ForeignReasoningMiddleware, ContextOverflowMiddleware, MemoryIndexMiddleware (the root's memory index first in the first human message of each request), RosterMiddleware (outside it: the root's roster of its open sub-agents, after the index), SubAgentOutcomeMiddleware (outermost on every sub-agent's model side: a refused or cut final answer rewritten, its reasoning kept, and marked, response_metadata["agentic_cli"]["outcome"], beside the other marks; a call that raises passes), RunControlMiddleware (inside it: a sub-agent run's control at its model calls, Delegations.control of the active run: a narrowed run's request offers its tools and KEPT_TOOLS only (RunControl.keeps), and its awrap_tool_call answers a call of any other unknown_tool_result, before the gate; the messages steered to it added to its state before each call, abefore_model; the call counted and the last allowed one given STEP_LIMIT_NOTE, with_note, its tools still bound; each answer's usage, langchain_tokens, to used; the run's last answer's tool calls dropped, without_calls; the framework's task among the request's tools, by identity, given the schema and description the run is offered, Delegations.task_offer by its depth, or left out when it is offered nothing); mark_latency/answer_latency: the run callback's mark of how long a call took, response_metadata["agentic_cli"]["latency_ms"]; only the gate has a synchronous tool or model wrapper (it denies the sync tool call), the rest wrap with the async ones (`InterruptedCallsMiddleware.before_agent` is a node hook, synchronous, run on async turns too): turns run through `astream`, and a synchronous run of a graph fails at the first without a sync wrapper, LangChain's NotImplementedError │ │ │ ├── tools.py # to_langchain_tools: a callable → StructuredTool whose .func/.coroutine is it │ │ │ ├── task_tool.py # build_task_tool: the framework's task on Deep Agents (a StructuredTool over what a run at the agent's first depth is offered, task_offer: the root's fixed, a sub-agent's rewritten per call by RunControlMiddleware; bound to the task declaration; a call by a run offered nothing answered unknown_tool_result, as ADK answers a tool it did not declare): a call → Delegations.delegate, whose shared-key change (the outside-content mark) and envelope (JSON, the ToolMessage) come back as one Command; SHARED_KEYS; inherited_messages (an inheriting run's history: the state's messages, the summary event applied, less the message that called task); build_follow_up_tools (with follow_ups: message_agent, stop_agent, check_agents, each a StructuredTool bound to its declaration, answering as task does) │ │ │ ├── event_processor.py # DeepAgentsEventProcessor (stream → WorkflowEvent, each call's LLM_USAGE, with its latency (answer_latency), recorded in the conversation's usage ledger before on_event, a run's end with what it used; every event its processor's agent's and run's (run=: a processor for one sub-agent run, its text activity, no TASK_PROGRESS), from the root namespace's items only (a graph a tool runs streams in its own); the task call's TOOL_RESULT shown as on ADK, from its envelope: show_as_delegation); RunCallback (every model call timed, its answer marked with its latency before any middleware sees it; a summary's usage recorded in the conversation's ledger; what a node reports inside itself, through the turn's `LiveEvents`: required; `compact()` called outside a reporting context gets one nobody reads) @@ -254,7 +254,7 @@ Workflow: - **Tool error handling**: All tools return `{"success": bool, ...}` dicts. Never raise `ToolError`. An exception that still escapes a tool is a bug, but it costs one call rather than the turn: on ADK, `workflow/adk/tool_error_plugin.py::ToolErrorPlugin` turns it into an error dict; on Deep Agents, `workflow/deepagents/middleware.py::ToolCallErrorMiddleware`, inside the permission gate, gives the same result, `{"success": false, "error": "<tool> failed: <Type>: <message>"}` cut to 500 characters (both use `workflow/tool_errors.py`). A call to a tool name the agent does not have gets ADK's own text, its first two lines (`unknown_tool_result`: "nope failed: ValueError: Tool 'nope' not found." and the agent's tools by name), logged `tool_not_found` at info (the model's mistake): on ADK the permission gate lets ADK's stand-in through (`is_unknown_tool`: a bare `BaseTool` described "Tool not found", which runs nothing; contract-tested) and `ToolErrorPlugin` answers its lookup error; on Deep Agents the gate answers it. It catches `Exception`, never `BaseException`, so cancelling still cancels (google-adk 2.15 hands a cancelled call's `CancelledError` to `ToolErrorPlugin` for cleanup, ignoring the answer: it answers nothing and logs `tool_cancelled` at debug, no warning). `task` raises nothing into it: a sub-agent's model or run failing (its summary or overflow included: its own tools' errors are results already) fails the run, whose envelope its parent reads (`error`: the provider's reason; on ADK out of ADK's plugin wrapper), reported at once through the turn's live events as one recoverable `ERROR`, `<instance> failed: <reason>`, the run's: the coordinator carries on. A sub-agent's overflow (still too long after its summary or trim) fails its run, on both backends, in the words of ADK's overflow handler, `<agent>: the request no longer fits <model>'s context window.` with `error_code` `CONTEXT_OVERFLOW` (`context.py::subagent_overflow_message`): ADK's `OverflowPlugin` answers the run's model call with it, Deep Agents' manager raises it (`RunFailed`). A refusal is no exception here (the framework adds no `ModelRefusalMiddleware`): a sub-agent whose final answer a model refused ends its run `refused`, and its parent reads, as its envelope's result, Deep Agents 0.7.34's notice ("The subagent stopped because a model refused the request. … Retrying the same request is unlikely to succeed; rephrase it or continue without it."), on both backends and whichever deepagents the pin installs (0.7.28 has no notice of its own; 0.7.34+ finds no refusal block left to word again); an answer cut at the output limit keeps its text, followed by `[cut off at the output limit]`, and its run ends `completed` and `partial`, with one recoverable warning ("<instance>'s answer was cut off at the output limit"); the answer's thoughts or reasoning are kept. ADK's `SubAgentOutcomePlugin` and Deep Agents' `SubAgentOutcomeMiddleware` rewrite and mark the answer, by `workflow/agents/outcome.py`. On ADK the plugin reads the answer's `finish_reason` (Claude's `refusal` and a Chat Completions `content_filter` arrive as `SAFETY`, `max_tokens` and `length` as `MAX_TOKENS`, Gemini's as themselves), the `error_code` ADK sets on an answer with no content (a Gemini prompt's `block_reason`), the `reason` an `OTHER` stop names in its JSON error message (ADK's OpenAI Responses adapter's `incomplete_details`, `content_filter` among them) and a text part `OpenAI refusal: <text>` (that adapter's refusal, and `OpenAICompatibleLlm`'s of a Chat Completions `refusal`, which ADK's class drops). On Deep Agents the middleware reads `response_metadata`'s `stop_reason` (ChatAnthropic), `finish_reason` (ChatOpenAI, ChatGoogleGenerativeAI), `incomplete_details.reason` (the Responses API) and `prompt_feedback.block_reason` (a Gemini prompt block), and a refusal the answer holds (a refusal block, standard or `non_standard`, or `additional_kwargs["refusal"]`). The root's own answers reach the user as their model gave them: on ADK a root's refusal with no answer (Claude's, Gemini's) is still the turn's one `ERROR` ("<model> returned no answer"), and a root on OpenRouter or an OpenAI-compatible server replies "OpenAI refusal: <text>". On both backends the root's own failure leaves the run: the turn's one `ERROR`. A gate or error result goes back as the call's `ToolMessage` with `status="error"`. LangGraph's `ToolNode` runs with `handle_tool_errors=True`. - **Tool result cap**: every tool result passes `workflow/tool_output.py::cap_tool_result` (registered, MCP and skill tools, `job_result`, a delegation's envelope on either backend, and the envelope a view's notice carries: `BaseWorkflowManager._user_ran` keeps `instance_result` capped): one over `tool_result_max_chars` is cut to its shape and as much of its head and tail as fits (the kept length is bisected, since JSON escapes vary), with a note (under `truncated`, or appended to a string) pointing at its full output in `./.{app_name}/tool-output/`, written for `read_file` to page by lines (lines over 2,000 characters split). A string that holds a JSON object (`json_object`: a delegation's envelope, which both task tools write unescaped, `ensure_ascii=False`; a framework tool's dict in a Deep Agents `ToolMessage`) is cut as that dict and given back as its JSON text, so the parent reads JSON still, on both backends. On ADK, `workflow/adk/tool_result_cap_plugin.py::ToolResultCapPlugin` is registered after `InterruptedCallsPlugin`, since ADK stops at the first `after_tool_callback` that returns a value, and it leaves out an agent with `after_tool_callback`s of its own (a native YAML app's, `build.own_after_tool_agents`), which ADK would skip once the cap answered. ADK's Claude and OpenAI Responses adapters send only a result's `content`, else its `result`, so the plugin also puts the note there (`_note_where_sent`). On Deep Agents, `ToolResultCapMiddleware` sits between the permission gate and `ToolCallErrorMiddleware`, so an error result is capped too, and reads a `ToolMessage` (its text cut by the cap's string rule, text blocks joined into the first) and each `ToolMessage` of a `Command`. A call of the framework's `read_file` (by identity, as each gate resolves tools) on a saved output is cut without a second save. Saving never fails the call (`tool_output_not_saved` warns once per folder, then debug), and a cap that raises leaves the result uncut (`tool_result_cap_failed` at warning, its traceback at debug). - **Summarizing on ADK (main agent only)**: every app's App (a native ADK YAML app's too, when its root's model has a context budget) has ADK's `EventsCompactionConfig` with `workflow/adk/compaction.py::AgentCliSummarizer` at the root's trigger (`context_budget`, as on Deep Agents); ADK checks before every agent's model call, and `MainAgentPlugin` (the first plugin) records the running agent in a ContextVar, so the summarizer writes only for the root (a sub-agent's run, on its type's runner, has no compaction config at all: a sub-agent compacting the shared session lost its brief and looped, 100 requests in one turn, offline). The summarizer picks its own range before paying for anything (`summary_range`: the newest `keep` tokens and the current turn kept, a cut only where a user turn starts, never parting a call from its result, long-running calls excepted since ADK re-injects them, nor leaving a kept event stamped inside the range; none for a saving under 20% of the trigger, the seed left out of it), writes on the root's own model (`_simple_model(SUMMARY_MAX_TOKENS, agent=root)`, thinking off) with `workflow/summary_prompt.py`, the rendering sized to that model's window (the middle cut, `MIDDLE_OMITTED`, the seed kept whole), and returns **user-role** text starting `SUMMARY_PREFIX` (a model-role first message is one Claude refuses), which the fit guard folds, after the memory index and the roster when the request has them, into the next user text (`fold_summary`), so no request holds two user messages in a row. `last_kept_turns` and `last_error` are for its callers: a manual summarizer warns of nothing itself. It reports through the turn's live events (`_run_and_stream` iterates the runner through `live_events.merged` under `reporting(live)`); any failure is one recoverable `ERROR` a turn, never raised to ADK. `NoAfterTurnCompactionRunner` overrides ADK's private `Runner._run_post_invocation_compaction` (contract-tested), so the prompt never waits for a summary after the answer. `FitGuardPlugin` is the last plugin (but `SentRequestLoggingPlugin`, which logs a request as sent, and `CallSentPlugin`, which starts the call's clock) and `OverflowPlugin` the one before it (`MemoryIndexPlugin`, when the root has a memory tool and `memory_index_enabled` is on, the one before that: it puts the conversation's memory index snapshot first in the root's requests, never in the session): the guard leaves a request's oldest turns out when it is over its agent's budget (keeping the newest turn and what opens the conversation, the memory index, the roster of the root's open sub-agents (`RosterPlugin`, before `MemoryIndexPlugin`, for a root with `message_agent`), then a summary: `protected_head`; in a sub-agent type's chain also the run's task message and its instance's brief, `brief_of`) and keeps each request as it came in (`request_as_seen`: one copy per model call, under the call's `EventActions`, which ADK passes to all three of its callbacks: each sub-agent run is an invocation of its own on a child session, but two runs of one type share that type's runner and its plugins, and a run drops only what its own cancelled calls left, as it ends), and the overflow handler, on a provider's overflow, summarizes now (the root, through `compact_session`, ADK's private `_run_compaction_for_token_threshold_config`; `_summarize_now` returns `WrittenSummary(text, kept_turns)`, and the retry is the index, the roster, the summary and those turns) or trims to half the budget (a sub-agent, or nothing to summarize), builds the retry from the guard's copy without the context cache, retries once on the agent's `canonical_model`, then answers the root with `LlmResponse(error_code="CONTEXT_OVERFLOW")`, never model text (ADK would store it as the reply), which `ADKEventProcessor` maps to the turn's `ERROR`; a retry that fails otherwise propagates, and `_run_and_stream` unwraps ADK's plugin-manager `RuntimeError` to the provider's error; a sub-agent's call that still does not fit is answered with an error response too, `CONTEXT_OVERFLOW` and `subagent_overflow_message`, which its run's processor keeps as the run's failure: the run ends `failed` with those words (`RunFailed`), its parent reads them in the envelope, and the user is warned once, by the framework's delegation (`agents/delegate.py`), as on Deep Agents. A native ADK YAML app gets all of it: only the building of its agents differs (`workflow/adk/build.py`). Its chat-mode sub-agents keep transferring, and an agent the root transfers to replies to the user (`build.reply_agents`: its text is the reply, recent_messages reads it, its overflow is the turn's clear error, its calls write the outside-content mark); the summary and the memory index stay the root's, so such an agent is trimmed by the fit guard, not summarized. An agent's own callbacks (a native app's) run after every plugin, and only when none answered: its before-model callbacks see the request after the fit guard, and the cap leaves out an agent with after-tool callbacks. A main agent whose model does not resolve through the catalog has no budget and no summary. -- **Sub-agents delegate and return**: on both backends a sub-agent run is a call of its parent's `task` tool (the framework's: `tools/_core/delegation.py` declares it, `workflow/agents/delegate.py` runs it) that returns in the same turn; only the root replies to the user (a sub-agent's `TEXT` carries `metadata["subagent"]`, and the CLI shows it as the events box's status line, under its run's name: `researcher-2 › …`; `/agents` picks among a conversation's instances), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the types the calling run may start, `Delegations.offered`: its own sub-agents, then, with `SubAgentPolicy.spawn_sources` holding `"agent"` and the run's depth below `max_spawn_depth`, the types whose `AgentConfig.spawnable_by` names `"agent"`, `workflow/agents/spawn.py`; a free type, in no `sub_agents` list, is never the root; `task` is offered for each run, ADK declaring it per request and Deep Agents rewriting a sub-agent's per model call, and a run offered nothing has none) and a brief (`workflow/agents/brief.py`: `title`, `objective`, `deliverable`, `constraints`, `known`, `done_when`), its schema and description the same on both backends (`task_parameters`, `task_description`: a line per type with its description, "The <name> agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both, through `Delegations.start` (a `StartRequest`, the one entry for a first run): it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents <id>`, never written to the conversation. It ends as the `RunAnswer` says: its last text (a reply that also called a tool included; none at all, an empty result shown `No answer`), `refused` or `partial` by the outcome mark, `failed` for an error or a raise (one recoverable `ERROR`, `<instance> failed: <reason>`, or the hook's own words, `RunFailed`: an overflow's; its result the text it wrote before it failed: a failed model call is the hook's `RunAnswer.error`, `failure_reason`, its warning's code `RunAnswer.error_code`, the error's type, and `RunFailed` carries `text=`); and the call's result is the run's envelope as JSON (`workflow/agents/envelope.py`), shown by `show_as_delegation`. A cancel of the caller's task stops the run's task first and ends the run `interrupted`. Each run works under its `RunControl` (`workflow/agents/control.py`, `AgentRun.control`), with its type's `AgentConfig.limits` over the policy's (`SubAgentPolicy.limits`, `DEFAULT_LIMITS`: 100 model calls): `Delegations.cancel(run_id, by=, error=)` cancels the run alone (its parent, the user or a limit), and the hook, seeing its own cancel (`own_cancel`), stops the run as a stopped turn's (ADK: its abort signal, its open calls sealed in its child session; Deep Agents: its stream closed) and returns what it has: the run ends `cancelled` with `cancelled_by` and that text, `partial`, while its siblings and the turn go on; the turn's own cancel still wins (`interrupted`). Past its `timeout` (counted from when its hook starts, `timing`) the run is cancelled by its limit (`time limit reached`); each model call is counted before it is made (`RunControlPlugin` in each sub-agent chain, `RunControlMiddleware` on each sub-agent's model side) and the last allowed one gets `STEP_LIMIT_NOTE` after its last message, its tools still declared (Claude refuses tool calls in a request that defines no tools); its answer's calls are dropped, never run, so the run completes `partial`, `step limit reached`; each call's tokens are counted after it, with what the run's other calls used (`RunControl(side_tokens=)`: its tools' side calls and its summaries, the ledger's rows of the run that are no agent step, `UsageLedger.by_purpose(run=)`), so the limit is the run's total as its usage record counts it, and past `max_tokens` an answer that makes tool calls is the run's last, its calls dropped, `cancelled` by its limit (`token limit reached`), while one that makes none ends the run as it would, `completed`, its result whole (a model that reports no usage counts none of its own). A turn starts at most `max_runs_per_turn` runs, at any depth (`sessions.runs_this_turn`): a call past it is the error result, no run started; `task`'s description says so (`limit_sentences`). At most `max_active` runs of a conversation work at once, at any depth (`workflow/agents/slots.py::SlotPool`, one per conversation, `Delegations.slots`; the root takes no slot): a run takes a slot right before its hook and its time limit start and gives it back at its end, however it ends; one that finds none waits `queued` (an `AGENT_RUN` and its record say so, then `running`), not counted against its `timeout`. A run lends its slot while it waits on its children (one lend for all it waits on at once; the child that ends last hands its slot straight back, so the tree in progress goes on ahead of the runs that have not started) or on the user (`waiting_on_user`: `input_required`, `queued` once answered while it waits for its slot back, then `running`, in `request_user_input` and in the permission engine from before its one-prompt lock until after it: a run waiting for a slot while holding the lock would hold every other run's prompt; a prompt no one can be shown, no input callback or its turn ended, lends nothing: `can_request_user_input`), so nested fan-out never deadlocks; a cancel, queued or lending, leaves no waiter in the heap and no slot taken. A message steered to a working run (`RunControl.steer`, through `Delegations.control(run)`) is added after its last message, as the user's, before its next model call, and stays in its transcript (ADK: appended to its child session, the run's later events stamped after it so a durable store reads them back in order; Deep Agents: added to its state); a sub-agent run's task message is never trimmed, on ADK neither by the fit guard nor by the overflow handler's retry, whatever was steered after it. A dialog whose run is stopped is withdrawn, the turn going on (`MessageProcessor`). `AgentConfig.inherit_context` sets what a run sees: False (the default) its task alone, True its parent's conversation too, read once as the run starts (the conversation after any summary; Deep Agents' less the message that called `task`, which ADK's copy keeps), before the task message, which then ends with `INHERITED_CONTEXT_NOTE` (whose conversation it reads, which message is its task); `validate_agent_graph` refuses a value that is not True or False, `inherit_context=True` on the root, on an agent with sub-agents and below another sub-agent. On ADK (`workflow/adk/task_tool.py::TaskTool`) every config-built agent is built on its own, with no ADK `sub_agents`, so ADK offers none `transfer_to_agent`, and gets ADK's identity line ("You are an agent. Your internal name is …"); a delegating agent has one `TaskTool`. A sub-agent is an instance that outlives its run: `idle` when the run ends, its next run a follow-up (`Delegations.follow_up`, through the same hook with `AgentRun.follow_up`, the message as written and no history), one run per instance at a time; a run's end leaves its instance `stopped` (once the user stopped it: its run cancelled by the user, or an idle one; only the user continues it), `closed` (`AgentConfig.continuable` False, or past `SubAgentPolicy.max_open`: the oldest idle one) or `idle`, `Delegations.close` closes an idle or stopped one and its descendants, and `AGENT_INSTANCE` carries a change without a run; the user controls any instance of the open conversation through the manager (`run_instance`: a follow-up as a turn of its own, its Ctrl+C the user's stop; `stop_instance`, `close_instance`, `steer_instance`; `tell_root`: a notice turn of the root, marked as a job's) and the CLI's `/agents` picker, `/agent stop|close <id>` and `/agent <id>`'s view (`cli/agent_view.py`: a line typed there is the instance's next run or a steer of the run that works, Ctrl+C the user's stop, `/back` the root's notice); on ADK a follow-up continues the instance's child session, the calls an earlier run left open answered first (`left_open_by`, from the instance's record), on Deep Agents the instance's own checkpointer thread (`instance_run_config`: its input the message and the caller's mark, the shared keys it changed compared with the thread's state as the run started). Each sub-agent type runs on its own runner (`App(name=child_app(app_name))`, the type's agent its root, `_agent_plugin_chain`: the main chain configured for a sub-agent, no memory index, no summary, `RunControlPlugin` and `SubAgentOutcomePlugin`; every plugin's per-call state keyed by invocation) over the manager's session service, on a child session per instance (`child_session_id`: `<conversation id>/<instance>`, the conversation id's `%` and `/` percent-encoded; an inheriting instance's gets the conversation's events copied once, at its first run, `task_tool.inherited_events`), under an app no conversation list reads. On Deep Agents (`workflow/deepagents/task_tool.py::build_task_tool`) each type's graph is built on its own, and a run `astream`s it in its task with `var_child_runnable_config` cleared, so its chunks reach its own loop alone, never its parent's stream; an inheriting run's history is the parent's messages with Deep Agents' summary event applied (`SummarizationMiddleware._apply_event_to_messages`, private: `tests/workflow/deepagents/test_compact.py` pins it), and `ForeignReasoningMiddleware(kind, agent=...)` leaves out the reasoning of AI messages another agent wrote. A native ADK YAML app keeps transferring (chat-mode sub-agents); a task-mode agent in one is refused at validation, since ADK runs its delegation outside the tool pipeline and keeps the call open across turns. With `SubAgentPolicy(follow_ups=True)` every agent that can have sub-agents (`can_have_children`: its own, or types it may start at run time) also gets `message_agent`, `stop_agent` and `check_agents` beside `task` (`workflow/agents/follow_ups.py::call_follow_up_tool` over `Delegations.message`/`stop`/`check`; ADK's `FollowUpTool`, Deep Agents' `build_follow_up_tools`; an own tool of one of their names fails the build, a Deep Agents MCP tool of one is skipped): `message_agent` continues an idle instance, steers a running one (before its next step; a run already stopping or finished is waited for, then the message follows the instance up or is refused; one being closed is refused as closed at once) or, with `interrupt` (refused, nothing cancelled, when no follow-up could start; an agent's keeps the turn's run it checked for), replaces its run (the user's interrupt is the user's stop); `stop_agent` cancels a running run by its parent (the instance idle; only the user's stop makes one `stopped`) and, with `close`, closes it and its descendants; a message steered to a run and not in its transcript when it ends goes to the instance's next run (`RunControl.stored`/`unstored`: ADK counts one stored as its child-session append returns, Deep Agents once the model call after it holds it); a run that did not complete fully names its open tasks in its envelope (`open_tasks`); a run whose parent's run was stopped by its control ends `cancelled` by its parent, not `interrupted`. +- **Sub-agents delegate and return**: on both backends a sub-agent run is a call of its parent's `task` tool (the framework's: `tools/_core/delegation.py` declares it, `workflow/agents/delegate.py` runs it) that returns in the same turn; only the root replies to the user (a sub-agent's `TEXT` carries `metadata["subagent"]`, and the CLI shows it as the events box's status line, under its run's name: `researcher-2 › …`; `/agents` picks among a conversation's instances), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the types the calling run may start, `Delegations.offered`: its own sub-agents, then, with `SubAgentPolicy.spawn_sources` holding `"agent"` and the run's depth below `max_spawn_depth`, the types whose `AgentConfig.spawnable_by` names `"agent"`, `workflow/agents/spawn.py`; a free type, in no `sub_agents` list, is never the root; `task` is offered for each run, ADK declaring it per request and Deep Agents rewriting a sub-agent's per model call, and a run offered nothing has none) and a brief (`workflow/agents/brief.py`: `title`, `objective`, `deliverable`, `constraints`, `known`, `done_when`), then `tools` (some of the type's own tools, `_agent_tool_names`: the run is offered only those and the tools every run keeps, `RunControl.keeps`, ADK's `RunControlPlugin` and Deep Agents' `RunControlMiddleware` filtering its requests and answering a call of another `unknown_tool_result`) and `model` (one of `AgentConfig.model_choices`, offered only when a type has some: the run is on the type's agent built on that choice at initialization, ADK a runner and Deep Agents a graph per (type, choice), resolved and budgeted with the rest, `_run_models`), its schema and description the same on both backends (`task_parameters`, `task_description`: a line per type with its description, "The <name> agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both, through `Delegations.start` (a `StartRequest`, the one entry for a first run): it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents <id>`, never written to the conversation. It ends as the `RunAnswer` says: its last text (a reply that also called a tool included; none at all, an empty result shown `No answer`), `refused` or `partial` by the outcome mark, `failed` for an error or a raise (one recoverable `ERROR`, `<instance> failed: <reason>`, or the hook's own words, `RunFailed`: an overflow's; its result the text it wrote before it failed: a failed model call is the hook's `RunAnswer.error`, `failure_reason`, its warning's code `RunAnswer.error_code`, the error's type, and `RunFailed` carries `text=`); and the call's result is the run's envelope as JSON (`workflow/agents/envelope.py`), shown by `show_as_delegation`. A cancel of the caller's task stops the run's task first and ends the run `interrupted`. Each run works under its `RunControl` (`workflow/agents/control.py`, `AgentRun.control`), with its type's `AgentConfig.limits` over the policy's (`SubAgentPolicy.limits`, `DEFAULT_LIMITS`: 100 model calls): `Delegations.cancel(run_id, by=, error=)` cancels the run alone (its parent, the user or a limit), and the hook, seeing its own cancel (`own_cancel`), stops the run as a stopped turn's (ADK: its abort signal, its open calls sealed in its child session; Deep Agents: its stream closed) and returns what it has: the run ends `cancelled` with `cancelled_by` and that text, `partial`, while its siblings and the turn go on; the turn's own cancel still wins (`interrupted`). Past its `timeout` (counted from when its hook starts, `timing`) the run is cancelled by its limit (`time limit reached`); each model call is counted before it is made (`RunControlPlugin` in each sub-agent chain, `RunControlMiddleware` on each sub-agent's model side) and the last allowed one gets `STEP_LIMIT_NOTE` after its last message, its tools still declared (Claude refuses tool calls in a request that defines no tools); its answer's calls are dropped, never run, so the run completes `partial`, `step limit reached`; each call's tokens are counted after it, with what the run's other calls used (`RunControl(side_tokens=)`: its tools' side calls and its summaries, the ledger's rows of the run that are no agent step, `UsageLedger.by_purpose(run=)`), so the limit is the run's total as its usage record counts it, and past `max_tokens` an answer that makes tool calls is the run's last, its calls dropped, `cancelled` by its limit (`token limit reached`), while one that makes none ends the run as it would, `completed`, its result whole (a model that reports no usage counts none of its own). A turn starts at most `max_runs_per_turn` runs, at any depth (`sessions.runs_this_turn`): a call past it is the error result, no run started; `task`'s description says so (`limit_sentences`). At most `max_active` runs of a conversation work at once, at any depth (`workflow/agents/slots.py::SlotPool`, one per conversation, `Delegations.slots`; the root takes no slot): a run takes a slot right before its hook and its time limit start and gives it back at its end, however it ends; one that finds none waits `queued` (an `AGENT_RUN` and its record say so, then `running`), not counted against its `timeout`. A run lends its slot while it waits on its children (one lend for all it waits on at once; the child that ends last hands its slot straight back, so the tree in progress goes on ahead of the runs that have not started) or on the user (`waiting_on_user`: `input_required`, `queued` once answered while it waits for its slot back, then `running`, in `request_user_input` and in the permission engine from before its one-prompt lock until after it: a run waiting for a slot while holding the lock would hold every other run's prompt; a prompt no one can be shown, no input callback or its turn ended, lends nothing: `can_request_user_input`), so nested fan-out never deadlocks; a cancel, queued or lending, leaves no waiter in the heap and no slot taken. A message steered to a working run (`RunControl.steer`, through `Delegations.control(run)`) is added after its last message, as the user's, before its next model call, and stays in its transcript (ADK: appended to its child session, the run's later events stamped after it so a durable store reads them back in order; Deep Agents: added to its state); a sub-agent run's task message is never trimmed, on ADK neither by the fit guard nor by the overflow handler's retry, whatever was steered after it. A dialog whose run is stopped is withdrawn, the turn going on (`MessageProcessor`). `AgentConfig.inherit_context` sets what a run sees: False (the default) its task alone, True its parent's conversation too, read once as the run starts (the conversation after any summary; Deep Agents' less the message that called `task`, which ADK's copy keeps), before the task message, which then ends with `INHERITED_CONTEXT_NOTE` (whose conversation it reads, which message is its task); `validate_agent_graph` refuses a value that is not True or False, `inherit_context=True` on the root, on an agent with sub-agents and below another sub-agent. On ADK (`workflow/adk/task_tool.py::TaskTool`) every config-built agent is built on its own, with no ADK `sub_agents`, so ADK offers none `transfer_to_agent`, and gets ADK's identity line ("You are an agent. Your internal name is …"); a delegating agent has one `TaskTool`. A sub-agent is an instance that outlives its run: `idle` when the run ends, its next run a follow-up (`Delegations.follow_up`, through the same hook with `AgentRun.follow_up`, the message as written and no history), one run per instance at a time; a run's end leaves its instance `stopped` (once the user stopped it: its run cancelled by the user, or an idle one; only the user continues it), `closed` (`AgentConfig.continuable` False, or past `SubAgentPolicy.max_open`: the oldest idle one) or `idle`, `Delegations.close` closes an idle or stopped one and its descendants, and `AGENT_INSTANCE` carries a change without a run; the user controls any instance of the open conversation through the manager (`run_instance`: a follow-up as a turn of its own, its Ctrl+C the user's stop; `stop_instance`, `close_instance`, `steer_instance`; `tell_root`: a notice turn of the root, marked as a job's) and the CLI's `/agents` picker, `/agent stop|close <id>` and `/agent <id>`'s view (`cli/agent_view.py`: a line typed there is the instance's next run or a steer of the run that works, Ctrl+C the user's stop, `/back` the root's notice); on ADK a follow-up continues the instance's child session, the calls an earlier run left open answered first (`left_open_by`, from the instance's record), on Deep Agents the instance's own checkpointer thread (`instance_run_config`: its input the message and the caller's mark, the shared keys it changed compared with the thread's state as the run started). Each sub-agent type runs on its own runner (`App(name=child_app(app_name))`, the type's agent its root, `_agent_plugin_chain`: the main chain configured for a sub-agent, no memory index, no summary, `RunControlPlugin` and `SubAgentOutcomePlugin`; every plugin's per-call state keyed by invocation) over the manager's session service, on a child session per instance (`child_session_id`: `<conversation id>/<instance>`, the conversation id's `%` and `/` percent-encoded; an inheriting instance's gets the conversation's events copied once, at its first run, `task_tool.inherited_events`), under an app no conversation list reads. On Deep Agents (`workflow/deepagents/task_tool.py::build_task_tool`) each type's graph is built on its own, and a run `astream`s it in its task with `var_child_runnable_config` cleared, so its chunks reach its own loop alone, never its parent's stream; an inheriting run's history is the parent's messages with Deep Agents' summary event applied (`SummarizationMiddleware._apply_event_to_messages`, private: `tests/workflow/deepagents/test_compact.py` pins it), and `ForeignReasoningMiddleware(kind, agent=...)` leaves out the reasoning of AI messages another agent wrote. A native ADK YAML app keeps transferring (chat-mode sub-agents); a task-mode agent in one is refused at validation, since ADK runs its delegation outside the tool pipeline and keeps the call open across turns. With `SubAgentPolicy(follow_ups=True)` every agent that can have sub-agents (`can_have_children`: its own, or types it may start at run time) also gets `message_agent`, `stop_agent` and `check_agents` beside `task` (`workflow/agents/follow_ups.py::call_follow_up_tool` over `Delegations.message`/`stop`/`check`; ADK's `FollowUpTool`, Deep Agents' `build_follow_up_tools`; an own tool of one of their names fails the build, a Deep Agents MCP tool of one is skipped): `message_agent` continues an idle instance, steers a running one (before its next step; a run already stopping or finished is waited for, then the message follows the instance up or is refused; one being closed is refused as closed at once) or, with `interrupt` (refused, nothing cancelled, when no follow-up could start; an agent's keeps the turn's run it checked for), replaces its run (the user's interrupt is the user's stop); `stop_agent` cancels a running run by its parent (the instance idle; only the user's stop makes one `stopped`) and, with `close`, closes it and its descendants; a message steered to a run and not in its transcript when it ends goes to the instance's next run (`RunControl.stored`/`unstored`: ADK counts one stored as its child-session append returns, Deep Agents once the model call after it holds it); a run that did not complete fully names its open tasks in its envelope (`open_tasks`); a run whose parent's run was stopped by its control ends `cancelled` by its parent, not `interrupted`. - **Token usage**: every model call the framework makes is one `LLM_USAGE`, on both backends, side calls included (`generate_simple`: `summarize`'s, `purpose` `tool`; `on_session_end`'s, `memory_extraction`, outside any turn; an app's own, `side_call`, or what its caller names with `workflow/usage.py::side_call`), its counts normalized where it is made (`normalized_tokens`: `prompt_tokens` every input token, cache reads and writes included; `completion_tokens` every output token, thinking included; ADK's read by its model's provider kind, `adk_usage_event`/`adk_tokens`, since Gemini and ADK's Claude adapter keep the thinking apart from the candidates and OpenAI's count it inside, an agent of no known kind read as apart; Deep Agents' by LangChain's one convention, `langchain_tokens`; the raw log's usage records alike), and timed (`latency_ms`: on ADK from the request to the answer, `workflow/adk/call_clock.py`'s plugins marking the answer's `custom_metadata`; on Deep Agents by the turn's `RunCallback`, which marks the answer's `response_metadata["agentic_cli"]`, beside the outcome mark; a side call, a summary and the overflow retry around their own request; no adapter sends either mark). Each is recorded in its conversation's ledger (`UsageLedger`; `BaseWorkflowManager.usage`/`usage_of`, in memory for the manager's life: a backend switch's new manager starts afresh, as with `agent_runs`) where it is made, before `on_event` (the event processors, ADK's summarizer, as soon as its call answers, Deep Agents' `RunCallback`, `_report_side_call`), under the run it is made in and its conversation's turn while one runs (as the manager counts them, `/compact` and job notices included: not `SessionInfo.turns`; none in another conversation's turn or from a task its turn outlived, which `_report_side_call` reports to no one); a sub-agent run's `AGENT_RUN` end carries what it used, by model (`metadata["usage"]`, `RunRecord.usage`). The CLI's status bar sums the events it sees (the open conversation's total, on any backend); `/status` shows the ledger by agent. LangGraph (deprecated) records no ledger. - **Tool registration**: Use `@register_tool(category=..., capabilities=..., description=...)` decorator. `capabilities=` is required — pass `EXEMPT` for tools that need no permission check or a list of `Capability(name, target_arg=...)` tuples the engine matches against rules. Tools are auto-discovered via the global `ToolRegistry`. A tool in `AgentConfig.tools` that the registry did not issue is denied at every call; building the agents names it once (`tool_not_registered`, per agent and tool: `BaseWorkflowManager._name_unregistered`): a plain callable, a `FunctionTool`/`StructuredTool` judged by the function it runs (as the gates unwrap it), an app's own tool class; ADK's own tool objects excepted (a built-in runs inside the model). `outside_content=True` (or a function of the call's arguments) declares that a call brings content from outside the user and the project into the conversation (a page, a document, a program's output): once the gate allows one, a memory write in that conversation is approved per call (see Permissions); an application's tools are unmarked unless they declare it, and a variant must declare the same flag as its tool. - **Async tools never block the event loop**: a synchronous tool runs on a worker thread on both backends; an async tool runs on the event loop itself, where a blocking call (DNS, a connect, a file lock's wait, a sleep, a subprocess wait, PDF parsing, page conversion, embedding) freezes the whole app, Ctrl+C included. An async tool runs its slow work with `asyncio.to_thread`. `tests/tools/test_async_tools_never_block.py` lists every async tool (the registry's, the factories' service-bound variants, Deep Agents' skill tools), so a new one fails until it is listed, and calls each through the loop guard (`tests/loop_guard.py`). diff --git a/README.md b/README.md index fd25457c..dec95571 100644 --- a/README.md +++ b/README.md @@ -1292,6 +1292,7 @@ configs = [coordinator, researcher, analyst] | `limits` | AgentLimits \| None | The agent's own per-run limits (`max_model_calls`, `timeout` in seconds, `max_tokens`), laid over the app's `SubAgentPolicy.limits` field by field: each of its runs works under them, and one past a limit ends (see [Sub-agent context](#sub-agent-context)). Not on the root | | `continuable` | bool | Whether an instance of this agent takes follow-ups after its run (`True`, the default) or is closed when its run ends (`False`, one-shot); see [Sub-agent context](#sub-agent-context). Not `False` on the root | | `spawnable_by` | frozenset[str] \| None | Who may start this agent at run time besides its parent: a set of `"agent"` (another agent's `task` call), `"skill"` and `"user"`, each also enabled by the app's `SubAgentPolicy.spawn_sources`; `None` (the default): only its parent. One in no `sub_agents` list is a free type, never the root; see [Sub-agent context](#sub-agent-context). Not on the root | +| `model_choices` | tuple[str, ...] | The models a delegation may run this agent on instead of its own (`task`'s `model`): references, bare ids or roles, as `model` takes them (`("fast",)`); each is resolved, with the agent's `model_settings`, and given its own context numbers at startup. Empty (the default): its own model alone; see [Sub-agent context](#sub-agent-context). Not on the root | The agent graph is validated before anything is allocated — ahead of model discovery and service creation. Duplicate names, unknown `sub_agents` @@ -1304,6 +1305,8 @@ run time only, and no root however it is listed; the root may not set `spawnable_by`, and a `spawnable_by` that is empty or names a source other than `agent`, `skill` and `user` raises too (a free type the app's policy lets no source start is a warning: `validate_agent_graph(configs, policy=...)`). +`model_choices` on the root, one that is no tuple or list of texts, and a choice +named twice raise it too. `inherit_context=True` on the root, on an agent with sub-agents of its own or on an agent below another sub-agent, and an `inherit_context` that is not True or False, raise it too, and, when the agents are built, so does a coordinator @@ -1324,7 +1327,8 @@ both backends. The parent calls the framework's `task` tool, the same on both: `agent_type`, one of its own sub-agents (or of the types it may start at run time, below), and a brief, `title` and `objective` (required), `deliverable`, `constraints`, `known` (what the parent already -knows that the task needs) and `done_when`. The sub-agent's run starts from its +knows that the task needs) and `done_when`, and optionally `tools` and `model` +(below). The sub-agent's run starts from its task message, the brief as sections (`# Task: <title>`, `## Objective`, …); it has a plan and a task list of its own (it starts with none, and what it saves stays with it: `/agents <id>` shows them), and works with its own prompt, @@ -1453,6 +1457,26 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", subagents=SubAgentPolicy(spawn_sources={"agent"}), ) ``` +- **Narrowing a run, and a cheaper model.** Any `task` call may give + `tools`, some of the type's own tools (its registered, skill and MCP + tools, by name; its plan's tools and the delegation tools always stay): + the run is offered only those, and a call of another is answered as one + of a tool it does not have. A type's `model_choices` are the models a call + may pick instead of its own (`model`, named in the type's line in `task`'s + description); each is resolved and given its context numbers at startup, + and runs as the type's agent built on it (ADK: a runner of its own; + Deep Agents: a graph of its own), within its own window. Anything else is + the call's error result, naming what it may be, and no run starts. The + instance keeps both: its follow-ups, and its runs after a restart, run + with them, and `/agents <id>` shows them. + + ```python + researcher = AgentConfig(name="researcher", prompt="Find facts.", + description="Finds facts.", tools=[web_search, web_fetch], + model="strong", model_choices=("fast",)) + # The coordinator's call: {"agent_type": "researcher", "title": "Look it up", + # "objective": "...", "tools": ["web_search"], "model": "fast"} + ``` - **The parent's tools.** With `subagents=SubAgentPolicy(follow_ups=True)` every agent that can have sub-agents (its own, or types it may start at run time) gets three more tools beside `task` (with the @@ -1648,6 +1672,7 @@ are `AgentConfig`'s, and an unknown one is an error: | `sub_agents`, `inherit_context` | The agents it may delegate to, and what a sub-agent sees: `false` (its task alone, the default) or `true` (its parent's conversation too; see [Sub-agent context](#sub-agent-context)) | | `brief_required`, `limits`, `continuable` | As on `AgentConfig`: `brief_required: [objective, deliverable]`, `limits: {max_model_calls: 30, timeout: 600, max_tokens: 200000}` (each limit read as written), `continuable: false` (one-shot) | | `spawnable_by` | Who may start it at run time, a list: `spawnable_by: [agent]` (read as a set; with no `sub_agents` naming it, a free type) | +| `model_choices` | The models a delegation may run it on instead of its own, a list: `model_choices: [fast]` (read as a tuple) | | `include_state_tools` | `true` by default: the plan and task tools are added | - **A tool is a name, resolved when the manager is built.** A bare name is From ec5c0adfc15d62cd1ff05ab5aa752010adeeaf44 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:20:57 -0500 Subject: [PATCH 10/11] Sub-agents: review fixes for model choices and narrowed tools A backend that cannot list a type's tools (ADK, an MCP toolset whose listing failed) raises ToolsUnlistedError, which Delegations answers as the call's error result, no run started or counted, instead of reporting the tools as gone; a message asks for a narrowed instance's tool names once; the configured tool names have one rule. Tests: the release closes a model choice's runner and server, the model is checked before the tools, two messages to a narrowed instance. Style: blank lines, wrapped docstrings, one expression for the overflow plugin's models. --- CHANGELOG.md | 7 +- CLAUDE.md | 2 +- src/agentic_cli/cli/agent_view.py | 8 +- src/agentic_cli/config.py | 4 +- src/agentic_cli/workflow/adk/manager.py | 30 +++-- src/agentic_cli/workflow/agents/brief.py | 3 +- src/agentic_cli/workflow/agents/control.py | 18 ++- src/agentic_cli/workflow/agents/delegate.py | 79 ++++++++++-- src/agentic_cli/workflow/base_manager.py | 14 +- src/agentic_cli/workflow/config.py | 4 +- src/agentic_cli/workflow/events.py | 4 +- src/agentic_cli/workflow/model_services.py | 8 +- tests/cli/test_agent_view.py | 1 + tests/cli/test_agents_command.py | 1 + tests/test_config.py | 1 + tests/workflow/adk/test_plugin_chain.py | 1 + tests/workflow/deepagents/test_skills.py | 1 + tests/workflow/test_adk_mcp_lifecycle.py | 121 ++++++++++++++++++ tests/workflow/test_agent_brief.py | 1 + tests/workflow/test_agent_control.py | 18 +++ tests/workflow/test_agent_delegate.py | 108 ++++++++++++++++ tests/workflow/test_agent_loader.py | 1 + tests/workflow/test_agent_run_event.py | 1 + tests/workflow/test_agent_runs.py | 2 + .../workflow/test_budgets_before_services.py | 1 + tests/workflow/test_manager_models.py | 31 +++++ tests/workflow/test_model_services.py | 1 + tests/workflow/test_skills.py | 1 + tests/workflow/test_subagent_config.py | 1 + tests/workflow/test_subagents_contract.py | 3 + 30 files changed, 435 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fba21bac..0229dede 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -610,7 +610,9 @@ the start of the entry's title. else is the call's error result, and no run starts nor counts toward the turn's ("The tools for 'researcher' must be some of its own: lookup.", "The model for 'researcher' must be one of its model choices: fast.", - "'researcher' has no model choices; leave model out."). `task`'s schema + "'researcher' has no model choices; leave model out."; a backend that + cannot list the type's MCP tools just now says so, "The tools of + 'researcher' could not be listed just now (OSError: …); try again."). `task`'s schema always has `tools` (with the default policy it is otherwise as it was), and `model` when a type it offers has choices, which its line names (`- researcher (model choices: fast): …`). The instance keeps them @@ -630,7 +632,8 @@ the start of the entry's title. default, for a type only its parent starts) and the policy's `spawn_sources` (the same three, `frozenset()` by default: nothing is started at run time, and an app keeps its `task` as it was, but for the - `tools` argument every call has: see **`task`'s `tools` and `model`…**). An agent's `task` call is the `"agent"` source: `task` lists, after + `tools` argument every call has: see **`task`'s `tools` and `model`…**). + An agent's `task` call is the `"agent"` source: `task` lists, after the caller's own sub-agents, the types agents may start, each with its description (`agentic_cli.workflow.agents.spawn`, provisional: `spawnable`, `may_spawn`, `can_have_children`; the manager's delegations' diff --git a/CLAUDE.md b/CLAUDE.md index 9400f507..d00c6883 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,7 +51,7 @@ agentic-cli/ │ │ ├── waiting_jobs.py # Which finished jobs wait to be told in the open conversation: one rule (JobRecord.awaiting_resume, then its own, no conversation's, or a gone conversation's: can_resume, then the other installed backends' readers, opens_anywhere: one another backend keeps is not gone, its job waits for it) for the deliveries, ↻N and the startup line │ │ └── usage_tracker.py # Token usage / status bar: ctx = the main agent's last prompt over its context_trigger (a call with a purpose, a sub-agent's, a summary's or a side call's, never moves it); the token segment the open conversation's total, every call of its turns; format_usage: /status's rows by agent and /agents <id>'s tokens by model │ ├── workflow/ -│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none), and _agent_tool_names, what a task call's tools may name (the agent's own tools by the names its model sees, KEPT_TOOLS left out; the base's: its configured tools; ADK and Deep Agents add MCP and skill tools); _run_models: a run's maps of each agent's model and numbers, its type's its model choice's when it runs on one; the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', each config's model_choices as its model would be, with its model_settings, into _choice_models by (agent, choice), choice_models, then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built, and _compute_choice_budgets (each model choice's, context_budget(agent, model=choice)): each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) +│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none), and _agent_tool_names, what a task call's tools may name (the agent's own tools by the names its model sees, KEPT_TOOLS left out; the base's: its configured tools; ADK and Deep Agents add MCP and skill tools; ADK raises delegate.ToolsUnlistedError for a toolset it could not list, which Delegations answers TOOLS_UNLISTED_ERROR); _run_models: a run's maps of each agent's model and numbers, its type's its model choice's when it runs on one; the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', each config's model_choices as its model would be, with its model_settings, into _choice_models by (agent, choice), choice_models, then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built, and _compute_choice_budgets (each model choice's, context_budget(agent, model=choice)): each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) │ │ ├── factory.py # create_workflow_manager_from_settings (_BACKENDS: orchestrator → "module:Class" + extra, imported when chosen; orchestrator=: another backend than the settings'; session_store=: the store a manager is built for, BaseWorkflowManager.session_store, the settings' by default; subagents=: the SubAgentPolicy the manager gets, checked before a backend is imported); orchestrator_of; check_backend (an unknown name, a missing extra) │ │ ├── session_readers.py # SessionReader: a backend's stored conversations read without its manager (list/info/exists/delete/aclose, rows naming the backend; delete deletes what the manager's does, ADK's sub-agent transcripts and records with the conversation), opened from the settings and a store (open_session_reader: the backend's own session code, adk/sessions.py::open_sessions and deepagents/sessions.py::open_sessions, imported on a worker thread; no agents, models or services; a sqlite store not made yet reads empty and is not made, Deep Agents not even imported for it; a database without its backend's tables, looked at read-only, reads empty, nothing written to it: no table, no journal mode); none for the memory store or LangGraph; ImportError (the install hint) for a missing extra; reader_backends │ │ ├── service_registry.py # get_service/require_service + ContextVar registry; the registry keys and KNOWN_SERVICE_KEYS, read from services.py's table diff --git a/src/agentic_cli/cli/agent_view.py b/src/agentic_cli/cli/agent_view.py index f10e4952..cecb2899 100644 --- a/src/agentic_cli/cli/agent_view.py +++ b/src/agentic_cli/cli/agent_view.py @@ -505,7 +505,10 @@ def _model(workflow: Any, record: "InstanceRecord") -> Any: def _budget(workflow: Any, record: "InstanceRecord") -> Any: - """The instance's context budget (its model choice's, when it has one); None when its manager manages none.""" + """The instance's context budget (its model choice's, when it has one). + + None when its manager manages none. + """ try: if record.model is not None: return workflow.context_budget(record.agent, model=record.model) @@ -528,7 +531,8 @@ def _last_prompt(workflow: Any, conversation: "SessionRef", record: "InstanceRec def _context(workflow: Any, conversation: "SessionRef", record: "InstanceRecord") -> str: """The status bar's ``ctx`` for the instance: its last prompt against its - own trigger (its model choice's, when it has one), as the main agent's is shown (``UsageTracker.format_context``).""" + own trigger (its model choice's, when it has one), as the main agent's is + shown (``UsageTracker.format_context``).""" budget = _budget(workflow, record) return UsageTracker( last_prompt_tokens=_last_prompt(workflow, conversation, record), diff --git a/src/agentic_cli/config.py b/src/agentic_cli/config.py index 615dcbd0..37d84605 100644 --- a/src/agentic_cli/config.py +++ b/src/agentic_cli/config.py @@ -339,8 +339,8 @@ def validate_settings( The static half of model validation: - every reference parses: ``default_model``, ``model_roles`` and each - agent's ``model`` and each of its ``model_choices`` (a role must map to a model, never another role); - ``models`` keys are checked when the settings load; + agent's ``model`` and each of its ``model_choices`` (a role must map to + a model, never another role); ``models`` keys are checked when the settings load; - every provider a reference names is built in or defined in ``model_providers``; - every provider a model will run on can be called: the default model's, diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index 4446ff75..7053d0a0 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -84,7 +84,13 @@ from agentic_cli.workflow.adk.task_tool import SHARED_KEYS, TaskTool, follow_up_tools from agentic_cli.workflow.adk.tool_result_cap_plugin import ToolResultCapPlugin from agentic_cli.workflow.agents.control import KEPT_TOOLS -from agentic_cli.workflow.agents.delegate import AgentRun, RunAnswer, RunFailed, failure_reason +from agentic_cli.workflow.agents.delegate import ( + AgentRun, + RunAnswer, + RunFailed, + ToolsUnlistedError, + failure_reason, +) from agentic_cli.workflow.agents.runs import own_plan_and_tasks from agentic_cli.workflow.agents.spawn import can_have_children from agentic_cli.workflow.context import OVERFLOW_ERROR_CODE @@ -315,6 +321,8 @@ def __init__( # The model choice each working run on one is on, by (conversation, # run id): what the raw log names the run's calls by (``_chosen_model``). + # Keyed by the conversation too: a RunRef does not name it, and run ids + # (``researcher-1#1``) repeat across conversations. self._chosen_runs: dict[tuple["SessionRef | None", str], "ResolvedModel"] = {} logger.debug( @@ -364,8 +372,14 @@ async def _agent_tool_names(self, agent: str) -> frozenset[str]: Its tools as its model sees them (callables, ADK tools, a skill toolset's tools) and each MCP toolset's, which ADK lists by connecting: done when first asked, once a build (the toolset stays connected for the - agent's runs, and its runner stops it). A listing that fails is logged - and asked again next time. The state and delegation tools are left out. + agent's runs, and its runner stops it; for a narrowed run on a model + choice that is one more idle connection, the type's own, until the + release). The state and delegation tools are left out. + + Raises: + ToolsUnlistedError: A toolset's listing failed (logged, and + listed again at the next ask): its names left out would read + as tools the type lacks. """ built = self._agents.get(agent) if built is None: @@ -384,7 +398,7 @@ async def _agent_tool_names(self, agent: str) -> frozenset[str]: found = {t.name for t in await tool.get_tools_with_prefix()} except Exception as exc: # noqa: BLE001 - a server that will not list logger.warning("mcp_tools_unlisted", agent=agent, error=str(exc)) - continue + raise ToolsUnlistedError(agent, exc) from exc # The toolset is kept with its names: its id is only its own while it lives. kept = listed[id(tool)] = (tool, found) names |= kept[1] @@ -923,10 +937,10 @@ def _chain( reply_agents=replies, budgets=budgets, kinds=kinds, - models=( - self._agent_model_refs() if models is self._resolved_models - else {name: str(model.ref) for name, model in models.items()} - ), + models={ + **self._agent_model_refs(), + **{name: str(model.ref) for name, model in models.items()}, + }, summarize_now=self._summarize_now, fit_guard=fit_guard, keep_task=keep_task, diff --git a/src/agentic_cli/workflow/agents/brief.py b/src/agentic_cli/workflow/agents/brief.py index a13bbd2d..30bf4e56 100644 --- a/src/agentic_cli/workflow/agents/brief.py +++ b/src/agentic_cli/workflow/agents/brief.py @@ -460,7 +460,8 @@ def _type_line(name: str, config: AgentConfig, *, warn: bool = False) -> str: The notes say that an inheriting type sees the caller's conversation and which brief fields the type needs beyond the title and the objective, and - names its model choices, last. A type without a description is "The <name> agent.", logged when ``warn``. + names its model choices, last. A type without a description is "The <name> + agent.", logged when ``warn``. """ description = config.description.strip() if not description: diff --git a/src/agentic_cli/workflow/agents/control.py b/src/agentic_cli/workflow/agents/control.py index 66accceb..c1dad796 100644 --- a/src/agentic_cli/workflow/agents/control.py +++ b/src/agentic_cli/workflow/agents/control.py @@ -45,7 +45,7 @@ from __future__ import annotations import asyncio -from collections.abc import Callable, Iterator +from collections.abc import Callable, Iterable, Iterator from contextlib import contextmanager from typing import TYPE_CHECKING, Any @@ -72,6 +72,22 @@ "save_plan", "get_plan", "save_tasks", "get_tasks", "task", "message_agent", "stop_agent", "check_agents", }) + + +def configured_tool_names(tools: Iterable[Any]) -> frozenset[str]: + """The names a type's configured tools go by, ``KEPT_TOOLS`` left out. + + A callable by its ``__name__``, a registered name as written and a dotted + import path by its last part (what the callable it imports is called); the + one rule for ``Delegations`` and for a manager's ``_agent_tool_names``. + """ + names = ( + tool.strip().rsplit(".", 1)[-1] if isinstance(tool, str) else getattr(tool, "__name__", "") + for tool in tools + ) + return frozenset(name for name in names if name and name not in KEPT_TOOLS) + + #: Who cancels a run at one of its limits. LIMIT = "limit" #: What stopped a run, as a call it left at its prompt is told. diff --git a/src/agentic_cli/workflow/agents/delegate.py b/src/agentic_cli/workflow/agents/delegate.py index d94c7c1c..7ff6695e 100644 --- a/src/agentic_cli/workflow/agents/delegate.py +++ b/src/agentic_cli/workflow/agents/delegate.py @@ -142,7 +142,7 @@ task_message, task_offer, ) -from agentic_cli.workflow.agents.control import KEPT_TOOLS, PARENT_CAUSE, RunControl +from agentic_cli.workflow.agents.control import PARENT_CAUSE, RunControl, configured_tool_names from agentic_cli.workflow.agents.envelope import ( CANCELLED_BY, INTERRUPTED_ERROR, @@ -224,6 +224,10 @@ STOPPED_ERROR = "{instance} was stopped by the user; only the user can continue it." RUNNING_ERROR = "{instance} is running: an instance runs one run at a time." TYPE_GONE_ERROR = "{instance}'s type '{agent}' is not one of this app's agents." +#: What a call is told when its backend could not list the type's tools just now. +TOOLS_UNLISTED_ERROR = ( + "The tools of '{agent_type}' could not be listed just now ({error}); try again." +) #: A follow-up to an instance started with a model or tools its type no longer has #: (``what``: ``the model <m>`` or ``the tools <a>, <b>``). CHOICE_GONE_ERROR = ( @@ -259,6 +263,23 @@ _OPEN = frozenset({INSTANCE_IDLE, INSTANCE_STOPPED}) +class ToolsUnlistedError(Exception): + """A backend's ``tool_names`` hook could not list a type's tools (an MCP server's, say). + + Raised instead of answering with the names without them, which would read + as tools the type lacks; asking again lists again. + + Attributes: + agent: The type. + reason: ``<Type>: <message>`` of what failed, cut to 200 characters. + """ + + def __init__(self, agent: str, cause: BaseException) -> None: + self.agent = agent + self.reason = truncate(f"{type(cause).__name__}: {cause}", 200) + super().__init__(f"The tools of {agent!r} could not be listed: {self.reason}") + + def started_by(caller: RunRef | None) -> str: """Who starts a run its parent delegated: ``agent:<the caller's instance>``. @@ -267,6 +288,10 @@ def started_by(caller: RunRef | None) -> str: return f"agent:{caller.instance if caller is not None else 'root'}" +#: ``follow_up``'s ``_own`` when ``message`` has not asked for the tool names (None is an answer). +_UNFETCHED = object() + + def _refused(error: str) -> Delegated: """The error result of a call that starts no run and steers none.""" return Delegated(result={"success": False, "error": error}, state={}, run=None) @@ -768,7 +793,11 @@ async def start(self, request: StartRequest) -> Delegated: ) async def follow_up( - self, request: FollowUpRequest, *, _reserved: list[bool] | None = None + self, + request: FollowUpRequest, + *, + _reserved: list[bool] | None = None, + _own: "frozenset[str] | None | object" = _UNFETCHED, ) -> Delegated: """Run the instance ``request`` names once more, to its end; its envelope. @@ -786,13 +815,21 @@ async def follow_up( tools is refused (``CHOICE_GONE_ERROR``). Everything up to the run's start event is one synchronous step, so two follow-ups of one instance cannot both start: the type's tool names a narrowed instance - is checked against are awaited before it, which suspends only where - a backend lists them for the first time. + is checked against are awaited before it (once: ``message`` hands over + the names it asked for, ``_own``), which suspends only where a + backend lists them for the first time. Tools its backend could not + list just now are the error result, as any refusal. """ conversation = ( request.conversation if request.conversation is not None else get_active_turn() ) - own = await self._instance_tools(conversation, request.instance) + try: + own = ( + await self._instance_tools(conversation, request.instance) + if _own is _UNFETCHED else _own + ) + except BriefError as error: + return _refused(str(error)) with _as_turn(conversation): error = self._follow_up_refused(conversation, request, own_tools=own) if error is not None: @@ -889,13 +926,16 @@ async def message( conversation = ( request.conversation if request.conversation is not None else get_active_turn() ) - own = await self._instance_tools(conversation, request.instance) + try: + own = await self._instance_tools(conversation, request.instance) + except BriefError as error: + return _refused(str(error)) with _as_turn(conversation): if not isinstance(request.message, str) or not request.message.strip(): return _refused(MESSAGE_NEEDED_ERROR) control = self._working_control(conversation, request) if control is None: - return await self.follow_up(request, _reserved=_reserved) + return await self.follow_up(request, _reserved=_reserved, _own=own) ref = control.ref if (conversation, ref.instance) in self._closing: return _refused(CLOSED_ERROR.format(instance=ref.instance)) @@ -1321,14 +1361,22 @@ def _follow_up_refused( return None async def _own_tools(self, config: AgentConfig) -> Collection[str]: - """The names of ``config``'s own tools: its backend's, else its configured tools'.""" - if self._tool_names is not None: + """The names of ``config``'s own tools: its backend's, else its configured tools'. + + The one place the backend's hook is asked. + + Raises: + BriefError: The backend could not list them just now + (``ToolsUnlistedError``): the text is the call's error result. + """ + if self._tool_names is None: + return configured_tool_names(config.tools) + try: return await self._tool_names(config.name) - names = ( - tool if isinstance(tool, str) else getattr(tool, "__name__", "") - for tool in config.tools - ) - return frozenset(name for name in names if name and name not in KEPT_TOOLS) + except ToolsUnlistedError as error: + raise BriefError( + TOOLS_UNLISTED_ERROR.format(agent_type=config.name, error=error.reason) + ) from error async def _instance_tools( self, conversation: SessionRef | None, instance: str @@ -1338,6 +1386,9 @@ async def _instance_tools( What a follow-up checks the instance's tools against. Awaited before the follow-up's synchronous step, and only for an instance that has tools to check, so any other never waits. + + Raises: + BriefError: The backend could not list them just now. """ record = self._runs.instance(conversation, instance) if record is None or record.tools is None: diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index fa1352d8..21c437fc 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -51,7 +51,7 @@ ) from agentic_cli.workflow import live_events from agentic_cli.workflow.config import AgentConfig -from agentic_cli.workflow.agents.control import KEPT_TOOLS +from agentic_cli.workflow.agents.control import configured_tool_names from agentic_cli.workflow.agents.delegate import ( STOPPED_BY_USER_ERROR, USER, @@ -1270,8 +1270,7 @@ async def _agent_tool_names(self, agent: str) -> frozenset[str]: config = next((c for c in self._agent_configs if c.name == agent), None) if config is None: return frozenset() - names = (getattr(tool, "__name__", "") for tool in self._build_tools(config, {})) - return frozenset(name for name in names if name and name not in KEPT_TOOLS) + return configured_tool_names(self._build_tools(config, {})) @property def settings(self) -> "BaseSettings": @@ -2608,7 +2607,9 @@ def _compute_budgets(self) -> "dict[str, ContextBudget]": } def _compute_choice_budgets(self) -> "dict[tuple[str, str], ContextBudget]": - """Each model choice's context numbers, by ``(agent, choice)``; none for a backend that manages none. + """Each model choice's context numbers, by ``(agent, choice)``. + + None for a backend that manages none. Called right after ``_compute_budgets``, with the same failure: a choice whose model leaves too small an input budget to work in. @@ -2714,7 +2715,10 @@ def _resolve_models(self, providers: Mapping[str, Provider]) -> None: "models_resolved", default=str(default.ref), agents={name: str(model.ref) for name, model in resolved.items()}, - choices={f"{name}/{choice}": str(model.ref) for (name, choice), model in choices.items()}, + choices={ + f"{name}/{choice}": str(model.ref) + for (name, choice), model in choices.items() + }, ) def _resolve_extra_models( diff --git a/src/agentic_cli/workflow/config.py b/src/agentic_cli/workflow/config.py index d399f794..ba840526 100644 --- a/src/agentic_cli/workflow/config.py +++ b/src/agentic_cli/workflow/config.py @@ -459,7 +459,9 @@ def _check_inherit_context(config_map: dict[str, AgentConfig], root: str) -> Non def _check_delegation_fields(config_map: dict[str, AgentConfig], root: str) -> None: - """Each agent's ``brief_required``, ``limits``, ``continuable`` and ``model_choices`` are what they say, and the root sets none. + """Each agent's delegation fields are what they say, and the root sets none. + + ``brief_required``, ``limits``, ``continuable`` and ``model_choices``. Raises: AgentGraphError: Naming the agent(s), the value and what to change. diff --git a/src/agentic_cli/workflow/events.py b/src/agentic_cli/workflow/events.py index 9d2cfd33..a1109e40 100644 --- a/src/agentic_cli/workflow/events.py +++ b/src/agentic_cli/workflow/events.py @@ -224,8 +224,8 @@ def agent_run( ``started`` (with its ``title``, its ``brief``, who it was ``started_by`` and its ``mode``; a first run of an instance also says whether the instance ``inherit_context`` and is ``continuable``, - and the ``tools`` and ``model`` its delegation gave it; a follow-up's start carries its ``input``, the message as - written), then one end status (``completed``, + and the ``tools`` and ``model`` its delegation gave it; a follow-up's + start carries its ``input``, the message as written), then one end status (``completed``, ``failed``, ``refused``, ``cancelled``, ``interrupted``: the constants of ``workflow/agents/runs.py``) with the first of its ``result``, its ``error``, whether the result is ``partial``, the tokens the run diff --git a/src/agentic_cli/workflow/model_services.py b/src/agentic_cli/workflow/model_services.py index dc66cb59..5522f152 100644 --- a/src/agentic_cli/workflow/model_services.py +++ b/src/agentic_cli/workflow/model_services.py @@ -146,7 +146,8 @@ def model_references( In order: the manager's own model (``manager_model``), ``default_model``, each ``model_roles`` value (so the model of each mapped role an agent names), then each agent's model that is a reference or a bare model id, - and each of its model choices that is one. One that does not parse is left out: validation reports it. + and each of its model choices that is one. One that does not parse is left + out: validation reports it. """ return tuple(_named_references(settings, agent_configs, manager_model)) @@ -223,7 +224,10 @@ def computed_roles( def _agent_models(agent_configs: Iterable["AgentConfig"]) -> list[ModelRef | RoleRef]: - """Each agent's model that names one (None runs on the default), then its choices; those that parse.""" + """Each agent's model that names one (None runs on the default), then its choices. + + Those that parse. + """ models: list[ModelRef | RoleRef] = [] for config in agent_configs: model = _agent_model(config) diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index f41fe33e..bcd70e8e 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -575,6 +575,7 @@ async def test_after_a_restart_its_view_and_panel_say_so(self, make_crew): SMALL_MODEL, format_tokens(budget.trigger) ) + class TestOffTheLoop: async def test_it_blocks_no_event_loop(self, make_crew): crew = make_crew( diff --git a/tests/cli/test_agents_command.py b/tests/cli/test_agents_command.py index 29b851dd..6b04f856 100644 --- a/tests/cli/test_agents_command.py +++ b/tests/cli/test_agents_command.py @@ -269,6 +269,7 @@ async def test_an_instances_model_choice_and_narrowed_tools_after_its_title( assert rows_of(panel.renderable)[:3 + len(shown)] == [ ("Type", "researcher"), ("Parent", "root"), ("Title", "Find X."), *shown, ] + async def test_a_runs_own_plan_and_tasks_after_its_result(self, manager): runs = Runs(manager, manager.session_ref("s1")) ref = runs.start("researcher", "c1", "Find X.", at=0) diff --git a/tests/test_config.py b/tests/test_config.py index 94766413..cbb06caf 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -682,6 +682,7 @@ def test_a_computed_role_choice_needs_a_tier(self, temp_workspace: Path, monkeyp "Anthropic or OpenAI key (GOOGLE_API_KEY, ANTHROPIC_API_KEY, OPENAI_API_KEY) so " "the newest fast-tier model is used.", ] + def test_a_malformed_agent_model_is_an_error(self, temp_workspace: Path): settings = self._settings(temp_workspace, {"GOOGLE_API_KEY": "test-key"}) agents = [AgentConfig(name="writer", prompt="p", model="gemini")] diff --git a/tests/workflow/adk/test_plugin_chain.py b/tests/workflow/adk/test_plugin_chain.py index 5612a44c..959a68c4 100644 --- a/tests/workflow/adk/test_plugin_chain.py +++ b/tests/workflow/adk/test_plugin_chain.py @@ -221,6 +221,7 @@ async def test_a_model_choices_runner_has_its_types_chain_on_the_choices_numbers assert (manager._variant_runners, manager._variant_agents) == ({}, {}) + async def test_a_main_agent_that_continues_its_sub_agents_gets_the_roster(project): """With the policy's ``follow_ups`` the main agent has ``message_agent``: its chain carries the roster, before the memory index; a sub-agent type's diff --git a/tests/workflow/deepagents/test_skills.py b/tests/workflow/deepagents/test_skills.py index edbcc8a9..c9bbaedb 100644 --- a/tests/workflow/deepagents/test_skills.py +++ b/tests/workflow/deepagents/test_skills.py @@ -751,6 +751,7 @@ async def call_tool(**arguments): finally: await manager.cleanup() assert manager._own_tool_names == {} + async def test_a_model_switch_rebuilds_them(self, ctx, monkeypatch): models = scripted(monkeypatch, writer=_steps(("load_skill", {"skill_name": "pdf-tools"}))) manager = _manager(ctx.settings, [_writer()]) diff --git a/tests/workflow/test_adk_mcp_lifecycle.py b/tests/workflow/test_adk_mcp_lifecycle.py index 2a7c3611..98905a40 100644 --- a/tests/workflow/test_adk_mcp_lifecycle.py +++ b/tests/workflow/test_adk_mcp_lifecycle.py @@ -28,6 +28,18 @@ from tests.loop_guard import no_blocking_calls # noqa: E402 from tests.workflow.adk.fakes import FakeAPI, anthropic_message # noqa: E402 from tests.workflow.test_manager_models import route # noqa: E402 +from tests.workflow.test_subagents_contract import ( # noqa: E402,F401 - fixtures + CHOICE, + FOLLOWING, + agent, + backend, + calls, + delegate, + envelope_read, + make_crew, + message, + says, +) #: The stdio MCP server the Deep Agents tests start; it records its pid. SERVER = Path(__file__).parent / "deepagents" / "mcp_server.py" @@ -132,6 +144,73 @@ async def test_a_sub_agents_mcp_tools_are_listed_when_first_asked_and_stop_with_ assert alive(pid_dir) == [], "a server outlived cleanup()" + +async def test_a_listing_that_fails_is_said_so_and_asked_again( + project, pid_dir, monkeypatch +): + """A toolset whose listing fails does not leave its names out of the answer + (the type would seem to lack them): the manager raises, and the next ask lists + again. A ``task`` call naming tools is told to try again, no run started.""" + from google.adk.tools.mcp_tool.mcp_toolset import McpToolset + + from agentic_cli.workflow.agents.delegate import ( + DelegationRequest, + ToolsUnlistedError, + ) + from agentic_cli.workflow.sessions import SessionRef, reset_active_turn, set_active_turn + + route(monkeypatch, anthropic, "AsyncAnthropic", + FakeAPI(anthropic_message({"type": "text", "text": "ok"}))) + server = MCPServerConfig( + name="atlas", command=sys.executable, args=[str(SERVER)], timeout=30, + env={"MCP_TEST_PID_DIR": str(pid_dir)}, tool_name_prefix="atlas", + ) + manager = GoogleADKWorkflowManager( + agent_configs=[ + AgentConfig(name="lead", prompt="Lead.", sub_agents=["researcher"]), + AgentConfig(name="researcher", prompt="Find.", description="Finds.", + mcp_servers=[server]), + ], + settings=BaseSettings(session_store="memory", default_model="claude-sonnet-4-6"), + ) + real = McpToolset.get_tools_with_prefix + failing = [True] + + async def listing(self, *args, **kwargs): + if failing[0]: + raise OSError("the server is down") + return await real(self, *args, **kwargs) + + monkeypatch.setattr(McpToolset, "get_tools_with_prefix", listing) + try: + await manager.initialize_services() + + with pytest.raises(ToolsUnlistedError) as caught: + await manager._agent_tool_names("researcher") + assert caught.value.reason == "OSError: the server is down" + + conversation = SessionRef(manager.app_name, "u", "s") + token = set_active_turn(conversation) + try: + refused = await manager._delegations.delegate(DelegationRequest( + caller=None, caller_agent="lead", call_id="c1", + arguments={"agent_type": "researcher", "title": "T", "objective": "O", + "tools": ["atlas_lookup"]}, + )) + finally: + reset_active_turn(token) + assert refused.result == {"success": False, "error": ( + "The tools of 'researcher' could not be listed just now " + "(OSError: the server is down); try again." + )} + assert refused.run is None + + failing[0] = False + assert await manager._agent_tool_names("researcher") == {"atlas_add", "atlas_lookup"} + finally: + await manager.cleanup() + + async def test_a_native_apps_toolset_outlives_its_runner_and_serves_the_next( project, pid_dir, monkeypatch ): @@ -184,3 +263,45 @@ async def test_a_native_apps_toolset_outlives_its_runner_and_serves_the_next( assert alive(pid_dir) == [], "a server outlived cleanup()" tools = [sorted(t["name"] for t in json.loads(r.content).get("tools", [])) for r in api.requests] assert tools == [["add", "lookup"], ["add", "lookup"]] + + +async def test_a_model_choices_runner_is_released_with_the_backend( + make_crew, backend, pid_dir +): + """A sub-agent type with an MCP server and a model choice, run on the + choice: the release closes what the variant holds. ADK's variant has a + toolset (a server) of its own, stopped by a model switch and by cleanup + and started again by the next run; Deep Agents' variant graph is dropped + by the release, the manager's MCP sessions its tools.""" + server = MCPServerConfig( + name="atlas", command=sys.executable, args=[str(SERVER)], timeout=30, + env={"MCP_TEST_PID_DIR": str(pid_dir)}, tool_name_prefix="atlas", + ) + crew = make_crew( + [agent("coordinator", sub_agents=("researcher",)), + agent("researcher", mcp_servers=[server], model_choices=(CHOICE,))], + subagents=FOLLOWING, + coordinator=[calls(delegate("researcher", "Find X.", "c1", model=CHOICE)), + says("Asked."), + calls(message("researcher-1", "Now find Y.", "c2")), says("Done.")], + researcher=[says("X is 42."), says("Y is 7.")], + ) + manager = crew.manager + try: + await crew.turn() + assert alive(pid_dir) + assert len(manager._variant_graphs if backend == "deepagents" + else manager._variant_runners) == 1 + + await manager.reinitialize(model="claude-opus-4-7", preserve_sessions=True) + if backend == "adk": + assert alive(pid_dir) == [] # no runner of the old build is left open + await crew.turn("Find Y too.") + assert alive(pid_dir) + assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Y is 7." + finally: + await manager.cleanup() + + assert alive(pid_dir) == [], "a server outlived cleanup()" + assert getattr(manager, "_variant_graphs", {}) == {} + assert dict(getattr(manager, "_variant_runners", {})) == {} diff --git a/tests/workflow/test_agent_brief.py b/tests/workflow/test_agent_brief.py index 006fad86..cd200c0a 100644 --- a/tests/workflow/test_agent_brief.py +++ b/tests/workflow/test_agent_brief.py @@ -333,6 +333,7 @@ def test_a_types_model_choices_are_named_last_in_its_notes(self): "- checker (its brief also needs: known; model choices: fast, " "anthropic:claude-haiku-4-5): Checks a claim." ) + def test_an_inheriting_type_says_so(self): text = task_description({"notes": NOTES, "researcher": RESEARCHER}, SubAgentPolicy()) assert "- notes (sees this conversation, so the brief need not repeat it): " in text diff --git a/tests/workflow/test_agent_control.py b/tests/workflow/test_agent_control.py index 8bd6bae5..ac07512e 100644 --- a/tests/workflow/test_agent_control.py +++ b/tests/workflow/test_agent_control.py @@ -20,6 +20,7 @@ TIME_LIMIT_CAUSE, TOKEN_LIMIT_CAUSE, RunControl, + configured_tool_names, ) from agentic_cli.workflow.agents.envelope import TIME_LIMIT_ERROR, TOKEN_LIMIT_ERROR from agentic_cli.workflow.agents.policy import AgentLimits @@ -444,3 +445,20 @@ def test_every_run_keeps_the_state_tools_and_the_delegation_tools(self): assert KEPT_TOOLS == { *(name for name, _ in state_tools._STATE_TOOLS), TASK_TOOL, *FOLLOW_UP_TOOLS, } + + +class TestConfiguredToolNames: + """The names a type's configured tools go by: one rule for every caller.""" + + def test_a_name_a_dotted_path_and_a_callable_each_by_its_own(self): + def lookup(): + return {} + + names = configured_tool_names( + ["web_fetch", "my_pkg.tools.custom_tool", lookup, " padded "] + ) + + assert names == {"web_fetch", "custom_tool", "lookup", "padded"} + + def test_the_state_and_delegation_tools_are_left_out(self): + assert configured_tool_names(["save_plan", "task", "lookup", ""]) == {"lookup"} diff --git a/tests/workflow/test_agent_delegate.py b/tests/workflow/test_agent_delegate.py index dc21208d..fbd4920f 100644 --- a/tests/workflow/test_agent_delegate.py +++ b/tests/workflow/test_agent_delegate.py @@ -58,6 +58,7 @@ RunAnswer, RunFailed, StartRequest, + ToolsUnlistedError, started_by, waiting_on_user, ) @@ -3009,6 +3010,7 @@ def stop_result(agent: str, status: str, stopped: str | None, closed: list[str]) def with_a_leaf(made: Callable[[], Delegations], working: dict[str, asyncio.Event]) -> Hook: """A hook in which ``middle``'s first run delegates to ``leaf`` once; the runs named in ``working`` work until cancelled; any other answers.""" + async def hook(run: AgentRun) -> RunAnswer: if run.ref.run in working: working[run.ref.run].set() @@ -4111,6 +4113,7 @@ async def test_a_start_blocks_no_event_loop(): def own_tools(names: dict[str, set[str]], asked: list[str] | None = None): """A backend's hook for each type's own tools (``_agent_tool_names``), recording who asked.""" + async def tool_names(agent: str) -> frozenset[str]: if asked is not None: asked.append(agent) @@ -4307,3 +4310,108 @@ async def test_an_instance_not_narrowed_never_asks_for_the_tools(self): assert tools_asked == [] assert [run.model for run in asked] == ["fast", "fast"] + + async def test_the_model_is_checked_before_the_tools(self): + """An instance whose type lost its model choice and a tool is told of the model.""" + hook, asked = answering() + names = {"choosy": {"lookup", "fetch_page"}} + made = delegations(hook, types=CHOOSING, tool_names=own_tools(names)) + await turned(lambda: made.delegate(request({**NARROW, "tools": ["lookup"]}))) + made._types["choosy"] = AgentConfig(name="choosy", prompt="p", + model_choices=("anthropic:claude-haiku-4-5",)) + names["choosy"] = {"fetch_page"} + + result, _ = await turned(lambda: made.follow_up(follow("choosy-1"))) + + assert result.result["error"] == ( + "choosy-1 was started with the model fast, which 'choosy' no longer has; " + "start a new one with task." + ) + assert len(asked) == 1 + + async def test_two_messages_at_once_to_a_narrowed_one_start_one_run_and_steer_the_other(self): + """As for an instance not narrowed, though a narrowed one's tool names are + asked for first, and by a hook that suspends every time.""" + taken: list[list[str]] = [] + hook, asked = answering() + + async def watching(run: AgentRun) -> RunAnswer: + taken.append(run.control.take_steering()) + run.control.stored() + return await hook(run) + + names = own_tools(OWN) + + async def suspending(agent: str): + await asyncio.sleep(0) + return await names(agent) + + runs = AgentRuns() + made = delegations(watching, runs=runs, types=CHOOSING, tool_names=suspending) + + async def work(): + await made.delegate(request(NARROW)) + return await asyncio.gather( + made.message(follow("choosy-1", "Find Y.", call_id="c2")), + made.message(follow("choosy-1", "Find Z.", call_id="c3")), + ) + + (first, second), _ = await turned(work) + + assert (first.result["run"], first.result["status"]) == ("choosy-1#2", RUN_COMPLETED) + assert second.result["status"] == "running" and second.result["run"] == "choosy-1#2" + assert [r.ref.run for r in runs.records(CONVERSATION)] == ["choosy-1#1", "choosy-1#2"] + + +UNLISTED = ("The tools of 'choosy' could not be listed just now " + "(OSError: the server is down); try again.") + + +def unlisting(agent: str, *, fail: list[bool]): + """A tool-names hook whose listing fails while ``fail[0]`` holds.""" + + async def tool_names(name: str) -> frozenset[str]: + if fail[0]: + raise ToolsUnlistedError(agent, OSError("the server is down")) + return frozenset(OWN.get(name, ())) + + return tool_names + + +class TestAListingThatFails: + """A backend that cannot list a type's tools says so: the call's error + result, no run started and none counted, and the next ask lists again.""" + + async def test_a_task_call_naming_tools_is_told_to_try_again(self): + hook, asked = answering() + fail = [True] + made = delegations(hook, types=CHOOSING, tool_names=unlisting("choosy", fail=fail)) + + async def work(): + refused = await made.delegate(request(NARROW)) + return refused, runs_this_turn() + + (result, counted), events = await turned(work) + + assert result.result == {"success": False, "error": UNLISTED} + assert (counted, events, asked) == (0, [], []) + fail[0] = False + result, _ = await turned(lambda: made.delegate(request(NARROW))) + assert result.result["status"] == RUN_COMPLETED + + @pytest.mark.parametrize("how", ["follow_up", "message"]) + async def test_a_narrowed_ones_follow_up_is_told_so(self, how): + hook, asked = answering() + fail = [False] + made = delegations(hook, types=CHOOSING, tool_names=unlisting("choosy", fail=fail)) + await turned(lambda: made.delegate(request(NARROW))) + fail[0] = True + + result, events = await turned(lambda: getattr(made, how)(follow("choosy-1"))) + + assert result.result == {"success": False, "error": UNLISTED} + assert (events, len(asked)) == ([], 1) + + def test_the_cause_is_cut_to_200_characters(self): + error = ToolsUnlistedError("choosy", ValueError("x" * 500)) + assert len(error.reason) <= 203 and error.reason.startswith("ValueError: xxx") diff --git a/tests/workflow/test_agent_loader.py b/tests/workflow/test_agent_loader.py index f6e06aab..572a68c6 100644 --- a/tests/workflow/test_agent_loader.py +++ b/tests/workflow/test_agent_loader.py @@ -319,6 +319,7 @@ def test_model_choices_is_a_list(self, tmp_path): load_agents_from_yaml(path) message = str(exc.value) assert "agents.0.model_choices" in message and "valid list" in message + def test_brief_required_is_a_list(self, tmp_path): path = _write( tmp_path, diff --git a/tests/workflow/test_agent_run_event.py b/tests/workflow/test_agent_run_event.py index b5c5e077..c116011a 100644 --- a/tests/workflow/test_agent_run_event.py +++ b/tests/workflow/test_agent_run_event.py @@ -107,6 +107,7 @@ def test_no_tools_or_model_unless_given(self): event = WorkflowEvent.agent_run(RESEARCHER, "started", title="Find X.") assert "tools" not in event.metadata and "model" not in event.metadata + def test_a_follow_ups_start_carries_its_input(self): second = RunRef("researcher", "researcher-1", "researcher-1#2", None, 1) diff --git a/tests/workflow/test_agent_runs.py b/tests/workflow/test_agent_runs.py index e9ac23fe..c6b4b6a2 100644 --- a/tests/workflow/test_agent_runs.py +++ b/tests/workflow/test_agent_runs.py @@ -471,6 +471,7 @@ def test_a_follow_ups_start_changes_neither(self): record = runs.instance(ONE, "researcher-1") assert (record.tools, record.model) == ((), "fast") + def test_a_childs_parent_is_its_parent_runs_instance(self): runs = AgentRuns() middle = started(runs, ONE, "c1", "middle") @@ -915,6 +916,7 @@ def test_tools_or_a_model_that_do_not_read_are_records_it_cannot_read(self, fiel with pytest.raises(ValueError, match="do not read"): AgentRuns().restore(ONE, data) + def test_the_instances_records_name(self): runs = AgentRuns() a_conversation(runs) diff --git a/tests/workflow/test_budgets_before_services.py b/tests/workflow/test_budgets_before_services.py index 171a68b4..c378cac3 100644 --- a/tests/workflow/test_budgets_before_services.py +++ b/tests/workflow/test_budgets_before_services.py @@ -206,6 +206,7 @@ async def test_a_choice_s_numbers_are_its_model_s(self, ctx, path, store_opener) await manager.cleanup() assert manager._choice_budgets == {} + class TestANativeAdkApp: async def test_the_configs_the_factory_passes_through_are_ignored(self, ctx, tmp_path): # ``create_workflow_manager_from_settings`` hands a native app's configs to diff --git a/tests/workflow/test_manager_models.py b/tests/workflow/test_manager_models.py index 589272e2..c2159359 100644 --- a/tests/workflow/test_manager_models.py +++ b/tests/workflow/test_manager_models.py @@ -1284,3 +1284,34 @@ async def ticker(): await manager.cleanup() assert ticks >= 5 + + +async def test_the_base_names_a_configured_types_tools_as_its_delegations_do(providers): + """``_agent_tool_names`` before a backend builds anything: a registered name, a + dotted path and a callable are named alike by the manager and by a + ``Delegations`` with no backend hook; the plan's tools are left out.""" + from types import SimpleNamespace + + from agentic_cli.tools import read_file + from agentic_cli.workflow.agents.delegate import Delegations + + configs = [ + AgentConfig(name="coordinator", prompt="p", sub_agents=["writer"]), + AgentConfig(name="writer", prompt="p", tools=[ + read_file, "web_fetch", "agentic_cli.tools.glob_tool.glob", + ]), + ] + manager = adk(configs, settings()) + + names = await manager._agent_tool_names("writer") + + assert names == {"read_file", "web_fetch", "glob"} + assert await Delegations._own_tools( + SimpleNamespace(_tool_names=None), configs[1] + ) == names + assert await manager._agent_tool_names("nobody") == frozenset() + # The manager has resolved its configs' strings; a Delegations over raw ones names alike. + raw = AgentConfig(name="writer", prompt="p", tools=[ + "web_fetch", "agentic_cli.tools.glob_tool.glob", read_file, + ]) + assert await Delegations._own_tools(SimpleNamespace(_tool_names=None), raw) == names diff --git a/tests/workflow/test_model_services.py b/tests/workflow/test_model_services.py index 3f92f7db..361a499f 100644 --- a/tests/workflow/test_model_services.py +++ b/tests/workflow/test_model_services.py @@ -490,6 +490,7 @@ def test_a_role_choice_is_computed(): assert model_services.computed_roles(settings, agents) == ("fast",) + def test_model_references_skip_what_does_not_parse(): """Validation reports each of them, before any catalog is built.""" agents = _agents("x y", "Lab:qwen3", "lab:", "") diff --git a/tests/workflow/test_skills.py b/tests/workflow/test_skills.py index 05c73b13..15d3f742 100644 --- a/tests/workflow/test_skills.py +++ b/tests/workflow/test_skills.py @@ -216,6 +216,7 @@ async def test_a_task_may_narrow_a_sub_agent_to_its_skill_tools_and_its_own(self assert await mgr._agent_tool_names("nobody") == frozenset() finally: await mgr.cleanup() + def test_yaml_loader_parses_skills(self, tmp_path): from agentic_cli.workflow.agent_loader import load_agents_from_yaml diff --git a/tests/workflow/test_subagent_config.py b/tests/workflow/test_subagent_config.py index 258432e9..7baa7949 100644 --- a/tests/workflow/test_subagent_config.py +++ b/tests/workflow/test_subagent_config.py @@ -63,6 +63,7 @@ def test_they_follow_inherit_context(self): def test_no_model_choices_by_default(self): assert AgentConfig(name="a", prompt="p").model_choices == () + def test_only_its_parent_starts_it_by_default(self): assert AgentConfig(name="a", prompt="p").spawnable_by is None diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 7b422aef..e5cc959e 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -552,6 +552,7 @@ def sent_models(self, agent: str) -> list[str]: ADK each request's, Deep Agents the model each request's chat was built for.""" assert self._sent_models is not None return self._sent_models(agent) + def opening(self, agent: str, call: int = -1) -> list[str]: """The text blocks of the first user message ``agent``'s model request ``call`` held, in order: what opens its conversation (the main @@ -823,6 +824,7 @@ def _deepagents_crew( models.chats[name] = _team_chat()( label=chat.label, script=chat.script, summaries=summaries ) + def chat_for(resolved: Any, *, settings: Any, app_name: str) -> Any: # Each agent's chat, as built for this model: what its requests went to. chat = models(resolved, settings=settings, app_name=app_name) @@ -6585,6 +6587,7 @@ async def test_a_follow_up_keeps_them(self, make_crew): assert crew.tool_names("researcher", 1) == NARROWED assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Y is 7." + class TestWhatATypeCannotTake: """A ``task`` call whose ``tools`` are not some of the type's own, or whose ``model`` is none of its choices, is its error result naming what it may From a7cddc61455cecbd01e305e3e311d09841723a3c Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:43:07 -0500 Subject: [PATCH 11/11] Sub-agents: rewrap model choices' lines Line breaks only, in the lines this change added that ran past 88 columns: docstrings, comments, calls and imports. Long string literals a test compares are left as they are. --- CHANGELOG.md | 6 +- src/agentic_cli/cli/agent_view.py | 3 +- src/agentic_cli/cli/agents_command.py | 11 +- src/agentic_cli/config.py | 9 +- src/agentic_cli/workflow/adk/manager.py | 22 ++- .../workflow/adk/run_control_plugin.py | 4 +- src/agentic_cli/workflow/agents/brief.py | 11 +- src/agentic_cli/workflow/agents/control.py | 3 +- src/agentic_cli/workflow/agents/delegate.py | 22 ++- src/agentic_cli/workflow/agents/runs.py | 4 +- src/agentic_cli/workflow/base_manager.py | 9 +- .../workflow/deepagents/agent_builder.py | 12 +- .../workflow/deepagents/manager.py | 3 +- src/agentic_cli/workflow/events.py | 6 +- src/agentic_cli/workflow/model_services.py | 4 +- tests/cli/test_agent_view.py | 9 +- tests/cli/test_agents_command.py | 6 +- tests/test_config.py | 16 +- tests/workflow/adk/test_plugin_chain.py | 4 +- tests/workflow/adk/test_run_control_plugin.py | 14 +- .../workflow/deepagents/test_agent_builder.py | 12 +- .../deepagents/test_run_control_middleware.py | 13 +- tests/workflow/deepagents/test_skills.py | 3 +- tests/workflow/test_adk_mcp_lifecycle.py | 22 ++- tests/workflow/test_agent_brief.py | 19 ++- tests/workflow/test_agent_control.py | 6 +- tests/workflow/test_agent_delegate.py | 66 +++++--- tests/workflow/test_agent_loader.py | 3 +- tests/workflow/test_agent_run_event.py | 10 +- tests/workflow/test_agent_runs.py | 4 +- .../workflow/test_budgets_before_services.py | 3 +- tests/workflow/test_manager_models.py | 15 +- tests/workflow/test_model_services.py | 10 +- tests/workflow/test_skills.py | 7 +- tests/workflow/test_subagent_config.py | 18 +- tests/workflow/test_subagents_contract.py | 154 +++++++++++++----- 36 files changed, 383 insertions(+), 160 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0229dede..61fc94b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -612,9 +612,9 @@ the start of the entry's title. "The model for 'researcher' must be one of its model choices: fast.", "'researcher' has no model choices; leave model out."; a backend that cannot list the type's MCP tools just now says so, "The tools of - 'researcher' could not be listed just now (OSError: …); try again."). `task`'s schema - always has `tools` (with the default policy it is otherwise as it was), - and `model` when a type it offers has choices, which its line names + 'researcher' could not be listed just now (OSError: …); try again."). + `task`'s schema always has `tools` (with the default policy it is otherwise as + it was), and `model` when a type it offers has choices, which its line names (`- researcher (model choices: fast): …`). The instance keeps them (`InstanceRecord.tools`, `.model`, in the records beside the conversation; records written before them read as all the tools and the diff --git a/src/agentic_cli/cli/agent_view.py b/src/agentic_cli/cli/agent_view.py index cecb2899..44747da3 100644 --- a/src/agentic_cli/cli/agent_view.py +++ b/src/agentic_cli/cli/agent_view.py @@ -498,7 +498,8 @@ def _runs_of(workflow: Any, conversation: "SessionRef", instance: str) -> list[" def _model(workflow: Any, record: "InstanceRecord") -> Any: - """The model the instance runs on: its model choice's when it has one, else its type's.""" + """The model the instance runs on: its model choice's when it has one, else its + type's.""" if record.model is not None: return getattr(workflow, "choice_models", {}).get((record.agent, record.model)) return getattr(workflow, "agent_models", {}).get(record.agent) diff --git a/src/agentic_cli/cli/agents_command.py b/src/agentic_cli/cli/agents_command.py index 04a232f0..a796c882 100644 --- a/src/agentic_cli/cli/agents_command.py +++ b/src/agentic_cli/cli/agents_command.py @@ -7,9 +7,9 @@ nothing; ``/agents <id>`` shows one instance (``researcher-2``) or one run (``researcher-2#1``): its type, its parent, its title, the model choice it runs on and the tools its delegation narrowed it -to (when it was given any), then each run's status (while it works ``running``, ``queued`` waiting -for a free working slot, or ``needs you`` waiting on the user; a completion -cut at its output limit ``completed (partial)``) and how long it ran (or has +to (when it was given any), then each run's status (while it works ``running``, +``queued`` waiting for a free working slot, or ``needs you`` waiting on the user; a +completion cut at its output limit ``completed (partial)``) and how long it ran (or has been running), the fields of its brief its parent filled (its objective, deliverable, constraints, what was known, when it is done; a follow-up's message in their place), the first lines of its result, the plan and the @@ -255,7 +255,10 @@ def _workflow(app: Any) -> Any: def _one( - records: list["RunRecord"], ledger: "UsageLedger", *, instance: "InstanceRecord | None" = None + records: list["RunRecord"], + ledger: "UsageLedger", + *, + instance: "InstanceRecord | None" = None, ) -> Panel: """``/agents <id>``'s panel: one instance's runs (one run's, for a run id). diff --git a/src/agentic_cli/config.py b/src/agentic_cli/config.py index 37d84605..15c7998d 100644 --- a/src/agentic_cli/config.py +++ b/src/agentic_cli/config.py @@ -467,7 +467,10 @@ def setting(who: str, spec: str | None) -> ModelRef | None: choices = getattr(config, "model_choices", None) or () for who, spec, own in ( (f"Agent {name!r}", getattr(config, "model", None), True), - *((f"Agent {name!r} (model choice {choice!r})", choice, False) for choice in choices), + *( + (f"Agent {name!r} (model choice {choice!r})", choice, False) + for choice in choices + ), ): if not spec: continue @@ -481,7 +484,9 @@ def setting(who: str, spec: str | None) -> ModelRef | None: # from the catalog at startup. mapped = roles.spec_for(parsed.role) if roles is not None else None if mapped is not None and parsed.role != "default": - runs.append((f"{who} (role {parsed.role!r})" if own else who, mapped)) + runs.append( + (f"{who} (role {parsed.role!r})" if own else who, mapped) + ) continue named.append((who, parsed)) runs.append((who, parsed)) diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index 7053d0a0..9021c38d 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -367,7 +367,8 @@ async def generate_simple(self, prompt: str, max_tokens: int = 500) -> str: return text async def _agent_tool_names(self, agent: str) -> frozenset[str]: - """The names a ``task`` call's ``tools`` may give for ``agent``: its built agent's. + """The names a ``task`` call's ``tools`` may give for ``agent``: its built + agent's. Its tools as its model sees them (callables, ADK tools, a skill toolset's tools) and each MCP toolset's, which ADK lists by connecting: @@ -399,7 +400,8 @@ async def _agent_tool_names(self, agent: str) -> frozenset[str]: except Exception as exc: # noqa: BLE001 - a server that will not list logger.warning("mcp_tools_unlisted", agent=agent, error=str(exc)) raise ToolsUnlistedError(agent, exc) from exc - # The toolset is kept with its names: its id is only its own while it lives. + # The toolset is kept with its names: its id is only its own while it + # lives. kept = listed[id(tool)] = (tool, found) names |= kept[1] return frozenset(names - KEPT_TOOLS) @@ -417,7 +419,9 @@ def _detach_backend(self) -> list[Closer]: self.__dict__.pop("_mcp_tool_names", None) runner, self._runner = self._runner, None runners, self._agent_runners = self._agent_runners, MappingProxyType({}) - chosen_runners, self._variant_runners = self._variant_runners, MappingProxyType({}) + chosen_runners, self._variant_runners = ( + self._variant_runners, MappingProxyType({}) + ) self._variant_agents = MappingProxyType({}) self._agents = MappingProxyType({}) self._root_agent = None @@ -438,7 +442,9 @@ def _detach_backend(self) -> list[Closer]: *( ( f"runner {name} on {choice}", - functools.partial(self._aclose_owned, owned, f"runner {name} on {choice}"), + functools.partial( + self._aclose_owned, owned, f"runner {name} on {choice}" + ), ) for (name, choice), owned in chosen_runners.items() ), @@ -1729,7 +1735,10 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: # usage and context the choice's under the type's name. _, budgets = self._run_models(run) models, kinds = dict(build.models), self._agent_kinds() - chosen = self._choice_models[(run.ref.agent, run.model)] if run.model is not None else None + chosen = ( + self._choice_models[(run.ref.agent, run.model)] + if run.model is not None else None + ) if chosen is not None: models[run.ref.agent] = str(chosen.ref) kinds[run.ref.agent] = chosen.record.kind.value @@ -1817,7 +1826,8 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: ) def _chosen_model(self, agent: str | None) -> "ResolvedModel | None": - """The model choice the run in progress is on, when it is ``agent``'s run; else None. + """The model choice the run in progress is on, when it is ``agent``'s run; else + None. What the raw LLM log names a call's model by (``LLMLoggingPlugin``): the one plugin serves every runner, and names a model by agent name. diff --git a/src/agentic_cli/workflow/adk/run_control_plugin.py b/src/agentic_cli/workflow/adk/run_control_plugin.py index 0a622c3e..d1323f43 100644 --- a/src/agentic_cli/workflow/adk/run_control_plugin.py +++ b/src/agentic_cli/workflow/adk/run_control_plugin.py @@ -198,7 +198,9 @@ def narrow(llm_request: LlmRequest, keeps: Callable[[str], bool]) -> None: left = [d for d in declarations if d.name is None or keeps(d.name)] if len(left) == len(declarations): kept.append(tool) - elif left or tool.model_dump(exclude={"function_declarations"}, exclude_none=True): + elif left or tool.model_dump( + exclude={"function_declarations"}, exclude_none=True + ): kept.append(tool.model_copy(update={"function_declarations": left or None})) llm_request.config.tools = kept or None diff --git a/src/agentic_cli/workflow/agents/brief.py b/src/agentic_cli/workflow/agents/brief.py index 30bf4e56..65ec3dc2 100644 --- a/src/agentic_cli/workflow/agents/brief.py +++ b/src/agentic_cli/workflow/agents/brief.py @@ -289,7 +289,8 @@ def read_choices( config: AgentConfig, own_tools: Collection[str] = (), ) -> tuple[frozenset[str] | None, str | None]: - """The tools and the model a ``task`` call gives its run: None each when left out (or null). + """The tools and the model a ``task`` call gives its run: None each when left out + (or null). ``tools`` are some of the type's own: ``own_tools`` are the names its backend gives it (the state and delegation tools left out), and none at @@ -312,7 +313,9 @@ def read_choices( isinstance(name, str) and name in own_tools for name in given ): raise BriefError( - TOOLS_ERROR.format(agent_type=agent_type, names=", ".join(sorted(own_tools))) + TOOLS_ERROR.format( + agent_type=agent_type, names=", ".join(sorted(own_tools)) + ) ) tools = frozenset(given) @@ -323,7 +326,9 @@ def read_choices( raise BriefError(NO_MODEL_CHOICES_ERROR.format(agent_type=agent_type)) if not isinstance(chosen, str) or chosen.strip() not in config.model_choices: raise BriefError( - MODEL_ERROR.format(agent_type=agent_type, names=", ".join(config.model_choices)) + MODEL_ERROR.format( + agent_type=agent_type, names=", ".join(config.model_choices) + ) ) model = chosen.strip() return tools, model diff --git a/src/agentic_cli/workflow/agents/control.py b/src/agentic_cli/workflow/agents/control.py index c1dad796..c175c148 100644 --- a/src/agentic_cli/workflow/agents/control.py +++ b/src/agentic_cli/workflow/agents/control.py @@ -82,7 +82,8 @@ def configured_tool_names(tools: Iterable[Any]) -> frozenset[str]: one rule for ``Delegations`` and for a manager's ``_agent_tool_names``. """ names = ( - tool.strip().rsplit(".", 1)[-1] if isinstance(tool, str) else getattr(tool, "__name__", "") + tool.strip().rsplit(".", 1)[-1] if isinstance(tool, str) + else getattr(tool, "__name__", "") for tool in tools ) return frozenset(name for name in names if name and name not in KEPT_TOOLS) diff --git a/src/agentic_cli/workflow/agents/delegate.py b/src/agentic_cli/workflow/agents/delegate.py index 7ff6695e..f8d855ac 100644 --- a/src/agentic_cli/workflow/agents/delegate.py +++ b/src/agentic_cli/workflow/agents/delegate.py @@ -142,7 +142,11 @@ task_message, task_offer, ) -from agentic_cli.workflow.agents.control import PARENT_CAUSE, RunControl, configured_tool_names +from agentic_cli.workflow.agents.control import ( + PARENT_CAUSE, + RunControl, + configured_tool_names, +) from agentic_cli.workflow.agents.envelope import ( CANCELLED_BY, INTERRUPTED_ERROR, @@ -264,7 +268,8 @@ class ToolsUnlistedError(Exception): - """A backend's ``tool_names`` hook could not list a type's tools (an MCP server's, say). + """A backend's ``tool_names`` hook could not list a type's tools (an MCP server's, + say). Raised instead of answering with the names without them, which would read as tools the type lacks; asking again lists again. @@ -288,7 +293,8 @@ def started_by(caller: RunRef | None) -> str: return f"agent:{caller.instance if caller is not None else 'root'}" -#: ``follow_up``'s ``_own`` when ``message`` has not asked for the tool names (None is an answer). +#: ``follow_up``'s ``_own`` when ``message`` has not asked for the tool names (None is +#: an answer). _UNFETCHED = object() @@ -1357,11 +1363,14 @@ def _follow_up_refused( if gone: what = f"the tools {', '.join(gone)}" if what is not None: - return CHOICE_GONE_ERROR.format(instance=found.instance, what=what, agent=found.agent) + return CHOICE_GONE_ERROR.format( + instance=found.instance, what=what, agent=found.agent + ) return None async def _own_tools(self, config: AgentConfig) -> Collection[str]: - """The names of ``config``'s own tools: its backend's, else its configured tools'. + """The names of ``config``'s own tools: its backend's, else its configured + tools'. The one place the backend's hook is asked. @@ -1381,7 +1390,8 @@ async def _own_tools(self, config: AgentConfig) -> Collection[str]: async def _instance_tools( self, conversation: SessionRef | None, instance: str ) -> frozenset[str] | None: - """The names of the own tools of ``instance``'s type, when it is a narrowed one; else None. + """The names of the own tools of ``instance``'s type, when it is a narrowed one; + else None. What a follow-up checks the instance's tools against. Awaited before the follow-up's synchronous step, and only for an instance that has diff --git a/src/agentic_cli/workflow/agents/runs.py b/src/agentic_cli/workflow/agents/runs.py index 48c119a8..73aa6ccd 100644 --- a/src/agentic_cli/workflow/agents/runs.py +++ b/src/agentic_cli/workflow/agents/runs.py @@ -498,8 +498,8 @@ def export(self, conversation: SessionRef | None) -> dict[str, Any]: ``{"v": RECORDS_VERSION, "saved": <now, ISO>, "numbered": {type: n}, "instances": [...], "runs": [...]}``: each instance's fields - (``InstanceRecord``, its ``tools`` a list) and each run's (``RunRecord``, its ``ref``'s - fields first, its times as ISO text, and ``end``: where its end was + (``InstanceRecord``, its ``tools`` a list) and each run's (``RunRecord``, its + ``ref``'s fields first, its times as ISO text, and ``end``: where its end was recorded, 0 for none yet), in the order they started, and the highest instance number of each type. ``saved`` is when this was taken: a run still working then is restored as ended at that time. diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index 21c437fc..6830eee3 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -1238,7 +1238,8 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: def _run_models( self, run: AgentRun ) -> "tuple[Mapping[str, ResolvedModel], Mapping[str, ContextBudget]]": - """The agents' models and context numbers a sub-agent ``run`` reads, by agent name. + """The agents' models and context numbers a sub-agent ``run`` reads, by agent + name. Those of the manager's, except that a run on a model choice (``run.model``) has its type's entries the choice's: its backend's @@ -1258,7 +1259,8 @@ def _run_models( return models, budgets async def _agent_tool_names(self, agent: str) -> frozenset[str]: - """The names a ``task`` call's ``tools`` may give for ``agent`` (a backend hook). + """The names a ``task`` call's ``tools`` may give for ``agent`` (a backend + hook). Asked for a call that names tools and for a narrowed instance's follow-up: the agent's own tools by the names its model sees (a @@ -2701,7 +2703,8 @@ def _resolve_models(self, providers: Mapping[str, Provider]) -> None: for choice in config.model_choices: try: choices[(config.name, choice)] = self._resolve_for( - dataclasses.replace(config, model=choice), roles, self._catalog, providers + dataclasses.replace(config, model=choice), + roles, self._catalog, providers ) except ModelResolutionError as exc: errors.append(str(exc)) diff --git a/src/agentic_cli/workflow/deepagents/agent_builder.py b/src/agentic_cli/workflow/deepagents/agent_builder.py index 3abee590..59f1eee5 100644 --- a/src/agentic_cli/workflow/deepagents/agent_builder.py +++ b/src/agentic_cli/workflow/deepagents/agent_builder.py @@ -230,8 +230,9 @@ def build_agent_tree( def build(name: str) -> "CompiledStateGraph": is_root = name == root return build_agent( - config_map[name], root=is_root, configs=configs, chat_model=chat_models[name], - resolved=resolved.get(name), tools=tools.get(name, []), prompt=prompts[name], + config_map[name], root=is_root, configs=configs, + chat_model=chat_models[name], resolved=resolved.get(name), + tools=tools.get(name, []), prompt=prompts[name], settings=settings, checkpointer=checkpointer, bound=bound, budget=budgets.get(name) if budgets is not None else None, summarizers=summarizers, open_calls=open_calls, marks=marks, @@ -249,7 +250,8 @@ def build(name: str) -> "CompiledStateGraph": graph = build_agent( variant.config, root=False, configs=configs, chat_model=variant.chat_model, resolved=variant.resolved, tools=tools.get(name, []), prompt=prompts[name], - settings=settings, checkpointer=checkpointer, bound=bound, budget=variant.budget, + settings=settings, checkpointer=checkpointer, bound=bound, + budget=variant.budget, open_calls=open_calls, marks=marks, delegations=delegations, ) if variant_graphs is not None: @@ -329,7 +331,9 @@ def build_agent( PatchToolCallsMiddleware() if open_calls is None else InterruptedCallsMiddleware(open_calls, root=root), *model_side, - *_tool_side(config, settings, bound=bound, open_calls=open_calls, marks=marks), + *_tool_side( + config, settings, bound=bound, open_calls=open_calls, marks=marks + ), ], state_schema=AgentCliState, name=name, diff --git a/src/agentic_cli/workflow/deepagents/manager.py b/src/agentic_cli/workflow/deepagents/manager.py index 1bf3d8fc..71c4779f 100644 --- a/src/agentic_cli/workflow/deepagents/manager.py +++ b/src/agentic_cli/workflow/deepagents/manager.py @@ -479,7 +479,8 @@ def _detach_store(self) -> list[Closer]: return [("checkpointer", functools.partial(self._close_connection, connection))] async def _agent_tool_names(self, agent: str) -> frozenset[str]: - """The names a ``task`` call's ``tools`` may give for ``agent``: its built tools'.""" + """The names a ``task`` call's ``tools`` may give for ``agent``: its built + tools'.""" names = self._own_tool_names.get(agent) return names if names is not None else await super()._agent_tool_names(agent) diff --git a/src/agentic_cli/workflow/events.py b/src/agentic_cli/workflow/events.py index a1109e40..be1f97dc 100644 --- a/src/agentic_cli/workflow/events.py +++ b/src/agentic_cli/workflow/events.py @@ -225,9 +225,9 @@ def agent_run( ``started_by`` and its ``mode``; a first run of an instance also says whether the instance ``inherit_context`` and is ``continuable``, and the ``tools`` and ``model`` its delegation gave it; a follow-up's - start carries its ``input``, the message as written), then one end status (``completed``, - ``failed``, ``refused``, ``cancelled``, ``interrupted``: the constants - of ``workflow/agents/runs.py``) with the first of its ``result``, its + start carries its ``input``, the message as written), then one end status + (``completed``, ``failed``, ``refused``, ``cancelled``, ``interrupted``: the + constants of ``workflow/agents/runs.py``) with the first of its ``result``, its ``error``, whether the result is ``partial``, the tokens the run used (``usage``) and, for a cancelled run, who cancelled it. ``metadata["agent"]`` is the sub-agent, as on every event an agent diff --git a/src/agentic_cli/workflow/model_services.py b/src/agentic_cli/workflow/model_services.py index 5522f152..edbf9ff8 100644 --- a/src/agentic_cli/workflow/model_services.py +++ b/src/agentic_cli/workflow/model_services.py @@ -192,7 +192,9 @@ def _named_references( named.setdefault(parsed, []).append(f"agent {config.name!r}") where = f"agent {config.name!r} model_choices" for choice in _agent_choices(config): - if isinstance(choice, ModelRef) and where not in named.setdefault(choice, []): + if isinstance(choice, ModelRef) and where not in named.setdefault( + choice, [] + ): named[choice].append(where) return named diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index bcd70e8e..71dc2a88 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -540,15 +540,18 @@ class TestAnInstanceOnAModelChoice: async def test_after_a_restart_its_view_and_panel_say_so(self, make_crew): first = make_crew( - follow_team(model_choices=(SMALL_MODEL,)), store="sqlite", models=SMALL_ENTRY, - coordinator=[calls(delegate("researcher", "Find X.", "c1", model=SMALL_MODEL, + follow_team(model_choices=(SMALL_MODEL,)), store="sqlite", + models=SMALL_ENTRY, + coordinator=[calls(delegate("researcher", "Find X.", "c1", + model=SMALL_MODEL, tools=["contract_lookup"])), says("Done.")], researcher=[says("X is 42.", usage=(1_200, 40))], ) await first.turn() await first.manager.cleanup() second = make_crew( - follow_team(model_choices=(SMALL_MODEL,)), store="sqlite", models=SMALL_ENTRY, + follow_team(model_choices=(SMALL_MODEL,)), store="sqlite", + models=SMALL_ENTRY, researcher=[says("Y is 7.", usage=(900, 30))], ) app = await app_on(second) diff --git a/tests/cli/test_agents_command.py b/tests/cli/test_agents_command.py index 6b04f856..f3d18f84 100644 --- a/tests/cli/test_agents_command.py +++ b/tests/cli/test_agents_command.py @@ -87,7 +87,8 @@ def start(self, agent: str, call_id: str, request: str, *, at: int, ref = self.manager.agent_runs.run_for(self.conversation, parent, call_id, agent) title = request.splitlines()[0] self._observe(WorkflowEvent.agent_run( - ref, "started", title=title, call_id=call_id, brief=brief, tools=tools, model=model, + ref, "started", title=title, call_id=call_id, brief=brief, tools=tools, + model=model, ), at) return ref @@ -252,7 +253,8 @@ async def test_an_instance_its_parent_title_run_result_and_tokens_by_model(self, ] @pytest.mark.parametrize("tools, model, shown", [ - (["lookup", "fetch_page"], "fast", [("Model", "fast"), ("Tools", "lookup, fetch_page")]), + (["lookup", "fetch_page"], "fast", + [("Model", "fast"), ("Tools", "lookup, fetch_page")]), ([], None, [("Tools", "none of its own")]), (None, HAIKU, [("Model", HAIKU)]), ]) diff --git a/tests/test_config.py b/tests/test_config.py index cbb06caf..0159f84e 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -653,14 +653,20 @@ def test_a_role_choice_needs_its_mapped_model_s_key(self, temp_workspace: Path): def test_a_malformed_model_choice_is_an_error(self, temp_workspace: Path): settings = self._settings(temp_workspace, {"GOOGLE_API_KEY": "test-key"}) - agents = [AgentConfig(name="writer", prompt="p", model_choices=("fast", "gemini"))] + agents = [AgentConfig( + name="writer", prompt="p", model_choices=("fast", "gemini") + )] (problem,) = self._problems(settings, agents) assert problem.startswith("Agent 'writer' (model choice 'gemini'): ") - def test_a_model_choice_on_an_undefined_provider_is_an_error(self, temp_workspace: Path): + def test_a_model_choice_on_an_undefined_provider_is_an_error( + self, temp_workspace: Path + ): settings = self._settings(temp_workspace, {"GOOGLE_API_KEY": "test-key"}) - agents = [AgentConfig(name="writer", prompt="p", model_choices=("third-box:mistral",))] + agents = [AgentConfig( + name="writer", prompt="p", model_choices=("third-box:mistral",) + )] (problem,) = self._problems(settings, agents) assert problem.startswith( @@ -668,7 +674,9 @@ def test_a_model_choice_on_an_undefined_provider_is_an_error(self, temp_workspac "names provider 'third-box'" ) - def test_a_computed_role_choice_needs_a_tier(self, temp_workspace: Path, monkeypatch): + def test_a_computed_role_choice_needs_a_tier( + self, temp_workspace: Path, monkeypatch + ): monkeypatch.setenv("OPENROUTER_API_KEY", "test-key") settings = self._settings( temp_workspace, diff --git a/tests/workflow/adk/test_plugin_chain.py b/tests/workflow/adk/test_plugin_chain.py index 959a68c4..8ec270de 100644 --- a/tests/workflow/adk/test_plugin_chain.py +++ b/tests/workflow/adk/test_plugin_chain.py @@ -186,7 +186,9 @@ async def test_a_delegating_app(project): assert logs == [shared] -async def test_a_model_choices_runner_has_its_types_chain_on_the_choices_numbers(project): +async def test_a_model_choices_runner_has_its_types_chain_on_the_choices_numbers( + project, +): """A sub-agent type with model choices has a runner of its own for each: its agent built on the choice's model, and the type's chain, in which every plugin that reads an agent's numbers, kind or model by name reads diff --git a/tests/workflow/adk/test_run_control_plugin.py b/tests/workflow/adk/test_run_control_plugin.py index 8854fc26..a6c3ee14 100644 --- a/tests/workflow/adk/test_run_control_plugin.py +++ b/tests/workflow/adk/test_run_control_plugin.py @@ -1,4 +1,5 @@ -"""ADK: a sub-agent run's limits, and the tools a narrowed run is offered, at its model calls (``workflow/adk/run_control_plugin.py``). +"""ADK: a sub-agent run's limits, and the tools a narrowed run is offered, at its model +calls (``workflow/adk/run_control_plugin.py``). What the plugin does to a request and an answer, alone. Whole turns, on both backends, are in the contract suite (``TestTheStepLimit``, @@ -250,7 +251,10 @@ def offering(*names: str) -> LlmRequest: def declared(request: LlmRequest) -> list[str]: - return [d.name for tool in request.config.tools or () for d in tool.function_declarations or ()] + return [ + d.name for tool in request.config.tools or () + for d in tool.function_declarations or () + ] class TestANarrowedRunsTools: @@ -265,7 +269,8 @@ async def test_its_tools_and_those_every_run_keeps_and_no_other(self): await plugin.before_model_callback(callback_context=None, llm_request=request) - assert list(request.tools_dict) == ["lookup", "save_plan", "task", "check_agents"] + assert list(request.tools_dict) == ["lookup", "save_plan", "task", + "check_agents"] assert declared(request) == ["lookup", "save_plan", "task", "check_agents"] # What is no function declaration stays. assert request.config.tools[1].google_search is not None @@ -275,7 +280,8 @@ def test_a_tool_left_with_no_declaration_goes(self): request.config.tools = [types.Tool(function_declarations=[ types.FunctionDeclaration(name="fetch_page", description="Fetch."), ])] - request.tools_dict = {"fetch_page": BaseTool(name="fetch_page", description="Fetch.")} + request.tools_dict = {"fetch_page": BaseTool(name="fetch_page", + description="Fetch.")} narrow(request, lambda name: False) diff --git a/tests/workflow/deepagents/test_agent_builder.py b/tests/workflow/deepagents/test_agent_builder.py index 1253e061..f08e1dd1 100644 --- a/tests/workflow/deepagents/test_agent_builder.py +++ b/tests/workflow/deepagents/test_agent_builder.py @@ -51,7 +51,10 @@ ) from agentic_cli.workflow.config import AgentConfig, AgentGraphError # noqa: E402 from agentic_cli.workflow.deepagents import agent_builder # noqa: E402 -from agentic_cli.workflow.deepagents.agent_builder import Variant, build_agent_tree # noqa: E402 +from agentic_cli.workflow.deepagents.agent_builder import ( # noqa: E402 + Variant, + build_agent_tree, +) from agentic_cli.workflow.deepagents.middleware import ( # noqa: E402 ActiveToolCallMiddleware, PermissionMiddleware, @@ -699,7 +702,8 @@ def spy(*args, **kwargs): [COORDINATOR, RESEARCHER], {"coordinator": ScriptedChat(), "researcher": own}, tools=tools, checkpointer=InMemorySaver(), - variants={("researcher", "fast"): Variant(config=RESEARCHER, chat_model=cheaper, + variants={("researcher", "fast"): Variant(config=RESEARCHER, + chat_model=cheaper, resolved=None)}, variant_graphs=variant_graphs, ) @@ -711,6 +715,8 @@ def spy(*args, **kwargs): assert (len(own.requests), len(cheaper.requests)) == (0, 1) *_, variant = made assert [m["name"] for m in made] == ["coordinator", "researcher", "researcher"] - assert (variant["model"], variant["system_prompt"]) == (cheaper, "You are researcher.") + assert (variant["model"], variant["system_prompt"]) == ( + cheaper, "You are researcher." + ) assert [tool.name for tool in variant["tools"]] == ["save_plan"] assert RunControlMiddleware in [type(m) for m in variant["middleware"]] diff --git a/tests/workflow/deepagents/test_run_control_middleware.py b/tests/workflow/deepagents/test_run_control_middleware.py index f559ae7f..bb66756b 100644 --- a/tests/workflow/deepagents/test_run_control_middleware.py +++ b/tests/workflow/deepagents/test_run_control_middleware.py @@ -289,7 +289,8 @@ def _named(name: str) -> StructuredTool: def _narrowing(tools: frozenset[str] | None, *, task_offered: bool = False): - """The middleware, over delegations whose run has ``tools`` (and offers ``task`` or not).""" + """The middleware, over delegations whose run has ``tools`` (and offers ``task`` or + not).""" control = RunControl(REF, AgentLimits(), tools=tools) delegations = SimpleNamespace( control=lambda run: control, @@ -298,7 +299,8 @@ def _narrowing(tools: frozenset[str] | None, *, task_offered: bool = False): return RunControlMiddleware(lambda: delegations) -TOOLS = [_named(name) for name in ("lookup", "fetch_page", "save_plan", "task", "check_agents")] +TOOLS = [_named(name) for name in ("lookup", "fetch_page", "save_plan", "task", + "check_agents")] async def test_a_narrowed_runs_request_offers_its_tools_and_those_every_run_keeps(): @@ -308,7 +310,9 @@ async def handler(request): sent.append([tool.name for tool in request.tools]) return AIMessage("Done.") - await _narrowing(frozenset({"lookup"})).awrap_model_call(_request(list(TOOLS)), handler) + await _narrowing(frozenset({"lookup"})).awrap_model_call( + _request(list(TOOLS)), handler + ) assert sent == [["lookup", "save_plan", "task", "check_agents"]] @@ -349,7 +353,8 @@ async def test_a_call_of_a_tool_it_was_not_given_is_one_it_does_not_have( @pytest.mark.parametrize("tools, name", [ - (frozenset({"lookup"}), "lookup"), (frozenset({"lookup"}), "save_plan"), (None, "fetch_page"), + (frozenset({"lookup"}), "lookup"), (frozenset({"lookup"}), "save_plan"), + (None, "fetch_page"), ]) async def test_a_call_of_a_tool_it_has_runs(tools, name): answer, ran = await _called(_narrowing(tools), name) diff --git a/tests/workflow/deepagents/test_skills.py b/tests/workflow/deepagents/test_skills.py index c9bbaedb..2c537f6b 100644 --- a/tests/workflow/deepagents/test_skills.py +++ b/tests/workflow/deepagents/test_skills.py @@ -734,7 +734,8 @@ async def call_tool(**arguments): return [{"type": "text", "text": "found"}], None _fake_mcp(monkeypatch, StructuredTool( - name="search", description="A server's tool.", args_schema={"type": "object"}, + name="search", description="A server's tool.", + args_schema={"type": "object"}, coroutine=call_tool, response_format="content_and_artifact", )) scripted(monkeypatch, lead=[], writer=[]) diff --git a/tests/workflow/test_adk_mcp_lifecycle.py b/tests/workflow/test_adk_mcp_lifecycle.py index 98905a40..351d9492 100644 --- a/tests/workflow/test_adk_mcp_lifecycle.py +++ b/tests/workflow/test_adk_mcp_lifecycle.py @@ -127,7 +127,8 @@ async def test_a_sub_agents_mcp_tools_are_listed_when_first_asked_and_stop_with_ AgentConfig(name="lead", prompt="Lead.", sub_agents=["researcher"]), AgentConfig(name="researcher", prompt="Find.", mcp_servers=[server]), ], - settings=BaseSettings(session_store="memory", default_model="claude-sonnet-4-6"), + settings=BaseSettings(session_store="memory", + default_model="claude-sonnet-4-6"), ) try: await manager.initialize_services() @@ -157,7 +158,11 @@ async def test_a_listing_that_fails_is_said_so_and_asked_again( DelegationRequest, ToolsUnlistedError, ) - from agentic_cli.workflow.sessions import SessionRef, reset_active_turn, set_active_turn + from agentic_cli.workflow.sessions import ( + SessionRef, + reset_active_turn, + set_active_turn, + ) route(monkeypatch, anthropic, "AsyncAnthropic", FakeAPI(anthropic_message({"type": "text", "text": "ok"}))) @@ -171,7 +176,8 @@ async def test_a_listing_that_fails_is_said_so_and_asked_again( AgentConfig(name="researcher", prompt="Find.", description="Finds.", mcp_servers=[server]), ], - settings=BaseSettings(session_store="memory", default_model="claude-sonnet-4-6"), + settings=BaseSettings(session_store="memory", + default_model="claude-sonnet-4-6"), ) real = McpToolset.get_tools_with_prefix failing = [True] @@ -206,7 +212,8 @@ async def listing(self, *args, **kwargs): assert refused.run is None failing[0] = False - assert await manager._agent_tool_names("researcher") == {"atlas_add", "atlas_lookup"} + assert await manager._agent_tool_names("researcher") == {"atlas_add", + "atlas_lookup"} finally: await manager.cleanup() @@ -283,7 +290,8 @@ async def test_a_model_choices_runner_is_released_with_the_backend( subagents=FOLLOWING, coordinator=[calls(delegate("researcher", "Find X.", "c1", model=CHOICE)), says("Asked."), - calls(message("researcher-1", "Now find Y.", "c2")), says("Done.")], + calls(message("researcher-1", "Now find Y.", "c2")), + says("Done.")], researcher=[says("X is 42."), says("Y is 7.")], ) manager = crew.manager @@ -298,7 +306,9 @@ async def test_a_model_choices_runner_is_released_with_the_backend( assert alive(pid_dir) == [] # no runner of the old build is left open await crew.turn("Find Y too.") assert alive(pid_dir) - assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Y is 7." + assert envelope_read( + crew.results_read("coordinator")["c2"] + )["result"] == "Y is 7." finally: await manager.cleanup() diff --git a/tests/workflow/test_agent_brief.py b/tests/workflow/test_agent_brief.py index cd200c0a..f89bb647 100644 --- a/tests/workflow/test_agent_brief.py +++ b/tests/workflow/test_agent_brief.py @@ -288,8 +288,10 @@ def test_the_tools_and_model_arguments_texts(self): def test_a_model_argument_once_a_type_has_model_choices(self): schema = task_parameters({"researcher": RESEARCHER, "checker": CHOOSING}) properties = schema["properties"] - assert list(properties) == ["agent_type", "title", *BRIEF_FIELDS, "tools", "model"] - assert properties["model"] == {"type": "string", "description": MODEL_DESCRIPTION} + assert list(properties) == ["agent_type", "title", *BRIEF_FIELDS, "tools", + "model"] + assert properties["model"] == {"type": "string", + "description": MODEL_DESCRIPTION} assert properties["agent_type"]["description"].endswith( "- checker (model choices: fast, anthropic:claude-haiku-4-5): Checks a claim." ) @@ -431,16 +433,20 @@ def test_both_left_out(self): assert read_choices({"agent_type": "checker"}, CHOOSING) == (None, None) def test_null_is_left_out(self): - assert read_choices({"tools": None, "model": None}, CHOOSING, OWN) == (None, None) + assert read_choices( + {"tools": None, "model": None}, CHOOSING, OWN + ) == (None, None) def test_some_of_its_own_tools(self): - tools, model = read_choices({"tools": ["lookup", "mcp_search", "lookup"]}, CHOOSING, OWN) + tools, model = read_choices({"tools": ["lookup", "mcp_search", "lookup"]}, + CHOOSING, OWN) assert (tools, model) == (frozenset({"lookup", "mcp_search"}), None) def test_none_of_them_is_a_narrowing_too(self): assert read_choices({"tools": []}, CHOOSING, OWN) == (frozenset(), None) - @pytest.mark.parametrize("tools", [["lookup", "write_file"], "lookup", [3], {"lookup": 1}]) + @pytest.mark.parametrize("tools", [["lookup", "write_file"], "lookup", [3], + {"lookup": 1}]) def test_anything_else_names_its_own(self, tools): with pytest.raises(BriefError) as exc: read_choices({"tools": tools}, CHOOSING, OWN) @@ -455,7 +461,8 @@ def test_a_type_with_no_tools_of_its_own(self): assert read_choices({"tools": []}, CHOOSING, frozenset()) == (frozenset(), None) @pytest.mark.parametrize("given, chosen", [ - ("fast", "fast"), (" anthropic:claude-haiku-4-5 ", "anthropic:claude-haiku-4-5"), + ("fast", "fast"), + (" anthropic:claude-haiku-4-5 ", "anthropic:claude-haiku-4-5"), ]) def test_one_of_its_model_choices_as_written(self, given, chosen): assert read_choices({"model": given}, CHOOSING) == (None, chosen) diff --git a/tests/workflow/test_agent_control.py b/tests/workflow/test_agent_control.py index ac07512e..32917cce 100644 --- a/tests/workflow/test_agent_control.py +++ b/tests/workflow/test_agent_control.py @@ -432,7 +432,8 @@ def test_a_run_not_narrowed_keeps_every_tool(self): def test_a_narrowed_run_keeps_its_tools_its_plan_and_its_delegation_tools(self): control = RunControl(REF, AgentLimits(), tools=frozenset({"lookup"})) - names = ["lookup", "fetch_page", "save_plan", "get_tasks", "task", "check_agents"] + names = ["lookup", "fetch_page", "save_plan", "get_tasks", "task", + "check_agents"] assert [name for name in names if control.keeps(name)] == [ "lookup", "save_plan", "get_tasks", "task", "check_agents", ] @@ -443,7 +444,8 @@ def test_every_run_keeps_the_state_tools_and_the_delegation_tools(self): from agentic_cli.tools._core.delegation import FOLLOW_UP_TOOLS, TASK_TOOL assert KEPT_TOOLS == { - *(name for name, _ in state_tools._STATE_TOOLS), TASK_TOOL, *FOLLOW_UP_TOOLS, + *(name for name, _ in state_tools._STATE_TOOLS), TASK_TOOL, + *FOLLOW_UP_TOOLS, } diff --git a/tests/workflow/test_agent_delegate.py b/tests/workflow/test_agent_delegate.py index fbd4920f..b1a97d3b 100644 --- a/tests/workflow/test_agent_delegate.py +++ b/tests/workflow/test_agent_delegate.py @@ -4106,13 +4106,15 @@ async def test_a_start_blocks_no_event_loop(): CHOOSY = AgentConfig(name="choosy", prompt="p", description="Chooses.", model_choices=("fast", "anthropic:claude-haiku-4-5")) CHOOSING = {**TYPES, "coordinator": AgentConfig( - name="coordinator", prompt="p", sub_agents=["researcher", "choosy"]), "choosy": CHOOSY} + name="coordinator", prompt="p", sub_agents=["researcher", "choosy"]), + "choosy": CHOOSY} NARROW = {"agent_type": "choosy", "title": "Look", "objective": "Look X up.", "tools": ["lookup"], "model": "fast"} def own_tools(names: dict[str, set[str]], asked: list[str] | None = None): - """A backend's hook for each type's own tools (``_agent_tool_names``), recording who asked.""" + """A backend's hook for each type's own tools (``_agent_tool_names``), recording who + asked.""" async def tool_names(agent: str) -> frozenset[str]: if asked is not None: @@ -4141,7 +4143,9 @@ async def test_the_run_gets_them_and_its_start_says_them(self): assert (run.tools, run.model) == (frozenset({"lookup"}), "fast") assert run.control.tools == frozenset({"lookup"}) start = runs_of_status(events, RUN_STARTED)[0] - assert (start.metadata["tools"], start.metadata["model"]) == (["lookup"], "fast") + assert (start.metadata["tools"], start.metadata["model"]) == ( + ["lookup"], "fast" + ) instance = runs.instance(CONVERSATION, "choosy-1") assert (instance.tools, instance.model) == (("lookup",), "fast") @@ -4174,7 +4178,8 @@ async def test_a_static_sub_agent_may_be_narrowed_too(self): ({**NARROW, "model": "strong"}, "The model for 'choosy' must be one of its model choices: fast, " "anthropic:claude-haiku-4-5."), - ({**BRIEF, "model": "fast"}, "'researcher' has no model choices; leave model out."), + ({**BRIEF, "model": "fast"}, + "'researcher' has no model choices; leave model out."), ({**NARROW, "objective": " "}, "The brief for 'choosy' is missing: objective."), ]) async def test_what_the_type_cannot_take_starts_no_run_and_counts_none( @@ -4195,7 +4200,8 @@ async def work(): async def test_without_a_backends_names_its_configured_tools_are_its_own(self): hook, asked = answering() - typed = AgentConfig(name="choosy", prompt="p", tools=[contract_tool, "web_fetch"]) + typed = AgentConfig(name="choosy", prompt="p", tools=[contract_tool, + "web_fetch"]) made = delegations(hook, types={**CHOOSING, "choosy": typed}) result, _ = await delegated(made, request({**NARROW, "model": None, @@ -4208,7 +4214,8 @@ async def test_a_start_request_carries_them_to_the_run(self): hook, asked = answering() made = delegations(hook, types=CHOOSING) - await started(made, start_request("choosy", tools=frozenset({"lookup"}), model="fast")) + await started(made, start_request("choosy", tools=frozenset({"lookup"}), + model="fast")) (run,) = asked assert (run.tools, run.model, run.control.tools) == ( @@ -4216,7 +4223,8 @@ async def test_a_start_request_carries_them_to_the_run(self): ) def test_the_fields_default_to_none(self): - made = StartRequest(agent_type="researcher", brief=Brief(title="T", objective="O"), + made = StartRequest(agent_type="researcher", brief=Brief(title="T", + objective="O"), started_by="user") assert (made.tools, made.model) == (None, None) run = AgentRun(ref=RESEARCHER, config=TYPES["researcher"], message="m", @@ -4259,7 +4267,8 @@ async def test_the_users_follow_up_and_a_restored_instance_too(self): await self.narrowed(made) again = AgentRuns() again.restore(CONVERSATION, runs.export(CONVERSATION)) - restarted = delegations(hook, runs=again, types=CHOOSING, tool_names=own_tools(OWN)) + restarted = delegations(hook, runs=again, types=CHOOSING, + tool_names=own_tools(OWN)) result, _ = await turned(lambda: restarted.follow_up(users("choosy-1"))) @@ -4271,8 +4280,9 @@ async def test_a_model_the_type_no_longer_has_is_refused(self): runs = AgentRuns() made = delegations(hook, runs=runs, types=CHOOSING, tool_names=own_tools(OWN)) await self.narrowed(made) - made._types["choosy"] = AgentConfig(name="choosy", prompt="p", - model_choices=("anthropic:claude-haiku-4-5",)) + made._types["choosy"] = AgentConfig( + name="choosy", prompt="p", model_choices=("anthropic:claude-haiku-4-5",) + ) result, events = await turned(lambda: made.follow_up(follow("choosy-1"))) @@ -4288,7 +4298,8 @@ async def test_tools_the_type_no_longer_has_are_refused(self): names = {"choosy": {"lookup", "fetch_page"}} made = delegations(hook, types=CHOOSING, tool_names=own_tools(names)) await turned(lambda: made.delegate(request({**NARROW, "model": None, - "tools": ["lookup", "fetch_page"]}))) + "tools": ["lookup", + "fetch_page"]}))) names["choosy"] = {"fetch_page"} result, events = await turned(lambda: made.message(users("choosy-1"))) @@ -4312,13 +4323,15 @@ async def test_an_instance_not_narrowed_never_asks_for_the_tools(self): assert [run.model for run in asked] == ["fast", "fast"] async def test_the_model_is_checked_before_the_tools(self): - """An instance whose type lost its model choice and a tool is told of the model.""" + """An instance whose type lost its model choice and a tool is told of the + model.""" hook, asked = answering() names = {"choosy": {"lookup", "fetch_page"}} made = delegations(hook, types=CHOOSING, tool_names=own_tools(names)) await turned(lambda: made.delegate(request({**NARROW, "tools": ["lookup"]}))) - made._types["choosy"] = AgentConfig(name="choosy", prompt="p", - model_choices=("anthropic:claude-haiku-4-5",)) + made._types["choosy"] = AgentConfig( + name="choosy", prompt="p", model_choices=("anthropic:claude-haiku-4-5",) + ) names["choosy"] = {"fetch_page"} result, _ = await turned(lambda: made.follow_up(follow("choosy-1"))) @@ -4329,7 +4342,9 @@ async def test_the_model_is_checked_before_the_tools(self): ) assert len(asked) == 1 - async def test_two_messages_at_once_to_a_narrowed_one_start_one_run_and_steer_the_other(self): + async def test_two_messages_at_once_to_a_narrowed_one_start_one_run_and_steer_the_other( + self, + ): """As for an instance not narrowed, though a narrowed one's tool names are asked for first, and by a hook that suspends every time.""" taken: list[list[str]] = [] @@ -4358,9 +4373,16 @@ async def work(): (first, second), _ = await turned(work) - assert (first.result["run"], first.result["status"]) == ("choosy-1#2", RUN_COMPLETED) - assert second.result["status"] == "running" and second.result["run"] == "choosy-1#2" - assert [r.ref.run for r in runs.records(CONVERSATION)] == ["choosy-1#1", "choosy-1#2"] + assert (first.result["run"], first.result["status"]) == ( + "choosy-1#2", RUN_COMPLETED + ) + assert ( + second.result["status"] == "running" + and second.result["run"] == "choosy-1#2" + ) + assert [r.ref.run for r in runs.records(CONVERSATION)] == [ + "choosy-1#1", "choosy-1#2" + ] UNLISTED = ("The tools of 'choosy' could not be listed just now " @@ -4385,7 +4407,9 @@ class TestAListingThatFails: async def test_a_task_call_naming_tools_is_told_to_try_again(self): hook, asked = answering() fail = [True] - made = delegations(hook, types=CHOOSING, tool_names=unlisting("choosy", fail=fail)) + made = delegations( + hook, types=CHOOSING, tool_names=unlisting("choosy", fail=fail) + ) async def work(): refused = await made.delegate(request(NARROW)) @@ -4403,7 +4427,9 @@ async def work(): async def test_a_narrowed_ones_follow_up_is_told_so(self, how): hook, asked = answering() fail = [False] - made = delegations(hook, types=CHOOSING, tool_names=unlisting("choosy", fail=fail)) + made = delegations( + hook, types=CHOOSING, tool_names=unlisting("choosy", fail=fail) + ) await turned(lambda: made.delegate(request(NARROW))) fail[0] = True diff --git a/tests/workflow/test_agent_loader.py b/tests/workflow/test_agent_loader.py index 572a68c6..272e30ea 100644 --- a/tests/workflow/test_agent_loader.py +++ b/tests/workflow/test_agent_loader.py @@ -313,7 +313,8 @@ def test_model_choices(self, tmp_path): def test_model_choices_is_a_list(self, tmp_path): path = _write( - tmp_path, "agents:\n - name: a\n instruction: hi\n model_choices: fast\n" + tmp_path, + "agents:\n - name: a\n instruction: hi\n model_choices: fast\n" ) with pytest.raises(ValidationError) as exc: load_agents_from_yaml(path) diff --git a/tests/workflow/test_agent_run_event.py b/tests/workflow/test_agent_run_event.py index c116011a..e2b112ff 100644 --- a/tests/workflow/test_agent_run_event.py +++ b/tests/workflow/test_agent_run_event.py @@ -92,13 +92,17 @@ def test_a_first_runs_start_carries_what_its_instance_keeps(self): def test_a_first_runs_start_carries_the_tools_and_model_it_was_given(self): event = WorkflowEvent.agent_run( - RESEARCHER, "started", title="Find X.", tools=("lookup", "fetch"), model="fast" + RESEARCHER, "started", title="Find X.", tools=("lookup", "fetch"), + model="fast" ) - assert (event.metadata["tools"], event.metadata["model"]) == (["lookup", "fetch"], "fast") + assert (event.metadata["tools"], event.metadata["model"]) == ( + ["lookup", "fetch"], "fast" + ) def test_none_of_its_own_tools_is_said_too(self): - event = WorkflowEvent.agent_run(RESEARCHER, "started", title="Find X.", tools=[]) + event = WorkflowEvent.agent_run(RESEARCHER, "started", title="Find X.", + tools=[]) assert event.metadata["tools"] == [] assert "model" not in event.metadata diff --git a/tests/workflow/test_agent_runs.py b/tests/workflow/test_agent_runs.py index c6b4b6a2..69d24616 100644 --- a/tests/workflow/test_agent_runs.py +++ b/tests/workflow/test_agent_runs.py @@ -908,7 +908,9 @@ def test_records_written_before_tools_and_model_read_them_as_none(self): ("tools", "lookup"), ("tools", [1]), ("tools", {"lookup": True}), ("model", 3), ("model", ["fast"]), ]) - def test_tools_or_a_model_that_do_not_read_are_records_it_cannot_read(self, field, value): + def test_tools_or_a_model_that_do_not_read_are_records_it_cannot_read( + self, field, value + ): runs = AgentRuns() a_conversation(runs) data = json.loads(json.dumps(runs.export(ONE))) diff --git a/tests/workflow/test_budgets_before_services.py b/tests/workflow/test_budgets_before_services.py index c378cac3..3a6532a7 100644 --- a/tests/workflow/test_budgets_before_services.py +++ b/tests/workflow/test_budgets_before_services.py @@ -158,7 +158,8 @@ async def test_a_window_that_works_builds_services_and_keeps_its_budgets( def _choosing(choice: str) -> list[AgentConfig]: - """A lead, and an agent whose tool needs a service (the jobs) with ``choice`` as its model choice.""" + """A lead, and an agent whose tool needs a service (the jobs) with ``choice`` as its + model choice.""" from agentic_cli.tools.jobs.tools import job_status return [ diff --git a/tests/workflow/test_manager_models.py b/tests/workflow/test_manager_models.py index c2159359..ba92a0aa 100644 --- a/tests/workflow/test_manager_models.py +++ b/tests/workflow/test_manager_models.py @@ -421,7 +421,8 @@ async def test_a_role_no_setting_maps_is_computed_and_its_provider_listed( provider whose newest fast-tier model it takes, as it does for an agent on that role.""" keys(monkeypatch, "anthropic") - manager = adk(team(model_choices=("fast",)), settings(default_model="claude-opus-4-7")) + manager = adk(team(model_choices=("fast",)), + settings(default_model="claude-opus-4-7")) await manager.initialize_services() try: @@ -439,7 +440,8 @@ async def test_a_choice_that_cannot_run_is_reported_with_the_rest_and_nothing_ke configs = [ AgentConfig(name="coordinator", prompt="p", sub_agents=["a", "b"]), AgentConfig(name="a", prompt="p", model="anthropic:claude-sonnet-4-5"), - AgentConfig(name="b", prompt="p", model_choices=("anthropic:claude-haiku-4-5",)), + AgentConfig(name="b", prompt="p", + model_choices=("anthropic:claude-haiku-4-5",)), ] manager = adk(configs, settings()) @@ -455,7 +457,8 @@ async def test_a_choice_that_cannot_run_is_reported_with_the_rest_and_nothing_ke async def test_a_choice_takes_the_agent_s_generation_settings( self, providers, monkeypatch ): - """A thinking level the choice's model lacks fails the start, as on the agent's own.""" + """A thinking level the choice's model lacks fails the start, as on the agent's + own.""" keys(monkeypatch, "anthropic") writer = ModelSettings(thinking=ThinkingSettings(mode="xhigh")) manager = adk( @@ -474,7 +477,8 @@ async def test_a_choice_takes_the_agent_s_generation_settings( async def test_a_model_switch_resolves_them_again(self, providers, monkeypatch): keys(monkeypatch, "google") - manager = adk(team(model_choices=("default",)), settings(default_model="gemini-2.5-pro")) + manager = adk(team(model_choices=("default",)), + settings(default_model="gemini-2.5-pro")) await manager.initialize_services() try: @@ -1310,7 +1314,8 @@ async def test_the_base_names_a_configured_types_tools_as_its_delegations_do(pro SimpleNamespace(_tool_names=None), configs[1] ) == names assert await manager._agent_tool_names("nobody") == frozenset() - # The manager has resolved its configs' strings; a Delegations over raw ones names alike. + # The manager has resolved its configs' strings; a Delegations over raw ones names + # alike. raw = AgentConfig(name="writer", prompt="p", tools=[ "web_fetch", "agentic_cli.tools.glob_tool.glob", read_file, ]) diff --git a/tests/workflow/test_model_services.py b/tests/workflow/test_model_services.py index 361a499f..c516cfd3 100644 --- a/tests/workflow/test_model_services.py +++ b/tests/workflow/test_model_services.py @@ -475,17 +475,21 @@ def test_model_choices_are_named_references_too(): ModelRef("anthropic", "claude-haiku-4-5"), ) assert model_services.reference_settings(settings, agents) == { - ModelRef("google", "gemini-2.5-flash"): "default_model and agent 'writer' model_choices", + ModelRef("google", "gemini-2.5-flash"): ( + "default_model and agent 'writer' model_choices" + ), ModelRef("google", "gemini-2.5-pro"): "agent 'writer'", ModelRef("anthropic", "claude-haiku-4-5"): "agent 'writer' model_choices", } def test_a_role_choice_is_computed(): - settings = BaseSettings(default_model="gemini-2.5-flash", model_roles={"strong": "o3"}) + settings = BaseSettings(default_model="gemini-2.5-flash", + model_roles={"strong": "o3"}) agents = [ AgentConfig(name="writer", prompt="p", model_choices=("fast", "strong")), - AgentConfig(name="critic", prompt="p", model_choices=("vision",)), # an app's role + # an app's role + AgentConfig(name="critic", prompt="p", model_choices=("vision",)), ] assert model_services.computed_roles(settings, agents) == ("fast",) diff --git a/tests/workflow/test_skills.py b/tests/workflow/test_skills.py index 15d3f742..6c85ee1c 100644 --- a/tests/workflow/test_skills.py +++ b/tests/workflow/test_skills.py @@ -192,7 +192,9 @@ def test_manager_attaches_skill_toolset(self, tmp_path, mock_context): # Scripts disabled by default -> run_skill_script not exposed. assert "run_skill_script" not in {t.name for t in skill_toolsets[0]._tools} - async def test_a_task_may_narrow_a_sub_agent_to_its_skill_tools_and_its_own(self, tmp_path): + async def test_a_task_may_narrow_a_sub_agent_to_its_skill_tools_and_its_own( + self, tmp_path + ): """What ``task``'s ``tools`` may name: the agent's own tools by their names, its skill toolset's tools, never the state or delegation tools.""" from agentic_cli.tools import read_file @@ -206,7 +208,8 @@ async def test_a_task_may_narrow_a_sub_agent_to_its_skill_tools_and_its_own(self ] with MockContext(google_api_key="test-key", session_store="memory") as context: mgr = GoogleADKWorkflowManager( - agent_configs=configs, settings=context.settings, model="gemini-2.5-flash" + agent_configs=configs, settings=context.settings, + model="gemini-2.5-flash" ) await mgr.initialize_services() try: diff --git a/tests/workflow/test_subagent_config.py b/tests/workflow/test_subagent_config.py index 7baa7949..8a726a0a 100644 --- a/tests/workflow/test_subagent_config.py +++ b/tests/workflow/test_subagent_config.py @@ -1,4 +1,5 @@ -"""A sub-agent type's delegation fields: ``brief_required``, ``limits``, ``continuable``, ``spawnable_by`` and ``model_choices``. +"""A sub-agent type's delegation fields: ``brief_required``, ``limits``, +``continuable``, ``spawnable_by`` and ``model_choices``. ``brief_required`` names the brief fields a delegation to the type must fill (the title and the objective are always needed); ``limits`` are the type's @@ -58,8 +59,10 @@ def test_an_instance_takes_follow_ups_by_default(self): def test_they_follow_inherit_context(self): # Appended: a positional AgentConfig(...) written before them still binds. names = [f.name for f in dataclasses.fields(AgentConfig)] - assert names[-6:] == ["inherit_context", "brief_required", "limits", "continuable", - "spawnable_by", "model_choices"] + assert names[-6:] == [ + "inherit_context", "brief_required", "limits", "continuable", + "spawnable_by", "model_choices", + ] def test_no_model_choices_by_default(self): assert AgentConfig(name="a", prompt="p").model_choices == () @@ -394,10 +397,13 @@ def test_the_policy_must_be_a_policy(self): class TestModelChoices: """``model_choices``: the models a delegation may pick instead of the type's own.""" - @pytest.mark.parametrize("value", [("fast",), ["fast", "anthropic:claude-haiku-4-5"], - ("claude-opus-4-7",)]) + @pytest.mark.parametrize("value", [ + ("fast",), ["fast", "anthropic:claude-haiku-4-5"], ("claude-opus-4-7",), + ]) def test_a_tuple_or_list_of_models_or_roles(self, value): - assert validate_agent_graph(team(writer={"model_choices": value})).root_name == "lead" + assert validate_agent_graph( + team(writer={"model_choices": value}) + ).root_name == "lead" @pytest.mark.parametrize("value", ["fast", ("fast", ""), ("fast", " "), (1,), None, {"fast"}]) diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index e5cc959e..2f21288f 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -1393,7 +1393,9 @@ async def test_a_delegation_ends_at_its_own_result(self, make_crew): (ended,) = runs_of(events, RUN_COMPLETED) assert (ended.run, ended.metadata["result"]) == (RESEARCHER, "X is 42.") assert events.index(results[0]) < events.index(ended) < events.index(results[1]) - assert envelope_read(crew.results_read("coordinator")["c1"])["result"] == "X is 42." + assert envelope_read( + crew.results_read("coordinator")["c1"] + )["result"] == "X is 42." async def test_after_ctrl_c_a_delegation_is_answered_as_interrupted(self, make_crew): crew = make_crew( @@ -1651,7 +1653,9 @@ async def test_an_answer_that_ended_well_is_not_touched(self, make_crew): events = await crew.turn() - assert envelope_read(crew.results_read("coordinator")["c1"])["result"] == "X is 42." + assert envelope_read( + crew.results_read("coordinator")["c1"] + )["result"] == "X is 42." (ended,) = runs_of(events, RUN_COMPLETED) assert ended.metadata["partial"] is False assert [e for e in events if e.type is EventType.ERROR] == [] @@ -2847,7 +2851,9 @@ async def test_a_trailing_empty_answer_leaves_the_last_text(self, make_crew): events = await crew.turn() - assert envelope_read(crew.results_read("coordinator")["c1"])["result"] == "X is 42." + assert envelope_read( + crew.results_read("coordinator")["c1"] + )["result"] == "X is 42." (ended,) = runs_of(events, RUN_COMPLETED) assert ended.metadata["result"] == "X is 42." @@ -3616,7 +3622,9 @@ async def test_ctrl_c_with_a_run_queued_and_another_lending_leaves_no_waiter( assert working(events, RUN_STARTED, RUN_QUEUED, RUN_RUNNING, RUN_COMPLETED) == [ ("researcher-2", RUN_STARTED), ("researcher-2", RUN_COMPLETED), ] - assert envelope_read(crew.results_read("coordinator")["c3"])["result"] == "Y is 7." + assert envelope_read( + crew.results_read("coordinator")["c3"] + )["result"] == "Y is 7." def asking_crew(make_crew, *, holder: Step, **scripts: list[Step]) -> Crew: @@ -3675,7 +3683,9 @@ async def answer(request: UserInputRequest) -> str: assert ended.index(("asker-1", RUN_COMPLETED)) < ended.index( ("researcher-1", RUN_COMPLETED) ) - assert envelope_read(crew.results_read("coordinator")["c1"])["result"] == "Asked." + assert envelope_read( + crew.results_read("coordinator")["c1"] + )["result"] == "Asked." assert (crew.slots().free, crew.slots().waiting) == (1, 0) async def test_a_run_answered_while_its_slot_works_for_another_waits_queued(self, make_crew): @@ -3706,7 +3716,9 @@ async def answer(request: UserInputRequest) -> str: assert [status for instance, status in working( events, RUN_INPUT_REQUIRED, RUN_QUEUED, RUN_RUNNING ) if instance == "asker-1"] == [RUN_INPUT_REQUIRED, RUN_QUEUED, RUN_RUNNING] - assert envelope_read(crew.results_read("coordinator")["c1"])["result"] == "Asked." + assert envelope_read( + crew.results_read("coordinator")["c1"] + )["result"] == "Asked." assert (crew.slots().free, crew.slots().waiting) == (1, 0) async def test_two_runs_at_permission_prompts_with_one_slot_both_finish( @@ -4305,7 +4317,9 @@ async def test_on_adk_a_child_session_the_store_lost_is_made_again(self, make_cr await crew.turn("Go on.") - assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Went on." + assert envelope_read( + crew.results_read("coordinator")["c2"] + )["result"] == "Went on." assert crew.message_count("researcher", 1) == 1 async def test_a_follow_up_that_ends_without_text_returns_none_of_the_first_runs( @@ -4322,7 +4336,9 @@ async def test_a_follow_up_that_ends_without_text_returns_none_of_the_first_runs await crew.turn() - assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "" + assert envelope_read( + crew.results_read("coordinator")["c2"] + )["result"] == "" async def test_an_inheriting_instance_sees_its_parents_conversation_once(self, make_crew): """The copy of the parent's conversation is made at the instance's first @@ -4342,7 +4358,9 @@ async def test_an_inheriting_instance_sees_its_parents_conversation_once(self, m first, second = crew.bodies("researcher") assert first.count("The parent said hello.") == 1 assert second.count("The parent said hello.") == 1 - assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Y is 7." + assert envelope_read( + crew.results_read("coordinator")["c2"] + )["result"] == "Y is 7." assert [len(answers) for _, answers in crew.call_results("researcher", 1)] == [ len(answers) for _, answers in crew.call_results("researcher", 0) ] @@ -4360,7 +4378,9 @@ async def test_a_follow_up_blocks_no_event_loop(self, make_crew): with no_blocking_calls(): await crew.turn("Go on.") - assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Went on." + assert envelope_read( + crew.results_read("coordinator")["c2"] + )["result"] == "Went on." class TestARefusedFollowUp: @@ -4515,7 +4535,9 @@ async def test_after_ctrl_c(self, make_crew): assert json.loads(answers["r1"]) == {"success": True, "value": 42} assert INTERRUPTED_BY_USER in answers["r2"] assert crew.last_message("researcher", 1) == "Go on." - assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Went on." + assert envelope_read( + crew.results_read("coordinator")["c2"] + )["result"] == "Went on." assert [(r.ref.run, r.status) for r in crew.records()] == [ ("researcher-1#1", RUN_INTERRUPTED), ("researcher-1#2", RUN_COMPLETED), ] @@ -4541,7 +4563,9 @@ async def test_after_its_parent_or_a_limit_stopped_it_and_the_turn_ended( assert json.loads(answers["r1"]) == {"success": True, "value": 42} assert json.loads(answers["r2"]) == interrupted(interrupted_by(cause)) assert INTERRUPTED_BY_USER not in answers["r2"] - assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Went on." + assert envelope_read( + crew.results_read("coordinator")["c2"] + )["result"] == "Went on." async def test_after_a_crash_in_a_new_process(self, make_crew, monkeypatch): first = make_crew( @@ -4574,7 +4598,9 @@ async def test_after_a_crash_in_a_new_process(self, make_crew, monkeypatch): assert [(call_id, len(held)) for call_id, held in second.call_results("coordinator", 0) if call_id == "c1"] == [("c1", 1)] assert INTERRUPTED in second.results_read("coordinator", 0)["c1"] - assert envelope_read(second.results_read("coordinator")["c2"])["result"] == "Went on." + assert envelope_read( + second.results_read("coordinator")["c2"] + )["result"] == "Went on." assert [(r.ref.run, r.status) for r in second.records()][-1] == ( "researcher-1#2", RUN_COMPLETED, ) @@ -4593,7 +4619,9 @@ async def test_it_runs_on_the_new_model_with_its_history_and_records(self, make_ await crew.manager.reinitialize(model="claude-haiku-4-5", preserve_sessions=True) await crew.turn("Now Y.") - assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Y is 7." + assert envelope_read( + crew.results_read("coordinator")["c2"] + )["result"] == "Y is 7." assert "X is 42." in crew.bodies("researcher")[1] assert crew.models("researcher") == ["claude-sonnet-4-6", "claude-haiku-4-5"] assert [(r.ref.run, r.status) for r in crew.records()] == [ @@ -5434,7 +5462,9 @@ async def test_nothing_is_left_and_its_id_numbers_from_1(self, make_crew, store) assert (crew.records(), crew.instances()) == ([], []) assert crew.ledger().totals() == UsageTotals() await crew.turn("Again.") - assert envelope_read(crew.results_read("coordinator")["c4"])["result"] == "Z is 3." + assert envelope_read( + crew.results_read("coordinator")["c4"] + )["result"] == "Z is 3." assert [r.ref.run for r in crew.records()] == ["researcher-1#1"] @@ -5483,7 +5513,9 @@ async def test_a_follow_up_after_its_summary_or_trim_still_holds_it(self, make_c if e.type is EventType.CONTEXT_TRIMMED] == ["researcher"] # ...and still held the brief, once. assert last.count("# Task: Find X.") == 1 - assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Y is 7." + assert envelope_read( + crew.results_read("coordinator")["c2"] + )["result"] == "Y is 7." def roster(*lines: str) -> str: @@ -5748,7 +5780,9 @@ async def view() -> None: assert crew.manager.interrupt_instance("researcher-1") is False # Its parent continues it. await crew.turn("Go on.") - assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Went on." + assert envelope_read( + crew.results_read("coordinator")["c2"] + )["result"] == "Went on." async def test_one_that_cannot_run_is_one_error_and_nothing_runs(self, make_crew): crew = make_crew( @@ -6494,14 +6528,16 @@ async def test_with_follow_ups_it_gets_the_parents_tools_and_the_roster(self, ma ] -# -- a delegation's tools and model ------------------------------------------------------ +# -- a delegation's tools and model ------------------------------------------------ def narrow_team(**researcher: Any) -> list[AgentConfig]: - """A coordinator, and a researcher with two tools of its own and its plan's tools.""" + """A coordinator, and a researcher with two tools of its own and its plan's + tools.""" return [ agent("coordinator", sub_agents=("researcher",)), - agent("researcher", tools=(contract_lookup, contract_whoami), include_state_tools=True, + agent("researcher", tools=(contract_lookup, contract_whoami), + include_state_tools=True, **researcher), ] @@ -6542,7 +6578,9 @@ async def test_its_requests_offer_only_its_tools_and_a_call_of_another_is_unknow "success": True, "value": 42, } assert SEEN == [] # contract_whoami never ran - assert envelope_read(crew.results_read("coordinator")["c1"])["result"] == "X is 42." + assert envelope_read( + crew.results_read("coordinator")["c1"] + )["result"] == "X is 42." (instance,) = crew.manager.agent_runs.instances(crew.conversation) assert (instance.tools, instance.model) == (("contract_lookup",), None) @@ -6562,8 +6600,10 @@ async def test_left_out_it_has_them_all(self, make_crew): async def test_a_type_started_at_run_time_is_narrowed_alike(self, make_crew): crew = make_crew( - [*team(), helper(tools=(contract_lookup, contract_whoami))], subagents=SPAWNING, - coordinator=[calls(delegate("helper", "Help.", "c1", tools=["contract_whoami"])), + [*team(), helper(tools=(contract_lookup, contract_whoami))], + subagents=SPAWNING, + coordinator=[calls(delegate("helper", "Help.", "c1", + tools=["contract_whoami"])), says("Done.")], helper=[says("Helped.")], ) @@ -6577,7 +6617,8 @@ async def test_a_follow_up_keeps_them(self, make_crew): narrow_team(), subagents=FOLLOWING, coordinator=[calls(delegate("researcher", "Find X.", "c1", tools=["contract_lookup"])), says("Asked."), - calls(message("researcher-1", "Now find Y.", "c2")), says("Done.")], + calls(message("researcher-1", "Now find Y.", "c2")), + says("Done.")], researcher=[says("X is 42."), says("Y is 7.")], ) @@ -6585,7 +6626,9 @@ async def test_a_follow_up_keeps_them(self, make_crew): await crew.turn("Find Y too.") assert crew.tool_names("researcher", 1) == NARROWED - assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Y is 7." + assert envelope_read( + crew.results_read("coordinator")["c2"] + )["result"] == "Y is 7." class TestWhatATypeCannotTake: @@ -6601,7 +6644,9 @@ class TestWhatATypeCannotTake: "The model for 'researcher' must be one of its model choices: " "anthropic:claude-haiku-4-5."), ], ids=["tools", "no-choices", "model"]) - async def test_starts_no_run_and_takes_no_count(self, make_crew, researcher, fields, error): + async def test_starts_no_run_and_takes_no_count( + self, make_crew, researcher, fields, error + ): crew = make_crew( narrow_team(**researcher), subagents=SubAgentPolicy(max_runs_per_turn=1), coordinator=[calls(delegate("researcher", "Find X.", "c1", **fields)), @@ -6615,9 +6660,13 @@ async def test_starts_no_run_and_takes_no_count(self, make_crew, researcher, fie "success": False, "error": error, } # The turn's one run is still its to start. - assert envelope_read(crew.results_read("coordinator", 2)["c2"])["result"] == "Y is 7." + assert envelope_read( + crew.results_read("coordinator", 2)["c2"] + )["result"] == "Y is 7." assert [r.ref.run for r in crew.records()] == ["researcher-1#1"] - assert [e.metadata["status"] for e in runs_of(events)] == [RUN_STARTED, RUN_COMPLETED] + assert [e.metadata["status"] for e in runs_of(events)] == [ + RUN_STARTED, RUN_COMPLETED + ] #: A cheaper model the researcher may be run on: a model choice. @@ -6653,14 +6702,18 @@ async def test_its_requests_go_to_the_choices_model_and_its_usage_is_under_it( narrow_team(model_choices=(CHOICE,)), coordinator=[calls(delegate("researcher", "Find X.", "c1", model=CHOICE), delegate("researcher", "Find Y.", "c2")), says("Done.")], - researcher=[says("X is 42.", usage=(100, 10)), says("Y is 7.", usage=(80, 8))], + researcher=[ + says("X is 42.", usage=(100, 10)), says("Y is 7.", usage=(80, 8)) + ], ) with no_blocking_calls(): await crew.turn() by_run = {r.ref.run: r for r in crew.records()} - assert sorted(crew.sent_models("researcher")) == ["claude-haiku-4-5", "claude-sonnet-4-6"] + assert sorted(crew.sent_models("researcher")) == [ + "claude-haiku-4-5", "claude-sonnet-4-6" + ] assert by_run["researcher-1#1"].usage == {CHOICE: {"input": 100, "output": 10}} assert by_run["researcher-2#1"].usage == { "anthropic:claude-sonnet-4-6": {"input": 80, "output": 8}, @@ -6676,7 +6729,8 @@ async def test_a_follow_up_runs_on_it_after_a_model_switch_too(self, make_crew): crew = make_crew( narrow_team(model_choices=(CHOICE,)), subagents=FOLLOWING, coordinator=[calls(delegate("researcher", "Find X.", "c1", model=CHOICE)), - says("Asked."), calls(message("researcher-1", "Now find Y.", "c2")), + says("Asked."), calls(message("researcher-1", "Now find Y.", + "c2")), says("Done.")], researcher=[says("X is 42."), says("Y is 7.")], ) @@ -6685,18 +6739,27 @@ async def test_a_follow_up_runs_on_it_after_a_model_switch_too(self, make_crew): await crew.manager.reinitialize(model="claude-opus-4-7", preserve_sessions=True) await crew.turn("Find Y too.") - assert crew.sent_models("researcher") == ["claude-haiku-4-5", "claude-haiku-4-5"] + assert crew.sent_models("researcher") == [ + "claude-haiku-4-5", "claude-haiku-4-5" + ] assert crew.sent_models("coordinator")[-1] == "claude-opus-4-7" assert "X is 42." in crew.bodies("researcher")[1] - assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Y is 7." + assert envelope_read( + crew.results_read("coordinator")["c2"] + )["result"] == "Y is 7." class TestAModelChoiceInTheRawLog: - async def test_its_calls_records_name_the_choices_model(self, make_crew, monkeypatch): + async def test_its_calls_records_name_the_choices_model( + self, make_crew, monkeypatch + ): settings = BaseSettings( - session_store="memory", default_model="claude-sonnet-4-6", raw_llm_logging=True + session_store="memory", default_model="claude-sonnet-4-6", + raw_llm_logging=True + ) + monkeypatch.setattr( + sys.modules[__name__], "_settings", lambda store, models=None: settings ) - monkeypatch.setattr(sys.modules[__name__], "_settings", lambda store, models=None: settings) crew = make_crew( narrow_team(model_choices=(CHOICE,)), coordinator=[calls(delegate("researcher", "Find X.", "c1", model=CHOICE)), @@ -6730,7 +6793,8 @@ async def test_the_follow_up_runs_as_its_first_run_did(self, make_crew): await first.manager.cleanup() second = make_crew( narrow_team(model_choices=(CHOICE,)), subagents=FOLLOWING, store="sqlite", - coordinator=[calls(message("researcher-1", "Now find Y.", "c2")), says("Done.")], + coordinator=[calls(message("researcher-1", "Now find Y.", "c2")), + says("Done.")], researcher=[says("Y is 7.")], ) @@ -6742,7 +6806,9 @@ async def test_the_follow_up_runs_as_its_first_run_did(self, make_crew): assert (instance.tools, instance.model) == (("contract_lookup",), CHOICE) assert second.sent_models("researcher") == ["claude-haiku-4-5"] assert second.tool_names("researcher") == NARROWED - assert envelope_read(second.results_read("coordinator")["c2"])["result"] == "Y is 7." + assert envelope_read( + second.results_read("coordinator")["c2"] + )["result"] == "Y is 7." class TestAChoicesSmallerWindow: @@ -6751,7 +6817,9 @@ class TestAChoicesSmallerWindow: choice's numbers (ADK's fit guard trims it, Deep Agents summarizes it), where on the type's own model it is sent whole.""" - @pytest.mark.parametrize("chosen", [SMALL_MODEL, None], ids=["the-choice", "its-own"]) + @pytest.mark.parametrize( + "chosen", [SMALL_MODEL, None], ids=["the-choice", "its-own"] + ) async def test_its_requests_fit_the_choices_budget(self, make_crew, chosen): crew = make_crew( [agent("coordinator", sub_agents=("reader",)), @@ -6770,11 +6838,15 @@ async def test_its_requests_fit_the_choices_budget(self, make_crew, chosen): events = await crew.turn("Have the reader sum it up.") sent = crew.bodies("reader")[-1] - trimmed = [e.metadata["agent"] for e in events if e.type is EventType.CONTEXT_TRIMMED] + trimmed = [ + e.metadata["agent"] for e in events if e.type is EventType.CONTEXT_TRIMMED + ] if chosen: assert crew.sent_models("reader") == ["claude-haiku-4-5"] assert "First: word" not in sent and trimmed == ["reader"] else: assert crew.sent_models("reader") == ["claude-sonnet-4-6"] assert "First: word" in sent and trimmed == [] - assert envelope_read(crew.results_read("coordinator")["c1"])["result"] == "It was words." + assert envelope_read( + crew.results_read("coordinator")["c1"] + )["result"] == "It was words."