From cf9bbc98f23d409743f59096aa1025e47a4407e9 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:24:17 -0500 Subject: [PATCH 01/12] Skills: log an ignored agent key at info, not as a warning With the default policy a skill's `agent:` key is ignored and the skill loads as instructions, exactly as before. Claude Code-style skills carry that key, so a warning printed agents x skills lines above the prompt at every start and model switch, to an end user who can do nothing about it: a visible change under the default policy. `skill_agent_ignored` is now logged at info (once per agent and skill per build, as before); an app that opted in still gets `skill_agent_not_startable` as a warning. --- CHANGELOG.md | 2 +- CLAUDE.md | 4 ++-- README.md | 4 ++-- src/agentic_cli/tools/skills/agents.py | 12 ++++++++---- tests/tools/test_skill_agents.py | 4 ++-- tests/workflow/test_subagents_contract.py | 7 ++++--- 6 files changed, 19 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bb6f790..a579b017 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -653,7 +653,7 @@ the start of the entry's title. 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 + does, and the build logs it at info, `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 diff --git a/CLAUDE.md b/CLAUDE.md index 3192c034..432fd418 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, 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" (general_purpose: made for the loading agent's type, based_on; a general-purpose agent's own loads start none) +│ │ │ ├── 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 at info, skill_agent_not_startable a warning, once per agent and skill though each backend 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" (general_purpose: made for the loading agent's type, based_on; a general-purpose agent's own loads start none) │ │ │ └── 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; `start_instance`: the user's new instance, `/agent new`, the same; `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 `, `/agent new ` 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`). With `SubAgentPolicy.general_purpose` (it needs a source) every enabled source may also start the built-in `general_purpose` type (`spawn.GENERAL_PURPOSE`; `task` lists it last, a skill may name it, `/agent new` may start it): no config of the app's (one named so is refused at validation while it is on), but one made for the type that starts it (`general_purpose_config`: that type's tools, MCP servers, skills and own model, `GENERAL_PURPOSE_PROMPT`, the plan's tools, a fresh context; `Delegations.config_for(agent_type, based_on=)`), its spawner the caller's type for `task` and a skill, the root for the user (`StartRequest.based_on` → `AgentRun.based_on`, `InstanceRecord.based_on`, so its follow-ups and its runs after a restart are made for the same type); it starts no agent (`can_have_children` False: no `task`, no parent's tools; a skill it loads that names a type is refused), `task`'s `tools` narrows it against its spawner's tools (`_agent_tool_names()`), and it has no model choices. Each backend builds one per type that may start it (`general_purpose_spawners`: the root, and with `max_spawn_depth` 2 or more each type that does not inherit when `"agent"` is a source, and each type with skills when `"skill"` is; `Delegations.general_purpose`) at initialization, through the builder that builds a model choice's, with MCP connections of its own (ADK `_general_agents`/`_general_runners`, its chain reading the spawner's model, kind and numbers under `general_purpose`; Deep Agents `_general_graphs`, a `Variant` with its own tools and prompt), the hooks picking it by `run.based_on` (`_run_models`, `_general_model`: the spawner's resolved model named for `general_purpose`), released with the rest and built again by a model switch. +- **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; `start_instance`: the user's new instance, `/agent new`, the same; `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 `, `/agent new ` 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 logs it at info, `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`). With `SubAgentPolicy.general_purpose` (it needs a source) every enabled source may also start the built-in `general_purpose` type (`spawn.GENERAL_PURPOSE`; `task` lists it last, a skill may name it, `/agent new` may start it): no config of the app's (one named so is refused at validation while it is on), but one made for the type that starts it (`general_purpose_config`: that type's tools, MCP servers, skills and own model, `GENERAL_PURPOSE_PROMPT`, the plan's tools, a fresh context; `Delegations.config_for(agent_type, based_on=)`), its spawner the caller's type for `task` and a skill, the root for the user (`StartRequest.based_on` → `AgentRun.based_on`, `InstanceRecord.based_on`, so its follow-ups and its runs after a restart are made for the same type); it starts no agent (`can_have_children` False: no `task`, no parent's tools; a skill it loads that names a type is refused), `task`'s `tools` narrows it against its spawner's tools (`_agent_tool_names()`), and it has no model choices. Each backend builds one per type that may start it (`general_purpose_spawners`: the root, and with `max_spawn_depth` 2 or more each type that does not inherit when `"agent"` is a source, and each type with skills when `"skill"` is; `Delegations.general_purpose`) at initialization, through the builder that builds a model choice's, with MCP connections of its own (ADK `_general_agents`/`_general_runners`, its chain reading the spawner's model, kind and numbers under `general_purpose`; Deep Agents `_general_graphs`, a `Variant` with its own tools and prompt), the hooks picking it by `run.based_on` (`_run_models`, `_general_model`: the spawner's resolved model named for `general_purpose`), released with the rest and built again by a model switch. - **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 fdc62595..4ec33003 100644 --- a/README.md +++ b/README.md @@ -1486,8 +1486,8 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", 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: + any skill does, and the build logs it at info (`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 diff --git a/src/agentic_cli/tools/skills/agents.py b/src/agentic_cli/tools/skills/agents.py index af4e76a1..c737b066 100644 --- a/src/agentic_cli/tools/skills/agents.py +++ b/src/agentic_cli/tools/skills/agents.py @@ -9,9 +9,9 @@ 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 loads as instructions, as any skill does, and the build logs it at info (``skill_agent_ignored``: other tools, Claude Code's among them, give skills -an ``agent`` key of their own). +an ``agent`` key of their own; such a skill loads as it always did). 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`` @@ -164,7 +164,8 @@ def refusal(self, skill: Any, depth: int) -> str | None: def check(self, skills: Sequence[Any]) -> None: """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).""" + could not start; log at info each that the app lets no skill start (the + key is ignored).""" if self._general(): return for skill in skills: @@ -172,8 +173,11 @@ def check(self, skills: Sequence[Any]) -> None: if name is None or (self._agent, skill.name) in self._warned: continue if not self.starts(skill): + # At info: the skill loads as it always did, and a warning + # would print above the prompt at every build, to a user who + # can do nothing about it. self._warned.add((self._agent, skill.name)) - logger.warning( + logger.info( "skill_agent_ignored", agent=self._agent, skill=skill.name, agent_type=name, message=IGNORED.format(skill=skill.name, agent=name), diff --git a/tests/tools/test_skill_agents.py b/tests/tools/test_skill_agents.py index 61c41a71..313ce379 100644 --- a/tests/tools/test_skill_agents.py +++ b/tests/tools/test_skill_agents.py @@ -176,7 +176,7 @@ class TestTheKeyWhileNoSkillMayStart: @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): + def test_it_is_ignored_and_logged_once_at_info(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) @@ -190,7 +190,7 @@ def test_it_is_ignored_and_warned_of_once(self, tmp_path, logged, policy, named) "this app does not let a skill start." ) assert logged == [{ - "event": "skill_agent_ignored", "log_level": "warning", "agent": "lead", + "event": "skill_agent_ignored", "log_level": "info", "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.", diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 0355eb40..92a414d3 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -7096,7 +7096,7 @@ async def test_a_load_that_may_not_start_its_agent_is_refused_and_starts_none( ) @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( + async def test_while_no_skill_may_start_one_the_key_is_ignored_and_logged_at_info( self, make_crew, project, monkeypatch, sources ): warned = recorded_warnings(monkeypatch) @@ -7127,12 +7127,13 @@ async def test_while_no_skill_may_start_one_the_key_is_ignored_and_warned_of( for call, e in shown.items()} == { "c1": (True, "notes"), "c2": (True, "research"), "c3": (True, "explore"), } - # Warned of once each, as the coordinator was built. + # Logged once each, as the coordinator was built: at info, since the + # skill loads as before and the app's user can do nothing about it. 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"), + ("skill_agent_ignored", "info", "coordinator"), } assert all(w["message"] == ( f"The skill '{w['skill']}' names the agent '{w['agent_type']}', but this app lets " From afd167c9582c5b83e50c3bd8f862fcb0f76ed373 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:25:06 -0500 Subject: [PATCH 02/12] Agent graph: refuse a model choice written with spaces around it A `task` call's model is compared stripped with each choice as written, so `" fast"` could never be picked, and `"fast"` beside `"fast "` was not caught as a choice named twice. validate_agent_graph now refuses an entry that is not its own strip, naming the agent and the entry. --- CHANGELOG.md | 2 ++ README.md | 4 ++-- src/agentic_cli/workflow/config.py | 14 ++++++++++++++ tests/workflow/test_subagent_config.py | 11 +++++++++++ 4 files changed, 29 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a579b017..2a4001a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -707,6 +707,8 @@ the start of the entry's title. numbers: `choice_models[(agent, choice)]` and `context_budget(agent, model=choice)`. `validate_agent_graph` raises `AgentGraphError` for `model_choices` on the root, for one that is no tuple or list of texts, + for a choice written with spaces around it ("Agent 'researcher' has the + model choice ' fast' with surrounding spaces: write it without them.") and for a choice named twice. - **`task`'s `tools` and `model`: a delegation may narrow its run's tools and pick a cheaper model, never widen, on both backends.** Every `task` call diff --git a/README.md b/README.md index 4ec33003..0c4494f4 100644 --- a/README.md +++ b/README.md @@ -1307,8 +1307,8 @@ than `agent`, `skill` and `user` raises too (a free type the app's policy lets no source start is a warning: `validate_agent_graph(configs, policy=...)`). An agent named `general_purpose` raises too while the policy enables the built-in type of that name (`SubAgentPolicy(general_purpose=True)`). -`model_choices` on the root, one that is no tuple or list of texts, and a choice -named twice raise it too. +`model_choices` on the root, one that is no tuple or list of texts, a choice +written with spaces around it and a choice named twice raise it too. `inherit_context=True` on the root, on an agent with sub-agents of its own or on an agent below another sub-agent, and an `inherit_context` that is not True or False, raise it too, and, when the agents are built, so does a coordinator diff --git a/src/agentic_cli/workflow/config.py b/src/agentic_cli/workflow/config.py index 2cd479ff..87fe108e 100644 --- a/src/agentic_cli/workflow/config.py +++ b/src/agentic_cli/workflow/config.py @@ -536,6 +536,20 @@ def _check_delegation_fields(config_map: dict[str, AgentConfig], root: str) -> N f"text: {', '.join(not_texts)}." ) + # A call names a choice stripped (``brief.read_choices``): one written with + # spaces around it could never be picked, nor be caught as named twice. + spaced = next( + ((name, choice) for name, config in config_map.items() + for choice in config.model_choices if choice != choice.strip()), + None, + ) + if spaced is not None: + name, choice = spaced + raise AgentGraphError( + f"Agent {name!r} has the model choice {choice!r} with surrounding spaces: " + "write it without them." + ) + twice = sorted( f"{name!r} ({choice!r})" for name, config in config_map.items() diff --git a/tests/workflow/test_subagent_config.py b/tests/workflow/test_subagent_config.py index 7c252d02..dca39307 100644 --- a/tests/workflow/test_subagent_config.py +++ b/tests/workflow/test_subagent_config.py @@ -416,6 +416,17 @@ def test_each_is_text(self, value): f"'writer' ({value!r})." ) + @pytest.mark.parametrize("choice", [" fast", "fast ", "\tfast\n"]) + def test_none_has_surrounding_spaces(self, choice): + """A choice is picked by the name a call gives, stripped: one written with + spaces could never be picked, and would not count as named twice.""" + with pytest.raises(AgentGraphError) as exc: + validate_agent_graph(team(writer={"model_choices": ("strong", choice, "fast")})) + assert str(exc.value) == ( + f"Agent 'writer' has the model choice {choice!r} with surrounding spaces: " + "write it without them." + ) + def test_none_is_named_twice(self): with pytest.raises(AgentGraphError) as exc: validate_agent_graph(team( From ebd77fed1c68deb1a2c0f81a1ae33d4cf4756158 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:25:27 -0500 Subject: [PATCH 03/12] CHANGELOG: one Added list, wrapped to its width A blank line split the Added list between the skill bullet and the model_choices bullet, and one line of the general_purpose bullet ran to 96 columns. --- CHANGELOG.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a4001a6..5947bac0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -601,12 +601,13 @@ the start of the entry's title. for it too, naming its spawner in `metadata["spawner"]`, and one that never answers is waited for once more per spawner), built again by a model switch and released with the others; a main agent with no sub-agents gets - `task` for it alone when agents may start it. Its instances are `general_purpose-`, and the - records keep the type each was made for (`InstanceRecord.based_on`, from - the run's start, `WorkflowEvent.agent_run(based_on=)`; records written - before it read None), so its follow-ups, the user's and after a restart, - run as its first run did (one whose type no longer makes one is refused as - a type that is gone), and its view shows that type's model and context. + `task` for it alone when agents may start it. Its instances are + `general_purpose-`, and the records keep the type each was made for + (`InstanceRecord.based_on`, from the run's start, + `WorkflowEvent.agent_run(based_on=)`; records written before it read + None), so its follow-ups, the user's and after a restart, run as its first + run did (one whose type no longer makes one is refused as a type that is + gone), and its view shows that type's model and context. While the policy enables it, an app's agent of that name is refused (`AgentGraphError`: "An agent named 'general_purpose' clashes with the built-in general_purpose type, which this app's SubAgentPolicy @@ -684,7 +685,6 @@ the start of the entry's title. 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 roles (`model_choices=("fast",)`; the agent YAML's `model_choices: From 60ffc6599715842525a358cb1aa8d92acb7fe1c7 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:26:42 -0500 Subject: [PATCH 04/12] Sub-agents: warn of a missing description once per type, not per choice A delegating type is built once more for each of its model choices, on both backends, and each build made its task offer with warnings on, so the same `subagent_without_description` warning came once more per choice. A model choice's agent (ADK) or graph (Deep Agents) now makes its offer without warnings: it offers what its type's own build did, and that build warned. --- src/agentic_cli/workflow/adk/manager.py | 5 ++++- src/agentic_cli/workflow/adk/task_tool.py | 6 +++++- .../workflow/deepagents/agent_builder.py | 9 +++++++-- .../workflow/deepagents/task_tool.py | 7 +++++-- tests/workflow/test_subagents_contract.py | 18 ++++++++++++++++++ 5 files changed, 39 insertions(+), 6 deletions(-) diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index 50220861..967a7f22 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -643,7 +643,10 @@ def _build_agent( f"Agent {config.name!r} delegates to sub-agents through a tool named " f"{TASK_TOOL!r}, so its own tools cannot include one; rename that tool." ) - tools = [*tools, TaskTool(config.name, lambda: self._delegations, root=root)] + # A model choice's agent offers what its type's offers, whose build warned. + tools = [*tools, TaskTool( + config.name, lambda: self._delegations, root=root, warn=model is None, + )] if self.subagent_policy.follow_ups: clash = next((name for name in FOLLOW_UP_TOOLS if name in names), None) if clash is not None: diff --git a/src/agentic_cli/workflow/adk/task_tool.py b/src/agentic_cli/workflow/adk/task_tool.py index fc75555b..713c2b4f 100644 --- a/src/agentic_cli/workflow/adk/task_tool.py +++ b/src/agentic_cli/workflow/adk/task_tool.py @@ -92,6 +92,9 @@ class TaskTool(BaseTool): agent: The agent's name. delegations: The manager's delegations, asked for at each call. root: Whether the agent is the root. + warn: Whether making its first offer warns of what it lacks (a type + offered with no description): False for an agent that is its + type built once more, on a model choice, whose own build warned. """ def __init__( @@ -100,8 +103,9 @@ def __init__( delegations: Callable[[], Delegations], *, root: bool = True, + warn: bool = True, ) -> None: - offer = delegations().task_offer(agent, 0 if root else 1, warn=True) + offer = delegations().task_offer(agent, 0 if root else 1, warn=warn) super().__init__( name=TASK_TOOL, description=offer.description if offer is not None else "" ) diff --git a/src/agentic_cli/workflow/deepagents/agent_builder.py b/src/agentic_cli/workflow/deepagents/agent_builder.py index 8fae41e8..a767d604 100644 --- a/src/agentic_cli/workflow/deepagents/agent_builder.py +++ b/src/agentic_cli/workflow/deepagents/agent_builder.py @@ -274,6 +274,8 @@ def build_variant(variant: Variant) -> "CompiledStateGraph": settings=settings, checkpointer=checkpointer, bound=bound, budget=variant.budget, open_calls=open_calls, marks=marks, delegations=delegations, + # Its type's own build warned of what the offer lacks. + warn=False, ) for key, variant in (variants or {}).items(): @@ -308,6 +310,7 @@ def build_agent( memory_index_forget: Callable[[], None] | None = None, delegations: "Callable[[], Delegations] | None" = None, roster: Callable[[], str] | None = None, + warn: bool = True, ) -> "CompiledStateGraph": """Build one agent's graph: ``config`` on ``chat_model``, with its tools and prompt. @@ -316,7 +319,9 @@ def build_agent( ``root`` says whether this is the root: only it has the memory index and the roster (passed only for it), and every other agent has the run control and the outcome middleware; a sub-agent's graph has no - checkpointer of its own unless the tree has one. + checkpointer of its own unless the tree has one. ``warn`` is whether its + ``task`` warns of what its offer lacks: False for a variant, whose type's + own build warned. Raises: AgentGraphError: A delegating agent's own tools include one named @@ -348,7 +353,7 @@ def build_agent( follows = delegates and delegations is not None and delegations().policy.follow_ups own = _own_tools(config, tools, delegates=delegates, follows=follows) if delegates and delegations is not None: - own = [*own, build_task_tool(name, delegations, root=root)] + own = [*own, build_task_tool(name, delegations, root=root, warn=warn)] if follows: own = [*own, *build_follow_up_tools(delegations)] return create_agent( diff --git a/src/agentic_cli/workflow/deepagents/task_tool.py b/src/agentic_cli/workflow/deepagents/task_tool.py index af5cd54b..89fb7126 100644 --- a/src/agentic_cli/workflow/deepagents/task_tool.py +++ b/src/agentic_cli/workflow/deepagents/task_tool.py @@ -80,7 +80,7 @@ def build_task_tool( - agent: str, delegations: Callable[[], Delegations], *, root: bool = True + agent: str, delegations: Callable[[], Delegations], *, root: bool = True, warn: bool = True ) -> StructuredTool: """``agent``'s ``task`` tool, which starts a run of a type the calling run may start. @@ -92,8 +92,11 @@ def build_task_tool( agent: The delegating agent's name. delegations: The manager's delegations, asked for at each call. root: Whether the agent is the root. + warn: Whether the offer warns of what it lacks (a type offered with no + description): False for a model choice's graph of its type, whose + own build warned. """ - offer = delegations().task_offer(agent, 0 if root else 1, warn=True) + offer = delegations().task_offer(agent, 0 if root else 1, warn=warn) async def task(runtime: ToolRuntime, **arguments: Any) -> Command: state = runtime.state diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 92a414d3..c6ebc1ea 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -6544,6 +6544,24 @@ async def test_the_missing_description_is_warned_of_at_build_and_not_for_each_ca "helper", "helper", "helper", ] + async def test_a_delegating_types_model_choices_warn_of_it_no_more(self, make_crew): + """A type built once more for each of its model choices offers what its + own build offers: the missing description is warned of once for it.""" + crew = make_crew( + [*team(), agent("helper", tools=(contract_lookup,), description="", + spawnable_by=frozenset({"agent"}), + model_choices=("anthropic:claude-haiku-4-5",))], + subagents=DEEPER, + ) + + with capture_logs() as logs: + await crew.manager.initialize_services() + + # The coordinator, the researcher and the helper; none for the helper's choice. + assert [log["agent"] for log in logs if log["event"] == "subagent_without_description"] == [ + "helper", "helper", "helper", + ] + class TestAParentOfRunTimeTypesOnly: async def test_with_follow_ups_it_gets_the_parents_tools_and_the_roster(self, make_crew): From c8e36af29e8f5c2b9cf0a5976e871cc9db3fde74 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:27:29 -0500 Subject: [PATCH 05/12] Sub-agents: a start cancelled before its run gives its count back Delegations.start counts a run toward max_runs_per_turn as it checks the limit, before it numbers the instance past the stored ones, so two starts in one answer cannot both pass it. A cancel during that await (a parent's stop of the calling run) started nothing but kept the count, costing the turn one of its runs. The count is now released on every path that leaves before the run starts, as message() does for its reservation. --- src/agentic_cli/workflow/agents/delegate.py | 12 ++++++++-- tests/workflow/test_agent_delegate.py | 26 +++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/agentic_cli/workflow/agents/delegate.py b/src/agentic_cli/workflow/agents/delegate.py index c0d3bde2..2bb6b0b4 100644 --- a/src/agentic_cli/workflow/agents/delegate.py +++ b/src/agentic_cli/workflow/agents/delegate.py @@ -833,7 +833,8 @@ async def start(self, request: StartRequest) -> Delegated: ``AGENT_RUN`` event, which carries ``request.started_by``. A caller that is a run lends its slot while it waits for this one. A cancel of the caller's task (the turn's) ends the run ``interrupted`` once it - has stopped, and goes on. + has stopped, and goes on; one before the run started (while it is + numbered) starts none and gives the turn back the run it counted. Raises: KeyError: ``request.agent_type`` is not one of the manager's types @@ -852,8 +853,15 @@ async def start(self, request: StartRequest) -> Delegated: refused = self._past_runs_per_turn(config.name) if refused is not None: return refused + # Counted as it is checked, so a start in the same answer cannot + # pass the limit while this one is numbered. count_run_this_turn() - await self._number_past_stored(conversation) + try: + await self._number_past_stored(conversation) + except BaseException: + if request.counted: + release_run_this_turn() # no run started from it: give its place back + raise ref = self._runs.run_for(conversation, request.caller, request.call_id, config.name) brief = request.brief self._emit(WorkflowEvent.agent_run( diff --git a/tests/workflow/test_agent_delegate.py b/tests/workflow/test_agent_delegate.py index 279d6a2f..714e31e9 100644 --- a/tests/workflow/test_agent_delegate.py +++ b/tests/workflow/test_agent_delegate.py @@ -4032,6 +4032,32 @@ async def source(): assert counted == 1 assert len(asked) == 2 + async def test_one_cancelled_while_it_is_numbered_gives_its_count_back(self): + """The count is taken before the instances are numbered (two starts at + once must not both pass the limit); a cancel there starts no run, and + the turn's runs are what they were.""" + hook, asked = answering() + # The first ask waits for good; the next (the second start's) answers. + stored, read = storing(asyncio.Event(), {"researcher": 0}) + made = delegations(hook, stored=stored, policy=SubAgentPolicy(max_runs_per_turn=1)) + counts: list[int | None] = [] + + async def work(): + starting = asyncio.create_task(made.start(start_request(call_id="c1"))) + await until(lambda: read != []) + counts.append(runs_this_turn()) # counted, while it is numbered + starting.cancel() + with contextlib.suppress(asyncio.CancelledError): + await starting + counts.append(runs_this_turn()) + return await made.start(start_request(call_id="c2")) + + second, _ = await turned(work) + + assert counts == [1, 0] + assert second.result["status"] == RUN_COMPLETED + assert [run.ref.run for run in asked] == ["researcher-1#1"] + async def test_numbered_past_the_stored(self): hook, _ = answering() stored, asked = storing({"researcher": 4}) From 1706d2a4e224362e4c5d7d972171f5b8ed226ac1 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:29:46 -0500 Subject: [PATCH 06/12] Sub-agents: list a narrowed instance's tools only to follow it up message() awaited the type's tool names before deciding anything, so steering a running narrowed instance could connect an ADK MCP toolset just to steer, and a listing that failed refused the steer with "try again". The names are what a follow-up is checked against: they are now asked for only when the message would start one (an idle instance's, an interrupt's), and the decision is made again after that await, in one step up to the follow-up's start, so a run that started meanwhile is steered and two messages to one idle instance still give one run and one steer. --- src/agentic_cli/workflow/agents/delegate.py | 47 ++++++++++++++++++--- tests/workflow/test_agent_delegate.py | 35 +++++++++++++++ 2 files changed, 76 insertions(+), 6 deletions(-) diff --git a/src/agentic_cli/workflow/agents/delegate.py b/src/agentic_cli/workflow/agents/delegate.py index 2bb6b0b4..95a1dc2c 100644 --- a/src/agentic_cli/workflow/agents/delegate.py +++ b/src/agentic_cli/workflow/agents/delegate.py @@ -1066,6 +1066,11 @@ async def message( per instance at a time: everything up to a follow-up's start is one synchronous step, so of two messages to one idle instance in one response the first starts its run and the second is steered into it. + A narrowed instance's tool names, which a follow-up is checked + against, are asked for before that step, and only when the message + would start one (an idle instance's, an interrupt's): a steer asks + for none, so a listing that fails refuses no steer, and a run that + started while they were listed is steered. A run that takes no more steps (cancelled, its work ended, or an instance its parent is closing) is not steered: its end is waited for, and the message then follows up the idle instance or is refused as @@ -1087,15 +1092,24 @@ async def message( conversation = ( request.conversation if request.conversation is not None else get_active_turn() ) - try: - own = await self._instance_tools(conversation, request.instance) - except BriefError as error: - return _refused(str(error)) + if not isinstance(request.message, str) or not request.message.strip(): + return _refused(MESSAGE_NEEDED_ERROR) + own: Any = _UNFETCHED + unlisted: BriefError | None = None + with _as_turn(conversation): + follows_up = self._follows_up(conversation, request, interrupt=interrupt) + if follows_up: + try: + own = await self._instance_tools(conversation, request.instance) + except BriefError as error: + unlisted = error with _as_turn(conversation): - if not isinstance(request.message, str) or not request.message.strip(): - return _refused(MESSAGE_NEEDED_ERROR) + # Decided again after that await, in one step from here to a + # follow-up's start: a run that started meanwhile is steered. control = self._working_control(conversation, request) if control is None: + if unlisted is not None: + return _refused(str(unlisted)) return await self.follow_up(request, _reserved=_reserved, _own=own) ref = control.ref if (conversation, ref.instance) in self._closing: @@ -1112,6 +1126,10 @@ async def message( ended = self._ends[(conversation, ref.run or "")] made_here = False if interrupt and not stopping: + if unlisted is not None: + return _refused(str(unlisted)) + # Asked for above: the interrupt's follow-up was the next step. + assert own is not _UNFETCHED error = self._follow_up_refused( conversation, request, running_ok=True, own_tools=own ) @@ -1361,6 +1379,23 @@ def _yours(self, conversation: SessionRef | None, caller: RunRef | None) -> list sender = caller.instance if caller is not None else "root" return [i for i in self._runs.instances(conversation) if i.parent == sender] + def _follows_up( + self, conversation: SessionRef | None, request: FollowUpRequest, *, interrupt: bool + ) -> bool: + """Whether ``message``'s next step starts a follow-up of the instance: + an idle one's (or one ``follow_up`` refuses), or an interrupt's of its + running run. What a narrowed instance's tool names are asked for: a + steer, a wait for a run that is stopping and the refusal of an + instance being closed need none.""" + control = self._working_control(conversation, request) + if control is None: + return True + return ( + interrupt + and not control.stopping + and (conversation, control.ref.instance) not in self._closing + ) + def _working_control( self, conversation: SessionRef | None, diff --git a/tests/workflow/test_agent_delegate.py b/tests/workflow/test_agent_delegate.py index 714e31e9..5ff79a86 100644 --- a/tests/workflow/test_agent_delegate.py +++ b/tests/workflow/test_agent_delegate.py @@ -4369,6 +4369,41 @@ async def test_the_model_is_checked_before_the_tools(self): ) assert len(asked) == 1 + async def test_a_steer_of_its_running_run_never_asks_for_the_tools(self): + """Only a follow-up checks a narrowed instance's tools: a message steered + into its running run asks the backend for none, so a listing that fails + just then refuses no steer.""" + hook, working, _ = blocking("choosy-1#2") + listed: list[str] = [] + fail = [False] + + async def listing(agent: str) -> frozenset[str]: + listed.append(agent) + if fail[0]: + raise ToolsUnlistedError(agent, OSError("the server is down")) + return frozenset(OWN.get(agent, ())) + + made = delegations(hook, types=CHOOSING, tool_names=listing) + + async def work(): + await made.delegate(request(NARROW)) + running = asyncio.create_task(made.message(follow("choosy-1"))) + await working["choosy-1#2"].wait() + before = list(listed) + fail[0] = True + steered = await made.message(follow("choosy-1", "Find Z too.", call_id="c3")) + made.cancel("choosy-1#2", by="parent", error="enough") + await running + return steered, before + + (steered, before), _ = await turned(work) + + assert steered.result == { + "success": True, "agent": "choosy-1", "run": "choosy-1#2", + "status": RUN_RUNNING, "note": STEERED, + } + assert listed == before == ["choosy", "choosy"] # the task call's, the follow-up's + async def test_two_messages_at_once_to_a_narrowed_one_start_one_run_and_steer_the_other( self, ): From b084116c08a02c1398ed1f444f4695981ec2a2aa Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:30:46 -0500 Subject: [PATCH 07/12] Sub-agents: the user's start stores its conversation after its reads start_instance stored a conversation not yet stored before reading an inheriting type's history and the conversation's state, so a read that raised left a 0-turn conversation listed with nothing in it. It is now stored after every read that can fail, right before the run starts. --- CLAUDE.md | 2 +- src/agentic_cli/workflow/base_manager.py | 13 ++++++++----- tests/workflow/test_subagents_contract.py | 22 ++++++++++++++++++++++ 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 432fd418..636660d2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,7 +51,7 @@ agentic-cli/ │ │ ├── waiting_jobs.py # Which finished jobs wait to be told in the open conversation: one rule (JobRecord.awaiting_resume, then its own, no conversation's, or a gone conversation's: can_resume, then the other installed backends' readers, opens_anywhere: one another backend keeps is not gone, its job waits for it) for the deliveries, ↻N and the startup line │ │ └── usage_tracker.py # Token usage / status bar: ctx = the main agent's last prompt over its context_trigger (a call with a purpose, a sub-agent's, a summary's or a side call's, never moves it); the token segment the open conversation's total, every call of its turns; format_usage: /status's rows by agent and /agents 's tokens by model │ ├── workflow/ -│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none), and _agent_tool_names, what a task call's tools may name (the agent's own tools by the names its model sees, KEPT_TOOLS left out; the base's: its configured tools; ADK and Deep Agents add MCP and skill tools; ADK raises delegate.ToolsUnlistedError for a toolset it could not list, which Delegations answers TOOLS_UNLISTED_ERROR); _run_models: a run's maps of each agent's model and numbers, its type's its model choice's when it runs on one, a general_purpose run's its spawner's (based_on; _general_model: the spawner's resolved model named general_purpose); the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), start_instance (a turn: Delegations.start_by_user, the user's new instance, parent root, depth 1, started_by user, counted toward no turn's runs; a type the user may not start or a blank objective one ERROR; a conversation not yet stored stored first, _keep_conversation: ADK's session with one state-only event, Deep Agents' index row, titled from the objective with no turns; an inheriting type's copy of the conversation from _inherited_history, the backend's hook: ADK's session's root-visible events, Deep Agents' root messages, summary applied; its first event the run's start), both streamed by _users_run (the run in a task of its own; _UsersRunEvents notes the run as its start is reported and until_started awaits that one future, so a stop before the consumer read it, or before the run started, stops it by the user as it starts, before its hook is entered), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', each config's model_choices as its model would be, with its model_settings, into _choice_models by (agent, choice), choice_models, then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built, and _compute_choice_budgets (each model choice's, context_budget(agent, model=choice)): each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) +│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none), and _agent_tool_names, what a task call's tools may name (the agent's own tools by the names its model sees, KEPT_TOOLS left out; the base's: its configured tools; ADK and Deep Agents add MCP and skill tools; ADK raises delegate.ToolsUnlistedError for a toolset it could not list, which Delegations answers TOOLS_UNLISTED_ERROR); _run_models: a run's maps of each agent's model and numbers, its type's its model choice's when it runs on one, a general_purpose run's its spawner's (based_on; _general_model: the spawner's resolved model named general_purpose); the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), start_instance (a turn: Delegations.start_by_user, the user's new instance, parent root, depth 1, started_by user, counted toward no turn's runs; a type the user may not start or a blank objective one ERROR; a conversation not yet stored stored right before the run starts (after the reads that can fail), _keep_conversation: ADK's session with one state-only event, Deep Agents' index row, titled from the objective with no turns; an inheriting type's copy of the conversation from _inherited_history, the backend's hook: ADK's session's root-visible events, Deep Agents' root messages, summary applied; its first event the run's start), both streamed by _users_run (the run in a task of its own; _UsersRunEvents notes the run as its start is reported and until_started awaits that one future, so a stop before the consumer read it, or before the run started, stops it by the user as it starts, before its hook is entered), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', each config's model_choices as its model would be, with its model_settings, into _choice_models by (agent, choice), choice_models, then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built, and _compute_choice_budgets (each model choice's, context_budget(agent, model=choice)): each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) │ │ ├── factory.py # create_workflow_manager_from_settings (_BACKENDS: orchestrator → "module:Class" + extra, imported when chosen; orchestrator=: another backend than the settings'; session_store=: the store a manager is built for, BaseWorkflowManager.session_store, the settings' by default; subagents=: the SubAgentPolicy the manager gets, checked before a backend is imported); orchestrator_of; check_backend (an unknown name, a missing extra) │ │ ├── session_readers.py # SessionReader: a backend's stored conversations read without its manager (list/info/exists/delete/aclose, rows naming the backend; delete deletes what the manager's does, ADK's sub-agent transcripts and records with the conversation), opened from the settings and a store (open_session_reader: the backend's own session code, adk/sessions.py::open_sessions and deepagents/sessions.py::open_sessions, imported on a worker thread; no agents, models or services; a sqlite store not made yet reads empty and is not made, Deep Agents not even imported for it; a database without its backend's tables, looked at read-only, reads empty, nothing written to it: no table, no journal mode); none for the memory store or LangGraph; ImportError (the install hint) for a missing extra; reader_backends │ │ ├── service_registry.py # get_service/require_service + ContextVar registry; the registry keys and KNOWN_SERVICE_KEYS, read from services.py's table diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index f741d8ab..d3995d99 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -1027,10 +1027,11 @@ async def start_instance( is ``stopped``; a stop before the run started stops the run as it starts. ``interrupt_instance`` ends it as a turn's cancel does. - A conversation that is not stored yet is stored first, titled from - the objective with no turns of the user's with the main agent - (``_keep_conversation``), so what the user did here is found by - ``/resume``, ``--continue`` and ``--resume``. + A conversation that is not stored yet is stored right before the run + starts (after every read that can fail, so a start that raised + stores nothing), titled from the objective with no turns of the + user's with the main agent (``_keep_conversation``), so what the user + did here is found by ``/resume``, ``--continue`` and ``--resume``. Yields: The run's ``WorkflowEvent``s, its start first. @@ -1045,13 +1046,15 @@ async def start_instance( if refused is not None: yield WorkflowEvent.error(refused) return - await self._keep_conversation(ref, objective) config = next((c for c in self._agent_configs if c.name == agent_type), None) history = None if config is not None and config.inherit_context: copy = await self._inherited_history(ref) history = lambda: copy # noqa: E731 - read once, before the run state = await self._conversation_state(ref) + # Stored after every read that can fail, right before the run + # starts: a start that raised lists no empty conversation. + await self._keep_conversation(ref, objective) async with contextlib.aclosing(self._users_run( ref, lambda: self._delegations.start_by_user( diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index c6ebc1ea..a3fdfaf1 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -7694,6 +7694,28 @@ async def test_a_refusal_stores_nothing(self, make_crew): assert not await crew.manager.session_exists(SESSION, user_id=USER) assert await crew.manager.list_sessions(user_id=USER) == [] + @pytest.mark.parametrize("read, inherit", [ + ("_conversation_state", False), ("_inherited_history", True), + ], ids=["its-state", "an-inheriting-types-history"]) + async def test_a_read_that_fails_stores_nothing(self, make_crew, read, inherit): + """The conversation is stored right before the run starts, after every + read that can fail: a start that raises lists no empty conversation.""" + crew = make_crew(user_team(inherit_context=inherit), subagents=STARTING, store="sqlite", + helper=[says("[never asked]")]) + await crew.manager.initialize_services() + + async def fails(ref: SessionRef) -> Any: + raise OSError("the store is unreadable") + + setattr(crew.manager, read, fails) + + with pytest.raises(OSError, match="the store is unreadable"): + await user_start(crew, "helper", "Help with X.") + + assert not await crew.manager.session_exists(SESSION, user_id=USER) + assert await crew.manager.list_sessions(user_id=USER) == [] + assert (crew.records(), crew.requests("helper")) == ([], 0) + class TestTheUsersStopOfANewInstance: """Stopping ``start_instance``'s stream (Ctrl+C in its view) is the user's From d07478bd08d0afd66f83757e7197150305804192 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:31:50 -0500 Subject: [PATCH 08/12] CLI: a refused /agent new leaves a fresh conversation fresh ConversationCore marked the conversation written for any start that reached a ready workflow, and a refusal (a type the user may not start) does, as the turn's one ERROR. Nothing ran and nothing was stored, yet ConversationCore.fresh turned false, so a /settings orchestrator change said "(applies to the next /new)" instead of moving the empty conversation. A start now counts as written once its run started, which is when the workflow stores the conversation; a start that raised or was cancelled still counts when the workflow was ready, as before. --- CLAUDE.md | 2 +- src/agentic_cli/cli/conversation.py | 36 +++++++++++++++++++++-------- tests/cli/test_agent_view.py | 12 ++++++++++ 3 files changed, 39 insertions(+), 11 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 636660d2..4c902297 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,7 +33,7 @@ agentic-cli/ │ │ ├── app.py # BaseCLIApp (subagents=: the SubAgentPolicy every manager the app builds gets, through its WorkflowController; main(): the command line, add_arguments/from_args, exit_status; session_start: how run() begins, the run's own conversation loaded before the prompt, also when the workflow did not start (_adopt_its_own: an id the app was given held from the start, one the run made from its first write); its resume once the prompt is up (_open_on_startup, holding the turn lock from before the prompt takes a line: a turn typed ahead waits and runs there; Ctrl+C there ends the app; --continue passes over conversations another process holds, _newest_free, the one chosen held beside the run's own until the switch); --continue and --resume find the conversation's backend from every installed backend's reader before the workflow is built (_start_on_its_backend: the run builds that backend once); the --resume hint at exit (the run's store named after a session_store change; the backend only when no reader reads it, LangGraph: --resume opens a conversation on its own); the session it builds; get_theme(name); /settings: _build_ui_items, apply_settings and save_settings delegate to cli/settings_ui.py (SettingsUI: an app's override applies); run() installs the ADK log filters first (workflow/adk/log_filters.py: an app built but never run installs none), then the SIGHUP/SIGTERM handlers that kill live execute_python runs before chaining to the previous handler (_stop_runs_on_signals); the LangGraph deprecation notice; start_new_session(backend=None): /new [backend] (the settings' orchestrator by default; another backend: the memories proposed, WorkflowController.switch_backend, then the switch to the new id at its place; a Ctrl+C once it runs opens its conversation first); a line typed runs in ConversationCore.run_turn (on _turn_parts: the app's parts as they are), then the jobs at the turn's end through the app's own resume_finished_jobs(); compact() (ConversationCore.compact), start_new_session() and resume_session(): /compact, /new and /resume, under the conversation's turn lock (_turn_lock: ConversationCore.turn_lock; pick_session(), the picker, is not: it waits on a dialog); session_store=memory keeps one conversation at a time (Place.kept; session_store: the run's store): /new drops the one left once the switch is made, after its memories are proposed (_drop: its delete_session, shielded; on another backend the manager released takes it along; one it cannot confirm gone, the workflow down or its lookup or delete raising, is remembered and dropped once a workflow is ready: before the next turn, or right after the turn whose own start revives the workflow, and always before that turn's delivery of finished jobs, /compact and the next /new, never while it is the open one: ConversationCore.drop_left), and resume_session, pick_session, --resume (status 1) and --continue (a new conversation) are refused with NOT_KEPT, before any look-up; every installed backend's conversations (list_conversations, delete_conversation, session_backend; cli/stored_conversations.py): the picker names each row's backend and returns a PickedConversation, and /resume opens a conversation on the backend that keeps it (_open_elsewhere: held there, memories proposed, switch_backend with the run's services, then the switch at its place; an id two backends keep opens on the running one, the other named); every change of conversation through ConversationCore.switch (_conversation; _session_id and _turned forward to it); the session_id setter deprecated (its synchronous part, switch_now, and a DeprecationWarning); a conversation's memories proposed once per conversation used (_turned); the memory proposals waiting, said at startup and after /new and /resume (_name_waiting_proposals); resume_finished_jobs(): ConversationCore.deliver_finished_jobs, the jobs waiting named at startup by ConversationCore.waiting_jobs (_name_its_waiting_jobs), none in a sub-agent's view; a sub-agent's view (cli/agent_view.py, provisional: agent_view, open_agent_view(id), leave_agent_view()): process_input gives a line typed there to AgentView.take, and draws its prompt and status bar again after a command; start_new_session and resume_session leave it first (_leave_view_first); run() binds Ctrl+C to the run in view (bind_ctrl_c) and interrupts one still working at exit, as a process exit does, waited for before the workflow closes (AgentView.interrupt: not the user's stop, the run interrupted and its sub-agent idle)) │ │ ├── commands.py # Command, CommandRegistry │ │ ├── job_monitor.py # JobMonitor: the status bar's jobs segment (running, queued, a finished job's note, ↻N: waiting_jobs' rule, can_resume answers kept 30 s (the other backends' look too: kept_elsewhere), forgotten after /sessions --delete or when the workflow is replaced), one tick every 2 s, its JobManager.list() on a worker thread -│ │ ├── conversation.py # ConversationCore: the conversation the turns run in (its id, turned, its lock at its Place: the backend and store, the store the run's for its whole life (Place.kept: not the memory store, where the CLI keeps one conversation at a time and NOT_KEPT says why nothing else opens), the backend recorded as the app starts, for a new conversation on another backend, and on a /settings change of the orchestrator while the workflow is down, its next start builds afresh and nothing of the conversation is stored (SettingsUI._move_here, WorkflowController.next_start_builds), never read from the settings in between; deferred: an id this run made (the start's, /new's, an orchestrator change's) is in no store, so it is held from its first write, hold_to_write under the turn lock before a turn, a job's notice or /compact (_held_to_write; a run in which no turn runs makes no lock file: a line typed while the workflow is down takes the hold before its retried start; a lock that cannot be taken, an OSError, leaves it unheld, said once, and the write goes on); fresh: nothing of it stored, opened_empty (an id this run made, or one a load found empty) and not written (no turn of it ran on a ready workflow), the one condition for another backend); switch: the one protocol (/new on any backend, /resume, startup, the same id in another place while the workflow is down): the target's lock taken (another process's refused), memories proposed, the workflow loads it (a stored one gone: not made, or, made already in another place, opened empty: gone), then made at once (lock, id, task list, usage counters) or let go, a workflow that took it given the old one back; made before the load when there is no other conversation to stay in (the same id, or another place: a new or stored conversation on another backend); a Ctrl+C at any await leaves one conversation held; switch_now: the deprecated session_id setter's part; turn_lock: what writes to the conversation and every switch take it; run_turn, compact and run_job_resume: a turn (echoed, held to write, turned, written once it reached a ready workflow; run_turn says whether it ran, whatever the processor returns), /compact and a finished job's notice under it, on TurnParts (the app's parts as they are); run_instance, start_instance and tell_root (_write): a line typed in a sub-agent's view as its next run (process_instance; written, not turned), /agent new's first run (process_start; written, not turned) and the main agent's notice after a view (process_notice; turned), under it too; deliver_finished_jobs: each job that waits here (cli/waiting_jobs.py's rule, which waiting_jobs names them by, the other backends' look through TurnParts.kept_elsewhere), every JobManager call on a worker thread, a delivery claimed only once it can reach the agent (process_resume(claim=), after the readiness check and can_resume; _claim_delivery: a claim a Ctrl+C stopped is handed back, JobManager.release_resume), a failure before the claim said once per job and conversation when the CLI tells jobs on its own (telling_on_its_own); to_drop/drop_left: the conversations /new left on the memory store that the store may still hold (the workflow down, a lookup or delete that raised), dropped through TurnParts.drop under the turn lock once a workflow is ready, before a turn, /compact or a delivery uses it (after a turn or /compact that started it), one try per point, done once the store has it no more (a workflow without supports_sessions has none), the open one skipped; a delivery with none to drop takes no turn lock +│ │ ├── conversation.py # ConversationCore: the conversation the turns run in (its id, turned, its lock at its Place: the backend and store, the store the run's for its whole life (Place.kept: not the memory store, where the CLI keeps one conversation at a time and NOT_KEPT says why nothing else opens), the backend recorded as the app starts, for a new conversation on another backend, and on a /settings change of the orchestrator while the workflow is down, its next start builds afresh and nothing of the conversation is stored (SettingsUI._move_here, WorkflowController.next_start_builds), never read from the settings in between; deferred: an id this run made (the start's, /new's, an orchestrator change's) is in no store, so it is held from its first write, hold_to_write under the turn lock before a turn, a job's notice or /compact (_held_to_write; a run in which no turn runs makes no lock file: a line typed while the workflow is down takes the hold before its retried start; a lock that cannot be taken, an OSError, leaves it unheld, said once, and the write goes on); fresh: nothing of it stored, opened_empty (an id this run made, or one a load found empty) and not written (no turn of it ran on a ready workflow), the one condition for another backend); switch: the one protocol (/new on any backend, /resume, startup, the same id in another place while the workflow is down): the target's lock taken (another process's refused), memories proposed, the workflow loads it (a stored one gone: not made, or, made already in another place, opened empty: gone), then made at once (lock, id, task list, usage counters) or let go, a workflow that took it given the old one back; made before the load when there is no other conversation to stay in (the same id, or another place: a new or stored conversation on another backend); a Ctrl+C at any await leaves one conversation held; switch_now: the deprecated session_id setter's part; turn_lock: what writes to the conversation and every switch take it; run_turn, compact and run_job_resume: a turn (echoed, held to write, turned, written once it reached a ready workflow; run_turn says whether it ran, whatever the processor returns), /compact and a finished job's notice under it, on TurnParts (the app's parts as they are); run_instance, start_instance and tell_root (_write): a line typed in a sub-agent's view as its next run (process_instance; written, not turned), /agent new's first run (process_start; written once its run started, a refusal leaving a fresh one fresh, not turned) and the main agent's notice after a view (process_notice; turned), under it too; deliver_finished_jobs: each job that waits here (cli/waiting_jobs.py's rule, which waiting_jobs names them by, the other backends' look through TurnParts.kept_elsewhere), every JobManager call on a worker thread, a delivery claimed only once it can reach the agent (process_resume(claim=), after the readiness check and can_resume; _claim_delivery: a claim a Ctrl+C stopped is handed back, JobManager.release_resume), a failure before the claim said once per job and conversation when the CLI tells jobs on its own (telling_on_its_own); to_drop/drop_left: the conversations /new left on the memory store that the store may still hold (the workflow down, a lookup or delete that raised), dropped through TurnParts.drop under the turn lock once a workflow is ready, before a turn, /compact or a delivery uses it (after a turn or /compact that started it), one try per point, done once the store has it no more (a workflow without supports_sessions has none), the open one skipped; a delivery with none to drop takes no turn lock │ │ ├── conversation_lock.py # ConversationLock: one process per stored conversation (flock under /locks/; ConversationCore holds it and refuses one held elsewhere; /sessions --delete too, through conversation_held) │ │ ├── builtin_commands.py # /help (by category; /help : its usage and examples), /status (the main agent's context rows: context_budget, in a sub-agent's view the instance's, AgentView.context_rows; why the workflow did not start: app.workflow_error; tokens by agent: the main agent, each sub-agent with its runs, the side calls by purpose, from the manager's usage ledger), /models (ModelsCommand: the list, each model's facts and sources, Status for an entry left out, the providers in use; /models searches the full listings; refresh), /sessions (every installed backend's, a Backend column; --delete= on the backend that keeps it, --backend= for an id two keep; on the memory store NOT_KEPT, no table, --delete refused), /resume [] (sessions; refused on the memory store), /jobs (resume: finished jobs; in a sub-agent's view JOBS_WAIT: they wait for /back), /compact [focus] (refused in a sub-agent's view: COMPACT_IN_VIEW), /new [backend] (an unknown backend or a missing extra refused: check_backend), ... │ │ ├── agents_command.py # /agents: the open conversation's sub-agent instances (agent_runs.instances under workflow.session_ref(app.session_id)) in a picker (a Dialog with one ChoiceField, as /resume's: `picker`), each followed by the ones it started (id · type · status · title), Enter opening the view of the one picked (app.open_agent_view); /agent opens its view (open_agent_view: cli/agent_view.py), /agent new starts one and opens its view (app.start_agent; the objective the rest of the line as typed; NEW_USAGE without one; AGENT_USAGE names it), /agent stop and /agent close are the user's stop and close (stop_instance, close_instance, the app's conversation named), each saying what it did or why not (NO_SUCH_AGENT, ALREADY_TEXT), nothing tried on records not read; /agents (its panel: tokens in/out from the usage ledger, usage_of, live for a running run; time): one instance (every run of it) or run (type, parent, title, the instance's Model and Tools when its delegation gave them, NO_OWN_TOOLS for none; each run's status and time, its brief's other fields (a follow-up's message in their place), its result's first lines, its own last plan and tasks, its error, its tokens by model); the records are the conversation's, kept beside it in its store and loaded with it (`workflow.load_agents`, asked by /agents too: a conversation resumed after a restart lists its runs before its first turn; a store that cannot be read is said, and the runs held shown), a run from before a restart showing its record's tokens by model (its usage, no call count); a module of its own, as /memory's diff --git a/src/agentic_cli/cli/conversation.py b/src/agentic_cli/cli/conversation.py index fc8b0b10..6b5a13ca 100644 --- a/src/agentic_cli/cli/conversation.py +++ b/src/agentic_cli/cli/conversation.py @@ -652,9 +652,11 @@ async def start_instance( A write to the conversation under the turn lock, as ``run_instance`` is: held to write, the conversations ``/new`` left dropped around - it, ``written`` once it reached a ready workflow, not ``turned``. - ``opens`` is called with the new instance's id once its run's start - names it (``MessageProcessor.process_start``). + it, not ``turned``, and ``written`` once its run started (the + workflow stores the conversation then): a refusal, which runs and + stores nothing, leaves a fresh conversation fresh. ``opens`` is + called with the new instance's id once its run's start names it + (``MessageProcessor.process_start``). Args: agent_type: The type to start. @@ -670,6 +672,14 @@ async def start_instance( asyncio.CancelledError: Ctrl+C stopped it, as the processor says, or while it waited for the turn lock. """ + started = False + + async def opening(instance: str) -> None: + nonlocal started + started = True # its run started: the conversation is stored + if opens is not None: + await opens(instance) + return await self._write( parts, lambda: parts.processor.process_start( @@ -680,9 +690,10 @@ async def start_instance( settings=parts.settings, usage_tracker=parts.tracker, session_id=self.session_id, - opens=opens, + opens=opening, ), turns=False, + reached=lambda result: started, ) async def tell_root(self, text: str, parts: TurnParts) -> bool: @@ -725,6 +736,7 @@ async def _write( *, turns: bool, echo: str | None = None, + reached: Callable[[Any], bool] | None = None, ) -> bool: """``run()`` under the turn lock: the frame of every write to the conversation. @@ -733,8 +745,9 @@ async def _write( Ctrl+C stops while it waits is shown and said cancelled, not dropped unseen). The conversation is held to write first; ``turned`` when ``turns`` (the main agent answered in it); ``written`` once ``run`` - reached a ready workflow (its result's status is not ``UNAVAILABLE``; - one that raised or was cancelled counts when the workflow was ready). + reached a ready workflow (``reached`` of its result; by default, its + status is not ``UNAVAILABLE``; one that raised or was cancelled + counts when the workflow was ready). Returns: Whether it ran: False when another process has the conversation @@ -760,15 +773,18 @@ async def _write( async with self._dropping_left(parts): if turns: self.turned = True - reached = False + wrote = False try: result = await run() - reached = getattr(result, "status", None) is not TurnStatus.UNAVAILABLE + wrote = ( + reached(result) if reached is not None + else getattr(result, "status", None) is not TurnStatus.UNAVAILABLE + ) except BaseException: - reached = parts.controller.is_ready # it may have begun + wrote = parts.controller.is_ready # it may have begun raise finally: - if reached: + if wrote: self.written = True return True finally: diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index f9af0007..0e632721 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -1123,6 +1123,18 @@ async def test_a_type_you_cannot_start_opens_no_view(self, make_crew): assert app.session.message == ">>> " assert crew.records() == [] + async def test_a_refusal_leaves_a_new_conversation_fresh(self, make_crew): + """Nothing ran and nothing was stored: the conversation is still one a + switch of backend may move, as before the command.""" + crew, app = await new_view(make_crew, store="sqlite") + app._conversation.opened_empty = True # as a new conversation is opened + + await typed(app, "/agent new researcher Find X.") + + assert said(app.session, "add_error")[-1].startswith("You cannot start 'researcher'") + assert not await app._is_stored(app.workflow, app.session_id) + assert app._conversation.fresh and not app._conversation.written + async def test_in_a_view_it_leaves_that_view_first(self, make_crew): crew, app = await in_a_view( make_crew, team=[*follow_team(), *user_team()[2:]], subagents=STARTING, From 3beba9db2e42f582b84f87d4e7b418c99154eb7a Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:33:40 -0500 Subject: [PATCH 09/12] Tests: an interrupt before the user's run starts starts none interrupt_instance can land once run_instance holds its run but before the run's task is made; _users_run then starts no run. Nothing pinned it: with the check removed, the contract suite and the view tests still passed. A contract scenario on both backends now lands the interrupt in that window (found by loop order on an initialized manager, within a 10 s deadline) and expects no second run, the instance idle and the stream ended as a turn's cancel. --- tests/workflow/test_subagents_contract.py | 51 +++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index a3fdfaf1..dee98508 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -6123,6 +6123,57 @@ async def view() -> None: assert entered == [] # stopped before its first step: no hook, no model call +class TestAnInterruptInTheWindowBeforeTheRunStarts: + """``interrupt_instance`` (a process exit) that lands once ``run_instance`` + holds its run, before the run's task is made: no run starts, the instance + stays ``idle``, and the stream ends as a turn's cancel ends it.""" + + async def test_an_interrupt_before_the_run_starts_starts_none(self, make_crew): + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[says("X is 42."), says("[never asked]")], + ) + # Ready first (its turn initialized it): only the follow-up's own steps + # run inside the window searched. + await crew.turn() + entered = watch_hook(crew) + + async def view() -> None: + async for _ in crew.manager.run_instance("researcher-1", "Go on."): + pass + + viewing = asyncio.create_task(view()) + loop = asyncio.get_running_loop() + deadline = loop.time() + 10 + landed = False + while loop.time() < deadline: + await asyncio.sleep(0) + held = next(iter(crew.manager._user_runs.values()), None) + if held is not None and held.work is None: + landed = crew.manager.interrupt_instance("researcher-1") + break + if viewing.done(): + break + if not landed: + ended = ( + f"the follow-up ended first: {viewing.exception() or 'no error'}" + if viewing.done() and not viewing.cancelled() else "no window within 10 s" + ) + viewing.cancel() + raise AssertionError(f"the interrupt could not be landed in the window: {ended}") + done, _ = await asyncio.wait({viewing}, timeout=10) + if not done: + await Crew.stop(viewing) + assert done, "the interrupted stream did not end" + + assert [r.ref.run for r in crew.records()] == ["researcher-1#1"] + assert crew.instances() == [("researcher-1", INSTANCE_IDLE)] + assert (entered, crew.requests("researcher")) == ([], 1) + assert viewing.cancelled() + assert crew.manager.interrupt_instance("researcher-1") is False + + class TestTheUsersControlAfterARestart: async def test_stop_and_close_load_the_records_first(self, make_crew): first = make_crew( From a69928fffd9307bb7b2493fe01e21b4f8b047dfe Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:37:31 -0500 Subject: [PATCH 10/12] Deep Agents: a model choice's skill tools are made for its provider A choice's graph reused its type's tools, skill tools included, and those were made for the type's own provider kind, which decides how a binary skill resource is sent: as an image only to a provider that reads one in a tool result. A choice on a Chat Completions endpoint got an image block it refuses, failing every later request of the instance's thread; one on a built-in provider below a configured type's lost its images. Each choice of a type with skills now gets skill tools made for the choice's model, as ADK builds a skill toolset per choice; its registered and MCP tools stay the type's own objects, so no MCP session opens again. The build's skill checks share one warned set, so a choice warns of no skill once more. --- CHANGELOG.md | 23 ++++---- CLAUDE.md | 2 +- .../workflow/deepagents/agent_builder.py | 9 ++- .../workflow/deepagents/manager.py | 27 +++++++++ tests/workflow/deepagents/test_skills.py | 58 +++++++++++++++++++ 5 files changed, 104 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5947bac0..8ef866cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -699,17 +699,18 @@ the start of the entry's title. agent and a runner of its own, whose plugin chain reads the choice's model, provider kind and context numbers under the type's name, so the fit guard and the overflow handler keep a run within them; on Deep - Agents a graph of its own, summarized by the choice's numbers. A model - switch builds them again, and the release closes them with the type's. A - run on a choice keeps its type's name in its events and records; its - usage is the choice's model's (`RunRecord.usage`, the ledger's - `by_model`, the raw LLM log). The manager gives each choice's model and - numbers: `choice_models[(agent, choice)]` and `context_budget(agent, - model=choice)`. `validate_agent_graph` raises `AgentGraphError` for - `model_choices` on the root, for one that is no tuple or list of texts, - for a choice written with spaces around it ("Agent 'researcher' has the - model choice ' fast' with surrounding spaces: write it without them.") - and for a choice named twice. + Agents a graph of its own, summarized by the choice's numbers, its skill + tools made for the choice's provider (how a binary resource is sent). A + model switch builds them again, and the release closes them with the + type's. A run on a choice keeps its type's name in its events and + records; its usage is the choice's model's (`RunRecord.usage`, the + ledger's `by_model`, the raw LLM log). The manager gives each choice's + model and numbers: `choice_models[(agent, choice)]` and + `context_budget(agent, model=choice)`. `validate_agent_graph` raises + `AgentGraphError` for `model_choices` on the root, for one that is no + tuple or list of texts, for a choice written with spaces around it + ("Agent 'researcher' has the model choice ' fast' with surrounding + spaces: write it without them.") and for a choice named twice. - **`task`'s `tools` and `model`: a delegation may narrow its run's tools and pick a cheaper model, never widen, on both backends.** Every `task` call may give `tools`, some of the type's own tools (its registered, skill and diff --git a/CLAUDE.md b/CLAUDE.md index 4c902297..f4677087 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -113,7 +113,7 @@ agentic-cli/ │ │ │ ├── call_clock.py # Every model call timed: CallClock (a clock per call, under its EventActions, held through an error until the answer a later plugin gives; the raw log keeps one too), CallSentPlugin (last: starts it as the request goes out), CallLatencyPlugin (second, after MainAgentPlugin: marks the answer, custom_metadata[LATENCY_KEY], which the event processor reads, call_latency; an answer already marked keeps its mark: mark_latency, the overflow retry's); no adapter sends it │ │ │ └── plugins.py # LLM traffic logging (raw_llm_logging): requests as sent (SentRequestLoggingPlugin, after the fit guard); each record names its agent's model (chosen=: a run's model choice's), the agent and its sub-agent run (the active run); latency per model call (call_clock.CallClock: a clock under the call's EventActions, as the fit guard keeps its copies); usage records go to the file only (the stream's LLM_USAGE is the event processor's), counted as the stream's (adk_usage_event, by the agent's kind: kinds); the summary call and the overflow retry are not logged on ADK (a follow-up) │ │ ├── deepagents/ # Deep Agents orchestrator (deepagents extra); imports neither adk/ nor langgraph/ -│ │ │ ├── manager.py # DeepAgentsWorkflowManager (turns, sessions, the release hooks: the agents and MCP sessions, the checkpointer and index; _agent_tool_names: each agent's own tools as built, _own_tool_names; MCP, skills, the job resume hooks (_conversation_exists, _deliver_job_notice), _compact_turn; _run_agent, the base's hook: the type's graph (_agent_graphs), or its model choice's (_variant_graphs, built from Variant(config, chat_model, resolved, budget) per (type, choice)), a general_purpose run on its spawner's (_general_graphs: a Variant with tools and prompt of its own, _agent_tools; its MCP notice names the spawner), its processor and RunCallback on _run_models' maps, astreamed in the run's task with var_child_runnable_config cleared, so its chunks reach its own loop alone, through a run-mode processor and a RunCallback of its own; the answer the last AIMessage with text, its outcome mark, the shared keys it changed by Deep Agents' _is_unchanged rule (copied), an overflow RunFailed) +│ │ │ ├── manager.py # DeepAgentsWorkflowManager (turns, sessions, the release hooks: the agents and MCP sessions, the checkpointer and index; _agent_tool_names: each agent's own tools as built, _own_tool_names; MCP, skills, the job resume hooks (_conversation_exists, _deliver_job_notice), _compact_turn; _run_agent, the base's hook: the type's graph (_agent_graphs), or its model choice's (_variant_graphs, built from Variant(config, chat_model, resolved, budget) per (type, choice), its type's tools but skill tools made for the choice's provider, _choice_tools, the skill checks warning once a build, _skill_warned), a general_purpose run on its spawner's (_general_graphs: a Variant with tools and prompt of its own, _agent_tools; its MCP notice names the spawner), its processor and RunCallback on _run_models' maps, astreamed in the run's task with var_child_runnable_config cleared, so its chunks reach its own loop alone, through a run-mode processor and a RunCallback of its own; the answer the last AIMessage with text, its outcome mark, the shared keys it changed by Deep Agents' _is_unchanged rule (copied), an overflow RunFailed) │ │ │ ├── agent_builder.py # build_agent_tree: one create_agent per AgentConfig, each on its own, through build_agent (one agent's graph, root= explicit; variants=: Variant, a sub-agent type on another model and its numbers, its graphs in variant_graphs=) (graphs=: kept by name for _run_agent; every agent compiled on the manager's checkpointer, a tree built without one compiling its sub-agents with none); root=: the graph's root (a free type listed first is no root); each agent can_have_children says gets task from task_tool.build_task_tool (delegations=), its own tool named task an AgentGraphError; general=/general_graphs=: the built-in general_purpose type's Variant per spawner, no task; 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 diff --git a/src/agentic_cli/workflow/deepagents/agent_builder.py b/src/agentic_cli/workflow/deepagents/agent_builder.py index a767d604..74ce4e45 100644 --- a/src/agentic_cli/workflow/deepagents/agent_builder.py +++ b/src/agentic_cli/workflow/deepagents/agent_builder.py @@ -112,8 +112,9 @@ class Variant: """One more graph of a sub-agent type, on another model (a model choice's). Built as the type's own is, with its tools and prompt (or its own: the - general-purpose agent's), but its model side from ``resolved`` and its - summarization from ``budget``. + general-purpose agent's, and a model choice's skill tools, made for its + provider), but its model side from ``resolved`` and its summarization + from ``budget``. Attributes: config: The type. @@ -121,7 +122,9 @@ class Variant: resolved: The choice's resolved model (None: a unit test's, with no model side). budget: The choice's context numbers; None: computed from ``resolved``. tools: Its tools; None: the type's (``build_agent_tree``'s ``tools``). A - type in no ``configs`` (the general-purpose one) has its own. + type in no ``configs`` (the general-purpose one) has its own, and a + model choice of a type with skills the type's with its skill tools + made for the choice's provider. prompt: Its system prompt; None: the type's. """ diff --git a/src/agentic_cli/workflow/deepagents/manager.py b/src/agentic_cli/workflow/deepagents/manager.py index b2add4dd..85aaf006 100644 --- a/src/agentic_cli/workflow/deepagents/manager.py +++ b/src/agentic_cli/workflow/deepagents/manager.py @@ -280,6 +280,9 @@ async def _do_initialize(self) -> None: config.name: config.get_prompt(self._settings) for config in self._agent_configs } + # What this build's skill checks warned of: a type's model choices have + # skill tools of their own, and warn once. + self._skill_warned: set[tuple[str, str]] = set() tools: dict[str, list[BaseTool]] = {} for config in self._agent_configs: tools[config.name], prompts[config.name] = await self._agent_tools( @@ -306,6 +309,9 @@ async def _do_initialize(self) -> None: ), resolved=self._choice_models[(config.name, choice)], budget=self._choice_budgets.get((config.name, choice)), + tools=self._choice_tools( + config, tools[config.name], model=self._choice_models[(config.name, choice)] + ), ) for config in self._agent_configs if config.name != root @@ -440,6 +446,26 @@ async def _agent_tools( own = await self._with_mcp_tools(config, own, spawner=spawner) return own, prompt + def _choice_tools( + self, config: AgentConfig, tools: list[BaseTool], *, model: "ResolvedModel" + ) -> list[BaseTool] | None: + """A model choice's tools: its type's ``tools``, with skill tools made for + the choice's ``model``, as the type's are made for its own (its provider + decides how a binary resource is sent, ``make_skill_tools``). + + The registered and MCP tools are the type's own objects: no MCP session + opens again for a choice. None for a type with no skills: the type's + tools as they are. + """ + if not config.skills: + return None + # The type's own skill tools left out, or their names would clash. + made, _ = self._skill_tools( + config, [tool for tool in tools if tool.name not in SKILL_TOOL_NAMES], model=model + ) + by_name = {tool.name: tool for tool in made} + return [by_name.get(tool.name, tool) for tool in tools] + def _skill_tools( self, config: AgentConfig, @@ -474,6 +500,7 @@ def _skill_tools( agents=SkillAgents( config.name, lambda: self._delegations, root=config.name == self._root_agent_name, + warned=getattr(self, "_skill_warned", None), ), ) logger.debug( diff --git a/tests/workflow/deepagents/test_skills.py b/tests/workflow/deepagents/test_skills.py index 282736b5..3b55295e 100644 --- a/tests/workflow/deepagents/test_skills.py +++ b/tests/workflow/deepagents/test_skills.py @@ -773,6 +773,64 @@ async def call_tool(**arguments): await manager.cleanup() assert manager._own_tool_names == {} + async def test_a_model_choices_skill_tools_are_made_for_its_provider( + self, tmp_path, monkeypatch, skills_dir + ): + """A model choice's graph has the skill tools of the choice's provider, as + the type's has its own's: a Chat Completions endpoint gets a binary + resource as a status (an image block would fail every later request of + the run's thread), Google as an image. Its other tools are the type's: + the same objects, its MCP sessions opened once.""" + from agentic_cli.tools import read_file + + async def call_tool(**arguments): + return [{"type": "text", "text": "found"}], None + + _fake_mcp(monkeypatch, StructuredTool( + name="search", description="A server's tool.", args_schema={"type": "object"}, + coroutine=call_tool, response_format="content_and_artifact", + )) + (tmp_path / "home").mkdir() + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("HOME", str(tmp_path / "home")) + logo = ("load_skill_resource", {"skill_name": "pdf-tools", "file_path": "assets/logo.png"}) + models = scripted( + monkeypatch, + lead=[ai(calls=[task("writer", "Draw it.", model="local:small")]), + ai(calls=[task("writer", "Draw it again.")]), ai("Done.")], + writer=[ai(calls=[logo]), ai("Drawn."), ai(calls=[logo]), ai("Drawn again.")], + ) + with MockContext( + google_api_key="test-key", session_store="memory", skills_dirs=[str(skills_dir)], + model_providers={"local": {"base_url": "http://localhost:8000/v1"}}, + models={"local:small": {"context_window": 32_000}}, + ) as context: + manager = _manager(context.settings, [ + AgentConfig(name="lead", prompt="Lead.", sub_agents=["writer"], + include_state_tools=False), + _writer(description="Writes.", tools=[read_file], + model_choices=("local:small",), + mcp_servers=[MCPServerConfig(name="atlas", command="srv")]), + ]) + try: + await turn(manager) + own = manager._agent_graphs["writer"].nodes["tools"].bound.tools_by_name + chosen = manager._variant_graphs[("writer", "local:small")].nodes[ + "tools"].bound.tools_by_name + finally: + await manager.cleanup() + + writer = models.chats["writer"] + (on_the_choice,) = _tool_messages(writer, 1, 1) + (on_its_own,) = _tool_messages(writer, 3, 1) + assert isinstance(on_the_choice.content, str) + assert "cannot be shown" in json.loads(on_the_choice.content)["status"] + assert [block["type"] for block in on_its_own.content] == ["text", "text", "image"] + assert list(chosen) == list(own) + assert all(chosen[name] is own[name] for name in ("read_file", "search")) + assert all(chosen[name] is not own[name] for name in SKILL_TOOL_NAMES) + assert identify_tool(chosen["load_skill"]) is get_registry().get("load_skill") + async def test_a_model_switch_rebuilds_them(self, ctx, monkeypatch): models = scripted(monkeypatch, writer=_steps(("load_skill", {"skill_name": "pdf-tools"}))) manager = _manager(ctx.settings, [_writer()]) From 2904ed981fd9735fad08545ec0c8493b869c273b Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:45:28 -0500 Subject: [PATCH 11/12] ADK: a narrowed run is not sent a built-in it was not given An ADK built-in such as google_search is one of a type's own tools: a task call's `tools` may name it. But narrowing kept every request entry that is no function declaration, so a run narrowed to ["read_file"] to keep it off the web was still sent Google Search, and the refusal text offered a narrowing that did not hold. A built-in adds a request entry and nothing to tools_dict, and the request does not say whose an entry is. At each model call of a narrowed run, each of the agent's own ADK tools that the run was not given and that is not in tools_dict now processes a request of its own (same model, a tool context of the same invocation), and the entries it adds there are left out of the real request; a built-in the run keeps is sent as ADK made it, and an entry no tool made (a code executor's) stays. The narrowing moves to a plugin of its own, RunToolsPlugin, first in each sub-agent chain's head, before the permission gate: the gate marks the conversation for the built-ins a request carries, and that mark now follows what is sent. RunControlPlugin keeps the limits and steering after the raw log. The CHANGELOG and README name the built-ins among what `tools` may give. --- CHANGELOG.md | 16 +- CLAUDE.md | 4 +- README.md | 24 +-- src/agentic_cli/workflow/adk/manager.py | 32 ++-- .../workflow/adk/run_control_plugin.py | 137 +++++++++++++++--- src/agentic_cli/workflow/base_manager.py | 8 +- .../adk/test_model_side_tools_mark.py | 79 ++++++++++ tests/workflow/adk/test_plugin_chain.py | 13 +- tests/workflow/adk/test_run_control_plugin.py | 97 ++++++++++++- 9 files changed, 341 insertions(+), 69 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ef866cd..a8af5a0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -714,13 +714,15 @@ the start of the entry's title. - **`task`'s `tools` and `model`: a delegation may narrow its run's tools and pick a cheaper model, never widen, on both backends.** Every `task` call may give `tools`, some of the type's own tools (its registered, skill and - MCP tools, by the names its model is offered them; the plan's tools and - the delegation tools are always kept): the run's model is offered only - those, and a call of any other is answered as one of a tool the agent - does not have (" failed: ValueError: Tool '' not found.", then - the tools it has), and the run goes on. A call to a type with model - choices may give `model`, one of them: the run is on that model. Anything - else is the call's error result, and no run starts nor counts toward the + MCP tools, and on ADK its built-ins such as `google_search`, by the names + its model is offered them; the plan's tools and the delegation tools are + always kept): the run's model is offered only those (a built-in it was not + given is not in its requests, so it marks no conversation either), and a + call of any other is answered as one of a tool the agent does not have + (" failed: ValueError: Tool '' not found.", then the tools it + has), and the run goes on. A call to a type with model choices may give + `model`, one of them: the run is on that model. Anything else is the + call's error result, and no run starts nor counts toward the turn's ("The tools for 'researcher' must be some of its own: lookup.", "The model for 'researcher' must be one of its model choices: fast.", "'researcher' has no model choices; leave model out."; a backend that diff --git a/CLAUDE.md b/CLAUDE.md index f4677087..9eb7f663 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -108,7 +108,7 @@ agentic-cli/ │ │ │ ├── context_cache_plugin.py # One Gemini cache attempt a turn │ │ │ ├── foreign_reasoning_plugin.py # No model is sent another provider's thoughts │ │ │ ├── subagent_outcome_plugin.py # SubAgentOutcomePlugin: a sub-agent's final answer a model refused or cut, rewritten in place (the refusal notice; the text and the cut-off note) and marked (custom_metadata agentic_cli_outcome), which the run's event processor ends it by; what it reads: finish_reason, error_code, an OTHER stop's JSON reason, the text "OpenAI refusal: "; in each sub-agent type's runner's chain (_agent_plugin_chain), after the raw log and RunControlPlugin; the root's answers untouched -│ │ │ ├── run_control_plugin.py # RunControlPlugin: a sub-agent run's control at its model calls (Delegations.control of the active run): a narrowed run's other tools left out of the request, its tools_dict and declarations (narrow: a call of one finds ADK's stand-in, unknown_tool_result), before the fit guard; the messages steered to it appended to its child session and the request before each call (the run's events from then on stamped after them, on_event_callback: ADK stamps an answer before its call's callbacks, and a durable store reads events back by time), the call counted and the last allowed one given STEP_LIMIT_NOTE (with_note: a part of the last user content; its tools stay declared), each answer's usage (adk_tokens) to used, with whether it makes calls, the run's last answer's function calls dropped (drop_calls: an empty text for calls alone); in each sub-agent type's chain, after the raw log, before SubAgentOutcomePlugin +│ │ │ ├── run_control_plugin.py # RunToolsPlugin and RunControlPlugin: a sub-agent run's control at its model calls (Delegations.control of the active run): RunToolsPlugin, first in the chain's head (before the permission gate, whose mark for the built-ins a request carries then follows what is sent, and the fit guard), leaves a narrowed run's other tools out of the request, its tools_dict and declarations (narrow: a call of one finds ADK's stand-in, unknown_tool_result), an ADK built-in it was not given too (built_in_entries: each built-in of the agent's own, google_search, url_context, not in tools_dict, processes a request of its own to show its entries), one it keeps as ADK made it; RunControlPlugin: the messages steered to it appended to its child session and the request before each call (the run's events from then on stamped after them, on_event_callback: ADK stamps an answer before its call's callbacks, and a durable store reads events back by time), the call counted and the last allowed one given STEP_LIMIT_NOTE (with_note: a part of the last user content; its tools stay declared), each answer's usage (adk_tokens) to used, with whether it makes calls, the run's last answer's function calls dropped (drop_calls: an empty text for calls alone); in each sub-agent type's chain, after the raw log, before SubAgentOutcomePlugin │ │ │ ├── log_filters.py # install_log_filters: what ADK would print over the CLI logged at debug instead (the warnings hook, filters by logger name: see Console Output); imports no ADK (the package loads LLMLoggingPlugin on first use); the plugin-manager filter reads overflow_plugin.OVERFLOW_PLUGIN_FAILED as a record comes; BaseCLIApp.run() installs them, once │ │ │ ├── call_clock.py # Every model call timed: CallClock (a clock per call, under its EventActions, held through an error until the answer a later plugin gives; the raw log keeps one too), CallSentPlugin (last: starts it as the request goes out), CallLatencyPlugin (second, after MainAgentPlugin: marks the answer, custom_metadata[LATENCY_KEY], which the event processor reads, call_latency; an answer already marked keeps its mark: mark_latency, the overflow retry's); no adapter sends it │ │ │ └── plugins.py # LLM traffic logging (raw_llm_logging): requests as sent (SentRequestLoggingPlugin, after the fit guard); each record names its agent's model (chosen=: a run's model choice's), the agent and its sub-agent run (the active run); latency per model call (call_clock.CallClock: a clock under the call's EventActions, as the fit guard keeps its copies); usage records go to the file only (the stream's LLM_USAGE is the event processor's), counted as the stream's (adk_usage_event, by the agent's kind: kinds); the summary call and the overflow retry are not logged on ADK (a follow-up) @@ -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; `start_instance`: the user's new instance, `/agent new`, the same; `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 `, `/agent new ` 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 logs it at info, `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`). With `SubAgentPolicy.general_purpose` (it needs a source) every enabled source may also start the built-in `general_purpose` type (`spawn.GENERAL_PURPOSE`; `task` lists it last, a skill may name it, `/agent new` may start it): no config of the app's (one named so is refused at validation while it is on), but one made for the type that starts it (`general_purpose_config`: that type's tools, MCP servers, skills and own model, `GENERAL_PURPOSE_PROMPT`, the plan's tools, a fresh context; `Delegations.config_for(agent_type, based_on=)`), its spawner the caller's type for `task` and a skill, the root for the user (`StartRequest.based_on` → `AgentRun.based_on`, `InstanceRecord.based_on`, so its follow-ups and its runs after a restart are made for the same type); it starts no agent (`can_have_children` False: no `task`, no parent's tools; a skill it loads that names a type is refused), `task`'s `tools` narrows it against its spawner's tools (`_agent_tool_names()`), and it has no model choices. Each backend builds one per type that may start it (`general_purpose_spawners`: the root, and with `max_spawn_depth` 2 or more each type that does not inherit when `"agent"` is a source, and each type with skills when `"skill"` is; `Delegations.general_purpose`) at initialization, through the builder that builds a model choice's, with MCP connections of its own (ADK `_general_agents`/`_general_runners`, its chain reading the spawner's model, kind and numbers under `general_purpose`; Deep Agents `_general_graphs`, a `Variant` with its own tools and prompt), the hooks picking it by `run.based_on` (`_run_models`, `_general_model`: the spawner's resolved model named for `general_purpose`), released with the rest and built again by a model switch. +- **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`, ADK's built-ins such as `google_search` among them: the run is offered only those and the tools every run keeps, `RunControl.keeps`, ADK's `RunToolsPlugin` and Deep Agents' `RunControlMiddleware` filtering its requests, a built-in it was not given left out too, 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; `start_instance`: the user's new instance, `/agent new`, the same; `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 `, `/agent new ` 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, `RunToolsPlugin`, `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 logs it at info, `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`). With `SubAgentPolicy.general_purpose` (it needs a source) every enabled source may also start the built-in `general_purpose` type (`spawn.GENERAL_PURPOSE`; `task` lists it last, a skill may name it, `/agent new` may start it): no config of the app's (one named so is refused at validation while it is on), but one made for the type that starts it (`general_purpose_config`: that type's tools, MCP servers, skills and own model, `GENERAL_PURPOSE_PROMPT`, the plan's tools, a fresh context; `Delegations.config_for(agent_type, based_on=)`), its spawner the caller's type for `task` and a skill, the root for the user (`StartRequest.based_on` → `AgentRun.based_on`, `InstanceRecord.based_on`, so its follow-ups and its runs after a restart are made for the same type); it starts no agent (`can_have_children` False: no `task`, no parent's tools; a skill it loads that names a type is refused), `task`'s `tools` narrows it against its spawner's tools (`_agent_tool_names()`), and it has no model choices. Each backend builds one per type that may start it (`general_purpose_spawners`: the root, and with `max_spawn_depth` 2 or more each type that does not inherit when `"agent"` is a source, and each type with skills when `"skill"` is; `Delegations.general_purpose`) at initialization, through the builder that builds a model choice's, with MCP connections of its own (ADK `_general_agents`/`_general_runners`, its chain reading the spawner's model, kind and numbers under `general_purpose`; Deep Agents `_general_graphs`, a `Variant` with its own tools and prompt), the hooks picking it by `run.based_on` (`_run_models`, `_general_model`: the spawner's resolved model named for `general_purpose`), released with the rest and built again by a model switch. - **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 0c4494f4..327cf3b9 100644 --- a/README.md +++ b/README.md @@ -1462,16 +1462,18 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", ``` - **Narrowing a run, and a cheaper model.** Any `task` call may give `tools`, some of the type's own tools (its registered, skill and MCP - tools, by name; its plan's tools and the delegation tools always stay): - the run is offered only those, and a call of another is answered as one - of a tool it does not have. A type's `model_choices` are the models a call - may pick instead of its own (`model`, named in the type's line in `task`'s - description); each is resolved and given its context numbers at startup, - and runs as the type's agent built on it (ADK: a runner of its own; - Deep Agents: a graph of its own), within its own window. Anything else is - the call's error result, naming what it may be, and no run starts. The - instance keeps both: its follow-ups, and its runs after a restart, run - with them, and `/agents ` shows them. + tools, and on ADK its built-ins such as `google_search`, by name; its + plan's tools and the delegation tools always stay): the run is offered + only those (a built-in it was not given is not in its requests), and a + call of another is answered as one of a tool it does not have. A type's + `model_choices` are the models a call may pick instead of its own + (`model`, named in the type's line in `task`'s description); each is + resolved and given its context numbers at startup, and runs as the + type's agent built on it (ADK: a runner of its own; Deep Agents: a graph + of its own), within its own window. Anything else is the call's error + result, naming what it may be, and no run starts. The instance keeps + both: its follow-ups, and its runs after a restart, run with them, and + `/agents ` shows them. ```python researcher = AgentConfig(name="researcher", prompt="Find facts.", @@ -2687,7 +2689,7 @@ agentic-cli/ │ │ │ ├── plugins.py # LLMLoggingPlugin │ │ │ ├── log_filters.py # What ADK would print over the CLI, logged at debug (installed by run()) │ │ │ ├── permission_plugin.py # PermissionPlugin (capability gating) -│ │ │ ├── run_control_plugin.py # RunControlPlugin: a sub-agent run's limits and steering at its model calls +│ │ │ ├── run_control_plugin.py # RunToolsPlugin, RunControlPlugin: a sub-agent run's tools, limits and steering at its model calls │ │ │ ├── task_progress_plugin.py # TaskProgressPlugin (deprecated, unused) │ │ │ └── tool_result_cap_plugin.py # ToolResultCapPlugin (the tool result cap) │ │ ├── deepagents/ # The Deep Agents backend (deepagents extra) diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index 967a7f22..9aa06a23 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -134,6 +134,7 @@ from agentic_cli.models import Provider, ResolvedModel, RoleMap from agentic_cli.workflow.context import ContextBudget from agentic_cli.workflow.adk.build import ADKBuild + from agentic_cli.workflow.agents.control import RunControl from agentic_cli.workflow.agents.policy import SubAgentPolicy from agentic_cli.workflow.sessions import SessionRef @@ -381,11 +382,14 @@ async def _agent_tool_names(self, agent: str) -> frozenset[str]: agent's. Its tools as its model sees them (callables, ADK tools, a skill - toolset's tools) and each MCP toolset's, which ADK lists by connecting: - done when first asked, once a build (the toolset stays connected for the - agent's runs, and its runner stops it; for a narrowed run on a model - choice that is one more idle connection, the type's own, until the - release). The state and delegation tools are left out. + toolset's tools; an ADK built-in such as ``google_search`` too, which + a narrowed run's requests leave out unless it is given, + ``run_control_plugin.RunToolsPlugin``) and each MCP toolset's, which + ADK lists by connecting: done when first asked, once a build (the + toolset stays connected for the agent's runs, and its runner stops + it; for a narrowed run on a model choice that is one more idle + connection, the type's own, until the release). The state and + delegation tools are left out. Raises: ToolsUnlistedError: A toolset's listing failed (logged, and @@ -881,6 +885,10 @@ def _agent_plugin_chain( Its own instances, in the app's order, but for what a sub-agent is: + - ``RunToolsPlugin`` first in the head: a narrowed run's request + holds only its tools (an ADK built-in it was not given left out + too) before the permission gate marks the conversation for the + built-ins a request carries, so the mark follows what is sent; - the permission gate writes no outside-content mark at a model call (a run's mark reaches the conversation with its result, ``adk/task_tool.py``), and the raw log is the app's own instance @@ -903,11 +911,18 @@ def _agent_plugin_chain( run on this one chain at once, and a provider may number their call ids alike. """ - from agentic_cli.workflow.adk.run_control_plugin import RunControlPlugin + from agentic_cli.workflow.adk.run_control_plugin import ( + RunControlPlugin, + RunToolsPlugin, + ) from agentic_cli.workflow.adk.subagent_outcome_plugin import SubAgentOutcomePlugin from agentic_cli.workflow.adk.tool_error_plugin import ToolErrorPlugin + def control() -> "RunControl | None": + return self._delegations.control(get_active_run()) + head: list = [ + RunToolsPlugin(control), PermissionPlugin(self._open_calls, marks=self._outside_marks), ToolErrorPlugin(self._open_calls), ] @@ -920,10 +935,7 @@ def _agent_plugin_chain( models = {**self._resolved_models, agent.name: model} if budget is not None: budgets = {**self._budgets, agent.name: budget} - head.append(RunControlPlugin( - lambda: self._delegations.control(get_active_run()), - kinds.get(agent.name), - )) + head.append(RunControlPlugin(control, kinds.get(agent.name))) head.append(SubAgentOutcomePlugin()) return self._chain( head=head, diff --git a/src/agentic_cli/workflow/adk/run_control_plugin.py b/src/agentic_cli/workflow/adk/run_control_plugin.py index d1323f43..64741644 100644 --- a/src/agentic_cli/workflow/adk/run_control_plugin.py +++ b/src/agentic_cli/workflow/adk/run_control_plugin.py @@ -1,16 +1,26 @@ -"""ADK plugin: a sub-agent run's control at each of its model calls (``workflow/agents/control.py``). +"""ADK plugins: a sub-agent run's control at each of its model calls (``workflow/agents/control.py``). In each sub-agent type's plugin chain (``GoogleADKWorkflowManager._agent_plugin_chain``), for the run in progress (``get_active_run``: the run's own task, -``agents/delegate.py``), whose control the manager's ``Delegations`` holds: - -- before each model call, a run narrowed to some of its type's tools - (``RunControl.tools``) has the others left out of the request and of - its ``tools_dict``, which ADK resolves a call from, so a call of one is - answered as one of a tool the agent does not have (``narrow``: before - the fit guard, which measures the narrowed request; a skill toolset's - instruction text stays in the system prompt, only its calls are refused); -- before each, the messages steered to the run since its last +``agents/delegate.py``), whose control the manager's ``Delegations`` holds. + +``RunToolsPlugin``, first in the chain's head: before each model call, a run +narrowed to some of its type's tools (``RunControl.tools``) has the others +left out of the request and of its ``tools_dict``, which ADK resolves a call +from, so a call of one is answered as one of a tool the agent does not have +(``narrow``). An ADK built-in it was not given (``google_search``, +``url_context``: it runs inside the model, so what it adds to the request is +no function declaration and nothing in ``tools_dict``) is left out too, its +entries found by having it process a request of its own +(``built_in_entries``); one the run keeps is sent as ADK made it. It runs +before the permission gate, whose mark for the built-ins a request carries +then follows what is sent, and before the fit guard, which measures the +narrowed request; a skill toolset's instruction text stays in the system +prompt, only its calls are refused. + +``RunControlPlugin``, after the raw log: + +- before each model call, the messages steered to the run since its last (``RunControl.take_steering``) go after its last message, each a user event appended to the run's child session (through the callback context's session service: the invocation's own session, which a session @@ -41,22 +51,25 @@ alone keeps an empty text, which ADK takes as the run's last answer (``MODEL_RETURNED_NO_CONTENT``, no failure for a run). -It changes the request, the answer and an event's time in place and +Each changes the request, the answer and an event's time in place and returns None, as ``ForeignReasoningPlugin`` does, so every plugin after it -still runs; what it keeps is kept by invocation, and let go of as the run -ends (two runs of one type share their runner, and this plugin). It sits -before ``SubAgentOutcomePlugin``, which then reads an answer whose calls were -dropped as the run's final one. The root's calls (no active run) and a run -without a control are left alone. +still runs; what ``RunControlPlugin`` keeps is kept by invocation, and let +go of as the run ends (two runs of one type share their runner, and these +plugins). It sits before ``SubAgentOutcomePlugin``, which then reads an +answer whose calls were dropped as the run's final one. The root's calls (no +active run) and a run without a control are left alone. """ from __future__ import annotations -from collections.abc import Callable +from collections.abc import Callable, Mapping, Sequence from typing import TYPE_CHECKING, Any, Optional from google.adk.events import Event +from google.adk.models.llm_request import LlmRequest from google.adk.plugins.base_plugin import BasePlugin +from google.adk.tools import BaseTool +from google.adk.tools.tool_context import ToolContext from google.genai import types from agentic_cli.workflow.agents.control import STEP_LIMIT_NOTE @@ -65,7 +78,6 @@ if TYPE_CHECKING: from google.adk.agents.callback_context import CallbackContext from google.adk.agents.invocation_context import InvocationContext - from google.adk.models.llm_request import LlmRequest from google.adk.models.llm_response import LlmResponse from agentic_cli.workflow.agents.control import RunControl @@ -76,6 +88,29 @@ _STAMP_STEP = 2e-6 +class RunToolsPlugin(BasePlugin): + """A narrowed sub-agent run's tools at its model calls (see the module docstring). + + Args: + control: The control of the run in progress (None: no run, or none + to control), asked at each call. + """ + + def __init__(self, control: Callable[[], RunControl | None]) -> None: + super().__init__(name="run_tools") + self._control = control + + async def before_model_callback( + self, *, callback_context: CallbackContext, llm_request: LlmRequest + ) -> Optional[LlmResponse]: + control = self._control() + if control is None or control.tools is None: + return None + built_ins = await built_in_entries(callback_context, llm_request, control.keeps) + narrow(llm_request, control.keeps, built_ins=built_ins) + return None + + class RunControlPlugin(BasePlugin): """A sub-agent run's limits at its model calls (see the module docstring). @@ -100,8 +135,6 @@ async def before_model_callback( control = self._control() if control is None: return None - if control.tools is not None: - narrow(llm_request, control.keeps) steered = control.take_steering() if steered: self._stamped[callback_context.invocation_id] = await _steer( @@ -179,18 +212,74 @@ async def _steer( return stamped -def narrow(llm_request: LlmRequest, keeps: Callable[[str], bool]) -> None: - """Leave the function tools ``keeps`` refuses out of ``llm_request``, in place. +async def built_in_entries( + callback_context: CallbackContext | None, + llm_request: LlmRequest, + keeps: Callable[[str], bool], +) -> dict[str, list[types.Tool]]: + """What each of the running agent's built-ins that ``keeps`` refuses added to + ``llm_request``, by the tool's name. + + A built-in (``google_search``, ``url_context``, a Vertex AI Search) is an + ADK tool of the agent's own (``agent.tools``, not a toolset's) that ADK did + not put in ``tools_dict``: it runs inside the model, and what it adds to the + request is a tool entry that is no function declaration. Which entry is + whose the request does not say, so each such tool processes a request of + its own, for the same model and with a tool context of the same + invocation, as ADK had it process this one (``process_llm_request``), at + each model call of a narrowed run; of what it adds there, the entries that + are more than function declarations are its. No callback context (no + agent to ask): none. + """ + get = getattr(callback_context, "get_invocation_context", None) + invocation = get() if get is not None else None + agent = getattr(invocation, "agent", None) + found: dict[str, list[types.Tool]] = {} + for tool in getattr(agent, "tools", None) or (): + if ( + not isinstance(tool, BaseTool) + or keeps(tool.name) + or tool.name in llm_request.tools_dict + ): + continue + alone = LlmRequest(model=llm_request.model) + await tool.process_llm_request( + tool_context=ToolContext(invocation), llm_request=alone + ) + found[tool.name] = [ + entry for entry in alone.config.tools or () + if entry.model_dump(exclude={"function_declarations"}, exclude_none=True) + ] + return found + + +def narrow( + llm_request: LlmRequest, + keeps: Callable[[str], bool], + *, + built_ins: Mapping[str, Sequence[types.Tool]] | None = None, +) -> None: + """Leave the tools ``keeps`` refuses out of ``llm_request``, in place. Out of ``tools_dict`` (what ADK resolves a call from: a call of a name left out gets ADK's answer for a tool that is not there) and out of the - declarations the model is sent. A tool left with no declaration and - nothing else (a built-in's field) goes; the others stay as they are. + declarations the model is sent. ``built_ins`` are the entries each + built-in added, by its name (``built_in_entries``): one ``keeps`` refuses + has each of its entries left out, once; one it keeps stays as ADK made + it. A tool left with no declaration and nothing else goes; an entry no + built-in made (a code executor's) stays as it is. """ for name in [name for name in llm_request.tools_dict if not keeps(name)]: del llm_request.tools_dict[name] + dropped = [ + entry for name, entries in (built_ins or {}).items() if not keeps(name) + for entry in entries + ] kept: list[types.Tool] = [] for tool in llm_request.config.tools or (): + if tool in dropped: + dropped.remove(tool) + continue declarations = tool.function_declarations if declarations is None: kept.append(tool) diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index d3995d99..0c9fb74d 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -1461,10 +1461,10 @@ async def _agent_tool_names(self, agent: str) -> frozenset[str]: Asked for a call that names tools and for a narrowed instance's follow-up: the agent's own tools by the names its model sees (a - backend adds its skill and MCP tools), the state and delegation tools - (``KEPT_TOOLS``) left out. The base's are the agent's configured tools - as ``_build_tools`` assembles them, each by its callable's name; an - agent that is not configured has none. + backend adds its skill and MCP tools, ADK its built-ins), the state + and delegation tools (``KEPT_TOOLS``) left out. The base's are the + agent's configured tools as ``_build_tools`` assembles them, each by + its callable's name; an agent that is not configured has none. """ config = next((c for c in self._agent_configs if c.name == agent), None) if config is None: diff --git a/tests/workflow/adk/test_model_side_tools_mark.py b/tests/workflow/adk/test_model_side_tools_mark.py index 59ae7d82..919adf8c 100644 --- a/tests/workflow/adk/test_model_side_tools_mark.py +++ b/tests/workflow/adk/test_model_side_tools_mark.py @@ -9,6 +9,7 @@ from __future__ import annotations +import json import textwrap from types import SimpleNamespace @@ -32,6 +33,7 @@ from agentic_cli.workflow.outside_content import OUTSIDE_CONTENT_KEY, OutsideContentMarks # noqa: E402 from agentic_cli.workflow.sessions import SessionRef, reset_active_turn, set_active_turn # noqa: E402 from tests.workflow.test_adk_context_cache import gemini_api, route_gemini # noqa: E402 +from tests.loop_guard import no_blocking_calls # noqa: E402 from tests.workflow.adk.fakes import FakeAPI # noqa: E402 from tests.workflow.test_manager_models import KEYS, adk, keys, settings # noqa: E402 @@ -247,3 +249,80 @@ async def test_the_agent_is_read_through_adks_public_accessor(active_turn): await plugin.before_model_callback(callback_context=context, llm_request=await _request()) assert marks.get(REF) == "code_executor" + + +# --- a narrowed sub-agent run ----------------------------------------------------------- + + +class GeminiTeam: + """The Gemini API for a team: each agent answers from its own script (a + part each call), told apart by its prompt; the bodies each was sent.""" + + def __init__(self, **scripts: list[dict]) -> None: + self.scripts = {name: list(parts) for name, parts in scripts.items()} + self.sent: dict[str, list[dict]] = {name: [] for name in scripts} + + def __call__(self, request) -> dict: + body = json.loads(request.content) + system = "".join( + part.get("text", "") for part in (body.get("systemInstruction") or {}).get("parts", ()) + ) + name = next(name for name in self.scripts if f"You are {name}." in system) + self.sent[name].append(body) + answer = gemini_api(request) + answer["candidates"][0]["content"]["parts"] = [self.scripts[name].pop(0)] + return answer + + +def _searches(body: dict) -> bool: + """Whether a Gemini request carries Google Search.""" + return any("googleSearch" in tool for tool in body.get("tools") or ()) + + +@pytest.mark.parametrize("given, sent, mark", [ + (["read_file"], False, None), + (["read_file", "google_search"], True, "google_search"), + (None, True, "google_search"), +], ids=["narrowed-without-it", "narrowed-to-keep-it", "not-narrowed"]) +async def test_a_narrowed_run_is_sent_a_built_in_only_when_it_keeps_it( + monkeypatch, given, sent, mark +): + """A built-in such as ``google_search`` is one of a type's own tools: a + ``task`` call's ``tools`` may name it, and a run narrowed without it is not + sent it, so nothing it never ran marks the conversation; one kept is sent as + ADK makes it, and marks it.""" + from agentic_cli.tools import read_file + + keys(monkeypatch, "google") + brief = {"agent_type": "researcher", "title": "Look", "objective": "Look it up."} + if given is not None: + brief["tools"] = given + api = GeminiTeam( + coordinator=[{"functionCall": {"name": "task", "args": brief}}, {"text": "Done."}], + researcher=[{"text": "Found it."}], + ) + route_gemini(monkeypatch, FakeAPI(api)) + manager = adk( + [ + AgentConfig(name="coordinator", prompt="You are coordinator.", + sub_agents=["researcher"], include_state_tools=False), + AgentConfig(name="researcher", prompt="You are researcher.", + description="Researches.", tools=[read_file, google_search], + include_state_tools=False), + ], + settings(default_model=MODEL, prompt_caching_enabled=False), + ) + try: + await manager.initialize_services() + with no_blocking_calls(): + [_ async for _ in manager.process("Look it up.", user_id="u", session_id="s")] + (researched,) = api.sent["researcher"] + assert _searches(researched) is sent + assert [ + declaration["name"] for tool in researched["tools"] + for declaration in tool.get("functionDeclarations", ()) + ] == ["read_file"] + assert _marked(manager) == mark + assert await _stored_mark(manager) == (mark or "") + finally: + await manager.cleanup() diff --git a/tests/workflow/adk/test_plugin_chain.py b/tests/workflow/adk/test_plugin_chain.py index 27971a52..99112c8d 100644 --- a/tests/workflow/adk/test_plugin_chain.py +++ b/tests/workflow/adk/test_plugin_chain.py @@ -31,11 +31,13 @@ A native ADK YAML app gets the same chain: only the building of its agents differs (``workflow/adk/build.py``). Each sub-agent type's runner has a chain -of its own in the same order (``_agent_plugin_chain``): no memory index, no roster, and -after the raw log (which records an answer as the model gave it) -``run_control``, where the run's limits are kept at its model calls, then -``subagent_outcome``, where a sub-agent's refused or cut answer is said so; -both change what they see in place, so every plugin after them still runs. +of its own in the same order (``_agent_plugin_chain``): no memory index, no roster, +``run_tools`` before ``permission``, so a narrowed run's request holds only +its tools before the gate marks the conversation for the built-ins it +carries, and after the raw log (which records an answer as the model gave +it) ``run_control``, where the run's limits are kept at its model calls, +then ``subagent_outcome``, where a sub-agent's refused or cut answer is said +so; each changes what it sees in place, so every plugin after it still runs. """ from __future__ import annotations @@ -168,6 +170,7 @@ async def test_a_delegating_app(project): assert helpers == [ "main_agent", "call_latency", + "run_tools", "permission", "tool_error", "llm_logging", diff --git a/tests/workflow/adk/test_run_control_plugin.py b/tests/workflow/adk/test_run_control_plugin.py index a6c3ee14..f6dc0c25 100644 --- a/tests/workflow/adk/test_run_control_plugin.py +++ b/tests/workflow/adk/test_run_control_plugin.py @@ -1,5 +1,6 @@ -"""ADK: a sub-agent run's limits, and the tools a narrowed run is offered, at its model -calls (``workflow/adk/run_control_plugin.py``). +"""ADK: a sub-agent run's limits, and the tools a narrowed run is offered (its +registered, skill and MCP tools, and ADK's built-ins), at its model calls +(``workflow/adk/run_control_plugin.py``). What the plugin does to a request and an answer, alone. Whole turns, on both backends, are in the contract suite (``TestTheStepLimit``, @@ -15,13 +16,19 @@ pytest.importorskip("google.adk") +from google.adk.agents import LlmAgent # noqa: E402 +from google.adk.agents.callback_context import CallbackContext # noqa: E402 +from google.adk.agents.invocation_context import InvocationContext # noqa: E402 from google.adk.models.llm_request import LlmRequest # noqa: E402 from google.adk.models.llm_response import LlmResponse # noqa: E402 -from google.adk.tools import BaseTool # noqa: E402 +from google.adk.sessions import InMemorySessionService # noqa: E402 +from google.adk.tools import BaseTool, FunctionTool, google_search # noqa: E402 +from google.adk.tools.tool_context import ToolContext # noqa: E402 from google.genai import types # noqa: E402 from agentic_cli.workflow.adk.run_control_plugin import ( # noqa: E402 RunControlPlugin, + RunToolsPlugin, drop_calls, narrow, with_note, @@ -34,6 +41,8 @@ REF = RunRef( agent="researcher", instance="researcher-1", run="researcher-1#1", parent_run=None, depth=1 ) +#: A model ADK's built-ins run on. +GEMINI = "gemini-2.5-flash" def user(*parts: types.Part) -> types.Content: @@ -250,6 +259,33 @@ def offering(*names: str) -> LlmRequest: return request +def lookup(q: str) -> dict: + """Look ``q`` up.""" + return {"success": True} + + +async def agent_context(tools: list) -> CallbackContext: + """A real callback context of a Gemini agent with ``tools``, as ADK passes + a plugin's model callbacks.""" + service = InMemorySessionService() + session = await service.create_session(app_name="app", user_id="u", session_id="s") + agent = LlmAgent(name="researcher", model=GEMINI, tools=list(tools)) + return CallbackContext(InvocationContext( + session_service=service, invocation_id="i", agent=agent, session=session, + )) + + +async def processed(context: CallbackContext, tools: list) -> LlmRequest: + """The request ADK builds once each of ``tools`` processed it, before the + model callbacks.""" + request = LlmRequest(model=GEMINI, contents=[user(text("# Task: Find X."))]) + for tool in tools: + await tool.process_llm_request( + tool_context=ToolContext(context.get_invocation_context()), llm_request=request + ) + return request + + def declared(request: LlmRequest) -> list[str]: return [ d.name for tool in request.config.tools or () @@ -264,7 +300,7 @@ class TestANarrowedRunsTools: async def test_its_tools_and_those_every_run_keeps_and_no_other(self): control = RunControl(REF, AgentLimits(), tools=frozenset({"lookup"})) - plugin = RunControlPlugin(lambda: control, "anthropic") + plugin = RunToolsPlugin(lambda: control) request = offering("lookup", "fetch_page", "save_plan", "task", "check_agents") await plugin.before_model_callback(callback_context=None, llm_request=request) @@ -272,9 +308,58 @@ async def test_its_tools_and_those_every_run_keeps_and_no_other(self): assert list(request.tools_dict) == ["lookup", "save_plan", "task", "check_agents"] assert declared(request) == ["lookup", "save_plan", "task", "check_agents"] - # What is no function declaration stays. + # What no tool of the agent's is known to have made (here no agent) stays. assert request.config.tools[1].google_search is not None + @pytest.mark.parametrize("kept, searches", [ + ({"lookup"}, False), ({"lookup", "google_search"}, True), + ], ids=["without-it", "keeping-it"]) + async def test_a_built_in_goes_unless_the_run_keeps_it(self, kept, searches): + """ADK's built-ins (``google_search``) run inside the model: what one adds + to a request is no function declaration, and nothing in ``tools_dict``. + A run narrowed without it is not sent it; one that keeps it is sent what + ADK made, as it made it.""" + tools = [FunctionTool(lookup), google_search] + context = await agent_context(tools) + request = await processed(context, tools) + made = list(request.config.tools) + control = RunControl(REF, AgentLimits(), tools=frozenset(kept)) + + await RunToolsPlugin(lambda: control).before_model_callback( + callback_context=context, llm_request=request + ) + + assert any(tool.google_search is not None for tool in request.config.tools) is searches + assert (declared(request), list(request.tools_dict)) == (["lookup"], ["lookup"]) + assert (made[1] in request.config.tools) is searches # ADK's own entry, kept + + def test_narrow_leaves_out_the_entries_of_the_built_ins_it_refuses(self): + request = offering("lookup") + search = request.config.tools[1] + code = types.Tool(code_execution=types.ToolCodeExecution()) + request.config.tools.append(code) + + narrow(request, lambda name: name == "lookup", + built_ins={"google_search": [search], "url_context": []}) + + # A code executor's entry is no tool's: it stays. + assert request.config.tools[1:] == [code] + assert declared(request) == ["lookup"] + + async def test_a_built_in_no_run_narrows_is_never_asked(self): + """A run not narrowed has every tool as ADK made it, built-ins too.""" + tools = [FunctionTool(lookup), google_search] + context = await agent_context(tools) + request = await processed(context, tools) + made = list(request.config.tools) + control = RunControl(REF, AgentLimits()) + + await RunToolsPlugin(lambda: control).before_model_callback( + callback_context=context, llm_request=request + ) + + assert request.config.tools == made + def test_a_tool_left_with_no_declaration_goes(self): request = LlmRequest(contents=[user(text("Go."))]) request.config.tools = [types.Tool(function_declarations=[ @@ -289,7 +374,7 @@ def test_a_tool_left_with_no_declaration_goes(self): async def test_a_run_not_narrowed_keeps_them_all(self): control = RunControl(REF, AgentLimits()) - plugin = RunControlPlugin(lambda: control, "anthropic") + plugin = RunToolsPlugin(lambda: control) request = offering("lookup", "fetch_page") await plugin.before_model_callback(callback_context=None, llm_request=request) From ae5090556fd60ec83c4862feda61c28c3eaae6f9 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:12:05 -0500 Subject: [PATCH 12/12] ADK: a refused built-in's entries learned once, and a failing one drops nothing A narrowed run found a refused built-in's request entries by running its process_llm_request on a request of its own at every model call. That ran a tool's work again each time (PreloadMemoryTool searches the memory), and a tool that raises there failed the run: google_search with bypass_multi_tools_limit on a model it does not serve, which ADK itself sends as an agent tool, so the run worked before narrowing knew of built-ins. RunToolsPlugin now learns each refused tool's entries once per model and keeps them for the build (a reinitialize makes a new chain); a tool that raises adds nothing to leave out, logged at debug once per tool and model. --- CLAUDE.md | 2 +- .../workflow/adk/run_control_plugin.py | 59 ++++++++-- tests/workflow/adk/test_run_control_plugin.py | 111 +++++++++++++++++- 3 files changed, 158 insertions(+), 14 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 9eb7f663..5554cf96 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -108,7 +108,7 @@ agentic-cli/ │ │ │ ├── context_cache_plugin.py # One Gemini cache attempt a turn │ │ │ ├── foreign_reasoning_plugin.py # No model is sent another provider's thoughts │ │ │ ├── subagent_outcome_plugin.py # SubAgentOutcomePlugin: a sub-agent's final answer a model refused or cut, rewritten in place (the refusal notice; the text and the cut-off note) and marked (custom_metadata agentic_cli_outcome), which the run's event processor ends it by; what it reads: finish_reason, error_code, an OTHER stop's JSON reason, the text "OpenAI refusal: "; in each sub-agent type's runner's chain (_agent_plugin_chain), after the raw log and RunControlPlugin; the root's answers untouched -│ │ │ ├── run_control_plugin.py # RunToolsPlugin and RunControlPlugin: a sub-agent run's control at its model calls (Delegations.control of the active run): RunToolsPlugin, first in the chain's head (before the permission gate, whose mark for the built-ins a request carries then follows what is sent, and the fit guard), leaves a narrowed run's other tools out of the request, its tools_dict and declarations (narrow: a call of one finds ADK's stand-in, unknown_tool_result), an ADK built-in it was not given too (built_in_entries: each built-in of the agent's own, google_search, url_context, not in tools_dict, processes a request of its own to show its entries), one it keeps as ADK made it; RunControlPlugin: the messages steered to it appended to its child session and the request before each call (the run's events from then on stamped after them, on_event_callback: ADK stamps an answer before its call's callbacks, and a durable store reads events back by time), the call counted and the last allowed one given STEP_LIMIT_NOTE (with_note: a part of the last user content; its tools stay declared), each answer's usage (adk_tokens) to used, with whether it makes calls, the run's last answer's function calls dropped (drop_calls: an empty text for calls alone); in each sub-agent type's chain, after the raw log, before SubAgentOutcomePlugin +│ │ │ ├── run_control_plugin.py # RunToolsPlugin and RunControlPlugin: a sub-agent run's control at its model calls (Delegations.control of the active run): RunToolsPlugin, first in the chain's head (before the permission gate, whose mark for the built-ins a request carries then follows what is sent, and the fit guard), leaves a narrowed run's other tools out of the request, its tools_dict and declarations (narrow: a call of one finds ADK's stand-in, unknown_tool_result), an ADK built-in it was not given too (built_in_entries: each built-in of the agent's own, google_search, url_context, not in tools_dict, processes a request of its own to show its entries, once per model for the build, kept by the plugin; one that raises there adds nothing to leave out, logged at debug once, built_in_entries_unknown), one it keeps as ADK made it; RunControlPlugin: the messages steered to it appended to its child session and the request before each call (the run's events from then on stamped after them, on_event_callback: ADK stamps an answer before its call's callbacks, and a durable store reads events back by time), the call counted and the last allowed one given STEP_LIMIT_NOTE (with_note: a part of the last user content; its tools stay declared), each answer's usage (adk_tokens) to used, with whether it makes calls, the run's last answer's function calls dropped (drop_calls: an empty text for calls alone); in each sub-agent type's chain, after the raw log, before SubAgentOutcomePlugin │ │ │ ├── log_filters.py # install_log_filters: what ADK would print over the CLI logged at debug instead (the warnings hook, filters by logger name: see Console Output); imports no ADK (the package loads LLMLoggingPlugin on first use); the plugin-manager filter reads overflow_plugin.OVERFLOW_PLUGIN_FAILED as a record comes; BaseCLIApp.run() installs them, once │ │ │ ├── call_clock.py # Every model call timed: CallClock (a clock per call, under its EventActions, held through an error until the answer a later plugin gives; the raw log keeps one too), CallSentPlugin (last: starts it as the request goes out), CallLatencyPlugin (second, after MainAgentPlugin: marks the answer, custom_metadata[LATENCY_KEY], which the event processor reads, call_latency; an answer already marked keeps its mark: mark_latency, the overflow retry's); no adapter sends it │ │ │ └── plugins.py # LLM traffic logging (raw_llm_logging): requests as sent (SentRequestLoggingPlugin, after the fit guard); each record names its agent's model (chosen=: a run's model choice's), the agent and its sub-agent run (the active run); latency per model call (call_clock.CallClock: a clock under the call's EventActions, as the fit guard keeps its copies); usage records go to the file only (the stream's LLM_USAGE is the event processor's), counted as the stream's (adk_usage_event, by the agent's kind: kinds); the summary call and the overflow retry are not logged on ADK (a follow-up) diff --git a/src/agentic_cli/workflow/adk/run_control_plugin.py b/src/agentic_cli/workflow/adk/run_control_plugin.py index 64741644..cb04a5cb 100644 --- a/src/agentic_cli/workflow/adk/run_control_plugin.py +++ b/src/agentic_cli/workflow/adk/run_control_plugin.py @@ -12,7 +12,9 @@ ``url_context``: it runs inside the model, so what it adds to the request is no function declaration and nothing in ``tools_dict``) is left out too, its entries found by having it process a request of its own -(``built_in_entries``); one the run keeps is sent as ADK made it. It runs +(``built_in_entries``), once per model for the build (the plugin keeps them; +a reinitialize makes a new chain): one that raises there adds nothing to +leave out. One the run keeps is sent as ADK made it. It runs before the permission gate, whose mark for the built-ins a request carries then follows what is sent, and before the fit guard, which measures the narrowed request; a skill toolset's instruction text stays in the system @@ -72,6 +74,7 @@ from google.adk.tools.tool_context import ToolContext from google.genai import types +from agentic_cli.logging import Loggers from agentic_cli.workflow.agents.control import STEP_LIMIT_NOTE from agentic_cli.workflow.usage import UsageTotals, adk_tokens @@ -82,6 +85,13 @@ from agentic_cli.workflow.agents.control import RunControl +logger = Loggers.workflow() + +#: What a built-in adds to a request on a model (``built_in_entries``), learned +#: once: by the tool's id and the model, the tool kept with them (an id is only +#: its own while it lives). +Learned = dict[tuple[int, "str | None"], tuple[BaseTool, list[types.Tool]]] + #: How much later than a steered message the run's next events are stamped, #: at least: past what a durable store keeps of a time (``DatabaseSessionService`` #: keeps microseconds), so it reads them back in the order they came. @@ -99,6 +109,8 @@ class RunToolsPlugin(BasePlugin): def __init__(self, control: Callable[[], RunControl | None]) -> None: super().__init__(name="run_tools") self._control = control + # The entries each refused built-in adds, per model, for the build. + self._learned: Learned = {} async def before_model_callback( self, *, callback_context: CallbackContext, llm_request: LlmRequest @@ -106,7 +118,9 @@ async def before_model_callback( control = self._control() if control is None or control.tools is None: return None - built_ins = await built_in_entries(callback_context, llm_request, control.keeps) + built_ins = await built_in_entries( + callback_context, llm_request, control.keeps, learned=self._learned + ) narrow(llm_request, control.keeps, built_ins=built_ins) return None @@ -216,6 +230,8 @@ async def built_in_entries( callback_context: CallbackContext | None, llm_request: LlmRequest, keeps: Callable[[str], bool], + *, + learned: Learned | None = None, ) -> dict[str, list[types.Tool]]: """What each of the running agent's built-ins that ``keeps`` refuses added to ``llm_request``, by the tool's name. @@ -226,10 +242,14 @@ async def built_in_entries( request is a tool entry that is no function declaration. Which entry is whose the request does not say, so each such tool processes a request of its own, for the same model and with a tool context of the same - invocation, as ADK had it process this one (``process_llm_request``), at - each model call of a narrowed run; of what it adds there, the entries that - are more than function declarations are its. No callback context (no - agent to ask): none. + invocation, as ADK had it process this one (``process_llm_request``); of + what it adds there, the entries that are more than function declarations + are its. Given ``learned``, each is asked once per model (its processing + may do work: ``PreloadMemoryTool`` searches the memory) and kept there. A + tool that raises on its own request adds nothing to leave out (logged at + debug, once per model): ``google_search`` with + ``bypass_multi_tools_limit`` on a model it does not serve, which ADK sends + as an agent tool instead. No callback context (no agent to ask): none. """ get = getattr(callback_context, "get_invocation_context", None) invocation = get() if get is not None else None @@ -242,14 +262,33 @@ async def built_in_entries( or tool.name in llm_request.tools_dict ): continue + key = (id(tool), llm_request.model) + known = learned.get(key) if learned is not None else None + if known is not None and known[0] is tool: + found[tool.name] = known[1] + continue alone = LlmRequest(model=llm_request.model) - await tool.process_llm_request( - tool_context=ToolContext(invocation), llm_request=alone - ) - found[tool.name] = [ + error: Exception | None = None + try: + await tool.process_llm_request( + tool_context=ToolContext(invocation), llm_request=alone + ) + except Exception as raised: # noqa: BLE001 - it adds nothing, the run goes on + error = raised + entries = [] if error is not None else [ entry for entry in alone.config.tools or () if entry.model_dump(exclude={"function_declarations"}, exclude_none=True) ] + found[tool.name] = entries + if learned is not None and learned.get(key, (None,))[0] is tool: + continue # another run of the build learned it meanwhile + if learned is not None: + learned[key] = (tool, entries) + if error is not None: + logger.debug( + "built_in_entries_unknown", tool=tool.name, model=llm_request.model, + error=f"{type(error).__name__}: {error}", + ) return found diff --git a/tests/workflow/adk/test_run_control_plugin.py b/tests/workflow/adk/test_run_control_plugin.py index f6dc0c25..0be7927d 100644 --- a/tests/workflow/adk/test_run_control_plugin.py +++ b/tests/workflow/adk/test_run_control_plugin.py @@ -2,9 +2,10 @@ registered, skill and MCP tools, and ADK's built-ins), at its model calls (``workflow/adk/run_control_plugin.py``). -What the plugin does to a request and an answer, alone. Whole turns, on both -backends, are in the contract suite (``TestTheStepLimit``, -``TestTheTokenLimit``, ``TestANarrowedRun``). +What the plugin does to a request and an answer, alone, and one whole ADK run +that only ADK's built-ins concern. Whole turns, on both backends, are in the +contract suite (``TestTheStepLimit``, ``TestTheTokenLimit``, +``TestANarrowedRun``). """ from __future__ import annotations @@ -23,6 +24,7 @@ from google.adk.models.llm_response import LlmResponse # noqa: E402 from google.adk.sessions import InMemorySessionService # noqa: E402 from google.adk.tools import BaseTool, FunctionTool, google_search # noqa: E402 +from google.adk.tools.google_search_tool import GoogleSearchTool # noqa: E402 from google.adk.tools.tool_context import ToolContext # noqa: E402 from google.genai import types # noqa: E402 @@ -382,3 +384,106 @@ async def test_a_run_not_narrowed_keeps_them_all(self): assert (list(request.tools_dict), declared(request)) == ( ["lookup", "fetch_page"], ["lookup", "fetch_page"] ) + + +class CountedBuiltIn(BaseTool): + """A built-in of an app's: it adds a request entry, and counts how often it was asked.""" + + def __init__(self) -> None: + super().__init__(name="counted_search", description="counted_search") + self.asked = 0 + + async def process_llm_request(self, *, tool_context, llm_request) -> None: + self.asked += 1 + llm_request.config.tools = [ + *(llm_request.config.tools or ()), types.Tool(google_search=types.GoogleSearch()), + ] + + +class TestABuiltInsEntriesLearned: + """What a refused built-in adds to a request is learned once per model, for + the build (the plugin, made again by a reinitialize): its + ``process_llm_request`` may do work, and runs again at no model call.""" + + async def test_once_for_two_model_calls_of_a_narrowed_run(self): + counted = CountedBuiltIn() + tools = [FunctionTool(lookup), counted] + context = await agent_context(tools) + control = RunControl(REF, AgentLimits(), tools=frozenset({"lookup"})) + plugin = RunToolsPlugin(lambda: control) + requests = [await processed(context, tools) for _ in range(2)] + asked = counted.asked # ADK's own processing of each request + + for request in requests: + await plugin.before_model_callback(callback_context=context, llm_request=request) + + assert counted.asked - asked == 1 + assert all(not request.config.tools[1:] for request in requests) + + async def test_one_that_cannot_say_drops_nothing_and_is_logged_once(self, monkeypatch): + """A built-in that raises on its own request (ADK's ``google_search`` with + ``bypass_multi_tools_limit`` on a model it does not serve: ADK sends it + as an agent tool instead) is taken to add nothing; its run goes on.""" + from agentic_cli.workflow.adk import run_control_plugin + + logged: list[tuple[str, dict]] = [] + monkeypatch.setattr(run_control_plugin, "logger", type("Recorder", (), { + "debug": staticmethod(lambda event, **fields: logged.append((event, fields))), + })()) + search = GoogleSearchTool(bypass_multi_tools_limit=True) + context = await agent_context([FunctionTool(lookup), search]) + control = RunControl(REF, AgentLimits(), tools=frozenset({"lookup"})) + plugin = RunToolsPlugin(lambda: control) + + for _ in range(2): + request = offering("lookup") + request.model = "claude-sonnet-4-6" + await plugin.before_model_callback(callback_context=context, llm_request=request) + assert request.config.tools[1].google_search is not None # nothing dropped + + assert [(event, fields["tool"], fields["model"]) for event, fields in logged] == [ + ("built_in_entries_unknown", "google_search", "claude-sonnet-4-6"), + ] + assert "not supported" in logged[0][1]["error"] + + +# --- a whole run -------------------------------------------------------------------- + + +@pytest.fixture +def claude_project(tmp_path, monkeypatch): + """A hermetic cwd and HOME, with a fake Claude key.""" + (tmp_path / "home").mkdir() + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("ANTHROPIC_API_KEY", "a-test-key") + + +async def test_a_run_narrowed_without_a_bypass_google_search_on_claude_completes( + claude_project, monkeypatch +): + """ADK sends ``google_search`` with ``bypass_multi_tools_limit`` as an agent + tool, and it serves Gemini alone: on Claude, its own request processing + raises. A run narrowed without it runs as it did before narrowing knew of + built-ins.""" + from tests.workflow.test_subagents_contract import ( + SIDE_CALLS, SUMMARIES, _adk_crew, agent, calls, contract_lookup, delegate, + envelope_read, says, + ) + + crew = _adk_crew( + [agent("coordinator", sub_agents=("researcher",)), + agent("researcher", tools=(contract_lookup, + GoogleSearchTool(bypass_multi_tools_limit=True)))], + {"coordinator": [calls(delegate("researcher", "Find X.", "c1", + tools=["contract_lookup"])), says("Done.")], + "researcher": [says("X is 42.")], SIDE_CALLS: [], SUMMARIES: []}, + monkeypatch, + ) + try: + await crew.turn() + envelope = envelope_read(crew.results_read("coordinator", 1)["c1"]) + finally: + await crew.manager.cleanup() + + assert (envelope["status"], envelope["result"]) == ("completed", "X is 42.")