From fdca7380db9238a9e527e37322a326dd066b6822 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:58:51 -0500 Subject: [PATCH 1/6] Skills: a skill's frontmatter may name the agent it starts SKILL_AGENT_KEY (agent, top level), skill_agent and skill_started_by (skill:). SkillAgents is one loading agent's: check warns, as the agent is built, of a skill whose agent its first run could not start (skill_agent_not_startable, once per agent and skill); start checks the type, the policy and the loading run's depth, then starts the run through Delegations.start with the skill's name and body as its brief, counted, and adds "skill" to its envelope. Delegations.types lists every agent type, read-only. --- src/agentic_cli/tools/skills/__init__.py | 19 +- src/agentic_cli/tools/skills/agents.py | 160 +++++++++++ src/agentic_cli/workflow/agents/delegate.py | 6 + tests/tools/test_skill_agents.py | 297 ++++++++++++++++++++ 4 files changed, 481 insertions(+), 1 deletion(-) create mode 100644 src/agentic_cli/tools/skills/agents.py create mode 100644 tests/tools/test_skill_agents.py diff --git a/src/agentic_cli/tools/skills/__init__.py b/src/agentic_cli/tools/skills/__init__.py index e7d18e25..29f9326c 100644 --- a/src/agentic_cli/tools/skills/__init__.py +++ b/src/agentic_cli/tools/skills/__init__.py @@ -9,10 +9,19 @@ Importing this package registers the skill tool names with the permission registry, so both backends bind their skill tools to the same definitions (the ADK PermissionPlugin and the Deep Agents gate both allow them). + +A skill whose frontmatter names an agent type starts a run of it when loaded +(``agents``). """ from typing import Any +from agentic_cli.tools.skills.agents import ( + SKILL_AGENT_KEY, + SkillAgents, + skill_agent, + skill_started_by, +) from agentic_cli.tools.skills.permissions import register_skill_tool_permissions from agentic_cli.tools.skills.store import SkillStore from agentic_cli.tools.skills.toolset import make_skill_toolset @@ -21,7 +30,15 @@ register_skill_tool_permissions() # make_skill_tools is left out: a star import would load LangChain. -__all__ = ["SkillStore", "make_skill_toolset", "register_skill_tool_permissions"] +__all__ = [ + "SKILL_AGENT_KEY", + "SkillAgents", + "SkillStore", + "make_skill_toolset", + "register_skill_tool_permissions", + "skill_agent", + "skill_started_by", +] def __getattr__(name: str) -> Any: diff --git a/src/agentic_cli/tools/skills/agents.py b/src/agentic_cli/tools/skills/agents.py new file mode 100644 index 00000000..4ae92746 --- /dev/null +++ b/src/agentic_cli/tools/skills/agents.py @@ -0,0 +1,160 @@ +"""A skill that starts an agent. + +A skill's ``SKILL.md`` may name one of the app's agent types at the top of its +frontmatter (``agent: researcher``). When an agent loads such a skill, a run of +that type starts, instead of the skill's instructions being handed back: its +task message is the skill's body under its name, its parent the loading +agent's run, ``started_by`` ``skill:``, and the load's result the run's +envelope with the skill's name added. + +A load starts a run only where any run-time start is allowed: the type is one +of the app's, the type's ``spawnable_by`` and the policy's ``spawn_sources`` +both hold ``"skill"``, and the loading run may start a type at its depth +(``max_spawn_depth``). Otherwise the load is refused and starts nothing, and a +skill whose agent its agent's first run could not start is warned of as the +agent is built: the app still starts, since a skill file can come from a +user's folder. + +``SkillAgents`` is one loading agent's: ADK's ``adk/skill_tool.py::SkillLoadTool`` +and Deep Agents' ``task_tool.start_skill_run`` call it. Imports no backend. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from typing import TYPE_CHECKING, Any + +from agentic_cli.logging import Loggers +from agentic_cli.workflow.agents.brief import Brief +from agentic_cli.workflow.agents.delegate import Delegated, StartRequest +from agentic_cli.workflow.agents.spawn import SKILL_SOURCE, may_spawn, spawnable +from agentic_cli.workflow.sessions import get_active_run + +if TYPE_CHECKING: + from agentic_cli.workflow.agents.delegate import Delegations + +logger = Loggers.tools() + +#: The frontmatter key (top level) that names the agent type a skill starts. +SKILL_AGENT_KEY = "agent" + +#: What a refused load says; ``reason`` is one of the three below. +SKILL_AGENT_ERROR = "The skill '{skill}' starts the agent '{agent}', which {reason}." +UNKNOWN_TYPE = "is not one of this app's agent types" +NOT_FOR_SKILLS = "this app does not let a skill start" +NOT_HERE = "cannot be started here: sub-agents cannot start sub-agents" + + +def skill_started_by(name: str) -> str: + """``started_by`` of a run the skill ``name`` starts.""" + return f"skill:{name}" + + +def skill_agent(skill: Any) -> str | None: + """The agent type ``skill`` names, or None. + + A value that is not text is taken as written, so it names no type and its + load is refused, never silently loaded as instructions. + """ + value = getattr(skill.frontmatter, SKILL_AGENT_KEY, None) + if value is None: + return None + return value if isinstance(value, str) else str(value) + + +class SkillAgents: + """What one agent's skills may start, and the start. + + Args: + agent: The loading agent's type name. + delegations: The manager's ``Delegations``, read when asked (it is + replaced with the workflow). + root: Whether the agent is the root (its first run is at depth 0, + any other agent's at 1). + warned: The (agent, skill) pairs already warned of, shared by the + builds of one agent (a type and its model choices): each is + logged once. None: this object's own. + """ + + def __init__( + self, + agent: str, + delegations: Callable[[], Delegations], + *, + root: bool, + warned: set[tuple[str, str]] | None = None, + ) -> None: + self._agent = agent + self._delegations = delegations + self._root = root + self._warned = warned if warned is not None else set() + + def _reason(self, name: str, depth: int) -> str | None: + """Why this agent's run at ``depth`` may not start the type ``name``, or None.""" + delegations = self._delegations() + types = delegations.types + config = types.get(name) + if config is None: + return UNKNOWN_TYPE + policy = delegations.policy + if name not in spawnable(list(types.values()), policy, SKILL_SOURCE): + return NOT_FOR_SKILLS + caller = types.get(self._agent) + if ( + not may_spawn(depth, policy) + or (caller is not None and caller.inherit_context) + or (depth > 0 and config.inherit_context) + ): + return NOT_HERE + return None + + def refusal(self, skill: Any, depth: int) -> str | None: + """The error a load of ``skill`` from a run at ``depth`` gets, or None to start it.""" + name = skill_agent(skill) + if name is None: + return None + reason = self._reason(name, depth) + if reason is None: + return None + return SKILL_AGENT_ERROR.format(skill=skill.name, agent=name, reason=reason) + + def check(self, skills: Sequence[Any]) -> None: + """Warn, once per skill, of each that this agent's first run could not start.""" + for skill in skills: + name = skill_agent(skill) + if name is None or (self._agent, skill.name) in self._warned: + continue + reason = self._reason(name, 0 if self._root else 1) + if reason is None: + continue + self._warned.add((self._agent, skill.name)) + logger.warning( + "skill_agent_not_startable", + agent=self._agent, skill=skill.name, agent_type=name, reason=reason, + ) + + async def start( + self, + skill: Any, + *, + call_id: str | None, + state: Mapping[str, Any], + history: Callable[[], Any] | None, + ) -> Delegated: + """Load ``skill``: start its agent's run, or refuse and start none.""" + caller = get_active_run() + refused = self.refusal(skill, caller.depth if caller is not None else 0) + if refused is not None: + return Delegated(result={"success": False, "error": refused}, state={}, run=None) + delegated = await self._delegations().start(StartRequest( + agent_type=skill_agent(skill) or "", + brief=Brief(title=skill.name, objective=skill.instructions), + started_by=skill_started_by(skill.name), + caller=caller, call_id=call_id, state=state, history=history, counted=True, + )) + if delegated.run is None: + return delegated + return Delegated( + result={**delegated.result, "skill": skill.name}, + state=delegated.state, run=delegated.run, + ) diff --git a/src/agentic_cli/workflow/agents/delegate.py b/src/agentic_cli/workflow/agents/delegate.py index f8d855ac..84f233d4 100644 --- a/src/agentic_cli/workflow/agents/delegate.py +++ b/src/agentic_cli/workflow/agents/delegate.py @@ -128,6 +128,7 @@ from contextlib import asynccontextmanager, contextmanager from contextvars import ContextVar from dataclasses import dataclass, field +from types import MappingProxyType from typing import TYPE_CHECKING, Any from agentic_cli.constants import truncate @@ -684,6 +685,11 @@ def slots(self, conversation: SessionRef | None) -> SlotPool: pool = self._pools[conversation] = SlotPool(self.policy.max_active) return pool + @property + def types(self) -> Mapping[str, AgentConfig]: + """Every agent type, by name, in config order (read-only): what ``start`` starts.""" + return MappingProxyType(self._types) + def sub_agents(self, agent: str) -> dict[str, AgentConfig]: """The types ``agent`` may start, by name, in its ``sub_agents``' order.""" caller = self._types.get(agent) diff --git a/tests/tools/test_skill_agents.py b/tests/tools/test_skill_agents.py new file mode 100644 index 00000000..ef87416b --- /dev/null +++ b/tests/tools/test_skill_agents.py @@ -0,0 +1,297 @@ +"""A skill that starts an agent (``tools/skills/agents.py``). + +The frontmatter key, read from skills as ADK's loader loads them; then +``SkillAgents`` over a manager's ``Delegations`` with a fake hook and no +backend: what a load may start (the type, the policy and the loading run's +depth), the warning as an agent is built, and the run a load starts. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pytest + +from agentic_cli.tools.skills import ( + SKILL_AGENT_KEY, + SkillAgents, + SkillStore, + skill_agent, + skill_started_by, +) +from agentic_cli.tools.skills import agents as agents_module +from agentic_cli.workflow import live_events +from agentic_cli.workflow.agents import RUN_COMPLETED, RUN_STARTED, AgentRuns, SubAgentPolicy +from agentic_cli.workflow.agents.brief import INHERITED_CONTEXT_NOTE, Brief, task_message +from agentic_cli.workflow.agents.delegate import RUNS_PER_TURN_ERROR, Delegations +from agentic_cli.workflow.config import AgentConfig +from agentic_cli.workflow.live_events import LiveEvents, merged +from agentic_cli.workflow.sessions import ( + SessionRef, + close_turn_scope, + open_turn_scope, + reset_active_run, + reset_active_turn, + runs_this_turn, + set_active_run, + set_active_turn, +) +from tests.loop_guard import no_blocking_calls +from tests.workflow.test_agent_delegate import answering, at + +CONVERSATION = SessionRef("app", "u", "s") +BODY = "Look into the question and report what you find." +TYPES = { + "lead": AgentConfig(name="lead", prompt="p", sub_agents=["middle"]), + "middle": AgentConfig(name="middle", prompt="p", description="Plans."), + "reader": AgentConfig(name="reader", prompt="p", description="Reads.", + inherit_context=True), + "helper": AgentConfig(name="helper", prompt="p", description="Helps.", + spawnable_by=frozenset({"skill"})), + "noter": AgentConfig(name="noter", prompt="p", description="Notes.", + spawnable_by=frozenset({"skill"}), inherit_context=True), + "asked": AgentConfig(name="asked", prompt="p", description="Asked.", + spawnable_by=frozenset({"agent"})), +} +SKILLS = SubAgentPolicy(spawn_sources={"skill"}) + + +def make_skill(parent: Path, name: str, frontmatter: str = "", body: str = BODY) -> Any: + """The skill ``parent/`` with ``frontmatter``'s extra lines, as ADK loads it.""" + folder = parent / name + folder.mkdir(parents=True) + (folder / "SKILL.md").write_text( + f"---\nname: {name}\ndescription: Does {name}.\n{frontmatter}---\n{body}\n", + encoding="utf-8", + ) + (skill,) = SkillStore().resolve([str(folder)]) + return skill + + +def made(hook=None, *, policy: SubAgentPolicy = SKILLS, runs: AgentRuns | None = None): + return Delegations( + runs=runs or AgentRuns(), policy=policy, types=TYPES, + hook=hook or answering()[0], + ) + + +@pytest.fixture +def logged(monkeypatch) -> list[dict[str, Any]]: + """Every log call of ``tools/skills/agents.py``, with its level.""" + events: list[dict[str, Any]] = [] + + class Recorder: + def __getattr__(self, level: str): + return lambda event, **fields: events.append( + {"event": event, "log_level": level, **fields} + ) + + monkeypatch.setattr(agents_module, "logger", Recorder()) + return events + + +class TestTheFrontmatterKey: + def test_names_the_agent_at_the_top_of_the_frontmatter(self, tmp_path): + assert SKILL_AGENT_KEY == "agent" + assert skill_agent(make_skill(tmp_path, "research", "agent: helper\n")) == "helper" + + @pytest.mark.parametrize("frontmatter, named", [ + ("", None), + ("agent:\n", None), + ("metadata:\n agent: helper\n", None), + ("agent: 3\n", "3"), + ("agent: [a, b]\n", "['a', 'b']"), + ], ids=["none", "empty", "under-metadata", "a-number", "a-list"]) + def test_anything_else_names_none_or_is_taken_as_written(self, tmp_path, frontmatter, named): + assert skill_agent(make_skill(tmp_path, "research", frontmatter)) == named + + def test_who_started_a_run_a_skill_starts(self): + assert skill_started_by("research") == "skill:research" + + +class TestWhatALoadMayStart: + @pytest.mark.parametrize("agent, root, policy, named, reason", [ + ("lead", True, SKILLS, "nobody", "is not one of this app's agent types"), + ("lead", True, SKILLS, "asked", "this app does not let a skill start"), + ("lead", True, SKILLS, "middle", "this app does not let a skill start"), + ("lead", True, SubAgentPolicy(spawn_sources={"agent"}), "helper", + "this app does not let a skill start"), + ("middle", False, SKILLS, "helper", + "cannot be started here: sub-agents cannot start sub-agents"), + ("reader", False, SubAgentPolicy(spawn_sources={"skill"}, max_spawn_depth=2), "helper", + "cannot be started here: sub-agents cannot start sub-agents"), + ("middle", False, SubAgentPolicy(spawn_sources={"skill"}, max_spawn_depth=2), "noter", + "cannot be started here: sub-agents cannot start sub-agents"), + ], ids=["unknown", "type-not-for-skills", "a-static-sub-agent", "policy-not-for-skills", + "past-the-depth", "an-inheriting-caller", "an-inheriting-type-below-the-root"]) + def test_a_skill_it_may_not_start_is_warned_of_as_the_agent_is_built( + self, tmp_path, logged, agent, root, policy, named, reason + ): + skill = make_skill(tmp_path, "research", f"agent: {named}\n") + agents = SkillAgents(agent, lambda: made(policy=policy), root=root) + + agents.check([skill]) + + assert logged == [{ + "event": "skill_agent_not_startable", "log_level": "warning", "agent": agent, + "skill": "research", "agent_type": named, "reason": reason, + }] + assert agents.refusal(skill, 0 if root else 1) == ( + f"The skill 'research' starts the agent '{named}', which {reason}." + ) + + @pytest.mark.parametrize("agent, root, policy, named", [ + ("lead", True, SKILLS, "helper"), + ("lead", True, SKILLS, "noter"), + ("middle", False, SubAgentPolicy(spawn_sources={"skill"}, max_spawn_depth=2), "helper"), + ], ids=["the-root", "an-inheriting-type-by-the-root", "a-sub-agent-above-the-depth"]) + def test_one_it_may_start_is_not(self, tmp_path, logged, agent, root, policy, named): + skill = make_skill(tmp_path, "research", f"agent: {named}\n") + agents = SkillAgents(agent, lambda: made(policy=policy), root=root) + + agents.check([skill, make_skill(tmp_path, "plain")]) + + assert logged == [] + assert agents.refusal(skill, 0 if root else 1) is None + + +async def loaded(agents: SkillAgents, skill: Any, *, caller=None, **fields: Any): + """``agents.start(skill)`` in a turn of ``CONVERSATION``, from ``caller``'s run; its + result, how many runs the turn counted, and what it reported.""" + live = LiveEvents() + out: dict[str, Any] = {} + + async def source(): + token = set_active_turn(CONVERSATION) + scope = open_turn_scope() + run = set_active_run(caller) + try: + with live_events.reporting(live): + out["result"] = await agents.start( + skill, call_id=fields.pop("call_id", "c1"), + state=fields.pop("state", {}), history=fields.pop("history", None), + ) + out["counted"] = runs_this_turn() + finally: + reset_active_run(run) + close_turn_scope(scope) + reset_active_turn(token) + if False: # pragma: no cover - a source that yields nothing itself + yield + + events = [item async for item in merged(source(), live)] + return out, events + + +class TestALoadStartsARun: + async def test_of_the_type_its_task_the_skills_body_its_result_the_envelope(self, tmp_path): + hook, asked = answering("Found it.") + runs = AgentRuns() + delegations = made(hook, runs=runs) + agents = SkillAgents("lead", lambda: delegations, root=True) + + with no_blocking_calls(): + out, events = await loaded( + agents, make_skill(tmp_path, "research", "agent: helper\n"), + state={"outside_content": "web_fetch"}, + ) + + assert out["result"].result == { + "success": True, "agent": "helper-1", "run": "helper-1#1", + "status": RUN_COMPLETED, "partial": False, "result": "Found it.", "error": None, + "skill": "research", + } + (run,) = asked + assert run.message == task_message(Brief(title="research", objective=BODY)) + assert (run.ref.depth, run.ref.parent_run, run.state, run.history) == ( + 1, None, {"outside_content": "web_fetch"}, None + ) + assert events[0].metadata["status"] == RUN_STARTED + assert (events[0].metadata["started_by"], events[0].metadata["call_id"], + events[0].metadata["title"]) == ("skill:research", "c1", "research") + assert out["counted"] == 1 + (record,) = runs.records(CONVERSATION) + assert record.started_by == "skill:research" + + async def test_under_the_run_that_loads_it(self, tmp_path): + hook, asked = answering() + deeper = SubAgentPolicy(spawn_sources={"skill"}, max_spawn_depth=2) + delegations = made(hook, policy=deeper) + agents = SkillAgents("middle", lambda: delegations, root=False) + + out, _ = await loaded( + agents, make_skill(tmp_path, "research", "agent: helper\n"), caller=at(1) + ) + + (run,) = asked + assert (run.ref.instance, run.ref.depth, run.ref.parent_run) == ( + "helper-1", 2, "middle-1#1" + ) + assert out["result"].result["skill"] == "research" + + async def test_an_inheriting_type_reads_the_callers_conversation(self, tmp_path): + hook, asked = answering() + delegations = made(hook) + agents = SkillAgents("lead", lambda: delegations, root=True) + + await loaded( + agents, make_skill(tmp_path, "notes", "agent: noter\n"), + history=lambda: ["the conversation"], + ) + + (run,) = asked + assert run.history == ["the conversation"] + assert run.message.endswith(INHERITED_CONTEXT_NOTE) + + async def test_one_it_may_not_start_starts_none_and_counts_none(self, tmp_path): + hook, asked = answering() + delegations = made(hook) + agents = SkillAgents("middle", lambda: delegations, root=False) + + out, events = await loaded( + agents, make_skill(tmp_path, "research", "agent: helper\n"), caller=at(1) + ) + + assert out["result"].result == { + "success": False, + "error": "The skill 'research' starts the agent 'helper', which cannot be " + "started here: sub-agents cannot start sub-agents.", + } + assert (out["result"].run, out["result"].state, asked, events, out["counted"]) == ( + None, {}, [], [], 0 + ) + + async def test_past_the_runs_a_turn_may_start_it_is_refused_as_task_is(self, tmp_path): + hook, asked = answering() + delegations = made(hook, policy=SubAgentPolicy(spawn_sources={"skill"}, + max_runs_per_turn=1)) + agents = SkillAgents("lead", lambda: delegations, root=True) + skill = make_skill(tmp_path, "research", "agent: helper\n") + live = LiveEvents() + results: list[Any] = [] + + async def source(): + token = set_active_turn(CONVERSATION) + scope = open_turn_scope() + try: + with live_events.reporting(live): + for call in ("c1", "c2"): + results.append(await agents.start( + skill, call_id=call, state={}, history=None + )) + finally: + close_turn_scope(scope) + reset_active_turn(token) + if False: # pragma: no cover + yield + + async for _ in merged(source(), live): + pass + + first, second = results + assert first.result["status"] == RUN_COMPLETED + assert second.result == { + "success": False, "error": RUNS_PER_TURN_ERROR.format(limit=1), + } + assert len(asked) == 1 From 4cf838781d08e9146253a15479a718b0e1400b80 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:01:28 -0500 Subject: [PATCH 2/6] ADK: loading a skill that names an agent starts it An agent with a skill whose frontmatter names an agent type gets the framework's load_skill (SkillLoadTool, ADK's declaration, bound as ADK's was) in its toolset: such a skill starts its agent through SkillAgents and answers with the run's envelope as JSON text, as task does; any other skill loads as ADK loads it. A load_skill envelope is shown as a delegation (ENVELOPE_TOOLS). The build's warning for a skill whose agent cannot be started is logged once per agent and skill, though ADK builds an agent once more for each model choice. The contract scenarios cover both backends. --- src/agentic_cli/tools/_core/delegation.py | 9 +- src/agentic_cli/tools/skills/toolset.py | 28 +- .../workflow/adk/event_processor.py | 9 +- src/agentic_cli/workflow/adk/manager.py | 34 +- src/agentic_cli/workflow/adk/skill_tool.py | 70 ++++ tests/workflow/test_skills.py | 106 +++++ tests/workflow/test_subagents_contract.py | 376 ++++++++++++++++++ 7 files changed, 617 insertions(+), 15 deletions(-) create mode 100644 src/agentic_cli/workflow/adk/skill_tool.py diff --git a/src/agentic_cli/tools/_core/delegation.py b/src/agentic_cli/tools/_core/delegation.py index 401bfc91..da5e8c05 100644 --- a/src/agentic_cli/tools/_core/delegation.py +++ b/src/agentic_cli/tools/_core/delegation.py @@ -35,9 +35,14 @@ STOP_AGENT_TOOL = "stop_agent" CHECK_AGENTS_TOOL = "check_agents" FOLLOW_UP_TOOLS = (MESSAGE_AGENT_TOOL, STOP_AGENT_TOOL, CHECK_AGENTS_TOOL) +#: The skill tool whose call starts a run when its skill names an agent type +#: (``tools/skills/agents.py``); registered with the other skill tools +#: (``tools/skills/permissions.py``). +LOAD_SKILL_TOOL = "load_skill" #: The tools whose result is a run's envelope, which the event processors -#: show as a delegation (``agents/runs.py::show_as_delegation``). -ENVELOPE_TOOLS = (TASK_TOOL, MESSAGE_AGENT_TOOL) +#: show as a delegation (``agents/runs.py::show_as_delegation``). A +#: ``load_skill`` result that is no envelope is shown as any result is. +ENVELOPE_TOOLS = (TASK_TOOL, MESSAGE_AGENT_TOOL, LOAD_SKILL_TOOL) FOLLOW_UP_CLASH_ERROR = ( "Agent {agent!r} continues its sub-agents through tools named message_agent, " "stop_agent and check_agents, so its own tools cannot include {tool!r}; rename that tool." diff --git a/src/agentic_cli/tools/skills/toolset.py b/src/agentic_cli/tools/skills/toolset.py index 31c3b47d..b20925b5 100644 --- a/src/agentic_cli/tools/skills/toolset.py +++ b/src/agentic_cli/tools/skills/toolset.py @@ -8,11 +8,21 @@ No supported manager path wires an executor today, so in practice scripts stay off; the parameter exists for a caller that owns one. + +A skill whose frontmatter names an agent type starts a run of it when loaded +(``agents.py``). For an agent with such a skill, given its ``SkillAgents``, +the toolset's ``load_skill`` is the framework's (``adk/skill_tool.py``); any +other toolset is ADK's own. """ from __future__ import annotations -from typing import Any +from typing import TYPE_CHECKING, Any + +from agentic_cli.tools.skills.agents import skill_agent + +if TYPE_CHECKING: + from agentic_cli.tools.skills.agents import SkillAgents def make_skill_toolset( @@ -20,6 +30,7 @@ def make_skill_toolset( *, code_executor: Any | None = None, additional_tools: list[Any] | None = None, + agents: SkillAgents | None = None, ) -> Any: """Create an ADK SkillToolset; script execution follows the executor. @@ -30,11 +41,15 @@ def make_skill_toolset( rather than offered and then failing. additional_tools: Tools surfaced when a skill with ``adk_additional_tools`` frontmatter is activated. + agents: The loading agent's ``SkillAgents``. Given, and one of the + skills naming an agent type, ``load_skill`` starts that agent + (and the skills that name one the agent could not start are + warned of). None: every skill loads as ADK loads it. Returns: A configured ``SkillToolset``. """ - from google.adk.tools.skill_toolset import RunSkillScriptTool, SkillToolset + from google.adk.tools.skill_toolset import LoadSkillTool, RunSkillScriptTool, SkillToolset toolset = SkillToolset( skills=skills, @@ -45,6 +60,15 @@ def make_skill_toolset( toolset._tools = [ t for t in toolset._tools if not isinstance(t, RunSkillScriptTool) ] + starting = {s.name: s for s in skills if skill_agent(s) is not None} + if agents is not None and starting: + from agentic_cli.workflow.adk.skill_tool import SkillLoadTool + + agents.check(skills) + toolset._tools = [ + SkillLoadTool(toolset, starting, agents) if type(t) is LoadSkillTool else t + for t in toolset._tools + ] _bind_skill_tool_identities(toolset) return toolset diff --git a/src/agentic_cli/workflow/adk/event_processor.py b/src/agentic_cli/workflow/adk/event_processor.py index 48f39e8e..51ddcbe8 100644 --- a/src/agentic_cli/workflow/adk/event_processor.py +++ b/src/agentic_cli/workflow/adk/event_processor.py @@ -13,7 +13,7 @@ from google.genai import types -from agentic_cli.tools._core.delegation import ENVELOPE_TOOLS, FOLLOW_UP_TOOLS, TASK_TOOL +from agentic_cli.tools._core.delegation import ENVELOPE_TOOLS, FOLLOW_UP_TOOLS from agentic_cli.tools._core.tasks import task_progress_data from agentic_cli.workflow.adk.call_clock import call_latency from agentic_cli.workflow.adk.subagent_outcome_plugin import OUTCOME_KEY @@ -93,7 +93,8 @@ class ADKEventProcessor: A tool's result is a failed ``TOOL_RESULT`` when it says so (``success`` false, an ``error`` value) or is an MCP tool's error result (``isError``), its error in ``metadata["error"]``, as on Deep Agents. A ``task`` call's - result (and that of each of the parent's other tools) is the JSON text + result (and that of each of the parent's other tools, and a + ``load_skill`` that started a run, ``adk/skill_tool.py``) is the JSON text of what the delegation returned (``adk/task_tool.py``), read back as its dict, as Deep Agents reads its ``ToolMessage``; an envelope (``task``'s, ``message_agent``'s run) is @@ -406,7 +407,7 @@ def process_part(self, part: Any, session_id: str) -> WorkflowEvent | None: if hasattr(part, "function_response") and part.function_response: tool_name = part.function_response.name response = part.function_response.response - if tool_name == TASK_TOOL or tool_name in FOLLOW_UP_TOOLS: + if tool_name in ENVELOPE_TOOLS or tool_name in FOLLOW_UP_TOOLS: response = _delegated(response) success, error = _outcome(response) @@ -501,7 +502,7 @@ def _with_call_id(event: WorkflowEvent, call_id: Any) -> WorkflowEvent: def _delegated(response: Any) -> Any: - """A ``task`` call's result (or a parent's tool's) as it returned it: the dict whose + """A ``task`` call's result (or a parent's tool's, or a skill's start) as it returned it: the dict whose JSON text ADK stores under ``result`` (``adk/task_tool.py``); anything else as it is.""" if isinstance(response, dict) and set(response) == {"result"}: try: diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index 9021c38d..eeda09cc 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -472,14 +472,16 @@ def _get_state_tools(self) -> list: return [save_plan, get_plan, save_tasks, get_tasks] def _assemble_agent_tools( - self, config: "AgentConfig", service_map: dict + self, config: "AgentConfig", service_map: dict, *, root: bool = False ) -> list: """Build an agent's tools: framework tools + state tools + MCP toolsets. MCP servers declared on the config are materialized into ADK ``McpToolset`` objects (ADK connects lazily) and appended after the - regular tools. Skills are appended as a ``SkillToolset``. The caller is - responsible for ``_wrap_long_running`` over the result. + regular tools. Skills are appended as a ``SkillToolset``, built for + this agent (``root``: whether it is the root, as its skills that start + agents are checked from its first depth). The caller is responsible + for ``_wrap_long_running`` over the result. """ tools = self._build_tools(config, service_map) mcp_servers = getattr(config, "mcp_servers", None) or [] @@ -494,15 +496,22 @@ def _assemble_agent_tools( skill_refs = getattr(config, "skills", None) or [] if skill_refs: - toolset = self._build_skill_toolset(skill_refs) + toolset = self._build_skill_toolset(skill_refs, agent=config.name, root=root) if toolset is not None: tools.append(toolset) logger.debug("skill_toolset_attached", agent=config.name) return tools - def _build_skill_toolset(self, skill_refs: list[str]): + def _build_skill_toolset( + self, skill_refs: list[str], *, agent: str | None = None, root: bool = False + ): """Resolve skill refs and build an ADK SkillToolset (discovery/read only). + Given the loading ``agent``, a skill that names an agent type starts + it when loaded (``tools/skills/agents.py``), and one its first run + could not start is warned of, once for each skill the build's agents + (a type and its model choices) share. + This path supplies no code executor, so ``run_skill_script`` is not exposed: only the discovery/read tools and the L1 metadata injection. (There used to be a ``skill_scripts_enabled`` setting that advertised @@ -515,7 +524,15 @@ def _build_skill_toolset(self, skill_refs: list[str]): skills = store.resolve(skill_refs) if not skills: return None - return make_skill_toolset(skills) + agents = None + if agent is not None: + from agentic_cli.tools.skills import SkillAgents + + agents = SkillAgents( + agent, lambda: self._delegations, root=root, + warned=getattr(self, "_skill_warned", None), + ) + return make_skill_toolset(skills, agents=agents) def _wrap_long_running(self, tools: list[Callable]) -> list: """Wrap tools flagged ``long_running`` as ADK ``LongRunningFunctionTool``. @@ -595,7 +612,7 @@ def _build_agent( 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) + tools = self._assemble_agent_tools(config, service_map, root=root) if root: tools = self._wrap_long_running(tools) if delegates: @@ -659,6 +676,9 @@ def _create_agents(self) -> Agent: agents: dict[str, LlmAgent] = {} variants: dict[tuple[str, str], LlmAgent] = {} + # What this build's skill checks warned of: an agent built once more + # for each model choice has skills of its own, and warns once. + self._skill_warned: set[tuple[str, str]] = set() service_map = self._get_service_tool_map() configs = list(graph.config_map.values()) diff --git a/src/agentic_cli/workflow/adk/skill_tool.py b/src/agentic_cli/workflow/adk/skill_tool.py new file mode 100644 index 00000000..5ddf766e --- /dev/null +++ b/src/agentic_cli/workflow/adk/skill_tool.py @@ -0,0 +1,70 @@ +"""ADK's ``load_skill`` for an agent with a skill that starts an agent. + +A skill whose frontmatter names an agent type starts a run of it when loaded +(``tools/skills/agents.py``). ADK's own ``LoadSkillTool`` hands a skill's +instructions back, so an agent with such a skill gets this subclass in its +place (``make_skill_toolset(agents=)``): a skill that names a type goes to +``SkillAgents.start`` and answers as ``task`` does (the run's envelope as JSON +text, the outside-content mark read from and written back to the caller's +state, an inheriting type given the conversation); any other skill loads as +ADK loads it, so an agent whose skills name no type keeps ADK's own tool, +object for object. + +The declaration is ADK's: the subclass changes what a call does, not what the +model is offered. ``make_skill_toolset`` binds the tool to the ``load_skill`` +declaration as it binds ADK's skill tools, so the permission gate knows it by +identity, and denies a ``SkillLoadTool`` built anywhere else. What it relies on +of ADK (``LoadSkillTool(toolset)``, ``run_async(args=, tool_context=)``) is +contract-tested. It is a module of its own because it subclasses ADK's class, +which the skills package imports lazily: ``make_skill_toolset`` imports this +module only when it builds the tool. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any + +from google.adk.tools.skill_toolset import LoadSkillTool, SkillToolset + +from agentic_cli.workflow.adk.task_tool import SHARED_KEYS, inherited_events + +if TYPE_CHECKING: + from google.adk.tools.tool_context import ToolContext + + from agentic_cli.tools.skills.agents import SkillAgents + + +class SkillLoadTool(LoadSkillTool): + """``load_skill``, starting the agent a skill names. + + Args: + toolset: The skill toolset the tool belongs to. + starting: The toolset's skills that name an agent type, by name. + agents: The loading agent's ``SkillAgents``. + """ + + def __init__( + self, toolset: SkillToolset, starting: Mapping[str, Any], agents: SkillAgents + ) -> None: + super().__init__(toolset) + self._starting = dict(starting) + self._agents = agents + + async def run_async(self, *, args: dict[str, Any], tool_context: ToolContext) -> Any: + name = args.get("skill_name") + skill = self._starting.get(name) if isinstance(name, str) else None + if skill is None: + return await super().run_async(args=args, tool_context=tool_context) + state = tool_context.state + session = tool_context.session + delegated = await self._agents.start( + skill, + call_id=tool_context.function_call_id or "", + state={key: state[key] for key in SHARED_KEYS if key in state}, + history=lambda: inherited_events(session.events), + ) + for key, value in delegated.state.items(): + state[key] = value + return json.dumps(delegated.result, ensure_ascii=False) diff --git a/tests/workflow/test_skills.py b/tests/workflow/test_skills.py index 6c85ee1c..d77b80e6 100644 --- a/tests/workflow/test_skills.py +++ b/tests/workflow/test_skills.py @@ -237,3 +237,109 @@ def test_yaml_loader_parses_skills(self, tmp_path): ) cfg = load_agents_from_yaml(path)[0] assert cfg.skills == ["pdf-tools", "./skills/sql"] + + +# --------------------------------------------------------------------------- +# A skill that starts an agent: the framework's load_skill +# --------------------------------------------------------------------------- + + +def _starting_skill(parent: Path, name: str = "research", agent: str = "helper") -> Path: + """A skill whose frontmatter names the agent type ``agent``.""" + skill_dir = parent / name + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text( + f"---\nname: {name}\ndescription: Researches.\nagent: {agent}\n---\nLook into it.\n", + encoding="utf-8", + ) + return skill_dir + + +def _agents(): + """The root ``lead``'s ``SkillAgents``, over delegations that may start ``helper``.""" + from agentic_cli.tools.skills import SkillAgents + from agentic_cli.workflow.agents import AgentRuns, SubAgentPolicy + from agentic_cli.workflow.agents.delegate import Delegations + + async def never(run): # pragma: no cover - no run starts here + raise AssertionError(run) + + delegations = Delegations( + runs=AgentRuns(), policy=SubAgentPolicy(spawn_sources={"skill"}), hook=never, + types={ + "lead": AgentConfig(name="lead", prompt="p"), + "helper": AgentConfig(name="helper", prompt="p", spawnable_by=frozenset({"skill"})), + }, + ) + return SkillAgents("lead", lambda: delegations, root=True) + + +def _load_skill(toolset): + (tool,) = [t for t in toolset._tools if t.name == "load_skill"] + return tool + + +class TestTheFrameworksLoadSkill: + def test_an_agent_with_a_skill_that_starts_one_gets_it_declared_as_adks(self, tmp_path): + from google.adk.tools.skill_toolset import SkillToolset + + from agentic_cli.tools.registry import get_registry, identify_tool + from agentic_cli.workflow.adk.skill_tool import SkillLoadTool + + skills = SkillStore().resolve([str(_make_skill(tmp_path)), str(_starting_skill(tmp_path))]) + + toolset = make_skill_toolset(skills, agents=_agents()) + + tool = _load_skill(toolset) + assert type(tool) is SkillLoadTool + assert identify_tool(tool) is get_registry().get("load_skill") + adks = _load_skill(SkillToolset(skills=skills)) + assert tool._get_declaration() == adks._get_declaration() + assert [t.name for t in toolset._tools] == [ + t.name for t in make_skill_toolset(skills)._tools + ] + + def test_without_such_a_skill_or_without_its_agents_it_is_adks_own(self, tmp_path): + from google.adk.tools.skill_toolset import LoadSkillTool + + plain = SkillStore().resolve([str(_make_skill(tmp_path))]) + starting = SkillStore().resolve([str(_starting_skill(tmp_path))]) + + for toolset in (make_skill_toolset(plain, agents=_agents()), make_skill_toolset(starting)): + assert type(_load_skill(toolset)) is LoadSkillTool + + async def test_the_gate_lets_the_one_the_framework_built_through_and_no_other( + self, tmp_path + ): + from agentic_cli.workflow.adk.permission_plugin import PermissionPlugin + from agentic_cli.workflow.adk.skill_tool import SkillLoadTool + + skills = SkillStore().resolve([str(_starting_skill(tmp_path))]) + toolset = make_skill_toolset(skills, agents=_agents()) + unbound = SkillLoadTool(toolset, {}, _agents()) + + async def gate(tool): + return await PermissionPlugin().before_tool_callback( + tool=tool, tool_args={"skill_name": "research"}, tool_context=None + ) + + assert await gate(_load_skill(toolset)) is None + denied = await gate(unbound) + assert denied["success"] is False and "not registered" in denied["error"] + + def test_what_it_rests_on_of_adks_load_skill(self, tmp_path): + """ADK's toolset holds one exact ``LoadSkillTool``, made from the toolset, + whose ``run_async`` takes ``args`` and ``tool_context`` by keyword.""" + import inspect + + from google.adk.tools.skill_toolset import LoadSkillTool, SkillToolset + + toolset = SkillToolset(skills=SkillStore().resolve([str(_make_skill(tmp_path))])) + + assert [type(t) for t in toolset._tools].count(LoadSkillTool) == 1 + assert LoadSkillTool(toolset).name == "load_skill" + parameters = inspect.signature(LoadSkillTool.run_async).parameters + assert {name: p.kind for name, p in parameters.items() if name != "self"} == { + "args": inspect.Parameter.KEYWORD_ONLY, + "tool_context": inspect.Parameter.KEYWORD_ONLY, + } diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 2f21288f..7aef069a 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -6850,3 +6850,379 @@ async def test_its_requests_fit_the_choices_budget(self, make_crew, chosen): assert envelope_read( crew.results_read("coordinator")["c1"] )["result"] == "It was words." + + +# -- skills that start an agent ------------------------------------------------------ + +#: Skills may start a type at run time: from the root alone (``max_spawn_depth`` 1). +SKILLS = SubAgentPolicy(spawn_sources={"skill"}) +#: The body of the skill the scenarios load: the objective of the run it starts. +RESEARCH = "Look into the question and report what you find." +#: The run's task message: the skill's name, then its body. +RESEARCH_TASK = f"# Task: research\n\n## Objective\n{RESEARCH}" + + +def make_skill( + parent: Path, name: str = "research", *, agent_type: str | None = "helper", + body: str = RESEARCH, +) -> str: + """A skill folder ``parent/`` whose frontmatter names ``agent_type`` + (None: no agent); its absolute path, as ``AgentConfig.skills`` takes it.""" + folder = parent / name + folder.mkdir(parents=True) + named = f"agent: {agent_type}\n" if agent_type is not None else "" + (folder / "SKILL.md").write_text( + f"---\nname: {name}\ndescription: Does {name}.\n{named}---\n{body}\n", encoding="utf-8" + ) + return str(folder) + + +def load(skill: str, call_id: str) -> Call: + """A ``load_skill`` call of the skill named ``skill``.""" + return use("load_skill", call_id, skill_name=skill) + + +def skill_team( + *skills: str, coordinator_tools: tuple[Any, ...] = (), **helper_fields: Any +) -> list[AgentConfig]: + """``team()``, its coordinator with ``skills`` (and ``coordinator_tools`` + besides its own), and the helper skills may start (``helper_fields``).""" + coordinator, researcher = team() + coordinator.skills = list(skills) + coordinator.tools = [*coordinator.tools, *coordinator_tools] + helper_fields.setdefault("spawnable_by", frozenset({"skill"})) + helper_fields.setdefault("tools", (contract_lookup,)) + return [coordinator, researcher, helper(**helper_fields)] + + +def refused_by_skill(agent_type: str, reason: str, skill: str = "research") -> dict[str, Any]: + """A load that starts no run, as its caller reads it.""" + return { + "success": False, + "error": f"The skill '{skill}' starts the agent '{agent_type}', which {reason}.", + } + + +class TestASkillThatStartsAnAgent: + async def test_the_root_loads_one_and_its_run_is_the_skills(self, make_crew, project): + crew = make_crew( + skill_team(make_skill(project.parent / "skills")), subagents=SKILLS, + coordinator=[calls(load("research", "c1")), says("Done.")], + helper=[says("Found it.")], + ) + + with no_blocking_calls(): + events = await crew.turn() + + assert envelope_read(crew.results_read("coordinator")["c1"]) == { + "success": True, "agent": "helper-1", "run": "helper-1#1", + "status": RUN_COMPLETED, "partial": False, "result": "Found it.", "error": None, + "skill": "research", + } + # Its task message is the skill's body under its name; its prompt and + # tools are its type's: a skill gives neither. + assert (crew.message_count("helper", 0), crew.last_message("helper", 0)) == ( + 1, RESEARCH_TASK + ) + assert crew.tool_names("helper") == ["contract_lookup"] + (record,) = crew.records() + assert (record.ref.instance, record.ref.depth, record.ref.parent_run, record.call_id, + record.started_by, record.title, record.brief) == ( + "helper-1", 1, None, "c1", "skill:research", "research", + {"title": "research", "objective": RESEARCH}, + ) + (instance,) = crew.manager.agent_runs.instances(crew.conversation) + assert (instance.agent, instance.parent, instance.depth, instance.status) == ( + "helper", "root", 1, INSTANCE_IDLE + ) + assert [e.metadata["status"] for e in runs_of(events)] == [RUN_STARTED, RUN_COMPLETED] + # Its result is shown as a delegation's, alike on both. + (shown,) = [e for e in events if e.type is EventType.TOOL_RESULT + and e.metadata.get("tool_call_id") == "c1"] + assert (shown.content, shown.metadata["success"], shown.metadata["result"]["skill"]) == ( + "Found it.", True, "research" + ) + assert [e.content for e in events if e.type is EventType.TEXT] == ["Found it.", "Done."] + + async def test_loaded_twice_in_one_response_it_starts_two_runs(self, make_crew, project): + crew = make_crew( + skill_team(make_skill(project.parent / "skills")), subagents=SKILLS, + coordinator=[calls(load("research", "c1"), load("research", "c2")), says("Both.")], + helper=[says("One answer."), says("The other answer.")], + ) + + await crew.turn() + + # Each call has one result, its own run's envelope. + assert [(call, len(results)) for call, results in crew.call_results("coordinator")] == [ + ("c1", 1), ("c2", 1), + ] + read = {call: envelope_read(text) + for call, text in crew.results_read("coordinator").items()} + assert sorted((found["agent"], found["status"], found["skill"]) + for found in read.values()) == [ + ("helper-1", RUN_COMPLETED, "research"), ("helper-2", RUN_COMPLETED, "research"), + ] + assert {call: (found["run"], found["result"]) for call, found in read.items()} == { + record.call_id: (record.ref.run, record.result) for record in crew.records() + } + assert sorted(found["result"] for found in read.values()) == [ + "One answer.", "The other answer.", + ] + assert [r.started_by for r in crew.records()] == ["skill:research"] * 2 + + @pytest.mark.parametrize("depth_limit", [1, 2]) + async def test_a_sub_agent_loads_one_only_above_the_depth_limit( + self, make_crew, project, depth_limit + ): + path = make_skill(project.parent / "skills") + crew = make_crew( + [agent("coordinator", sub_agents=("researcher",)), + agent("researcher", skills=[path]), + helper(spawnable_by=frozenset({"skill"}), tools=(contract_lookup,))], + subagents=SubAgentPolicy(spawn_sources={"skill"}, max_spawn_depth=depth_limit), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[calls(load("research", "r1")), says("Reported.")], + helper=[says("Found it.")], + ) + + events = await crew.turn() + + read = json.loads(crew.results_read("researcher", 1)["r1"]) + if depth_limit == 1: + # At the limit: refused, no run started. + assert read == refused_by_skill( + "helper", "cannot be started here: sub-agents cannot start sub-agents" + ) + assert [r.ref.instance for r in crew.records()] == ["researcher-1"] + assert crew.requests("helper") == 0 + assert [e.run.instance for e in runs_of(events, RUN_STARTED)] == ["researcher-1"] + else: + # The loading agent's run is its parent. + assert (read["agent"], read["status"], read["skill"]) == ( + "helper-1", RUN_COMPLETED, "research" + ) + assert [(r.ref.instance, r.ref.depth, r.ref.parent_run, r.started_by) + for r in crew.records()] == [ + ("researcher-1", 1, None, "agent:root"), + ("helper-1", 2, "researcher-1#1", "skill:research"), + ] + + @pytest.mark.parametrize("skill_agent, spawnable_by, sources, reason", [ + ("nobody", {"skill"}, {"skill"}, "is not one of this app's agent types"), + ("helper", {"agent"}, {"agent", "skill"}, "this app does not let a skill start"), + ("helper", {"skill"}, {"agent"}, "this app does not let a skill start"), + ("researcher", {"skill"}, {"skill"}, "this app does not let a skill start"), + ], ids=["unknown-type", "type-not-for-skills", "policy-not-for-skills", "a-static-sub-agent"]) + async def test_a_load_that_may_not_start_its_agent_is_refused_and_starts_none( + self, make_crew, project, skill_agent, spawnable_by, sources, reason + ): + crew = make_crew( + skill_team(make_skill(project.parent / "skills", agent_type=skill_agent), + spawnable_by=frozenset(spawnable_by)), + subagents=SubAgentPolicy(spawn_sources=sources), + coordinator=[calls(load("research", "c1")), says("Could not.")], + helper=[says("[never asked]")], researcher=[says("[never asked]")], + ) + + events = await crew.turn() + + assert json.loads(crew.results_read("coordinator")["c1"]) == refused_by_skill( + skill_agent, reason + ) + assert (runs_of(events), crew.records()) == ([], []) + assert (crew.requests("helper"), crew.requests("researcher")) == (0, 0) + (shown,) = [e for e in events if e.type is EventType.TOOL_RESULT] + assert (shown.metadata["success"], shown.metadata["error"]) == ( + False, refused_by_skill(skill_agent, reason)["error"] + ) + + async def test_with_the_default_policy_a_plain_skill_loads_and_one_naming_an_agent_does_not( + self, make_crew, project, monkeypatch + ): + from agentic_cli.tools.skills import agents as skill_agents + + warned: list[dict[str, Any]] = [] + + class Recorder: + def __getattr__(self, level: str): + return lambda event, **fields: warned.append( + {"event": event, "log_level": level, **fields} + ) + + monkeypatch.setattr(skill_agents, "logger", Recorder()) + skills = project.parent / "skills" + crew = make_crew( + skill_team(make_skill(skills, "notes", agent_type=None, body="Write notes."), + make_skill(skills)), + coordinator=[calls(load("notes", "c1"), load("research", "c2")), says("Done.")], + helper=[says("[never asked]")], + ) + + events = await crew.turn() + + read = crew.results_read("coordinator") + loaded = json.loads(read["c1"]) + assert (loaded["skill_name"], loaded["instructions"]) == ("notes", "Write notes.") + assert json.loads(read["c2"]) == refused_by_skill( + "helper", "this app does not let a skill start" + ) + assert (runs_of(events), crew.records(), crew.requests("helper")) == ([], [], 0) + shown = {e.metadata["tool_call_id"]: e for e in events if e.type is EventType.TOOL_RESULT} + assert (shown["c1"].metadata["success"], shown["c1"].metadata["result"]["skill_name"]) == ( + True, "notes" + ) + assert shown["c2"].metadata["success"] is False + # Warned of once, as the coordinator was built. + assert warned == [{ + "event": "skill_agent_not_startable", "log_level": "warning", + "agent": "coordinator", "skill": "research", "agent_type": "helper", + "reason": "this app does not let a skill start", + }] + + @pytest.mark.parametrize("first", ["skill", "task"]) + async def test_its_run_counts_toward_the_turns_runs(self, make_crew, project, first): + from agentic_cli.workflow.agents.delegate import RUNS_PER_TURN_ERROR + + skill, task = load("research", "c1"), delegate("researcher", "Find X.", "c1") + later = (delegate("researcher", "Find X.", "c2") if first == "skill" + else load("research", "c2")) + crew = make_crew( + skill_team(make_skill(project.parent / "skills")), + subagents=SubAgentPolicy(spawn_sources={"skill"}, max_runs_per_turn=1), + coordinator=[calls(skill if first == "skill" else task), calls(later), + says("Done.")], + helper=[says("Found it.")], researcher=[says("X is 42.")], + ) + + await crew.turn() + + assert json.loads(crew.results_read("coordinator", 2)["c2"]) == { + "success": False, "error": RUNS_PER_TURN_ERROR.format(limit=1), + } + assert [r.ref.instance for r in crew.records()] == [ + "helper-1" if first == "skill" else "researcher-1" + ] + + async def test_after_ctrl_c_its_call_is_answered_once_and_its_run_interrupted( + self, make_crew, project + ): + crew = make_crew( + skill_team(make_skill(project.parent / "skills"), tools=(contract_block,)), + subagents=SKILLS, + coordinator=[calls(load("research", "c1")), says("Starting over.")], + helper=[calls(use("contract_block", "h1"))], + ) + + turn = crew.start() + try: + await asyncio.wait_for(BLOCKING["started"].wait(), 10) + finally: + await crew.stop(turn) + await crew.turn("Never mind.") + + assert [(call, len(results)) for call, results in crew.call_results("coordinator")] == [ + ("c1", 1), + ] + assert INTERRUPTED_BY_USER in crew.results_read("coordinator")["c1"] + (record,) = crew.records() + assert (record.ref.instance, record.status) == ("helper-1", RUN_INTERRUPTED) + + async def test_a_failed_run_is_its_envelope(self, make_crew, project): + crew = make_crew( + skill_team(make_skill(project.parent / "skills")), subagents=SKILLS, + coordinator=[calls(load("research", "c1")), says("It failed.")], + helper=[fails("overloaded")], + ) + + events = await crew.turn() + + read = envelope_read(crew.results_read("coordinator")["c1"]) + assert (read["success"], read["agent"], read["status"], read["skill"]) == ( + False, "helper-1", RUN_FAILED, "research" + ) + assert "overloaded" in read["error"] + (warning,) = [e for e in events if e.type is EventType.ERROR] + assert warning.content == f"helper-1 failed: {read['error']}" + assert [e.content for e in events if e.type is EventType.TEXT] == ["It failed."] + + async def test_an_inheriting_type_reads_the_conversation(self, make_crew, project): + from agentic_cli.workflow.agents.brief import Brief, task_message + + crew = make_crew( + [agent("coordinator", skills=[make_skill(project.parent / "skills")]), + helper(spawnable_by=frozenset({"skill"}), inherit_context=True)], + subagents=SKILLS, + coordinator=[says("Noted, Ada."), calls(load("research", "c1")), says("Done.")], + helper=[says("The code is 7.")], + ) + + await crew.turn("My name is Ada and the code is 7.") + await crew.turn("Look into it.") + + (first,) = crew.bodies("helper") + assert "My name is Ada and the code is 7." in first + assert crew.last_message("helper", 0) == task_message( + Brief(title="research", objective=RESEARCH), inherit=True + ) + assert envelope_read(crew.results_read("coordinator")["c1"])["result"] == ( + "The code is 7." + ) + + async def test_the_callers_mark_reaches_its_run(self, make_crew, project): + crew = make_crew( + skill_team(make_skill(project.parent / "skills"), + coordinator_tools=(contract_bring_outside_content,)), + subagents=SKILLS, + coordinator=[calls(use("contract_bring_outside_content", "c1")), + calls(load("research", "c2")), says("Done.")], + helper=[says("Found it.")], + ) + + await crew.turn() + + assert await crew.instance_mark("helper-1") == "contract_bring_outside_content" + + async def test_its_runs_mark_reaches_the_conversation(self, make_crew, project): + crew = make_crew( + skill_team(make_skill(project.parent / "skills"), + tools=(contract_lookup, contract_bring_outside_content)), + subagents=SKILLS, + coordinator=[calls(load("research", "c1")), says("Done.")], + helper=[calls(use("contract_bring_outside_content", "h1")), says("Found it.")], + ) + + await crew.turn() + + assert (await crew.marked()) is True + + async def test_a_type_with_model_choices_warns_of_its_skill_once( + self, make_crew, project, monkeypatch + ): + from agentic_cli.tools.skills import agents as skill_agents + + warned: list[dict[str, Any]] = [] + + class Recorder: + def __getattr__(self, level: str): + return lambda event, **fields: warned.append( + {"event": event, "log_level": level, **fields} + ) + + monkeypatch.setattr(skill_agents, "logger", Recorder()) + path = make_skill(project.parent / "skills", agent_type="nobody") + crew = make_crew( + [agent("coordinator", sub_agents=("researcher",)), + agent("researcher", skills=[path], model_choices=(CHOICE,))], + subagents=SKILLS, + coordinator=[says("Done.")], + ) + + await crew.turn() + + # The type is built once for each model choice, its skills too: one warning. + assert warned == [{ + "event": "skill_agent_not_startable", "log_level": "warning", + "agent": "researcher", "skill": "research", "agent_type": "nobody", + "reason": "is not one of this app's agent types", + }] From 0e2798035e06e2ff01e6433776280e9a14ba56d0 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:04:34 -0500 Subject: [PATCH 3/6] Deep Agents: loading a skill that names an agent starts it load_skill takes the call's runtime, which the tool node injects; a skill whose frontmatter names an agent type starts it through SkillAgents (start_skill_run, beside task's coroutine) and answers as task does, one Command with the envelope and the run's shared-state change. The tools' declarations are unchanged, and any other skill loads as before. --- .../tools/skills/langchain_tools.py | 59 +++++++++++++++++-- .../workflow/deepagents/manager.py | 13 +++- .../workflow/deepagents/task_tool.py | 34 ++++++++++- tests/workflow/deepagents/test_skills.py | 20 +++++++ 4 files changed, 116 insertions(+), 10 deletions(-) diff --git a/src/agentic_cli/tools/skills/langchain_tools.py b/src/agentic_cli/tools/skills/langchain_tools.py index 60db44d4..f235a6a0 100644 --- a/src/agentic_cli/tools/skills/langchain_tools.py +++ b/src/agentic_cli/tools/skills/langchain_tools.py @@ -34,24 +34,36 @@ skill tools are bound to (``permissions.py``): both backends gate a skill tool by the same contract (EXEMPT), and an object the framework did not build is denied, whatever its name. + +A skill whose frontmatter names an agent type starts a run of it when loaded +(``agents.py``), given the agent's ``SkillAgents`` (``make_skill_tools(agents=)``): +``load_skill`` takes the call's runtime, which LangGraph's tool node injects, +and hands the skill to ``workflow/deepagents/task_tool.py::start_skill_run``. +The tools' declarations are unchanged, and any other skill loads as above. """ from __future__ import annotations import base64 import copy +import functools import json import mimetypes -from collections.abc import Callable, Sequence -from typing import Any +from collections.abc import Awaitable, Callable, Sequence +from typing import TYPE_CHECKING, Any from google.adk.skills.prompt import format_skills_as_xml from langchain_core.tools import BaseTool, StructuredTool, ToolException +from langgraph.prebuilt import ToolRuntime from agentic_cli.models import ProviderKind from agentic_cli.tools.registry import bind_tool_identity, get_registry +from agentic_cli.tools.skills.agents import skill_agent from agentic_cli.workflow.sessions import get_active_turn +if TYPE_CHECKING: + from agentic_cli.tools.skills.agents import SkillAgents + LIST_SKILLS = "list_skills" LOAD_SKILL = "load_skill" LOAD_SKILL_RESOURCE = "load_skill_resource" @@ -161,7 +173,10 @@ def make_skill_tools( - skills: Sequence[Any], *, provider: ProviderKind | None = None + skills: Sequence[Any], + *, + provider: ProviderKind | None = None, + agents: SkillAgents | None = None, ) -> tuple[list[BaseTool], str]: """One agent's skills as its three skill tools, and its skills instruction. @@ -170,6 +185,9 @@ def make_skill_tools( provider: The agent's model's provider kind. A binary resource is sent as an image only to a provider that reads one in a tool result; without it, every binary resource is a status. + agents: The agent's ``SkillAgents``. Given, a skill that names an + agent type starts it when loaded (and one its agent could not + start is warned of now). None: every skill loads as ADK loads it. Returns: The tools, bound to the framework's skill tool definitions, and the @@ -182,7 +200,7 @@ def make_skill_tools( """ if not skills: return [], "" - answers = _SkillAnswers(skills, images=provider in _IMAGE_PROVIDERS) + answers = _SkillAnswers(skills, images=provider in _IMAGE_PROVIDERS, agents=agents) tools = [ _tool(LIST_SKILLS, answers.list_skills), _tool(LOAD_SKILL, answers.load_skill), @@ -227,7 +245,9 @@ def _error_content(error: ToolException) -> str: class _SkillAnswers: """What one agent's skill tools answer, from its skills in memory.""" - def __init__(self, skills: Sequence[Any], *, images: bool = False) -> None: + def __init__( + self, skills: Sequence[Any], *, images: bool = False, agents: SkillAgents | None = None + ) -> None: self._images = images self._skills: dict[str, Any] = {} for skill in skills: @@ -237,16 +257,26 @@ def __init__(self, skills: Sequence[Any], *, images: bool = False) -> None: self._misses_turn: object = _NO_TURN self._misses = 0 self._resource_paths = _adk_resource_listing() + self._start = _starter(agents, list(self._skills.values())) # Unknown arguments are ignored, as ADK ignores them. async def list_skills(self, **_: Any) -> str: return format_skills_as_xml(list(self._skills.values())) - async def load_skill(self, skill_name: Any = None, **_: Any) -> dict[str, Any]: + async def load_skill( + self, skill_name: Any = None, runtime: ToolRuntime | None = None, **_: Any + ) -> Any: + """A skill's instructions; a skill that names an agent type starts it instead. + + ``runtime`` is injected by the tool node; a call without one (outside + a graph) loads every skill as plain instructions. + """ if not skill_name: raise _Failed("Argument 'skill_name' is required.", "INVALID_ARGUMENTS") skill = self._skill(skill_name) + if self._start is not None and runtime is not None and skill_agent(skill) is not None: + return await self._start(skill, runtime) answer: dict[str, Any] = { "skill_name": skill_name, "instructions": skill.instructions, @@ -310,6 +340,23 @@ def _miss(self) -> int: return self._misses +def _starter( + agents: SkillAgents | None, skills: Sequence[Any] +) -> Callable[[Any, ToolRuntime], Awaitable[Any]] | None: + """What starts the agent a skill names, or None when no skill names one. + + Imported when the tools are built: a first import during a call would + hold the event loop. The skills whose agent could not be started are + warned of here. + """ + if agents is None or not any(skill_agent(skill) is not None for skill in skills): + return None + from agentic_cli.workflow.deepagents.task_tool import start_skill_run + + agents.check(skills) + return functools.partial(start_skill_run, agents) + + def _adk_resource_listing() -> Callable[[Any], list[str]] | None: """How ADK's ``load_skill`` lists a skill's resources, or None: none before google-adk 2.15. diff --git a/src/agentic_cli/workflow/deepagents/manager.py b/src/agentic_cli/workflow/deepagents/manager.py index 71c4779f..3236fd72 100644 --- a/src/agentic_cli/workflow/deepagents/manager.py +++ b/src/agentic_cli/workflow/deepagents/manager.py @@ -52,7 +52,7 @@ from agentic_cli.constants import truncate from agentic_cli.logging import Loggers from agentic_cli.tools.registry import ToolDefinition, identify_tool -from agentic_cli.tools.skills import SkillStore +from agentic_cli.tools.skills import SkillAgents, SkillStore from agentic_cli.tools.skills.langchain_tools import SKILL_TOOL_NAMES, make_skill_tools from agentic_cli.workflow.base_manager import BaseWorkflowManager, Closer from agentic_cli.workflow.checkpointers import ( @@ -394,7 +394,8 @@ def _skill_tools( """``config``'s skills as skill tools, and the instruction its prompt gets. The skills resolve as on ADK: an absolute path to a skill folder, or a - name under ``skills_dirs``. + name under ``skills_dirs``. A skill that names an agent type starts it + when loaded, as on ADK. Raises: ValueError: A skill cannot be found or loaded (``SkillStore``). @@ -411,7 +412,13 @@ def _skill_tools( ) skills = SkillStore(self._settings.skills_dirs or []).resolve(config.skills) skill_tools, instruction = make_skill_tools( - skills, provider=self._resolved_models[config.name].record.kind + skills, + provider=self._resolved_models[config.name].record.kind, + # The base validated the graph before this build, so the root is set. + agents=SkillAgents( + config.name, lambda: self._delegations, + root=config.name == self._root_agent_name, + ), ) logger.debug( "skill_tools_attached", agent=config.name, skills=[s.name for s in skills] diff --git a/src/agentic_cli/workflow/deepagents/task_tool.py b/src/agentic_cli/workflow/deepagents/task_tool.py index 1c6e457f..af5cd54b 100644 --- a/src/agentic_cli/workflow/deepagents/task_tool.py +++ b/src/agentic_cli/workflow/deepagents/task_tool.py @@ -31,6 +31,10 @@ ``check_agents``), each bound to its own declaration and answering as ``task`` does: its result as JSON, one ``ToolMessage``, the shared state a follow-up run changed in the same ``Command``. + +A ``load_skill`` call of a skill that names an agent type starts that run here +too (``start_skill_run``, from ``tools/skills/langchain_tools.py``), answered +as ``task`` is. """ from __future__ import annotations @@ -49,7 +53,7 @@ from langgraph.types import Command from agentic_cli.logging import Loggers -from agentic_cli.tools._core.delegation import FOLLOW_UP_TOOLS, TASK_TOOL +from agentic_cli.tools._core.delegation import FOLLOW_UP_TOOLS, LOAD_SKILL_TOOL, TASK_TOOL from agentic_cli.tools.registry import bind_tool_identity, get_registry from agentic_cli.workflow.agents.brief import ( follow_up_description, @@ -63,6 +67,7 @@ from agentic_cli.workflow.tool_errors import unknown_tool_result if TYPE_CHECKING: + from agentic_cli.tools.skills.agents import SkillAgents from agentic_cli.workflow.agents.delegate import Delegations logger = Loggers.workflow() @@ -127,6 +132,33 @@ async def task(runtime: ToolRuntime, **arguments: Any) -> Command: return tool +async def start_skill_run(agents: SkillAgents, skill: Any, runtime: ToolRuntime) -> Command: + """A ``load_skill`` of ``skill``, which names an agent type: the run it starts. + + Answered as ``task`` is: one ``ToolMessage`` with the envelope (or the + refusal) as JSON, and the shared state the run changed in the same + ``Command``. + + Args: + agents: The loading agent's ``SkillAgents``. + skill: The skill, an ADK ``Skill``. + runtime: The call's runtime, which the tool node injects. + """ + state = runtime.state + delegated = await agents.start( + skill, + call_id=runtime.tool_call_id, + state={key: state[key] for key in SHARED_KEYS if key in state}, + history=lambda: inherited_messages(state), + ) + answer = ToolMessage( + json.dumps(delegated.result, ensure_ascii=False), + tool_call_id=runtime.tool_call_id, + name=LOAD_SKILL_TOOL, + ) + return Command(update={**delegated.state, "messages": [answer]}) + + def build_follow_up_tools(delegations: Callable[[], Delegations]) -> list[StructuredTool]: """The parent's tools (``message_agent``, ``stop_agent``, ``check_agents``), in ``FOLLOW_UP_TOOLS`` order. diff --git a/tests/workflow/deepagents/test_skills.py b/tests/workflow/deepagents/test_skills.py index 2c537f6b..282736b5 100644 --- a/tests/workflow/deepagents/test_skills.py +++ b/tests/workflow/deepagents/test_skills.py @@ -487,6 +487,26 @@ async def load(provider, file_path): assert "cannot be shown" in status["status"] assert "injected" not in status["status"] + def test_with_a_skill_that_starts_an_agent_they_are_declared_as_before( + self, skills_dir, tmp_path + ): + """Loading such a skill starts its agent, through the same tools: the + model is offered what ADK offers, and each tool is bound as before.""" + from langchain_core.utils.function_calling import convert_to_openai_tool + + from tests.workflow.test_skills import _agents, _starting_skill + + skills = [*_skills(skills_dir), *SkillStore().resolve([str(_starting_skill(tmp_path))])] + + tools, instruction = make_skill_tools(skills, agents=_agents()) + + plain, _ = make_skill_tools(skills) + assert [convert_to_openai_tool(t) for t in tools] == [ + convert_to_openai_tool(t) for t in plain + ] + assert instruction == SKILLS_INSTRUCTION + assert [identify_tool(t) for t in tools] == [identify_tool(t) for t in plain] + def test_duplicate_skill_names_raise_as_on_adk(self, skills_dir): skill = _skills(skills_dir)[0] From a69754ff69e56fbfc92b760eeb41f2464d2671c4 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:05:05 -0500 Subject: [PATCH 4/6] Docs: skills that start an agent The CHANGELOG's Added bullet, the README's skills row and Sub-agent context bullet, and CLAUDE.md's skills, ADK and Deep Agents lines and the sub-agent paragraph. --- CHANGELOG.md | 32 ++++++++++++++++++++++++++++++++ CLAUDE.md | 14 ++++++++------ README.md | 32 +++++++++++++++++++++++++++++++- 3 files changed, 71 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61fc94b6..6ee818d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -575,6 +575,38 @@ the start of the entry's title. ### Added +- **A skill that starts an agent: the frontmatter key `agent`, on both + backends.** A skill's `SKILL.md` may name one of the app's agent types at + the top of its frontmatter (`agent: researcher`). When an agent loads it + (`load_skill`), a run of that type starts instead of the skill's + instructions being handed back: its task message is the skill's body + under its name (`# Task: `, `## Objective`), its parent the + loading agent's run, `started_by: skill:`, counted toward + `max_runs_per_turn` as a `task` call's run is, and the call's result is + the run's envelope with `"skill": ""` added, shown as a + delegation. The skill gives no tools and no system prompt: the run has + its type's own. The app allows it as for any type started at run time: + the type's `spawnable_by` and `SubAgentPolicy.spawn_sources` both hold + `"skill"`, and the loading run is one that may start a type + (`max_spawn_depth`: by default the main agent alone; an inheriting agent + starts none, and an inheriting type is started by the main agent alone). + Otherwise the load starts no run and its result says why: `{"success": + false, "error": "The skill 'research' starts the agent 'helper', which + this app does not let a skill start."}` (or `is not one of this app's + agent types`, or `cannot be started here: sub-agents cannot start + sub-agents`), and a skill whose agent its agent's first run could not + start is warned of as the agent is built (`skill_agent_not_startable`); + the app still starts. A skill without the key loads as before; one whose + frontmatter already had a top-level `agent` key for another use now asks + for that agent type. `agentic_cli.tools.skills` (provisional): + `SKILL_AGENT_KEY`, `skill_agent`, `skill_started_by`, `SkillAgents`; + `make_skill_toolset(..., agents=)` and `make_skill_tools(..., agents=)` + take an agent's `SkillAgents` (without it every skill loads as ADK + loads it), and the manager's delegations' `types` lists every agent + type. On ADK the framework's `load_skill` (`SkillLoadTool`, with ADK's + declaration) takes the place of ADK's in an agent's toolset only when one + of its skills names an agent type. + - **`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: diff --git a/CLAUDE.md b/CLAUDE.md index d00c6883..41d71570 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -84,11 +84,12 @@ 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, 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 - 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: ; 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 failed: , 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: , "; limit_sentences: the limits it states, "At most sub-agents work at once; more calls in one response wait for a free slot. At most 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 - 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: ; 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; types: every agent type by name, read-only, what a skill's start checks against), 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 failed: , 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: , "; limit_sentences: the limits it states, "At most sub-agents work at once; more calls in one response wait for a free slot. At most 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); 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) +│ │ │ ├── skill_tool.py # SkillLoadTool: load_skill for an agent with a skill that names an agent type (a LoadSkillTool with ADK's declaration, bound by make_skill_toolset as ADK's is): such a skill → SkillAgents.start, its result JSON text as task's, the mark from and back to the caller's state, an inheriting type given inherited_events; any other skill as ADK loads it; imported by make_skill_toolset only │ │ │ ├── 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 │ │ │ ├── fit_guard_plugin.py # FitGuardPlugin: a request over its agent's budget has its oldest turns left out (drop_turns); what opens the conversation, the memory index, the roster, then a summary (protected_head, never dropped; is_roster), folded into the next user text (fold_summary); in a sub-agent type's chain (keep_task) a run's task message, its invocation's user content, and its instance's brief (brief_of: the event of its child session whose state delta set BRIEF_KEY) never dropped either, the first kept turn joining them (a message steered after a tool result starts a turn); request_as_seen │ │ │ ├── overflow_plugin.py # OverflowPlugin (OVERFLOW_PLUGIN_FAILED: ADK's wrapper of its errors, which the manager unwraps): a provider's overflow summarized (the root; the retry: the memory index and roster that open the request, the summary and the turns it kept) or trimmed (a sub-agent's keeping its task message and its instance's brief), retried once (the retry timed around its own request: call_clock.mark_latency), then CONTEXT_OVERFLOW: overflow_message for an agent that replies (reply_agents), subagent_overflow_message for a sub-agent's run (root None on its runner), which fails it; a sub-agent's trimmed retry keeps its task message (keep_task) @@ -116,7 +117,7 @@ agentic-cli/ │ │ │ ├── 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) +│ │ │ ├── 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); start_skill_run (a load_skill of a skill that names an agent type: SkillAgents.start, answered as task is, one Command) │ │ │ ├── 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) │ │ │ ├── sessions.py # thread_id(SessionRef), instance_thread_id and instance_run_config (a sub-agent instance's thread, [app, user, session, instance], its checkpoints' metadata carrying instance and thread_kind: instance), CheckpointSessions (instances: read from the instance threads' first input checkpoints (source input, step -1: one a thread, no later one; each holds its first run's input, which the saver decodes: the brief, and an inheriting instance's copy of its parent's conversation); stored_instances: those threads and the stored records' ids and counters; agent_records/save_agent_records/delete_agent_records: a conversation's sub-agent records, an item of the store beside the checkpointer under (agentic_cli, agents, , ), keyed by the session id; delete: those threads first, then the records, then the conversation; a first run onto a thread the store keeps fails (the manager's check); rows from an index in the store beside the checkpointer, written as a turn starts (its input counted: a killed process still lists it), then from the newest root checkpoint as it ends and after /compact; a database from before it scanned once per app and user), job notifications and notices to the root (`notice_message`, `tell_root`; `is_notice`: either, left out of recent and a row); open_sessions: a store's conversations for a reader, without the manager (empty without the checkpoints table, looked at read-only before any setup) │ │ │ ├── summarization.py # Each agent's thresholds from its budget (the manager's _budgets, given to build_agent_tree(budgets=); context_budget when none); NoArchiveBackend; history filters; compact()'s cut, summary and event (marked: the count reported before it is no trigger, _should_summarize); OverflowMapped: the summary model's overflows as ContextOverflowError, inside its retry; a request's count includes the memory index (index=) and the roster (roster=), and a summary written drops their snapshots before the request goes on (on_written=); an instance's brief (brief_message: its first run's task message, marked; is_brief, brief_of: the last marked), restated first in each summary message of its thread that stands for it (_partition_messages, _build_new_messages_with_path, per call through _BRIEF) @@ -153,11 +154,12 @@ agentic-cli/ │ │ │ ├── planning.py # save_plan/get_plan core (+ checkbox parsing) │ │ │ ├── tasks.py # save_tasks/get_tasks core (+ progress parsing) │ │ │ ├── state_tools.py # Declares save_plan/get_plan/save_tasks/get_tasks (declare_tool) -│ │ │ └── delegation.py # Declares task, the framework's delegation tool on both backends, and the parent's tools that continue a sub-agent (FOLLOW_UP_TOOLS: message_agent, stop_agent, check_agents), exempt: reserved names; ENVELOPE_TOOLS (task, message_agent: shown as a delegation); FOLLOW_UP_CLASH_ERROR +│ │ │ └── delegation.py # Declares task, the framework's delegation tool on both backends, and the parent's tools that continue a sub-agent (FOLLOW_UP_TOOLS: message_agent, stop_agent, check_agents), exempt: reserved names; ENVELOPE_TOOLS (task, message_agent, load_skill: LOAD_SKILL_TOOL; an envelope shown as a delegation); FOLLOW_UP_CLASH_ERROR │ │ ├── adk/state_tools.py # ADK-native plan/task tools (ToolContext.state) │ │ ├── langgraph/state_tools.py # LangGraph-library plan/task tools (Command/InjectedState): Deep Agents and LangGraph -│ │ ├── skills/ # Agent Skills: SkillStore, the ADK toolset (toolset.py) -│ │ │ └── langchain_tools.py # make_skill_tools: list_skills/load_skill/load_skill_resource for Deep Agents +│ │ ├── skills/ # Agent Skills: SkillStore, the ADK toolset (toolset.py: make_skill_toolset(agents=), ADK's load_skill replaced by adk/skill_tool.py's SkillLoadTool for an agent with a skill that names an agent type) +│ │ │ ├── agents.py # A skill that starts an agent: SKILL_AGENT_KEY (the frontmatter's top-level agent), skill_agent, skill_started_by (skill:); SkillAgents(agent, delegations, root=): check as the agent is built (skill_agent_not_startable, warning, once per agent and skill though ADK builds an agent for each model choice; the app still starts), start at a load (the type one of the app's, spawnable for "skill", may_spawn at the loading run's depth, none by an inheriting agent nor, below the root, of an inheriting type; else SKILL_AGENT_ERROR, no run): Delegations.start (the brief the skill's name and body, counted, no tools or model), the envelope with "skill" +│ │ │ └── langchain_tools.py # make_skill_tools: list_skills/load_skill/load_skill_resource for Deep Agents (agents=: a skill that names an agent type starts it, workflow/deepagents/task_tool.py::start_skill_run, from the call's injected runtime) │ │ ├── jobs/ # Long-running jobs: JobManager, backends (a spec pinned at submit: a subprocess job runs where it was submitted; one on a backend that does not survive a restart, in-process, is claimed at submit and runs only in its submitter, FAILED if still queued at close; JobRecord.started_by: the sub-agent instance whose call submitted it), job_* tools │ │ │ └── resume.py # job_result_payload, JOB_NOTICE_HEADER, job_notice_ask (a sub-agent's job named: JOB_NOTICE_ASK_FOR): what a finished job tells the agent │ │ ├── sandbox/ # Stateful code-execution sandbox (sandbox_execute); stage_inputs and the docker backend's _collect_outputs copy through descriptors of inputs/ and outputs/ (the kernel can swap either for a symlink); an input whose path runs through the session's directory is refused, on docker any session's (sandbox_root_for(settings): /sandbox); calls on one session run one at a time (SandboxManager: a lock per session; a reset or cleanup during a call stops its cell, SandboxBackend.stop, and leaves the kernel's shutdown to that call) @@ -254,7 +256,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": " failed: : "}` 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`, ` failed: `, 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, `: the request no longer fits '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 ("'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: ` (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` (" returned no answer"), and a root on OpenRouter or an OpenAI-compatible server replies "OpenAI refusal: ". 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`), 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 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 `, 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`, ` failed: `, 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 ` and `/agent `'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`: `/`, 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 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 `, 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`, ` failed: `, 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 ` and `/agent `'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`: `/`, 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`. A skill whose frontmatter names a type (`agent: `, `tools/skills/agents.py`) starts a run of it when an agent loads it, on both backends (ADK: `adk/skill_tool.py::SkillLoadTool` in `load_skill`'s place; Deep Agents: `_SkillAnswers.load_skill`), when the type's `spawnable_by` and the policy's `spawn_sources` hold `"skill"` and the loading run may start one (`may_spawn`): through `Delegations.start` (`started_by: skill:`, the loading run its parent, its task message the skill's body under its name, counted toward `max_runs_per_turn`), the call's result the envelope with `"skill"`, shown as a delegation; otherwise `{"success": false, "error": "The skill '' starts the agent '', which ."}`, no run, and a skill its agent's first run could not start is warned of as the agent is built (`skill_agent_not_startable`). - **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 dec95571..a65f213e 100644 --- a/README.md +++ b/README.md @@ -1286,7 +1286,7 @@ configs = [coordinator, researcher, analyst] | `model` | str \| None | A model reference (`anthropic:claude-sonnet-5-5`), a bare model id, or a role (`fast`); without one, the `default` role (see [Models and providers](#models-and-providers)) | | `model_settings` | ModelSettings \| None | The agent's thinking, `max_tokens`, sampling settings and `extra` (see [Thinking](#thinking)) | | `mcp_servers` | list[MCPServerConfig] | MCP servers whose tools the agent gets (ADK and Deep Agents) | -| `skills` | list[str] | Agent Skills: a skill folder's absolute path, or a name under `skills_dirs` (ADK and Deep Agents; never looked up in the working directory) | +| `skills` | list[str] | Agent Skills: a skill folder's absolute path, or a name under `skills_dirs` (ADK and Deep Agents; never looked up in the working directory). A skill whose frontmatter names an agent type (`agent: researcher`) starts a run of it when loaded; see [Sub-agent context](#sub-agent-context) | | `inherit_context` | bool | What a sub-agent sees when its parent delegates to it: its task alone (`False`, the default) or its parent's conversation too (`True`); see [Sub-agent context](#sub-agent-context) (ADK and Deep Agents) | | `brief_required` | tuple[str, ...] | The brief fields a delegation to this agent must fill (default `("objective",)`; `title` and `objective` are always required): any of `deliverable`, `constraints`, `known`, `done_when`. A `task` call that leaves one empty starts no run, and its caller reads which. Not on the root | | `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 | @@ -1477,6 +1477,36 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", # The coordinator's call: {"agent_type": "researcher", "title": "Look it up", # "objective": "...", "tools": ["web_search"], "model": "fast"} ``` +- **Skills that start an agent.** A skill may name an agent type at the top + of its `SKILL.md` frontmatter, `agent: researcher`; with the type's + `spawnable_by={"skill"}` and `SubAgentPolicy(spawn_sources={"skill"})`, + an agent that loads the skill starts a run of that type instead of + reading the skill's instructions. The run's task message is the skill's + body under its name (`# Task: research`, `## Objective`), its parent the + loading agent's run (`started_by: skill:research`), and it counts toward + `max_runs_per_turn`; the `load_skill` call's result is the run's envelope + with `"skill": "research"` added. The skill gives no tools and no system + prompt: the run has its type's. A load is refused, no run started, when + the type is not one of the app's, when the type or the policy does not + let a skill start it, or from a run that may start no type + (`max_spawn_depth`; an inheriting agent starts none, and an inheriting + type is started by the main agent alone): `{"success": false, "error": + "The skill 'research' starts the agent 'researcher', which this app does + not let a skill start."}`. Such a skill is also warned of as its agent is + built (`skill_agent_not_startable`), and the app still starts. + + ```markdown + --- + name: todo-audit + description: List the project's open TODO comments. + agent: auditor + --- + Find every TODO comment under src/, group them by file, and report them + as a list with each one's line number. + ``` + + Its body is all a fresh type's run reads (an inheriting type reads the + conversation too), so write it as a task that stands on its own. - **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 From 1505ffa66a9c72a75a272418b95d5bc6a8421724 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:35:03 -0500 Subject: [PATCH 5/6] Skills: the agent key is ignored where no skill may start an agent; an empty skill is refused The frontmatter key counts only when "skill" is in SubAgentPolicy.spawn_sources: otherwise the skill loads as instructions, as any skill does (other tools give skills an agent key of their own), and the build warns once per agent and skill (skill_agent_ignored); ADK keeps its own load_skill. A skill with no instructions has no task and is refused, and warned of at build. Tests for the build warning after a model switch, the instance's tools and model, a type's brief_required, and a crash's open load_skill call. --- CHANGELOG.md | 23 ++- CLAUDE.md | 4 +- README.md | 9 +- src/agentic_cli/tools/skills/agents.py | 45 ++++- .../tools/skills/langchain_tools.py | 26 +-- src/agentic_cli/tools/skills/toolset.py | 23 +-- .../workflow/adk/event_processor.py | 9 +- tests/tools/test_skill_agents.py | 59 +++++- tests/workflow/test_skills.py | 18 +- tests/workflow/test_subagents_contract.py | 179 ++++++++++++++---- 10 files changed, 301 insertions(+), 94 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ee818d3..07dc1dc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -577,35 +577,38 @@ the start of the entry's title. - **A skill that starts an agent: the frontmatter key `agent`, on both backends.** A skill's `SKILL.md` may name one of the app's agent types at - the top of its frontmatter (`agent: researcher`). When an agent loads it - (`load_skill`), a run of that type starts instead of the skill's - instructions being handed back: its task message is the skill's body + the top of its frontmatter (`agent: researcher`). Where the app lets a + skill start an agent (`"skill"` in `SubAgentPolicy.spawn_sources`; with + the default policy it does not, and the key is ignored: the skill loads + as instructions, as any skill does, and the build warns of it, + `skill_agent_ignored`, since other tools give skills an `agent` key of + their own), when an agent loads it (`load_skill`), a run of that type + starts instead of the skill's instructions being handed back: its task message is the skill's body under its name (`# Task: `, `## Objective`), its parent the loading agent's run, `started_by: skill:`, counted toward `max_runs_per_turn` as a `task` call's run is, and the call's result is the run's envelope with `"skill": ""` added, shown as a delegation. The skill gives no tools and no system prompt: the run has its type's own. The app allows it as for any type started at run time: - the type's `spawnable_by` and `SubAgentPolicy.spawn_sources` both hold - `"skill"`, and the loading run is one that may start a type + the type's `spawnable_by` holds `"skill"` too, and the loading run is one that may start a type (`max_spawn_depth`: by default the main agent alone; an inheriting agent starts none, and an inheriting type is started by the main agent alone). Otherwise the load starts no run and its result says why: `{"success": false, "error": "The skill 'research' starts the agent 'helper', which this app does not let a skill start."}` (or `is not one of this app's agent types`, or `cannot be started here: sub-agents cannot start - sub-agents`), and a skill whose agent its agent's first run could not + sub-agents`; or `needs the skill's instructions as its task, and this + skill has none`), and a skill whose agent its agent's first run could not start is warned of as the agent is built (`skill_agent_not_startable`); - the app still starts. A skill without the key loads as before; one whose - frontmatter already had a top-level `agent` key for another use now asks - for that agent type. `agentic_cli.tools.skills` (provisional): + the app still starts. A skill without the key loads as before. + `agentic_cli.tools.skills` (provisional): `SKILL_AGENT_KEY`, `skill_agent`, `skill_started_by`, `SkillAgents`; `make_skill_toolset(..., agents=)` and `make_skill_tools(..., agents=)` take an agent's `SkillAgents` (without it every skill loads as ADK loads it), and the manager's delegations' `types` lists every agent type. On ADK the framework's `load_skill` (`SkillLoadTool`, with ADK's declaration) takes the place of ADK's in an agent's toolset only when one - of its skills names an agent type. + of its skills names an agent type and the app lets a skill start one. - **`AgentConfig.model_choices`: the models a delegation may run a type on instead of its own, on both backends.** References, bare model ids or diff --git a/CLAUDE.md b/CLAUDE.md index 41d71570..bb755117 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -158,7 +158,7 @@ agentic-cli/ │ │ ├── adk/state_tools.py # ADK-native plan/task tools (ToolContext.state) │ │ ├── langgraph/state_tools.py # LangGraph-library plan/task tools (Command/InjectedState): Deep Agents and LangGraph │ │ ├── skills/ # Agent Skills: SkillStore, the ADK toolset (toolset.py: make_skill_toolset(agents=), ADK's load_skill replaced by adk/skill_tool.py's SkillLoadTool for an agent with a skill that names an agent type) -│ │ │ ├── agents.py # A skill that starts an agent: SKILL_AGENT_KEY (the frontmatter's top-level agent), skill_agent, skill_started_by (skill:); SkillAgents(agent, delegations, root=): check as the agent is built (skill_agent_not_startable, warning, once per agent and skill though ADK builds an agent for each model choice; the app still starts), start at a load (the type one of the app's, spawnable for "skill", may_spawn at the loading run's depth, none by an inheriting agent nor, below the root, of an inheriting type; else SKILL_AGENT_ERROR, no run): Delegations.start (the brief the skill's name and body, counted, no tools or model), the envelope with "skill" +│ │ │ ├── agents.py # A skill that starts an agent: SKILL_AGENT_KEY (the frontmatter's top-level agent), skill_agent, skill_started_by (skill:); SkillAgents(agent, delegations, root=): starts (the key counts only with "skill" in spawn_sources: otherwise it is ignored and the skill loads as instructions, ADK's own toolset kept), check as the agent is built (skill_agent_ignored, or skill_agent_not_startable, warning, once per agent and skill though ADK builds an agent for each model choice; the app still starts), start at a load (the type one of the app's, spawnable for "skill", may_spawn at the loading run's depth, none by an inheriting agent nor, below the root, of an inheriting type, and the skill's instructions not empty; else SKILL_AGENT_ERROR, no run): Delegations.start (the brief the skill's name and body, counted, no tools or model), the envelope with "skill" │ │ │ └── langchain_tools.py # make_skill_tools: list_skills/load_skill/load_skill_resource for Deep Agents (agents=: a skill that names an agent type starts it, workflow/deepagents/task_tool.py::start_skill_run, from the call's injected runtime) │ │ ├── jobs/ # Long-running jobs: JobManager, backends (a spec pinned at submit: a subprocess job runs where it was submitted; one on a backend that does not survive a restart, in-process, is claimed at submit and runs only in its submitter, FAILED if still queued at close; JobRecord.started_by: the sub-agent instance whose call submitted it), job_* tools │ │ │ └── resume.py # job_result_payload, JOB_NOTICE_HEADER, job_notice_ask (a sub-agent's job named: JOB_NOTICE_ASK_FOR): what a finished job tells the agent @@ -256,7 +256,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": " failed: : "}` 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`, ` failed: `, 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, `: the request no longer fits '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 ("'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: ` (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` (" returned no answer"), and a root on OpenRouter or an OpenAI-compatible server replies "OpenAI refusal: ". 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`), 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 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 `, 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`, ` failed: `, 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 ` and `/agent `'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`: `/`, 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`. A skill whose frontmatter names a type (`agent: `, `tools/skills/agents.py`) starts a run of it when an agent loads it, on both backends (ADK: `adk/skill_tool.py::SkillLoadTool` in `load_skill`'s place; Deep Agents: `_SkillAnswers.load_skill`), when the type's `spawnable_by` and the policy's `spawn_sources` hold `"skill"` and the loading run may start one (`may_spawn`): through `Delegations.start` (`started_by: skill:`, the loading run its parent, its task message the skill's body under its name, counted toward `max_runs_per_turn`), the call's result the envelope with `"skill"`, shown as a delegation; otherwise `{"success": false, "error": "The skill '' starts the agent '', which ."}`, no run, and a skill its agent's first run could not start is warned of as the agent is built (`skill_agent_not_startable`). +- **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 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 `, 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`, ` failed: `, 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 ` and `/agent `'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`: `/`, 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`. A skill whose frontmatter names a type (`agent: `, `tools/skills/agents.py`) starts a run of it when an agent loads it where the app lets a skill start an agent (`"skill"` in `spawn_sources`; otherwise the key is ignored, the skill loads as instructions and the build warns, `skill_agent_ignored`), on both backends (ADK: `adk/skill_tool.py::SkillLoadTool` in `load_skill`'s place; Deep Agents: `_SkillAnswers.load_skill`), when the type's `spawnable_by` holds `"skill"`, the skill has instructions and the loading run may start one (`may_spawn`): through `Delegations.start` (`started_by: skill:`, the loading run its parent, its task message the skill's body under its name, counted toward `max_runs_per_turn`), the call's result the envelope with `"skill"`, shown as a delegation; otherwise `{"success": false, "error": "The skill '' starts the agent '', which ."}`, no run, and a skill its agent's first run could not start is warned of as the agent is built (`skill_agent_not_startable`). - **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 a65f213e..a47c65a4 100644 --- a/README.md +++ b/README.md @@ -1286,7 +1286,7 @@ configs = [coordinator, researcher, analyst] | `model` | str \| None | A model reference (`anthropic:claude-sonnet-5-5`), a bare model id, or a role (`fast`); without one, the `default` role (see [Models and providers](#models-and-providers)) | | `model_settings` | ModelSettings \| None | The agent's thinking, `max_tokens`, sampling settings and `extra` (see [Thinking](#thinking)) | | `mcp_servers` | list[MCPServerConfig] | MCP servers whose tools the agent gets (ADK and Deep Agents) | -| `skills` | list[str] | Agent Skills: a skill folder's absolute path, or a name under `skills_dirs` (ADK and Deep Agents; never looked up in the working directory). A skill whose frontmatter names an agent type (`agent: researcher`) starts a run of it when loaded; see [Sub-agent context](#sub-agent-context) | +| `skills` | list[str] | Agent Skills: a skill folder's absolute path, or a name under `skills_dirs` (ADK and Deep Agents; never looked up in the working directory). A skill whose frontmatter names an agent type (`agent: researcher`) starts a run of it when loaded, where the app lets a skill start an agent (otherwise the key is ignored); see [Sub-agent context](#sub-agent-context) | | `inherit_context` | bool | What a sub-agent sees when its parent delegates to it: its task alone (`False`, the default) or its parent's conversation too (`True`); see [Sub-agent context](#sub-agent-context) (ADK and Deep Agents) | | `brief_required` | tuple[str, ...] | The brief fields a delegation to this agent must fill (default `("objective",)`; `title` and `objective` are always required): any of `deliverable`, `constraints`, `known`, `done_when`. A `task` call that leaves one empty starts no run, and its caller reads which. Not on the root | | `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 | @@ -1481,14 +1481,17 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", of its `SKILL.md` frontmatter, `agent: researcher`; with the type's `spawnable_by={"skill"}` and `SubAgentPolicy(spawn_sources={"skill"})`, an agent that loads the skill starts a run of that type instead of - reading the skill's instructions. The run's task message is the skill's + reading the skill's instructions. Without `"skill"` in `spawn_sources` + (the default) the key is ignored: the skill loads as instructions, as any + skill does, and the build warns of it (`skill_agent_ignored`). The run's task message is the skill's body under its name (`# Task: research`, `## Objective`), its parent the loading agent's run (`started_by: skill:research`), and it counts toward `max_runs_per_turn`; the `load_skill` call's result is the run's envelope with `"skill": "research"` added. The skill gives no tools and no system prompt: the run has its type's. A load is refused, no run started, when the type is not one of the app's, when the type or the policy does not - let a skill start it, or from a run that may start no type + let a skill start it, for a skill with no instructions (nothing to be the + task), or from a run that may start no type (`max_spawn_depth`; an inheriting agent starts none, and an inheriting type is started by the main agent alone): `{"success": false, "error": "The skill 'research' starts the agent 'researcher', which this app does diff --git a/src/agentic_cli/tools/skills/agents.py b/src/agentic_cli/tools/skills/agents.py index 4ae92746..889f334d 100644 --- a/src/agentic_cli/tools/skills/agents.py +++ b/src/agentic_cli/tools/skills/agents.py @@ -7,6 +7,12 @@ agent's run, ``started_by`` ``skill:``, and the load's result the run's envelope with the skill's name added. +The key takes effect only where the app lets a skill start an agent +(``"skill"`` in ``SubAgentPolicy.spawn_sources``); otherwise it is ignored, the +skill loads as instructions, as any skill does, and the build warns of it +(``skill_agent_ignored``: other tools, Claude Code's among them, give skills +an ``agent`` key of their own). + A load starts a run only where any run-time start is allowed: the type is one of the app's, the type's ``spawnable_by`` and the policy's ``spawn_sources`` both hold ``"skill"``, and the loading run may start a type at its depth @@ -43,6 +49,12 @@ UNKNOWN_TYPE = "is not one of this app's agent types" NOT_FOR_SKILLS = "this app does not let a skill start" NOT_HERE = "cannot be started here: sub-agents cannot start sub-agents" +NO_TASK = "needs the skill's instructions as its task, and this skill has none" +#: The build's warning for a key that is ignored, its text. +IGNORED = ( + "The skill '{skill}' names the agent '{agent}', but this app lets no skill " + "start an agent: it loads as instructions." +) def skill_started_by(name: str) -> str: @@ -89,8 +101,16 @@ def __init__( self._root = root self._warned = warned if warned is not None else set() - def _reason(self, name: str, depth: int) -> str | None: - """Why this agent's run at ``depth`` may not start the type ``name``, or None.""" + def starts(self, skill: Any) -> bool: + """Whether loading ``skill`` is a start: it names an agent type and the app + lets a skill start one (``"skill"`` in ``spawn_sources``).""" + return ( + skill_agent(skill) is not None + and SKILL_SOURCE in self._delegations().policy.spawn_sources + ) + + def _reason(self, skill: Any, name: str, depth: int) -> str | None: + """Why this agent's run at ``depth`` may not start the type ``name`` for ``skill``.""" delegations = self._delegations() types = delegations.types config = types.get(name) @@ -106,25 +126,36 @@ def _reason(self, name: str, depth: int) -> str | None: or (depth > 0 and config.inherit_context) ): return NOT_HERE + if not skill.instructions.strip(): + return NO_TASK return None def refusal(self, skill: Any, depth: int) -> str | None: """The error a load of ``skill`` from a run at ``depth`` gets, or None to start it.""" name = skill_agent(skill) - if name is None: + if name is None or not self.starts(skill): return None - reason = self._reason(name, depth) + reason = self._reason(skill, name, depth) if reason is None: return None return SKILL_AGENT_ERROR.format(skill=skill.name, agent=name, reason=reason) def check(self, skills: Sequence[Any]) -> None: - """Warn, once per skill, of each that this agent's first run could not start.""" + """Warn, once per skill, of each that names an agent this agent's first run + could not start, or that the app lets no skill start (the key is ignored).""" for skill in skills: name = skill_agent(skill) if name is None or (self._agent, skill.name) in self._warned: continue - reason = self._reason(name, 0 if self._root else 1) + if not self.starts(skill): + self._warned.add((self._agent, skill.name)) + logger.warning( + "skill_agent_ignored", + agent=self._agent, skill=skill.name, agent_type=name, + message=IGNORED.format(skill=skill.name, agent=name), + ) + continue + reason = self._reason(skill, name, 0 if self._root else 1) if reason is None: continue self._warned.add((self._agent, skill.name)) @@ -141,7 +172,7 @@ async def start( state: Mapping[str, Any], history: Callable[[], Any] | None, ) -> Delegated: - """Load ``skill``: start its agent's run, or refuse and start none.""" + """Load ``skill``, which ``starts``: start its agent's run, or refuse and start none.""" caller = get_active_run() refused = self.refusal(skill, caller.depth if caller is not None else 0) if refused is not None: diff --git a/src/agentic_cli/tools/skills/langchain_tools.py b/src/agentic_cli/tools/skills/langchain_tools.py index f235a6a0..1af59a40 100644 --- a/src/agentic_cli/tools/skills/langchain_tools.py +++ b/src/agentic_cli/tools/skills/langchain_tools.py @@ -36,7 +36,8 @@ is denied, whatever its name. A skill whose frontmatter names an agent type starts a run of it when loaded -(``agents.py``), given the agent's ``SkillAgents`` (``make_skill_tools(agents=)``): +(``agents.py``), where the app lets a skill start an agent, given the agent's +``SkillAgents`` (``make_skill_tools(agents=)``): ``load_skill`` takes the call's runtime, which LangGraph's tool node injects, and hands the skill to ``workflow/deepagents/task_tool.py::start_skill_run``. The tools' declarations are unchanged, and any other skill loads as above. @@ -58,7 +59,6 @@ from agentic_cli.models import ProviderKind from agentic_cli.tools.registry import bind_tool_identity, get_registry -from agentic_cli.tools.skills.agents import skill_agent from agentic_cli.workflow.sessions import get_active_turn if TYPE_CHECKING: @@ -185,9 +185,10 @@ def make_skill_tools( provider: The agent's model's provider kind. A binary resource is sent as an image only to a provider that reads one in a tool result; without it, every binary resource is a status. - agents: The agent's ``SkillAgents``. Given, a skill that names an - agent type starts it when loaded (and one its agent could not - start is warned of now). None: every skill loads as ADK loads it. + agents: The agent's ``SkillAgents``. Given, and the app lets a skill + start an agent, a skill that names an agent type starts it when + loaded (one its agent could not start, or the app lets no skill + start, is warned of now). None: every skill loads as ADK loads it. Returns: The tools, bound to the framework's skill tool definitions, and the @@ -257,6 +258,7 @@ def __init__( self._misses_turn: object = _NO_TURN self._misses = 0 self._resource_paths = _adk_resource_listing() + self._agents = agents self._start = _starter(agents, list(self._skills.values())) # Unknown arguments are ignored, as ADK ignores them. @@ -275,7 +277,7 @@ async def load_skill( if not skill_name: raise _Failed("Argument 'skill_name' is required.", "INVALID_ARGUMENTS") skill = self._skill(skill_name) - if self._start is not None and runtime is not None and skill_agent(skill) is not None: + if self._start is not None and runtime is not None and self._agents.starts(skill): return await self._start(skill, runtime) answer: dict[str, Any] = { "skill_name": skill_name, @@ -343,17 +345,19 @@ def _miss(self) -> int: def _starter( agents: SkillAgents | None, skills: Sequence[Any] ) -> Callable[[Any, ToolRuntime], Awaitable[Any]] | None: - """What starts the agent a skill names, or None when no skill names one. + """What starts the agent a skill names, or None when no skill does. Imported when the tools are built: a first import during a call would - hold the event loop. The skills whose agent could not be started are - warned of here. + hold the event loop. The skills whose agent could not be started, or + whose key is ignored, are warned of here. """ - if agents is None or not any(skill_agent(skill) is not None for skill in skills): + if agents is None: + return None + agents.check(skills) + if not any(agents.starts(skill) for skill in skills): return None from agentic_cli.workflow.deepagents.task_tool import start_skill_run - agents.check(skills) return functools.partial(start_skill_run, agents) diff --git a/src/agentic_cli/tools/skills/toolset.py b/src/agentic_cli/tools/skills/toolset.py index b20925b5..7903fd38 100644 --- a/src/agentic_cli/tools/skills/toolset.py +++ b/src/agentic_cli/tools/skills/toolset.py @@ -10,17 +10,16 @@ off; the parameter exists for a caller that owns one. A skill whose frontmatter names an agent type starts a run of it when loaded -(``agents.py``). For an agent with such a skill, given its ``SkillAgents``, -the toolset's ``load_skill`` is the framework's (``adk/skill_tool.py``); any -other toolset is ADK's own. +(``agents.py``), where the app lets a skill start an agent. For an agent with +such a skill, given its ``SkillAgents``, the toolset's ``load_skill`` is the +framework's (``adk/skill_tool.py``); any other toolset is ADK's own, and a +skill whose key is ignored there is warned of. """ from __future__ import annotations from typing import TYPE_CHECKING, Any -from agentic_cli.tools.skills.agents import skill_agent - if TYPE_CHECKING: from agentic_cli.tools.skills.agents import SkillAgents @@ -41,10 +40,11 @@ def make_skill_toolset( rather than offered and then failing. additional_tools: Tools surfaced when a skill with ``adk_additional_tools`` frontmatter is activated. - agents: The loading agent's ``SkillAgents``. Given, and one of the - skills naming an agent type, ``load_skill`` starts that agent - (and the skills that name one the agent could not start are - warned of). None: every skill loads as ADK loads it. + agents: The loading agent's ``SkillAgents``. Given, and the app lets + a skill start an agent, a skill naming an agent type starts that + agent when loaded; the skills that name one the agent could not + start, or the app lets no skill start, are warned of. None: every + skill loads as ADK loads it. Returns: A configured ``SkillToolset``. @@ -60,11 +60,12 @@ def make_skill_toolset( toolset._tools = [ t for t in toolset._tools if not isinstance(t, RunSkillScriptTool) ] - starting = {s.name: s for s in skills if skill_agent(s) is not None} + if agents is not None: + agents.check(skills) + starting = {s.name: s for s in skills if agents is not None and agents.starts(s)} if agents is not None and starting: from agentic_cli.workflow.adk.skill_tool import SkillLoadTool - agents.check(skills) toolset._tools = [ SkillLoadTool(toolset, starting, agents) if type(t) is LoadSkillTool else t for t in toolset._tools diff --git a/src/agentic_cli/workflow/adk/event_processor.py b/src/agentic_cli/workflow/adk/event_processor.py index 51ddcbe8..568e6ecb 100644 --- a/src/agentic_cli/workflow/adk/event_processor.py +++ b/src/agentic_cli/workflow/adk/event_processor.py @@ -502,8 +502,13 @@ def _with_call_id(event: WorkflowEvent, call_id: Any) -> WorkflowEvent: def _delegated(response: Any) -> Any: - """A ``task`` call's result (or a parent's tool's, or a skill's start) as it returned it: the dict whose - JSON text ADK stores under ``result`` (``adk/task_tool.py``); anything else as it is.""" + """The result of a call that delegates, as it returned it. + + That is a ``task`` call's (or a parent's tool's), or a ``load_skill`` that + started a run or was refused one: the dict whose JSON text ADK stores under + ``result`` (``adk/task_tool.py``, ``adk/skill_tool.py``). Anything else is + returned as it is. + """ if isinstance(response, dict) and set(response) == {"result"}: try: parsed = json.loads(response["result"]) diff --git a/tests/tools/test_skill_agents.py b/tests/tools/test_skill_agents.py index ef87416b..166ce7c2 100644 --- a/tests/tools/test_skill_agents.py +++ b/tests/tools/test_skill_agents.py @@ -115,15 +115,13 @@ class TestWhatALoadMayStart: ("lead", True, SKILLS, "nobody", "is not one of this app's agent types"), ("lead", True, SKILLS, "asked", "this app does not let a skill start"), ("lead", True, SKILLS, "middle", "this app does not let a skill start"), - ("lead", True, SubAgentPolicy(spawn_sources={"agent"}), "helper", - "this app does not let a skill start"), ("middle", False, SKILLS, "helper", "cannot be started here: sub-agents cannot start sub-agents"), ("reader", False, SubAgentPolicy(spawn_sources={"skill"}, max_spawn_depth=2), "helper", "cannot be started here: sub-agents cannot start sub-agents"), ("middle", False, SubAgentPolicy(spawn_sources={"skill"}, max_spawn_depth=2), "noter", "cannot be started here: sub-agents cannot start sub-agents"), - ], ids=["unknown", "type-not-for-skills", "a-static-sub-agent", "policy-not-for-skills", + ], ids=["unknown", "type-not-for-skills", "a-static-sub-agent", "past-the-depth", "an-inheriting-caller", "an-inheriting-type-below-the-root"]) def test_a_skill_it_may_not_start_is_warned_of_as_the_agent_is_built( self, tmp_path, logged, agent, root, policy, named, reason @@ -141,6 +139,21 @@ def test_a_skill_it_may_not_start_is_warned_of_as_the_agent_is_built( f"The skill 'research' starts the agent '{named}', which {reason}." ) + def test_one_with_no_instructions_has_no_task_and_is_refused(self, tmp_path, logged): + skill = make_skill(tmp_path, "research", "agent: helper\n", body=" ") + agents = SkillAgents("lead", lambda: made(), root=True) + reason = "needs the skill's instructions as its task, and this skill has none" + + agents.check([skill]) + + assert logged == [{ + "event": "skill_agent_not_startable", "log_level": "warning", "agent": "lead", + "skill": "research", "agent_type": "helper", "reason": reason, + }] + assert agents.refusal(skill, 0) == ( + f"The skill 'research' starts the agent 'helper', which {reason}." + ) + @pytest.mark.parametrize("agent, root, policy, named", [ ("lead", True, SKILLS, "helper"), ("lead", True, SKILLS, "noter"), @@ -156,6 +169,46 @@ def test_one_it_may_start_is_not(self, tmp_path, logged, agent, root, policy, na assert agents.refusal(skill, 0 if root else 1) is None +class TestTheKeyWhileNoSkillMayStart: + """With ``"skill"`` not in ``spawn_sources`` (the default) the key is ignored: + the skill loads as instructions, and the build says so.""" + + @pytest.mark.parametrize("policy", [SubAgentPolicy(), SubAgentPolicy(spawn_sources={"agent"})], + ids=["default", "agents-only"]) + @pytest.mark.parametrize("named", ["Explore", "helper"], ids=["no-such-type", "a-real-type"]) + def test_it_is_ignored_and_warned_of_once(self, tmp_path, logged, policy, named): + skill = make_skill(tmp_path, "research", f"agent: {named}\n") + agents = SkillAgents("lead", lambda: made(policy=policy), root=True) + + agents.check([skill, make_skill(tmp_path, "plain")]) + agents.check([skill]) + + assert not agents.starts(skill) + assert agents.refusal(skill, 0) is None + assert logged == [{ + "event": "skill_agent_ignored", "log_level": "warning", "agent": "lead", + "skill": "research", "agent_type": named, + "message": f"The skill 'research' names the agent '{named}', but this app lets " + "no skill start an agent: it loads as instructions.", + }] + + def test_where_a_skill_may_start_it_starts(self, tmp_path, logged): + skill = make_skill(tmp_path, "research", "agent: helper\n") + agents = SkillAgents("lead", lambda: made(), root=True) + + assert agents.starts(skill) and not agents.starts(make_skill(tmp_path, "plain")) + + def test_builds_of_one_agent_share_what_they_warned_of(self, tmp_path, logged): + skill = make_skill(tmp_path, "research", "agent: Explore\n") + warned: set = set() + + for _ in range(2): + SkillAgents("lead", lambda: made(policy=SubAgentPolicy()), root=True, + warned=warned).check([skill]) + + assert [entry["event"] for entry in logged] == ["skill_agent_ignored"] + + async def loaded(agents: SkillAgents, skill: Any, *, caller=None, **fields: Any): """``agents.start(skill)`` in a turn of ``CONVERSATION``, from ``caller``'s run; its result, how many runs the turn counted, and what it reported.""" diff --git a/tests/workflow/test_skills.py b/tests/workflow/test_skills.py index d77b80e6..8c35c49a 100644 --- a/tests/workflow/test_skills.py +++ b/tests/workflow/test_skills.py @@ -255,8 +255,9 @@ def _starting_skill(parent: Path, name: str = "research", agent: str = "helper") return skill_dir -def _agents(): - """The root ``lead``'s ``SkillAgents``, over delegations that may start ``helper``.""" +def _agents(sources: frozenset[str] | set[str] = frozenset({"skill"})): + """The root ``lead``'s ``SkillAgents``, over delegations that may start ``helper`` + (from ``sources``).""" from agentic_cli.tools.skills import SkillAgents from agentic_cli.workflow.agents import AgentRuns, SubAgentPolicy from agentic_cli.workflow.agents.delegate import Delegations @@ -265,7 +266,7 @@ async def never(run): # pragma: no cover - no run starts here raise AssertionError(run) delegations = Delegations( - runs=AgentRuns(), policy=SubAgentPolicy(spawn_sources={"skill"}), hook=never, + runs=AgentRuns(), policy=SubAgentPolicy(spawn_sources=sources), hook=never, types={ "lead": AgentConfig(name="lead", prompt="p"), "helper": AgentConfig(name="helper", prompt="p", spawnable_by=frozenset({"skill"})), @@ -308,6 +309,17 @@ def test_without_such_a_skill_or_without_its_agents_it_is_adks_own(self, tmp_pat for toolset in (make_skill_toolset(plain, agents=_agents()), make_skill_toolset(starting)): assert type(_load_skill(toolset)) is LoadSkillTool + @pytest.mark.parametrize("sources", [set(), {"agent"}], ids=["default", "agents-only"]) + def test_while_no_skill_may_start_one_the_toolset_is_adks_own(self, tmp_path, sources): + """The key is ignored: ``load_skill`` is ADK's own, object for object.""" + from google.adk.tools.skill_toolset import LoadSkillTool + + skills = SkillStore().resolve([str(_starting_skill(tmp_path))]) + + toolset = make_skill_toolset(skills, agents=_agents(sources)) + + assert type(_load_skill(toolset)) is LoadSkillTool + async def test_the_gate_lets_the_one_the_framework_built_through_and_no_other( self, tmp_path ): diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 7aef069a..b2e8960a 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -6903,6 +6903,22 @@ def refused_by_skill(agent_type: str, reason: str, skill: str = "research") -> d } +def recorded_warnings(monkeypatch) -> list[dict[str, Any]]: + """Every log call of ``tools/skills/agents.py``, with its level.""" + from agentic_cli.tools.skills import agents as skill_agents + + events: list[dict[str, Any]] = [] + + class Recorder: + def __getattr__(self, level: str): + return lambda event, **fields: events.append( + {"event": event, "log_level": level, **fields} + ) + + monkeypatch.setattr(skill_agents, "logger", Recorder()) + return events + + class TestASkillThatStartsAnAgent: async def test_the_root_loads_one_and_its_run_is_the_skills(self, make_crew, project): crew = make_crew( @@ -6936,6 +6952,10 @@ async def test_the_root_loads_one_and_its_run_is_the_skills(self, make_crew, pro "helper", "root", 1, INSTANCE_IDLE ) assert [e.metadata["status"] for e in runs_of(events)] == [RUN_STARTED, RUN_COMPLETED] + # A skill gives no tools and no model: the instance runs on its type's own. + assert (instance.tools, instance.model) == (None, None) + started = runs_of(events, RUN_STARTED)[0].metadata + assert "tools" not in started and "model" not in started # Its result is shown as a delegation's, alike on both. (shown,) = [e for e in events if e.type is EventType.TOOL_RESULT and e.metadata.get("tool_call_id") == "c1"] @@ -7011,9 +7031,8 @@ async def test_a_sub_agent_loads_one_only_above_the_depth_limit( @pytest.mark.parametrize("skill_agent, spawnable_by, sources, reason", [ ("nobody", {"skill"}, {"skill"}, "is not one of this app's agent types"), ("helper", {"agent"}, {"agent", "skill"}, "this app does not let a skill start"), - ("helper", {"skill"}, {"agent"}, "this app does not let a skill start"), ("researcher", {"skill"}, {"skill"}, "this app does not let a skill start"), - ], ids=["unknown-type", "type-not-for-skills", "policy-not-for-skills", "a-static-sub-agent"]) + ], ids=["unknown-type", "type-not-for-skills", "a-static-sub-agent"]) async def test_a_load_that_may_not_start_its_agent_is_refused_and_starts_none( self, make_crew, project, skill_agent, spawnable_by, sources, reason ): @@ -7037,48 +7056,70 @@ async def test_a_load_that_may_not_start_its_agent_is_refused_and_starts_none( False, refused_by_skill(skill_agent, reason)["error"] ) - async def test_with_the_default_policy_a_plain_skill_loads_and_one_naming_an_agent_does_not( - self, make_crew, project, monkeypatch + @pytest.mark.parametrize("sources", [set(), {"agent"}], ids=["default", "agents-only"]) + async def test_while_no_skill_may_start_one_the_key_is_ignored_and_warned_of( + self, make_crew, project, monkeypatch, sources ): - from agentic_cli.tools.skills import agents as skill_agents - - warned: list[dict[str, Any]] = [] - - class Recorder: - def __getattr__(self, level: str): - return lambda event, **fields: warned.append( - {"event": event, "log_level": level, **fields} - ) - - monkeypatch.setattr(skill_agents, "logger", Recorder()) + warned = recorded_warnings(monkeypatch) skills = project.parent / "skills" crew = make_crew( skill_team(make_skill(skills, "notes", agent_type=None, body="Write notes."), + make_skill(skills, "explore", agent_type="Explore"), make_skill(skills)), - coordinator=[calls(load("notes", "c1"), load("research", "c2")), says("Done.")], + subagents=SubAgentPolicy(spawn_sources=sources), + coordinator=[calls(load("notes", "c1"), load("research", "c2"), + load("explore", "c3")), says("Done.")], helper=[says("[never asked]")], ) events = await crew.turn() - read = crew.results_read("coordinator") - loaded = json.loads(read["c1"]) - assert (loaded["skill_name"], loaded["instructions"]) == ("notes", "Write notes.") - assert json.loads(read["c2"]) == refused_by_skill( - "helper", "this app does not let a skill start" - ) + # Each loads as instructions, the plain result's keys, whatever it names. + read = {call: json.loads(text) for call, text in crew.results_read("coordinator").items()} + assert {call: (found["skill_name"], found["instructions"]) + for call, found in read.items()} == { + "c1": ("notes", "Write notes."), "c2": ("research", RESEARCH), + "c3": ("explore", RESEARCH), + } + assert read["c2"]["frontmatter"]["agent"] == "helper" assert (runs_of(events), crew.records(), crew.requests("helper")) == ([], [], 0) shown = {e.metadata["tool_call_id"]: e for e in events if e.type is EventType.TOOL_RESULT} - assert (shown["c1"].metadata["success"], shown["c1"].metadata["result"]["skill_name"]) == ( - True, "notes" + assert {call: (e.metadata["success"], e.metadata["result"]["skill_name"]) + for call, e in shown.items()} == { + "c1": (True, "notes"), "c2": (True, "research"), "c3": (True, "explore"), + } + # Warned of once each, as the coordinator was built. + assert sorted((w["skill"], w["agent_type"]) for w in warned) == [ + ("explore", "Explore"), ("research", "helper"), + ] + assert {(w["event"], w["log_level"], w["agent"]) for w in warned} == { + ("skill_agent_ignored", "warning", "coordinator"), + } + assert all(w["message"] == ( + f"The skill '{w['skill']}' names the agent '{w['agent_type']}', but this app lets " + "no skill start an agent: it loads as instructions." + ) for w in warned) + + async def test_a_skill_with_no_instructions_has_no_task_and_is_refused( + self, make_crew, project, monkeypatch + ): + warned = recorded_warnings(monkeypatch) + reason = "needs the skill's instructions as its task, and this skill has none" + crew = make_crew( + skill_team(make_skill(project.parent / "skills", body=" ")), subagents=SKILLS, + coordinator=[calls(load("research", "c1")), says("Could not.")], + helper=[says("[never asked]")], ) - assert shown["c2"].metadata["success"] is False - # Warned of once, as the coordinator was built. - assert warned == [{ - "event": "skill_agent_not_startable", "log_level": "warning", - "agent": "coordinator", "skill": "research", "agent_type": "helper", - "reason": "this app does not let a skill start", - }] + + events = await crew.turn() + + assert json.loads(crew.results_read("coordinator")["c1"]) == refused_by_skill( + "helper", reason + ) + assert (runs_of(events), crew.records(), crew.requests("helper")) == ([], [], 0) + assert [(w["event"], w["reason"]) for w in warned] == [ + ("skill_agent_not_startable", reason) + ] @pytest.mark.parametrize("first", ["skill", "task"]) async def test_its_run_counts_toward_the_turns_runs(self, make_crew, project, first): @@ -7199,17 +7240,7 @@ async def test_its_runs_mark_reaches_the_conversation(self, make_crew, project): async def test_a_type_with_model_choices_warns_of_its_skill_once( self, make_crew, project, monkeypatch ): - from agentic_cli.tools.skills import agents as skill_agents - - warned: list[dict[str, Any]] = [] - - class Recorder: - def __getattr__(self, level: str): - return lambda event, **fields: warned.append( - {"event": event, "log_level": level, **fields} - ) - - monkeypatch.setattr(skill_agents, "logger", Recorder()) + warned = recorded_warnings(monkeypatch) path = make_skill(project.parent / "skills", agent_type="nobody") crew = make_crew( [agent("coordinator", sub_agents=("researcher",)), @@ -7226,3 +7257,67 @@ def __getattr__(self, level: str): "agent": "researcher", "skill": "research", "agent_type": "nobody", "reason": "is not one of this app's agent types", }] + + async def test_the_build_warns_again_after_a_model_switch( + self, make_crew, project, monkeypatch + ): + warned = recorded_warnings(monkeypatch) + crew = make_crew( + skill_team(make_skill(project.parent / "skills", agent_type="nobody")), + subagents=SKILLS, coordinator=[says("One."), says("Two.")], + ) + + await crew.turn() + assert len(warned) == 1 + await crew.manager.reinitialize(model="claude-haiku-4-5", preserve_sessions=True) + await crew.turn("Again.") + + # Once for each build. + assert [w["event"] for w in warned] == ["skill_agent_not_startable"] * 2 + + async def test_a_skill_does_not_fill_the_types_brief(self, make_crew, project): + # ``brief_required`` is asked of ``task`` calls: a skill gives a title and + # an objective alone. + crew = make_crew( + skill_team(make_skill(project.parent / "skills"), + brief_required=("objective", "deliverable", "done_when")), + subagents=SKILLS, + coordinator=[calls(load("research", "c1")), says("Done.")], + helper=[says("Found it.")], + ) + + await crew.turn() + + read = envelope_read(crew.results_read("coordinator")["c1"]) + assert (read["success"], read["status"], read["result"]) == ( + True, RUN_COMPLETED, "Found it." + ) + + async def test_after_a_crash_its_open_call_is_answered_at_the_next_turn( + self, make_crew, project, monkeypatch + ): + path = make_skill(project.parent / "skills") + first = make_crew( + skill_team(path, tools=(contract_block,)), subagents=SKILLS, store="sqlite", + coordinator=[calls(load("research", "c1"))], + helper=[calls(use("contract_block", "h1"))], + ) + with no_seals(monkeypatch): + turn = first.start() + try: + await asyncio.wait_for(BLOCKING["started"].wait(), 10) + finally: + await first.stop(turn) + await killed_mid_call(first, "helper-1") + await first.manager.cleanup() + + second = make_crew( + skill_team(path, tools=(contract_block,)), subagents=SKILLS, store="sqlite", + coordinator=[says("Starting over.")], + ) + await second.turn("Go on.") + + # Answered once, as a ``task`` call the crash left open is. + assert [(call, len(held)) for call, held in second.call_results("coordinator", 0) + if call == "c1"] == [("c1", 1)] + assert INTERRUPTED in second.results_read("coordinator", 0)["c1"] From 4be6760e9410154775ea928e3f4ece4b4c12e8f9 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:55:17 -0500 Subject: [PATCH 6/6] Skills: a start the policy ignores is refused; docs rewrapped SkillAgents.refusal gives 'this app does not let a skill start' for a skill whose key the app ignores, so a start that comes anyway starts and counts nothing; a load still treats such a skill as instructions before asking. Docs: the reason count, the README's policy sentence, CLAUDE.md's skills line and the rewrapped paragraphs. --- CHANGELOG.md | 61 ++++++++++++++------------ CLAUDE.md | 2 +- README.md | 35 ++++++++------- src/agentic_cli/tools/skills/agents.py | 13 ++++-- tests/tools/test_skill_agents.py | 22 +++++++++- 5 files changed, 81 insertions(+), 52 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 07dc1dc1..7611ccc3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -576,39 +576,42 @@ the start of the entry's title. ### Added - **A skill that starts an agent: the frontmatter key `agent`, on both - backends.** A skill's `SKILL.md` may name one of the app's agent types at - the top of its frontmatter (`agent: researcher`). Where the app lets a - skill start an agent (`"skill"` in `SubAgentPolicy.spawn_sources`; with - the default policy it does not, and the key is ignored: the skill loads - as instructions, as any skill does, and the build warns of it, - `skill_agent_ignored`, since other tools give skills an `agent` key of - their own), when an agent loads it (`load_skill`), a run of that type - starts instead of the skill's instructions being handed back: its task message is the skill's body + backends.** A skill's `SKILL.md` may name one of the app's agent types + at the top of its frontmatter (`agent: researcher`). Where the app + lets a skill start an agent (`"skill"` in + `SubAgentPolicy.spawn_sources`; with the default policy it does not, + and the key is ignored: the skill loads as instructions, as any skill + does, and the build warns of it, `skill_agent_ignored`, since other + tools give skills an `agent` key of their own), when an agent loads it + (`load_skill`), a run of that type starts instead of the skill's + instructions being handed back: its task message is the skill's body under its name (`# Task: `, `## Objective`), its parent the loading agent's run, `started_by: skill:`, counted toward - `max_runs_per_turn` as a `task` call's run is, and the call's result is - the run's envelope with `"skill": ""` added, shown as a + `max_runs_per_turn` as a `task` call's run is, and the call's result + is the run's envelope with `"skill": ""` added, shown as a delegation. The skill gives no tools and no system prompt: the run has its type's own. The app allows it as for any type started at run time: - the type's `spawnable_by` holds `"skill"` too, and the loading run is one that may start a type - (`max_spawn_depth`: by default the main agent alone; an inheriting agent - starts none, and an inheriting type is started by the main agent alone). - Otherwise the load starts no run and its result says why: `{"success": - false, "error": "The skill 'research' starts the agent 'helper', which - this app does not let a skill start."}` (or `is not one of this app's - agent types`, or `cannot be started here: sub-agents cannot start - sub-agents`; or `needs the skill's instructions as its task, and this - skill has none`), and a skill whose agent its agent's first run could not - start is warned of as the agent is built (`skill_agent_not_startable`); - the app still starts. A skill without the key loads as before. - `agentic_cli.tools.skills` (provisional): - `SKILL_AGENT_KEY`, `skill_agent`, `skill_started_by`, `SkillAgents`; - `make_skill_toolset(..., agents=)` and `make_skill_tools(..., agents=)` - take an agent's `SkillAgents` (without it every skill loads as ADK - loads it), and the manager's delegations' `types` lists every agent - type. On ADK the framework's `load_skill` (`SkillLoadTool`, with ADK's - declaration) takes the place of ADK's in an agent's toolset only when one - of its skills names an agent type and the app lets a skill start one. + the type's `spawnable_by` holds `"skill"` too, and the loading run is + one that may start a type (`max_spawn_depth`: by default the main + agent alone; an inheriting agent starts none, and an inheriting type + is started by the main agent alone). Otherwise the load starts no run + and its result says why: `{"success": false, "error": "The skill + 'research' starts the agent 'helper', which this app does not let a + skill start."}` (or `is not one of this app's agent types`, or `cannot + be started here: sub-agents cannot start sub-agents`; or `needs the + skill's instructions as its task, and this skill has none`), and a + skill whose agent its agent's first run could not start is warned of + as the agent is built (`skill_agent_not_startable`); the app still + starts. A skill without the key loads as before. + `agentic_cli.tools.skills` (provisional): `SKILL_AGENT_KEY`, + `skill_agent`, `skill_started_by`, `SkillAgents`; + `make_skill_toolset(..., agents=)` and `make_skill_tools(..., + agents=)` take an agent's `SkillAgents` (without it every skill loads + as ADK loads it), and the manager's delegations' `types` lists every + agent type. On ADK the framework's `load_skill` (`SkillLoadTool`, with + ADK's declaration) takes the place of ADK's in an agent's toolset only + when one of its skills names an agent type and the app lets a skill + start one. - **`AgentConfig.model_choices`: the models a delegation may run a type on instead of its own, on both backends.** References, bare model ids or diff --git a/CLAUDE.md b/CLAUDE.md index bb755117..d7394f05 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -157,7 +157,7 @@ agentic-cli/ │ │ │ └── delegation.py # Declares task, the framework's delegation tool on both backends, and the parent's tools that continue a sub-agent (FOLLOW_UP_TOOLS: message_agent, stop_agent, check_agents), exempt: reserved names; ENVELOPE_TOOLS (task, message_agent, load_skill: LOAD_SKILL_TOOL; an envelope shown as a delegation); FOLLOW_UP_CLASH_ERROR │ │ ├── adk/state_tools.py # ADK-native plan/task tools (ToolContext.state) │ │ ├── langgraph/state_tools.py # LangGraph-library plan/task tools (Command/InjectedState): Deep Agents and LangGraph -│ │ ├── skills/ # Agent Skills: SkillStore, the ADK toolset (toolset.py: make_skill_toolset(agents=), ADK's load_skill replaced by adk/skill_tool.py's SkillLoadTool for an agent with a skill that names an agent type) +│ │ ├── skills/ # Agent Skills: SkillStore, the ADK toolset (toolset.py: make_skill_toolset(agents=), ADK's load_skill replaced by adk/skill_tool.py's SkillLoadTool for an agent with a skill that names an agent type, where the app lets a skill start one) │ │ │ ├── agents.py # A skill that starts an agent: SKILL_AGENT_KEY (the frontmatter's top-level agent), skill_agent, skill_started_by (skill:); SkillAgents(agent, delegations, root=): starts (the key counts only with "skill" in spawn_sources: otherwise it is ignored and the skill loads as instructions, ADK's own toolset kept), check as the agent is built (skill_agent_ignored, or skill_agent_not_startable, warning, once per agent and skill though ADK builds an agent for each model choice; the app still starts), start at a load (the type one of the app's, spawnable for "skill", may_spawn at the loading run's depth, none by an inheriting agent nor, below the root, of an inheriting type, and the skill's instructions not empty; else SKILL_AGENT_ERROR, no run): Delegations.start (the brief the skill's name and body, counted, no tools or model), the envelope with "skill" │ │ │ └── langchain_tools.py # make_skill_tools: list_skills/load_skill/load_skill_resource for Deep Agents (agents=: a skill that names an agent type starts it, workflow/deepagents/task_tool.py::start_skill_run, from the call's injected runtime) │ │ ├── jobs/ # Long-running jobs: JobManager, backends (a spec pinned at submit: a subprocess job runs where it was submitted; one on a backend that does not survive a restart, in-process, is claimed at submit and runs only in its submitter, FAILED if still queued at close; JobRecord.started_by: the sub-agent instance whose call submitted it), job_* tools diff --git a/README.md b/README.md index a47c65a4..b253f70f 100644 --- a/README.md +++ b/README.md @@ -1477,26 +1477,27 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", # The coordinator's call: {"agent_type": "researcher", "title": "Look it up", # "objective": "...", "tools": ["web_search"], "model": "fast"} ``` -- **Skills that start an agent.** A skill may name an agent type at the top - of its `SKILL.md` frontmatter, `agent: researcher`; with the type's +- **Skills that start an agent.** A skill may name an agent type at the + top of its `SKILL.md` frontmatter, `agent: researcher`; with the type's `spawnable_by={"skill"}` and `SubAgentPolicy(spawn_sources={"skill"})`, an agent that loads the skill starts a run of that type instead of reading the skill's instructions. Without `"skill"` in `spawn_sources` - (the default) the key is ignored: the skill loads as instructions, as any - skill does, and the build warns of it (`skill_agent_ignored`). The run's task message is the skill's - body under its name (`# Task: research`, `## Objective`), its parent the - loading agent's run (`started_by: skill:research`), and it counts toward - `max_runs_per_turn`; the `load_skill` call's result is the run's envelope - with `"skill": "research"` added. The skill gives no tools and no system - prompt: the run has its type's. A load is refused, no run started, when - the type is not one of the app's, when the type or the policy does not - let a skill start it, for a skill with no instructions (nothing to be the - task), or from a run that may start no type - (`max_spawn_depth`; an inheriting agent starts none, and an inheriting - type is started by the main agent alone): `{"success": false, "error": - "The skill 'research' starts the agent 'researcher', which this app does - not let a skill start."}`. Such a skill is also warned of as its agent is - built (`skill_agent_not_startable`), and the app still starts. + (the default) the key is ignored: the skill loads as instructions, as + any skill does, and the build warns of it (`skill_agent_ignored`). The + run's task message is the skill's body under its name (`# Task: + research`, `## Objective`), its parent the loading agent's run + (`started_by: skill:research`), and it counts toward + `max_runs_per_turn`; the `load_skill` call's result is the run's + envelope with `"skill": "research"` added. The skill gives no tools and + no system prompt: the run has its type's. A load is refused, no run + started, when the type is not one of the app's, when the type does not + let a skill start it, for a skill with no instructions (nothing to be + the task), or from a run that may start no type (`max_spawn_depth`; an + inheriting agent starts none, and an inheriting type is started by the + main agent alone): `{"success": false, "error": "The skill 'research' + starts the agent 'researcher', which this app does not let a skill + start."}`. Such a skill is also warned of as its agent is built + (`skill_agent_not_startable`), and the app still starts. ```markdown --- diff --git a/src/agentic_cli/tools/skills/agents.py b/src/agentic_cli/tools/skills/agents.py index 889f334d..c99db0ed 100644 --- a/src/agentic_cli/tools/skills/agents.py +++ b/src/agentic_cli/tools/skills/agents.py @@ -44,7 +44,7 @@ #: The frontmatter key (top level) that names the agent type a skill starts. SKILL_AGENT_KEY = "agent" -#: What a refused load says; ``reason`` is one of the three below. +#: What a refused load says; ``reason`` is one of the four below. SKILL_AGENT_ERROR = "The skill '{skill}' starts the agent '{agent}', which {reason}." UNKNOWN_TYPE = "is not one of this app's agent types" NOT_FOR_SKILLS = "this app does not let a skill start" @@ -131,11 +131,16 @@ def _reason(self, skill: Any, name: str, depth: int) -> str | None: return None def refusal(self, skill: Any, depth: int) -> str | None: - """The error a load of ``skill`` from a run at ``depth`` gets, or None to start it.""" + """The error a start of ``skill`` from a run at ``depth`` gets, or None to start it. + + A skill that names no agent is no start (None). One whose key the app + ignores (``starts`` is false) is refused too: a load treats it as + instructions before asking, and a start that comes anyway starts nothing. + """ name = skill_agent(skill) - if name is None or not self.starts(skill): + if name is None: return None - reason = self._reason(skill, name, depth) + reason = self._reason(skill, name, depth) if self.starts(skill) else NOT_FOR_SKILLS if reason is None: return None return SKILL_AGENT_ERROR.format(skill=skill.name, agent=name, reason=reason) diff --git a/tests/tools/test_skill_agents.py b/tests/tools/test_skill_agents.py index 166ce7c2..fd582db6 100644 --- a/tests/tools/test_skill_agents.py +++ b/tests/tools/test_skill_agents.py @@ -184,7 +184,11 @@ def test_it_is_ignored_and_warned_of_once(self, tmp_path, logged, policy, named) agents.check([skill]) assert not agents.starts(skill) - assert agents.refusal(skill, 0) is None + # A load treats it as instructions before asking; a start is refused. + assert agents.refusal(skill, 0) == ( + f"The skill 'research' starts the agent '{named}', which " + "this app does not let a skill start." + ) assert logged == [{ "event": "skill_agent_ignored", "log_level": "warning", "agent": "lead", "skill": "research", "agent_type": named, @@ -192,6 +196,22 @@ def test_it_is_ignored_and_warned_of_once(self, tmp_path, logged, policy, named) "no skill start an agent: it loads as instructions.", }] + @pytest.mark.parametrize("policy", [SubAgentPolicy(), SubAgentPolicy(spawn_sources={"agent"})], + ids=["default", "agents-only"]) + async def test_a_start_is_refused_and_counts_none(self, tmp_path, policy): + hook, asked = answering() + delegations = made(hook, policy=policy) + agents = SkillAgents("lead", lambda: delegations, root=True) + + out, events = await loaded(agents, make_skill(tmp_path, "research", "agent: helper\n")) + + assert out["result"].result == { + "success": False, + "error": "The skill 'research' starts the agent 'helper', which " + "this app does not let a skill start.", + } + assert (out["result"].run, asked, events, out["counted"]) == (None, [], [], 0) + def test_where_a_skill_may_start_it_starts(self, tmp_path, logged): skill = make_skill(tmp_path, "research", "agent: helper\n") agents = SkillAgents("lead", lambda: made(), root=True)