diff --git a/CHANGELOG.md b/CHANGELOG.md index 032b26af..bde3e9bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -575,9 +575,56 @@ the start of the entry's title. ### Added +- **Agent types started at run time: `AgentConfig.spawnable_by`, free types + and `SubAgentPolicy.spawn_sources`, on both backends.** A type may be + started while the app runs, besides by its parent in the configured tree, + when the app allows it twice: the type's `spawnable_by` (a set of `"agent"`, + `"skill"`, `"user"`; the agent YAML's `spawnable_by: [agent]`; None, the + default, for a type only its parent starts) and the policy's + `spawn_sources` (the same three, `frozenset()` by default: nothing is + started at run time, and an app keeps its `task` as it was, byte for + byte). An agent's `task` call is the `"agent"` source: `task` lists, after + the caller's own sub-agents, the types agents may start, each with its + description (`agentic_cli.workflow.agents.spawn`, provisional: `spawnable`, + `may_spawn`, `can_have_children`; the manager's delegations' + `offered(agent, depth)`), so an agent with no sub-agents of its own gets + `task` when there is a type it may start, and, with `follow_ups`, the + parent's tools and the roster. A run is numbered, recorded and run as a + delegation is: `-`, `started_by: agent:`, parent the + caller, its envelope the call's result. A type in no `sub_agents` list + that sets `spawnable_by` is a free type (`AgentGraph.free_types`, in config + order): never the root, wherever it is listed, in configs or YAML, and built + as any sub-agent is (ADK: a runner of its own; Deep Agents: a graph of its + own). An inheriting type is offered to the root alone. `validate_agent_graph` + takes the policy (`policy=`, keyword; the managers pass theirs) and raises + `AgentGraphError` for a root that sets `spawnable_by` ("Agent 'lead' is the + root agent and cannot set spawnable_by: only a sub-agent type is started at + run time."; with every unreferenced agent free, "Agent graph has no root: + …"), a source that is not one of the three ("Agent 'helper' has + spawnable_by {'agents'}: each source must be one of 'agent', 'skill', + 'user'.") and an empty one; a free type no source the policy enables can + start is a warning (`subagent_type_unreachable`), since an app may enable + sources per install. `SubAgentPolicy` keeps `spawn_sources` as a frozenset + and refuses, with a `ValueError`, a source other than the three + (`SubAgentPolicy.spawn_sources has {'agents'}: each source must be one of + 'agent', 'skill', 'user'.`). +- **`SubAgentPolicy.max_spawn_depth`: from how deep a run may start a type at + run time** (1 by default, a positive int): a run at depth `d` (the root is + 0) is offered the types agents may start only while `d` is below it, so by + default the root alone starts them, and a type started at depth 1 starts + none; the configured tree keeps the depth it declares. `task` is offered + for each run, on both backends: a type that runs at several depths lists + what its run may start (ADK declares it for each request; Deep Agents + rewrites a sub-agent's for each model call), a run offered nothing has no + `task` (a call of it gets the answer for a tool the agent does not have), + and a call naming a type its run is not offered is refused as an unknown + `agent_type`, no run started. When no run a call starts may start one, + `task`'s description says so after its limits: "Sub-agents cannot start + sub-agents." - **The main agent's requests list its open sub-agents, when it can continue - them.** With `SubAgentPolicy(follow_ups=True)` a main agent with sub-agents - (it has `message_agent`) is told which of its own sub-agents are open: a + them.** With `SubAgentPolicy(follow_ups=True)` a main agent that can have + sub-agents (its own, or types it may start at run time; it has + `message_agent`) is told which of its own sub-agents are open: a roster after the memory index, ``, the line `Your sub-agents in this conversation (message_agent continues one):`, then one line per idle, stopped or running instance, newest first, `- (, @@ -675,8 +722,9 @@ the start of the entry's title. session through `self.session`, not as a class attribute with a value. - **A parent's tools that continue its sub-agents, `message_agent`, `stop_agent` and `check_agents`, on both backends, with - `SubAgentPolicy(follow_ups=True)`.** Every agent with sub-agents gets them - beside `task`; with the policy at its defaults (`follow_ups` False) an + `SubAgentPolicy(follow_ups=True)`.** Every agent that can have sub-agents + (its own, or types it may start at run time) gets them beside `task`; with + the policy at its defaults (`follow_ups` False) an agent gets `task` alone. The names are declared by the framework, exempt, as `task` is (`tools/_core/delegation.py`: `FOLLOW_UP_TOOLS`), so an app's `register_tool(name="message_agent")` (or either other) raises, an agent @@ -1898,16 +1946,18 @@ the start of the entry's title. rather than replace it. - **One `task` tool on both backends, which takes a brief.** **Breaking:** ADK offered one tool per sub-agent (`researcher(request=...)`) and Deep - Agents its own `task(description=, subagent_type=)`; now every agent - with sub-agents is offered the framework's `task`, the same on both - (`workflow/agents/brief.py`): `agent_type`, one of its own sub-agents, + Agents its own `task(description=, subagent_type=)`; now every agent with + sub-agents (or types it may start at run time: see Added: **Agent types + started at run time…**) is offered the framework's `task`, the same on both + (`workflow/agents/brief.py`): `agent_type`, one of the types the calling run + may start (its own sub-agents first), each listed in the tool's description with what it does and the brief fields it requires, then the brief, `title` and `objective` (required), `deliverable`, `constraints`, `known` and `done_when`. The run's first message is the task message, `# Task: ` and a section per filled field (`## Objective`, `## Deliverable`, `## Constraints`, `## What is already known`, `## Done when`). A call whose brief misses a field its - type requires, or names a type that is not the caller's, starts no run: + type requires, or names a type its run may not start, starts no run: its result is `{"success": false, "error": ...}` naming what to fix. A instance's first run starts with no plan and no tasks (its follow-ups continue its own), and what it saves stays with it (the status bar's task list is the conversation's alone). On ADK nothing else diff --git a/CLAUDE.md b/CLAUDE.md index 1bc2a327..26d5fc0a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -62,8 +62,8 @@ agentic-cli/ │ │ ├── live_events.py # LiveEvents, merged: events reported inside a turn (reporting/report) reach its stream as they happen; on_stop: a consumer that stops early, before the source is cancelled; emit gives an event that names no run the active one (get_active_run) │ │ ├── usage.py # Token usage: normalized_tokens, the one place a provider's report becomes the counts every LLM_USAGE carries (prompt_tokens every input token, cache included; completion_tokens every output token, thinking included): adk_tokens (ADK's, by provider kind: Gemini's and ADK's Claude adapter's thinking apart from the candidates, OpenAI's inside; an unknown kind's apart), adk_usage_event (the one place ADK's usage becomes an LLM_USAGE: the event processor, the summarizer, generate_simple, the raw log), langchain_tokens (every partner package's, langchain-openai's priority and flex tiers' parts too), llm_usage_event; PURPOSE_* (none: the root's step; subagent, summarization, tool, memory_extraction, side_call) and side_call (what a caller's side calls are for); UsageLedger (a conversation's calls, a row each, each with its latency_ms: totals by run, agent, model, purpose and turn; a row's turn its conversation's while a turn of it runs, as the manager counts them, None in another conversation's turn or a task its turn outlived; by_agent, by_purpose, by_model, run_usage), UsageLedgers (a manager's, by conversation, filed under the turn a call is made in; for the manager's life: a backend switch's new manager starts afresh, a run's totals by model kept with its record; forget: a deleted conversation's) │ │ ├── interrupts.py # What a call a cancel or a crash left open is answered with; OpenCalls (each manager's record, kept by conversation: only that conversation's turns clear it; within it by the instance whose run made each call, run=, the active run by default, so an instance's next run reads what an earlier one recorded; cancelled/take_cancel with instance=: a stopped run of an instance, whose calls a conversation's clear keeps until its next run takes the stop); forget(ref): everything of a deleted conversation, a failed turn's calls and every stop with its cause; unrecorded: a call no record holds; job_for_call: a job of the turn's conversation and of the run whose call it answers (started_by) only; fresh_call_id: the id a call whose provider reused one gets (the old one and a short suffix, `[A-Za-z0-9_-]`, at most 40 characters); `cancelled(cause=)`/`answer(cause=)`: what a call left at its prompt, or running, in a sub-agent run stopped by its parent or a limit is told stopped it (`not_run(cause)`: `Not run: its parent stopped the run before this call ran.`, `its time limit`, `its token limit`; `interrupted_by(cause)`, `INTERRUPTED_BY`: `Interrupted: its parent stopped the run before this call finished; …`), kept with the instance's stop until its next run takes it -│ │ ├── config.py # AgentConfig (brief_required: the brief fields it asks a delegation to fill; limits: its own AgentLimits, over the policy's; continuable: False makes a type one-shot, closed when its run ends), AgentGraph, validate_agent_graph (rules 1-14, the first failure the most fundamental; 11-14: brief_required names brief fields, limits is an AgentLimits, continuable is True or False, the root sets none of the three) -│ │ ├── agent_loader.py # load_agents_from_yaml: the framework's agent YAML → AgentConfig (unknown keys refused; brief_required, continuable, limits: {max_model_calls, timeout, max_tokens} read strictly, AgentLimits checking them); create_workflow_manager_from_yaml +│ │ ├── config.py # AgentConfig (brief_required: the brief fields it asks a delegation to fill; limits: its own AgentLimits, over the policy's; continuable: False makes a type one-shot, closed when its run ends; spawnable_by: who may start it at run time, of SPAWN_SOURCES), AgentGraph (free_types: spawnable_by set, in no sub_agents list, never the root), validate_agent_graph (policy=: the managers pass theirs; rules 1-14, the first failure the most fundamental; 7: one root among the agents that are not free types, spawnable_by checked first, the root setting none; 11-14: brief_required names brief fields, limits is an AgentLimits, continuable is True or False, the root sets none of the three; a free type no enabled source can start warned of, subagent_type_unreachable) +│ │ ├── agent_loader.py # load_agents_from_yaml: the framework's agent YAML → AgentConfig (unknown keys refused; brief_required, continuable, limits: {max_model_calls, timeout, max_tokens} read strictly, AgentLimits checking them; spawnable_by: a list, read as a frozenset); create_workflow_manager_from_yaml │ │ ├── settings.py # Workflow/tool settings schema; models, model_providers, model_roles and permissions in Annotated form (an app's override warns nothing); _merge_shipped_entries: the app's models and model_providers, then the sources', field by field, and the app's permissions before the sources' (at load only); permissions: the union of every trusted source's rules, each list concatenated, a duplicate once (_source_sections reads each source's value as the sources hook filed it) │ │ ├── context.py # ContextBudget/context_budget: when to summarize (window or the 128k floor, budget, trigger, keep; both backends, the CLI); FailedSummaries: a range whose summary failed is skipped for the rest of its turn (keyed by its live events, weakly) until it grows by MIN_SAVING of the trigger; SUMMARY_FAILED: the one warning a failed summary gives, on both backends; is_context_overflow, overflow_message, subagent_overflow_message (a sub-agent's overflow warning, both backends); prompt_room/cut_middle/MIN_PROMPT_ROOM: a side call's prompt in characters its model takes │ │ ├── retry.py # is_rate_limit_error: a provider's 429 told from other failures (a failed turn's ERROR says so: rate_limited, which the CLI reports); no retry logic, the provider clients retry (retry_max_attempts, retry_initial_delay) @@ -84,11 +84,11 @@ agentic-cli/ │ │ │ ├── capabilities.py # Capability, EXEMPT │ │ │ ├── matchers.py # PathMatcher, URLMatcher, ShellMatcher, StringGlobMatcher │ │ │ └── rules.py, store.py, prompt.py (build_request(run=): a sub-agent's prompt opens with its run; is_permission_request: by its perm- id) -│ │ ├── agents/ # Sub-agents: runs.py: the RUN_* statuses (a working run's: RUN_QUEUED, RUN_RUNNING, RUN_INPUT_REQUIRED, RUN_WORKING_STATUSES; a record says running from its start), INSTANCE_RUNNING/IDLE/STOPPED/CLOSED and INSTANCE_STATUSES, InstanceRecord (an instance: parent, depth, title, status, runs, continuable), RunRecord (input: a follow-up's message as written, "" for a first run), AgentRuns (a manager's runs and instances by conversation: run_for names <agent>-<n> and its first run #1 per (conversation, parent run, call id), a new one once it ended; next_run: an instance's next run; instances/instance, kept from the events: a start makes or reopens the instance running, an end sets its status from instance_status, AGENT_INSTANCE a change without a run; number_from: past the instances a conversation's store keeps, a count never lowered; observe records AGENT_RUN under the turn it is reported in; interrupt_open; a record's usage: what the run used, by model, from its end event or the ledger; its plan and tasks: the run's own last, from its end event; RECORDS_VERSION, export (a conversation's records as JSON-safe data: v, saved, numbered, instances, runs) and restore (replaces them; a run found working ends interrupted, INTERRUPTED_ERROR, at the later of its start and saved, its instance idle, closed for a type that is not continuable; each run's end order stored (end), any time or field that does not read ValueError; counters never below an instance kept; ValueError for another version or records that do not read, nothing changed), stored_instance_ids (the instances stored records name; None for none), AgentRuns(on_change=): told each change, never by restore), run_title, result_head, run_instance and run_number (the one reader of a run id: researcher-2#1's instance and number), run_label (how a dialog names a run: researcher-2 (researcher, run 1)), SUBAGENT_ERROR_PREFIX (ADK's old words for a failed delegation, kept for callers), show_as_delegation(result, envelope) (a delegation's TOOL_RESULT shown alike on both backends: the result's first line, or Failed: <error>; metadata["result"] the envelope); a record's brief, started_by, mode and cancelled_by; delegate.py: Delegations (delegate(DelegationRequest) → Delegated and follow_up(FollowUpRequest) → Delegated: the one place a run starts and ends, on both backends (a follow-up is the instance's next run through the same hook, AgentRun.follow_up: refused as an error result, no run, for an unknown or not-yours instance (NOT_YOURS_ERROR, YOURS, NO_SUB_AGENTS), a closed one (CLOSED_ERROR), one the user stopped when an agent sends it (STOPPED_ERROR), a running one (RUNNING_ERROR), one whose type the app no longer has (TYPE_GONE_ERROR) and a blank message (NO_MESSAGE_ERROR); an agent's counts toward max_runs_per_turn, the user's (started_by USER) does not; a run's end carries the status it leaves its instance in: stopped for the user's cancel, closed for a type that is not continuable or the oldest idle one past max_open, else idle; close(conversation, instance, reason=): an idle or stopped instance and its descendants, AGENT_INSTANCE closed; open_calls=: the manager's OpenCalls, whose stop recorded for an instance is taken when the instance is left closed (its end, close, max_open, or a turn that stops a one-shot run), so its calls are freed; max_open ranks by AgentRuns.end_order, the order ends were recorded in, never the clock): the brief read against the caller's own sub-agents, the run named (a turn's first run past the instances its conversation's store keeps: stored=, asked once per conversation per turn, again after a failed or stopped ask), its AGENT_RUN start and end observed and reported, the backend's hook (RunHook: AgentRun → RunAnswer) run in a task of its own with the run active and no tool call, the end by the answer (completed, partial for a cut or the step limit, refused, failed for an error or a raise, with one recoverable ERROR <instance> failed: <reason>, or RunFailed's own words, its result the text the run wrote before it failed (RunFailed(text=); a failed model call the hook's RunAnswer.error, failure_reason, with error_code its type, the warning's code), cancelled by its control with what the hook had), interrupted on its turn's cancel, which wins; the envelope as the result; each run under its RunControl, the type's limits over the policy's, kept while it works: control(run), cancel(run_id, by=, error=), the run alone; a call past max_runs_per_turn the error result RUNS_PER_TURN_ERROR, no run; the stored instances asked under a lock per conversation; forget(conversation): a deleted one's slots, unread messages, waiting closes and asks; each run in a working slot of its conversation's SlotPool, slots(conversation): policy.max_active slots, made on first use and kept, the root taking none: taken right before its hook and its time limit, queued then running while it waits for one, given back at its end, straight back to a caller that waits on it alone; a caller that delegates lends its slot while it waits for its children), DelegationRequest, FollowUpRequest, AgentRun (control, follow_up), RunAnswer, RunFailed, started_by, waiting_on_user (a sub-agent run waiting on the user: input_required, its slot lent, queued while its take-back waits for a slot, then running; nested waits once; request_user_input and the permission engine); records.py: RecordsWriter (each conversation's records written to its store as they change: changed, one write at a time per conversation taking the records as it starts, so changes made meanwhile go together in the next; flush, flush_all, discard (a delete's: what waits dropped, the write under way waited for); a failed write warned once per conversation, subagent_records_not_saved, never raised); slots.py: SlotPool (acquire(priority): a free slot, else a future in a heap by priority, RETURNING before NEW, then arrival; release; lent(slot, on_wait=): the slot lent while its run waits, nested lends once, taken back at RETURNING after (on_wait called when that has to wait), at most one take-back waiting for a slot and none once it is held (a wait that starts while one is queued takes it over, and one handed the slot withdraws any queued since), nothing taken back after a cancel, so a tool's caught timeout around a question leaves its run working without a slot, input_required until its next question is answered (running again, still without a slot) or its end; hand_back(slot, to): a child's slot to its parent waiting on it alone; free, waiting; a cancelled waiter leaves the heap, one handed a slot as it is cancelled hands it on; not asyncio.Semaphore), Slot (held, lent), RETURNING, NEW; control.py: RunControl (one run's: cancel(by=, error=) its task, the first cancel winning, own_cancel for the hook that takes it and returns, finish: the hook's work ended, no cancel after it (ADK's state read loses no answer), timing: the time limit while the hook runs; model_call/at_step_limit/final_call: the step limit, STEP_LIMIT_NOTE on the last allowed call; used: the token limit, against its own calls and side_tokens (its side calls and summaries, from the ledger), an answer past it that makes calls the run's last, cancelled by it, one that makes none its result (calls=); model_call once final stays final; a cancel leaves a task its turn is cancelling alone; steer/take_steering), STEP_LIMIT_NOTE; outcome.py: a sub-agent's refused or cut answer (outcome_of, the refusal notice as Deep Agents 0.7.34 words it, cut_off, cut_off_warning, OPENAI_REFUSAL_PREFIX: how ADK's OpenAI adapters word a refusal); policy.py: SubAgentPolicy (max_active, max_runs_per_turn, limits, max_open) and AgentLimits (max_model_calls, timeout, max_tokens; over: a type's limits over the policy's, field by field, None taking the base's), DEFAULT_LIMITS (100 model calls), frozen and checked as they are made (a ValueError naming the field), as_policy (the one reading of a subagents= argument: a TypeError for anything but a policy or None); brief.py: BRIEF_FIELDS, Brief, BriefError, read_brief (a task call's agent type and brief, against the types its caller may start: the error texts), task_message (a run's first message, a section per filled field; an inheriting type's ends with INHERITED_CONTEXT_NOTE), task_parameters and task_description (task's schema and description, the same for both backends; limit_sentences: the limits it states, "At most <max_active> sub-agents work at once; more calls in one response wait for a free slot. At most <max_runs_per_turn> runs per turn."); envelope.py: envelope (a delegation run's result: success only for completed, a one-line error, cancelled_by for a cancelled run), read_envelope (a dict or its JSON text, else None; never raises), view_notice (`VIEW_NOTICE`: what the root is told once the user worked with an instance), the limit and interrupted error texts; `Delegations.message` (an idle instance's follow-up; a running one's run steered, or with `interrupt` cancelled by its parent and followed up; one run per instance, so of two messages to one idle instance in one answer the first runs and the second is steered into it), `stop` (a running instance's run cancelled by its parent, the instance idle; `close` closes it and its descendants, a running one's at its run's end), `check`, `steer(conversation, run, message)`, `stop_by_user`/`close_by_user` (`STOPPED_BY_USER_ERROR`, `CLOSED_BY_USER`: a running run cancelled by the user and waited for), `stop_cause(run)` and `cancel(..., conversation=)`; a message steered to a run that its transcript does not hold when it ends (`RunControl.unstored`) is kept for the instance's next run; a run whose parent's run its control stopped ends `cancelled` by its parent (`its parent's run was stopped`); a run that did not complete fully names its open tasks in its envelope (`envelope(open_tasks=)`, `open_task_descriptions`) and a cancelled run keeps its plan and tasks; `SubAgentPolicy.follow_ups`; brief.py: `follow_up_description`/`follow_up_parameters` (the parent's tools' texts); follow_ups.py: `call_follow_up_tool` (a message_agent, stop_agent or check_agents call as the run in progress); roster.py: roster_text (the main agent's open sub-agents, newest first, one line each, ROSTER_OPEN/ROSTER_HEADER/ROSTER_CLOSE, at most ROSTER_MAX characters in whole lines, "" for none open), Rosters (a snapshot per conversation, as MemoryIndex: now, forget, clear; the root's own instances, parent root) +│ │ ├── agents/ # Sub-agents: runs.py: the RUN_* statuses (a working run's: RUN_QUEUED, RUN_RUNNING, RUN_INPUT_REQUIRED, RUN_WORKING_STATUSES; a record says running from its start), INSTANCE_RUNNING/IDLE/STOPPED/CLOSED and INSTANCE_STATUSES, InstanceRecord (an instance: parent, depth, title, status, runs, continuable), RunRecord (input: a follow-up's message as written, "" for a first run), AgentRuns (a manager's runs and instances by conversation: run_for names <agent>-<n> and its first run #1 per (conversation, parent run, call id), a new one once it ended; next_run: an instance's next run; instances/instance, kept from the events: a start makes or reopens the instance running, an end sets its status from instance_status, AGENT_INSTANCE a change without a run; number_from: past the instances a conversation's store keeps, a count never lowered; observe records AGENT_RUN under the turn it is reported in; interrupt_open; a record's usage: what the run used, by model, from its end event or the ledger; its plan and tasks: the run's own last, from its end event; RECORDS_VERSION, export (a conversation's records as JSON-safe data: v, saved, numbered, instances, runs) and restore (replaces them; a run found working ends interrupted, INTERRUPTED_ERROR, at the later of its start and saved, its instance idle, closed for a type that is not continuable; each run's end order stored (end), any time or field that does not read ValueError; counters never below an instance kept; ValueError for another version or records that do not read, nothing changed), stored_instance_ids (the instances stored records name; None for none), AgentRuns(on_change=): told each change, never by restore), run_title, result_head, run_instance and run_number (the one reader of a run id: researcher-2#1's instance and number), run_label (how a dialog names a run: researcher-2 (researcher, run 1)), SUBAGENT_ERROR_PREFIX (ADK's old words for a failed delegation, kept for callers), show_as_delegation(result, envelope) (a delegation's TOOL_RESULT shown alike on both backends: the result's first line, or Failed: <error>; metadata["result"] the envelope); a record's brief, started_by, mode and cancelled_by; delegate.py: Delegations (delegate(DelegationRequest) → Delegated and follow_up(FollowUpRequest) → Delegated: the one place a run starts and ends, on both backends (a follow-up is the instance's next run through the same hook, AgentRun.follow_up: refused as an error result, no run, for an unknown or not-yours instance (NOT_YOURS_ERROR, YOURS, NO_SUB_AGENTS), a closed one (CLOSED_ERROR), one the user stopped when an agent sends it (STOPPED_ERROR), a running one (RUNNING_ERROR), one whose type the app no longer has (TYPE_GONE_ERROR) and a blank message (NO_MESSAGE_ERROR); an agent's counts toward max_runs_per_turn, the user's (started_by USER) does not; a run's end carries the status it leaves its instance in: stopped for the user's cancel, closed for a type that is not continuable or the oldest idle one past max_open, else idle; close(conversation, instance, reason=): an idle or stopped instance and its descendants, AGENT_INSTANCE closed; open_calls=: the manager's OpenCalls, whose stop recorded for an instance is taken when the instance is left closed (its end, close, max_open, or a turn that stops a one-shot run), so its calls are freed; max_open ranks by AgentRuns.end_order, the order ends were recorded in, never the clock): the brief read against what the calling run may start (offered(agent, depth): its own sub-agents, then, while may_spawn, the types agents may start at run time, an inheriting one for the root alone; task_offer: task's TaskOffer for that run, None for nothing), then start(StartRequest), the one entry for a first run (counted unless the user's, started_by as given; who may start the type is the asker's to check), the run named (a turn's first run past the instances its conversation's store keeps: stored=, asked once per conversation per turn, again after a failed or stopped ask), its AGENT_RUN start and end observed and reported, the backend's hook (RunHook: AgentRun → RunAnswer) run in a task of its own with the run active and no tool call, the end by the answer (completed, partial for a cut or the step limit, refused, failed for an error or a raise, with one recoverable ERROR <instance> failed: <reason>, or RunFailed's own words, its result the text the run wrote before it failed (RunFailed(text=); a failed model call the hook's RunAnswer.error, failure_reason, with error_code its type, the warning's code), cancelled by its control with what the hook had), interrupted on its turn's cancel, which wins; the envelope as the result; each run under its RunControl, the type's limits over the policy's, kept while it works: control(run), cancel(run_id, by=, error=), the run alone; a call past max_runs_per_turn the error result RUNS_PER_TURN_ERROR, no run; the stored instances asked under a lock per conversation; forget(conversation): a deleted one's slots, unread messages, waiting closes and asks; each run in a working slot of its conversation's SlotPool, slots(conversation): policy.max_active slots, made on first use and kept, the root taking none: taken right before its hook and its time limit, queued then running while it waits for one, given back at its end, straight back to a caller that waits on it alone; a caller that delegates lends its slot while it waits for its children), DelegationRequest, StartRequest, FollowUpRequest, AgentRun (control, follow_up), RunAnswer, RunFailed, started_by, waiting_on_user (a sub-agent run waiting on the user: input_required, its slot lent, queued while its take-back waits for a slot, then running; nested waits once; request_user_input and the permission engine); records.py: RecordsWriter (each conversation's records written to its store as they change: changed, one write at a time per conversation taking the records as it starts, so changes made meanwhile go together in the next; flush, flush_all, discard (a delete's: what waits dropped, the write under way waited for); a failed write warned once per conversation, subagent_records_not_saved, never raised); slots.py: SlotPool (acquire(priority): a free slot, else a future in a heap by priority, RETURNING before NEW, then arrival; release; lent(slot, on_wait=): the slot lent while its run waits, nested lends once, taken back at RETURNING after (on_wait called when that has to wait), at most one take-back waiting for a slot and none once it is held (a wait that starts while one is queued takes it over, and one handed the slot withdraws any queued since), nothing taken back after a cancel, so a tool's caught timeout around a question leaves its run working without a slot, input_required until its next question is answered (running again, still without a slot) or its end; hand_back(slot, to): a child's slot to its parent waiting on it alone; free, waiting; a cancelled waiter leaves the heap, one handed a slot as it is cancelled hands it on; not asyncio.Semaphore), Slot (held, lent), RETURNING, NEW; control.py: RunControl (one run's: cancel(by=, error=) its task, the first cancel winning, own_cancel for the hook that takes it and returns, finish: the hook's work ended, no cancel after it (ADK's state read loses no answer), timing: the time limit while the hook runs; model_call/at_step_limit/final_call: the step limit, STEP_LIMIT_NOTE on the last allowed call; used: the token limit, against its own calls and side_tokens (its side calls and summaries, from the ledger), an answer past it that makes calls the run's last, cancelled by it, one that makes none its result (calls=); model_call once final stays final; a cancel leaves a task its turn is cancelling alone; steer/take_steering), STEP_LIMIT_NOTE; outcome.py: a sub-agent's refused or cut answer (outcome_of, the refusal notice as Deep Agents 0.7.34 words it, cut_off, cut_off_warning, OPENAI_REFUSAL_PREFIX: how ADK's OpenAI adapters word a refusal); policy.py: SubAgentPolicy (max_active, max_runs_per_turn, limits, max_open, follow_ups, spawn_sources: of SPAWN_SOURCES, kept as a frozenset, max_spawn_depth) and AgentLimits (max_model_calls, timeout, max_tokens; over: a type's limits over the policy's, field by field, None taking the base's), DEFAULT_LIMITS (100 model calls), frozen and checked as they are made (a ValueError naming the field), as_policy (the one reading of a subagents= argument: a TypeError for anything but a policy or None); brief.py: BRIEF_FIELDS, Brief, BriefError, read_brief (a task call's agent type and brief, against the types its caller may start: the error texts), task_message (a run's first message, a section per filled field; an inheriting type's ends with INHERITED_CONTEXT_NOTE), task_parameters and task_description (task's schema and description, the same for both backends; limit_sentences: the limits it states, "At most <max_active> sub-agents work at once; more calls in one response wait for a free slot. At most <max_runs_per_turn> runs per turn.", then DEPTH_SENTENCE, "Sub-agents cannot start sub-agents.", when no run the call starts may start one; warn=False for a description made per run), TaskOffer and task_offer (both, for the types one run may start); envelope.py: envelope (a delegation run's result: success only for completed, a one-line error, cancelled_by for a cancelled run), read_envelope (a dict or its JSON text, else None; never raises), view_notice (`VIEW_NOTICE`: what the root is told once the user worked with an instance), the limit and interrupted error texts; `Delegations.message` (an idle instance's follow-up; a running one's run steered, or with `interrupt` cancelled by its parent and followed up; one run per instance, so of two messages to one idle instance in one answer the first runs and the second is steered into it), `stop` (a running instance's run cancelled by its parent, the instance idle; `close` closes it and its descendants, a running one's at its run's end), `check`, `steer(conversation, run, message)`, `stop_by_user`/`close_by_user` (`STOPPED_BY_USER_ERROR`, `CLOSED_BY_USER`: a running run cancelled by the user and waited for), `stop_cause(run)` and `cancel(..., conversation=)`; a message steered to a run that its transcript does not hold when it ends (`RunControl.unstored`) is kept for the instance's next run; a run whose parent's run its control stopped ends `cancelled` by its parent (`its parent's run was stopped`); a run that did not complete fully names its open tasks in its envelope (`envelope(open_tasks=)`, `open_task_descriptions`) and a cancelled run keeps its plan and tasks; `SubAgentPolicy.follow_ups`; brief.py: `follow_up_description`/`follow_up_parameters` (the parent's tools' texts); follow_ups.py: `call_follow_up_tool` (a message_agent, stop_agent or check_agents call as the run in progress); spawn.py: spawnable (the types a source may start at run time: the policy's spawn_sources and the type's spawnable_by), may_spawn (depth below max_spawn_depth), can_have_children (who is built with task, and with follow_ups the parent's tools and the roster: sub-agents, or a type agents may start while the root or runs below it may), depth_sentence_applies, AGENT_SOURCE/SKILL_SOURCE/USER_SOURCE; no backend imports; roster.py: roster_text (the main agent's open sub-agents, newest first, one line each, ROSTER_OPEN/ROSTER_HEADER/ROSTER_CLOSE, at most ROSTER_MAX characters in whole lines, "" for none open), Rosters (a snapshot per conversation, as MemoryIndex: now, forget, clear; the root's own instances, parent root) │ │ ├── adk/ # ADK orchestrator │ │ │ ├── manager.py # GoogleADKWorkflowManager (the agents built from configs or, adk_config_path, by ADK from a native YAML (library-only: no BaseCLIApp starts one; loaded once per manager at the first _validate_agent_graph (_native_root: the settings' keys exported first; a retry, a model switch and a start after cleanup build on the same tree, whose toolsets the closed runner left reusable), its agents' models resolved leniently in _resolve_extra_models, the base's hook, its registered tools' services detected; configs passed with it ignored, adk_native_configs_ignored): the only difference; _do_initialize builds the app from the tree alone, _build_app → ADKBuild, through the hooks _plugin_chain (the whole chain, top to bottom, its head _init_plugins), _compaction_config (None for a root without a budget), _context_cache_config, _agent_model_refs; the event processor built from the build; a config-built agent's prompt as an instruction provider, sent as written: no `{name}` state injection; _compact_turn: ADK's compaction once, in the base's compact turn; supports_compact False once built for a root without a budget (_no_compact_support says why); the job resume hooks: _conversation_exists (the session read without its events, num_recent_events=0), _deliver_job_notice (the notice, for every app); _run_config: the agents' synchronous tools run in ADK's tool thread pool, 8 workers; _run_and_stream: a run that fails yields the turn's one ERROR, last, none after an ERROR already yielded, and keeps the record of its calls that returned for the next turn (OpenCalls.failed; _answer_left_open forgets it once its answers are stored); the agents: _create_agents builds each config's agent on its own (_agents, by name; no ADK sub_agents), a delegating one with a TaskTool (its own tool named task: AgentGraphError); a runner per sub-agent type (_agent_runners: NoAfterTurnCompactionRunner on App(name=child_app(app_name), root_agent=the type's agent, plugins=_agent_plugin_chain(agent), the app's context cache, no compaction) over the session service, closed with the main runner by _detach_backend, rebuilt by every initialization); _run_agent, the base's hook: the instance's child session (_child_session: a first run makes it from run.state and an inheriting instance's copied events, once; never one the store keeps, whose instance numbering goes past: ADK's create_session refuses it, and the run fails; a follow-up takes the stored session, answers the calls an earlier run left open there (left_open_by) and passes the caller's mark when it holds none; one the store lost is made as a first run's), _stored_instances (the base's hook: the highest instance number of each type the conversation's child sessions keep), the type's runner on the task message (a follow-up's own message) with an abort signal set before it is closed, a run-mode ADKEventProcessor, the raw log's records reported as they come (_report_raw_log); a model's failure raised as the provider's (_plugin_cause), an overflow RunFailed, a reply that is no answer RunAnswer(error=), the shared keys it changed read back) │ │ │ ├── build.py # ADKBuild (root, reply_agents, plugins, compaction, cache, models); load_native_root (from_config at validation; what ADK cannot load, wrapped as AgentGraphError naming the file, ADK's error the cause; a root that is not an LlmAgent, a name used twice in the tree and a task-mode agent refused, AgentGraphError naming it; ensure_direct_anthropic); what the run reads of any tree: reply_agents (the root and the chat-mode agents it can transfer to), own_after_tool_agents (left out by the cap) -│ │ │ ├── task_tool.py # TaskTool: the framework's task on ADK (a BaseTool; its declaration task_parameters' JSON schema, parameters_json_schema; its description task_description; bound to the task declaration, an exact TaskTool only): a call → Delegations.delegate, the run's shared-key changes written to the caller's state, the envelope returned as JSON text (ADK's OpenAI Responses adapter sends only a dict's result); SHARED_KEYS (the outside-content mark alone); inherited_events (an inheriting run's history: the session's root-visible events, copied); FollowUpTool (with follow_ups: message_agent, stop_agent, check_agents, each an exact FollowUpTool bound to its declaration, the result as JSON text; an own tool of one of their names fails the build) +│ │ │ ├── task_tool.py # TaskTool: the framework's task on ADK (a BaseTool; declared for each request what the run that asks may start, Delegations.task_offer by get_active_run's depth, the root's own requests 0: task_parameters' JSON schema, parameters_json_schema, and task_description; None, no task declared, for a run offered nothing; its description attribute the offer at its first depth, warned of once; bound to the task declaration, an exact TaskTool only): a call → Delegations.delegate, the run's shared-key changes written to the caller's state, the envelope returned as JSON text (ADK's OpenAI Responses adapter sends only a dict's result); SHARED_KEYS (the outside-content mark alone); inherited_events (an inheriting run's history: the session's root-visible events, copied); FollowUpTool (with follow_ups: message_agent, stop_agent, check_agents, each an exact FollowUpTool bound to its declaration, the result as JSON text; an own tool of one of their names fails the build) │ │ │ ├── compaction.py # AgentCliSummarizer (main agent only; summary_range, render_events; its usage normalized, timed and recorded in the conversation's ledger, ledgers, as soon as the call answers: an empty summary's too; on_written: a summary written drops the conversation's memory index snapshot), MainAgentPlugin (the running agent, first in every chain), NoAfterTurnCompactionRunner, compact_session │ │ │ ├── fit_guard_plugin.py # FitGuardPlugin: a request over its agent's budget has its oldest turns left out (drop_turns); what opens the conversation, the memory index, the roster, then a summary (protected_head, never dropped; is_roster), folded into the next user text (fold_summary); in a sub-agent type's chain (keep_task) a run's task message, its invocation's user content, and its instance's brief (brief_of: the event of its child session whose state delta set BRIEF_KEY) never dropped either, the first kept turn joining them (a message steered after a tool result starts a turn); request_as_seen │ │ │ ├── overflow_plugin.py # OverflowPlugin (OVERFLOW_PLUGIN_FAILED: ADK's wrapper of its errors, which the manager unwraps): a provider's overflow summarized (the root; the retry: the memory index and roster that open the request, the summary and the turns it kept) or trimmed (a sub-agent's keeping its task message and its instance's brief), retried once (the retry timed around its own request: call_clock.mark_latency), then CONTEXT_OVERFLOW: overflow_message for an agent that replies (reply_agents), subagent_overflow_message for a sub-agent's run (root None on its runner), which fails it; a sub-agent's trimmed retry keeps its task message (keep_task) @@ -113,10 +113,10 @@ agentic-cli/ │ │ │ └── plugins.py # LLM traffic logging (raw_llm_logging): requests as sent (SentRequestLoggingPlugin, after the fit guard); each record names its agent's model, the agent and its sub-agent run (the active run); latency per model call (call_clock.CallClock: a clock under the call's EventActions, as the fit guard keeps its copies); usage records go to the file only (the stream's LLM_USAGE is the event processor's), counted as the stream's (adk_usage_event, by the agent's kind: kinds); the summary call and the overflow retry are not logged on ADK (a follow-up) │ │ ├── deepagents/ # Deep Agents orchestrator (deepagents extra); imports neither adk/ nor langgraph/ │ │ │ ├── manager.py # DeepAgentsWorkflowManager (turns, sessions, the release hooks: the agents and MCP sessions, the checkpointer and index; MCP, skills, the job resume hooks (_conversation_exists, _deliver_job_notice), _compact_turn; _run_agent, the base's hook: the type's graph (_agent_graphs) astreamed in the run's task with var_child_runnable_config cleared, so its chunks reach its own loop alone, through a run-mode processor and a RunCallback of its own; the answer the last AIMessage with text, its outcome mark, the shared keys it changed by Deep Agents' _is_unchanged rule (copied), an overflow RunFailed) -│ │ │ ├── agent_builder.py # build_agent_tree: one create_agent per AgentConfig, each on its own (graphs=: kept by name for _run_agent; every agent compiled on the manager's checkpointer, a tree built without one compiling its sub-agents with none); a delegating agent's task from task_tool.build_task_tool (delegations=), its own tool named task an AgentGraphError; every sub-agent's RunControlMiddleware (delegations=), inside its SubAgentOutcomeMiddleware -│ │ │ ├── middleware.py # InterruptedCallsMiddleware (each call recorded and answered as the active run's; a call id the agent's state holds renamed as the answer arrives, awrap_model_call outside the model side, fresh_call_id; a call answered by a result of its id between its answer and the next), PermissionMiddleware, ToolResultCapMiddleware, ToolCallErrorMiddleware, ActiveToolCallMiddleware (each call the active tool call around its tool), ForeignReasoningMiddleware, ContextOverflowMiddleware, MemoryIndexMiddleware (the root's memory index first in the first human message of each request), RosterMiddleware (outside it: the root's roster of its open sub-agents, after the index), SubAgentOutcomeMiddleware (outermost on every sub-agent's model side: a refused or cut final answer rewritten, its reasoning kept, and marked, response_metadata["agentic_cli"]["outcome"], beside the other marks; a call that raises passes), RunControlMiddleware (inside it: a sub-agent run's control at its model calls, Delegations.control of the active run: the messages steered to it added to its state before each call, abefore_model; the call counted and the last allowed one given STEP_LIMIT_NOTE, with_note, its tools still bound; each answer's usage, langchain_tokens, to used; the run's last answer's tool calls dropped, without_calls); 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 +│ │ │ ├── agent_builder.py # build_agent_tree: one create_agent per AgentConfig, each on its own (graphs=: kept by name for _run_agent; every agent compiled on the manager's checkpointer, a tree built without one compiling its sub-agents with none); root=: the graph's root (a free type listed first is no root); each agent can_have_children says gets task from task_tool.build_task_tool (delegations=), its own tool named task an AgentGraphError; every sub-agent's RunControlMiddleware (delegations=), inside its SubAgentOutcomeMiddleware +│ │ │ ├── middleware.py # InterruptedCallsMiddleware (each call recorded and answered as the active run's; a call id the agent's state holds renamed as the answer arrives, awrap_model_call outside the model side, fresh_call_id; a call answered by a result of its id between its answer and the next), PermissionMiddleware, ToolResultCapMiddleware, ToolCallErrorMiddleware, ActiveToolCallMiddleware (each call the active tool call around its tool), ForeignReasoningMiddleware, ContextOverflowMiddleware, MemoryIndexMiddleware (the root's memory index first in the first human message of each request), RosterMiddleware (outside it: the root's roster of its open sub-agents, after the index), SubAgentOutcomeMiddleware (outermost on every sub-agent's model side: a refused or cut final answer rewritten, its reasoning kept, and marked, response_metadata["agentic_cli"]["outcome"], beside the other marks; a call that raises passes), RunControlMiddleware (inside it: a sub-agent run's control at its model calls, Delegations.control of the active run: the messages steered to it added to its state before each call, abefore_model; the call counted and the last allowed one given STEP_LIMIT_NOTE, with_note, its tools still bound; each answer's usage, langchain_tokens, to used; the run's last answer's tool calls dropped, without_calls; the framework's task among the request's tools, by identity, given the schema and description the run is offered, Delegations.task_offer by its depth, or left out when it is offered nothing); mark_latency/answer_latency: the run callback's mark of how long a call took, response_metadata["agentic_cli"]["latency_ms"]; only the gate has a synchronous tool or model wrapper (it denies the sync tool call), the rest wrap with the async ones (`InterruptedCallsMiddleware.before_agent` is a node hook, synchronous, run on async turns too): turns run through `astream`, and a synchronous run of a graph fails at the first without a sync wrapper, LangChain's NotImplementedError │ │ │ ├── tools.py # to_langchain_tools: a callable → StructuredTool whose .func/.coroutine is it -│ │ │ ├── task_tool.py # build_task_tool: the framework's task on Deep Agents (a StructuredTool over task_parameters' JSON schema, bound to the task declaration): a call → Delegations.delegate, whose shared-key change (the outside-content mark) and envelope (JSON, the ToolMessage) come back as one Command; SHARED_KEYS; inherited_messages (an inheriting run's history: the state's messages, the summary event applied, less the message that called task); build_follow_up_tools (with follow_ups: message_agent, stop_agent, check_agents, each a StructuredTool bound to its declaration, answering as task does) +│ │ │ ├── task_tool.py # build_task_tool: the framework's task on Deep Agents (a StructuredTool over what a run at the agent's first depth is offered, task_offer: the root's fixed, a sub-agent's rewritten per call by RunControlMiddleware; bound to the task declaration; a call by a run offered nothing answered unknown_tool_result, as ADK answers a tool it did not declare): a call → Delegations.delegate, whose shared-key change (the outside-content mark) and envelope (JSON, the ToolMessage) come back as one Command; SHARED_KEYS; inherited_messages (an inheriting run's history: the state's messages, the summary event applied, less the message that called task); build_follow_up_tools (with follow_ups: message_agent, stop_agent, check_agents, each a StructuredTool bound to its declaration, answering as task does) │ │ │ ├── event_processor.py # DeepAgentsEventProcessor (stream → WorkflowEvent, each call's LLM_USAGE, with its latency (answer_latency), recorded in the conversation's usage ledger before on_event, a run's end with what it used; every event its processor's agent's and run's (run=: a processor for one sub-agent run, its text activity, no TASK_PROGRESS), from the root namespace's items only (a graph a tool runs streams in its own); the task call's TOOL_RESULT shown as on ADK, from its envelope: show_as_delegation); RunCallback (every model call timed, its answer marked with its latency before any middleware sees it; a summary's usage recorded in the conversation's ledger; what a node reports inside itself, through the turn's `LiveEvents`: required; `compact()` called outside a reporting context gets one nobody reads) │ │ │ ├── sessions.py # thread_id(SessionRef), instance_thread_id and instance_run_config (a sub-agent instance's thread, [app, user, session, instance], its checkpoints' metadata carrying instance and thread_kind: instance), CheckpointSessions (instances: read from the instance threads' first input checkpoints (source input, step -1: one a thread, no later one; each holds its first run's input, which the saver decodes: the brief, and an inheriting instance's copy of its parent's conversation); stored_instances: those threads and the stored records' ids and counters; agent_records/save_agent_records/delete_agent_records: a conversation's sub-agent records, an item of the store beside the checkpointer under (agentic_cli, agents, <app>, <user>), keyed by the session id; delete: those threads first, then the records, then the conversation; a first run onto a thread the store keeps fails (the manager's check); rows from an index in the store beside the checkpointer, written as a turn starts (its input counted: a killed process still lists it), then from the newest root checkpoint as it ends and after /compact; a database from before it scanned once per app and user), job notifications and notices to the root (`notice_message`, `tell_root`; `is_notice`: either, left out of recent and a row); open_sessions: a store's conversations for a reader, without the manager (empty without the checkpoints table, looked at read-only before any setup) │ │ │ ├── summarization.py # Each agent's thresholds from its budget (the manager's _budgets, given to build_agent_tree(budgets=); context_budget when none); NoArchiveBackend; history filters; compact()'s cut, summary and event (marked: the count reported before it is no trigger, _should_summarize); OverflowMapped: the summary model's overflows as ContextOverflowError, inside its retry; a request's count includes the memory index (index=) and the roster (roster=), and a summary written drops their snapshots before the request goes on (on_written=); an instance's brief (brief_message: its first run's task message, marked; is_brief, brief_of: the last marked), restated first in each summary message of its thread that stands for it (_partition_messages, _build_new_messages_with_path, per call through _BRIEF) @@ -254,7 +254,7 @@ Workflow: - **Tool error handling**: All tools return `{"success": bool, ...}` dicts. Never raise `ToolError`. An exception that still escapes a tool is a bug, but it costs one call rather than the turn: on ADK, `workflow/adk/tool_error_plugin.py::ToolErrorPlugin` turns it into an error dict; on Deep Agents, `workflow/deepagents/middleware.py::ToolCallErrorMiddleware`, inside the permission gate, gives the same result, `{"success": false, "error": "<tool> failed: <Type>: <message>"}` cut to 500 characters (both use `workflow/tool_errors.py`). A call to a tool name the agent does not have gets ADK's own text, its first two lines (`unknown_tool_result`: "nope failed: ValueError: Tool 'nope' not found." and the agent's tools by name), logged `tool_not_found` at info (the model's mistake): on ADK the permission gate lets ADK's stand-in through (`is_unknown_tool`: a bare `BaseTool` described "Tool not found", which runs nothing; contract-tested) and `ToolErrorPlugin` answers its lookup error; on Deep Agents the gate answers it. It catches `Exception`, never `BaseException`, so cancelling still cancels (google-adk 2.15 hands a cancelled call's `CancelledError` to `ToolErrorPlugin` for cleanup, ignoring the answer: it answers nothing and logs `tool_cancelled` at debug, no warning). `task` raises nothing into it: a sub-agent's model or run failing (its summary or overflow included: its own tools' errors are results already) fails the run, whose envelope its parent reads (`error`: the provider's reason; on ADK out of ADK's plugin wrapper), reported at once through the turn's live events as one recoverable `ERROR`, `<instance> failed: <reason>`, the run's: the coordinator carries on. A sub-agent's overflow (still too long after its summary or trim) fails its run, on both backends, in the words of ADK's overflow handler, `<agent>: the request no longer fits <model>'s context window.` with `error_code` `CONTEXT_OVERFLOW` (`context.py::subagent_overflow_message`): ADK's `OverflowPlugin` answers the run's model call with it, Deep Agents' manager raises it (`RunFailed`). A refusal is no exception here (the framework adds no `ModelRefusalMiddleware`): a sub-agent whose final answer a model refused ends its run `refused`, and its parent reads, as its envelope's result, Deep Agents 0.7.34's notice ("The subagent stopped because a model refused the request. … Retrying the same request is unlikely to succeed; rephrase it or continue without it."), on both backends and whichever deepagents the pin installs (0.7.28 has no notice of its own; 0.7.34+ finds no refusal block left to word again); an answer cut at the output limit keeps its text, followed by `[cut off at the output limit]`, and its run ends `completed` and `partial`, with one recoverable warning ("<instance>'s answer was cut off at the output limit"); the answer's thoughts or reasoning are kept. ADK's `SubAgentOutcomePlugin` and Deep Agents' `SubAgentOutcomeMiddleware` rewrite and mark the answer, by `workflow/agents/outcome.py`. On ADK the plugin reads the answer's `finish_reason` (Claude's `refusal` and a Chat Completions `content_filter` arrive as `SAFETY`, `max_tokens` and `length` as `MAX_TOKENS`, Gemini's as themselves), the `error_code` ADK sets on an answer with no content (a Gemini prompt's `block_reason`), the `reason` an `OTHER` stop names in its JSON error message (ADK's OpenAI Responses adapter's `incomplete_details`, `content_filter` among them) and a text part `OpenAI refusal: <text>` (that adapter's refusal, and `OpenAICompatibleLlm`'s of a Chat Completions `refusal`, which ADK's class drops). On Deep Agents the middleware reads `response_metadata`'s `stop_reason` (ChatAnthropic), `finish_reason` (ChatOpenAI, ChatGoogleGenerativeAI), `incomplete_details.reason` (the Responses API) and `prompt_feedback.block_reason` (a Gemini prompt block), and a refusal the answer holds (a refusal block, standard or `non_standard`, or `additional_kwargs["refusal"]`). The root's own answers reach the user as their model gave them: on ADK a root's refusal with no answer (Claude's, Gemini's) is still the turn's one `ERROR` ("<model> returned no answer"), and a root on OpenRouter or an OpenAI-compatible server replies "OpenAI refusal: <text>". On both backends the root's own failure leaves the run: the turn's one `ERROR`. A gate or error result goes back as the call's `ToolMessage` with `status="error"`. LangGraph's `ToolNode` runs with `handle_tool_errors=True`. - **Tool result cap**: every tool result passes `workflow/tool_output.py::cap_tool_result` (registered, MCP and skill tools, `job_result`, a delegation's envelope on either backend, and the envelope a view's notice carries: `BaseWorkflowManager._user_ran` keeps `instance_result` capped): one over `tool_result_max_chars` is cut to its shape and as much of its head and tail as fits (the kept length is bisected, since JSON escapes vary), with a note (under `truncated`, or appended to a string) pointing at its full output in `./.{app_name}/tool-output/`, written for `read_file` to page by lines (lines over 2,000 characters split). A string that holds a JSON object (`json_object`: a delegation's envelope, which both task tools write unescaped, `ensure_ascii=False`; a framework tool's dict in a Deep Agents `ToolMessage`) is cut as that dict and given back as its JSON text, so the parent reads JSON still, on both backends. On ADK, `workflow/adk/tool_result_cap_plugin.py::ToolResultCapPlugin` is registered after `InterruptedCallsPlugin`, since ADK stops at the first `after_tool_callback` that returns a value, and it leaves out an agent with `after_tool_callback`s of its own (a native YAML app's, `build.own_after_tool_agents`), which ADK would skip once the cap answered. ADK's Claude and OpenAI Responses adapters send only a result's `content`, else its `result`, so the plugin also puts the note there (`_note_where_sent`). On Deep Agents, `ToolResultCapMiddleware` sits between the permission gate and `ToolCallErrorMiddleware`, so an error result is capped too, and reads a `ToolMessage` (its text cut by the cap's string rule, text blocks joined into the first) and each `ToolMessage` of a `Command`. A call of the framework's `read_file` (by identity, as each gate resolves tools) on a saved output is cut without a second save. Saving never fails the call (`tool_output_not_saved` warns once per folder, then debug), and a cap that raises leaves the result uncut (`tool_result_cap_failed` at warning, its traceback at debug). - **Summarizing on ADK (main agent only)**: every app's App (a native ADK YAML app's too, when its root's model has a context budget) has ADK's `EventsCompactionConfig` with `workflow/adk/compaction.py::AgentCliSummarizer` at the root's trigger (`context_budget`, as on Deep Agents); ADK checks before every agent's model call, and `MainAgentPlugin` (the first plugin) records the running agent in a ContextVar, so the summarizer writes only for the root (a sub-agent's run, on its type's runner, has no compaction config at all: a sub-agent compacting the shared session lost its brief and looped, 100 requests in one turn, offline). The summarizer picks its own range before paying for anything (`summary_range`: the newest `keep` tokens and the current turn kept, a cut only where a user turn starts, never parting a call from its result, long-running calls excepted since ADK re-injects them, nor leaving a kept event stamped inside the range; none for a saving under 20% of the trigger, the seed left out of it), writes on the root's own model (`_simple_model(SUMMARY_MAX_TOKENS, agent=root)`, thinking off) with `workflow/summary_prompt.py`, the rendering sized to that model's window (the middle cut, `MIDDLE_OMITTED`, the seed kept whole), and returns **user-role** text starting `SUMMARY_PREFIX` (a model-role first message is one Claude refuses), which the fit guard folds, after the memory index and the roster when the request has them, into the next user text (`fold_summary`), so no request holds two user messages in a row. `last_kept_turns` and `last_error` are for its callers: a manual summarizer warns of nothing itself. It reports through the turn's live events (`_run_and_stream` iterates the runner through `live_events.merged` under `reporting(live)`); any failure is one recoverable `ERROR` a turn, never raised to ADK. `NoAfterTurnCompactionRunner` overrides ADK's private `Runner._run_post_invocation_compaction` (contract-tested), so the prompt never waits for a summary after the answer. `FitGuardPlugin` is the last plugin (but `SentRequestLoggingPlugin`, which logs a request as sent, and `CallSentPlugin`, which starts the call's clock) and `OverflowPlugin` the one before it (`MemoryIndexPlugin`, when the root has a memory tool and `memory_index_enabled` is on, the one before that: it puts the conversation's memory index snapshot first in the root's requests, never in the session): the guard leaves a request's oldest turns out when it is over its agent's budget (keeping the newest turn and what opens the conversation, the memory index, the roster of the root's open sub-agents (`RosterPlugin`, before `MemoryIndexPlugin`, for a root with `message_agent`), then a summary: `protected_head`; in a sub-agent type's chain also the run's task message and its instance's brief, `brief_of`) and keeps each request as it came in (`request_as_seen`: one copy per model call, under the call's `EventActions`, which ADK passes to all three of its callbacks: each sub-agent run is an invocation of its own on a child session, but two runs of one type share that type's runner and its plugins, and a run drops only what its own cancelled calls left, as it ends), and the overflow handler, on a provider's overflow, summarizes now (the root, through `compact_session`, ADK's private `_run_compaction_for_token_threshold_config`; `_summarize_now` returns `WrittenSummary(text, kept_turns)`, and the retry is the index, the roster, the summary and those turns) or trims to half the budget (a sub-agent, or nothing to summarize), builds the retry from the guard's copy without the context cache, retries once on the agent's `canonical_model`, then answers the root with `LlmResponse(error_code="CONTEXT_OVERFLOW")`, never model text (ADK would store it as the reply), which `ADKEventProcessor` maps to the turn's `ERROR`; a retry that fails otherwise propagates, and `_run_and_stream` unwraps ADK's plugin-manager `RuntimeError` to the provider's error; a sub-agent's call that still does not fit is answered with an error response too, `CONTEXT_OVERFLOW` and `subagent_overflow_message`, which its run's processor keeps as the run's failure: the run ends `failed` with those words (`RunFailed`), its parent reads them in the envelope, and the user is warned once, by the framework's delegation (`agents/delegate.py`), as on Deep Agents. A native ADK YAML app gets all of it: only the building of its agents differs (`workflow/adk/build.py`). Its chat-mode sub-agents keep transferring, and an agent the root transfers to replies to the user (`build.reply_agents`: its text is the reply, recent_messages reads it, its overflow is the turn's clear error, its calls write the outside-content mark); the summary and the memory index stay the root's, so such an agent is trimmed by the fit guard, not summarized. An agent's own callbacks (a native app's) run after every plugin, and only when none answered: its before-model callbacks see the request after the fit guard, and the cap leaves out an agent with after-tool callbacks. A main agent whose model does not resolve through the catalog has no budget and no summary. -- **Sub-agents delegate and return**: on both backends a sub-agent run is a call of its parent's `task` tool (the framework's: `tools/_core/delegation.py` declares it, `workflow/agents/delegate.py` runs it) that returns in the same turn; only the root replies to the user (a sub-agent's `TEXT` carries `metadata["subagent"]`, and the CLI shows it as the events box's status line, under its run's name: `researcher-2 › …`; `/agents` picks among a conversation's instances), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the caller's own sub-agents) and a brief (`workflow/agents/brief.py`: `title`, `objective`, `deliverable`, `constraints`, `known`, `done_when`), its schema and description the same on both backends (`task_parameters`, `task_description`: a line per type with its description, "The <name> agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both: it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents <id>`, never written to the conversation. It ends as the `RunAnswer` says: its last text (a reply that also called a tool included; none at all, an empty result shown `No answer`), `refused` or `partial` by the outcome mark, `failed` for an error or a raise (one recoverable `ERROR`, `<instance> failed: <reason>`, or the hook's own words, `RunFailed`: an overflow's; its result the text it wrote before it failed: a failed model call is the hook's `RunAnswer.error`, `failure_reason`, its warning's code `RunAnswer.error_code`, the error's type, and `RunFailed` carries `text=`); and the call's result is the run's envelope as JSON (`workflow/agents/envelope.py`), shown by `show_as_delegation`. A cancel of the caller's task stops the run's task first and ends the run `interrupted`. Each run works under its `RunControl` (`workflow/agents/control.py`, `AgentRun.control`), with its type's `AgentConfig.limits` over the policy's (`SubAgentPolicy.limits`, `DEFAULT_LIMITS`: 100 model calls): `Delegations.cancel(run_id, by=, error=)` cancels the run alone (its parent, the user or a limit), and the hook, seeing its own cancel (`own_cancel`), stops the run as a stopped turn's (ADK: its abort signal, its open calls sealed in its child session; Deep Agents: its stream closed) and returns what it has: the run ends `cancelled` with `cancelled_by` and that text, `partial`, while its siblings and the turn go on; the turn's own cancel still wins (`interrupted`). Past its `timeout` (counted from when its hook starts, `timing`) the run is cancelled by its limit (`time limit reached`); each model call is counted before it is made (`RunControlPlugin` in each sub-agent chain, `RunControlMiddleware` on each sub-agent's model side) and the last allowed one gets `STEP_LIMIT_NOTE` after its last message, its tools still declared (Claude refuses tool calls in a request that defines no tools); its answer's calls are dropped, never run, so the run completes `partial`, `step limit reached`; each call's tokens are counted after it, with what the run's other calls used (`RunControl(side_tokens=)`: its tools' side calls and its summaries, the ledger's rows of the run that are no agent step, `UsageLedger.by_purpose(run=)`), so the limit is the run's total as its usage record counts it, and past `max_tokens` an answer that makes tool calls is the run's last, its calls dropped, `cancelled` by its limit (`token limit reached`), while one that makes none ends the run as it would, `completed`, its result whole (a model that reports no usage counts none of its own). A turn starts at most `max_runs_per_turn` runs, at any depth (`sessions.runs_this_turn`): a call past it is the error result, no run started; `task`'s description says so (`limit_sentences`). At most `max_active` runs of a conversation work at once, at any depth (`workflow/agents/slots.py::SlotPool`, one per conversation, `Delegations.slots`; the root takes no slot): a run takes a slot right before its hook and its time limit start and gives it back at its end, however it ends; one that finds none waits `queued` (an `AGENT_RUN` and its record say so, then `running`), not counted against its `timeout`. A run lends its slot while it waits on its children (one lend for all it waits on at once; the child that ends last hands its slot straight back, so the tree in progress goes on ahead of the runs that have not started) or on the user (`waiting_on_user`: `input_required`, `queued` once answered while it waits for its slot back, then `running`, in `request_user_input` and in the permission engine from before its one-prompt lock until after it: a run waiting for a slot while holding the lock would hold every other run's prompt; a prompt no one can be shown, no input callback or its turn ended, lends nothing: `can_request_user_input`), so nested fan-out never deadlocks; a cancel, queued or lending, leaves no waiter in the heap and no slot taken. A message steered to a working run (`RunControl.steer`, through `Delegations.control(run)`) is added after its last message, as the user's, before its next model call, and stays in its transcript (ADK: appended to its child session, the run's later events stamped after it so a durable store reads them back in order; Deep Agents: added to its state); a sub-agent run's task message is never trimmed, on ADK neither by the fit guard nor by the overflow handler's retry, whatever was steered after it. A dialog whose run is stopped is withdrawn, the turn going on (`MessageProcessor`). `AgentConfig.inherit_context` sets what a run sees: False (the default) its task alone, True its parent's conversation too, read once as the run starts (the conversation after any summary; Deep Agents' less the message that called `task`, which ADK's copy keeps), before the task message, which then ends with `INHERITED_CONTEXT_NOTE` (whose conversation it reads, which message is its task); `validate_agent_graph` refuses a value that is not True or False, `inherit_context=True` on the root, on an agent with sub-agents and below another sub-agent. On ADK (`workflow/adk/task_tool.py::TaskTool`) every config-built agent is built on its own, with no ADK `sub_agents`, so ADK offers none `transfer_to_agent`, and gets ADK's identity line ("You are an agent. Your internal name is …"); a delegating agent has one `TaskTool`. A sub-agent is an instance that outlives its run: `idle` when the run ends, its next run a follow-up (`Delegations.follow_up`, through the same hook with `AgentRun.follow_up`, the message as written and no history), one run per instance at a time; a run's end leaves its instance `stopped` (once the user stopped it: its run cancelled by the user, or an idle one; only the user continues it), `closed` (`AgentConfig.continuable` False, or past `SubAgentPolicy.max_open`: the oldest idle one) or `idle`, `Delegations.close` closes an idle or stopped one and its descendants, and `AGENT_INSTANCE` carries a change without a run; the user controls any instance of the open conversation through the manager (`run_instance`: a follow-up as a turn of its own, its Ctrl+C the user's stop; `stop_instance`, `close_instance`, `steer_instance`; `tell_root`: a notice turn of the root, marked as a job's) and the CLI's `/agents` picker, `/agent stop|close <id>` and `/agent <id>`'s view (`cli/agent_view.py`: a line typed there is the instance's next run or a steer of the run that works, Ctrl+C the user's stop, `/back` the root's notice); on ADK a follow-up continues the instance's child session, the calls an earlier run left open answered first (`left_open_by`, from the instance's record), on Deep Agents the instance's own checkpointer thread (`instance_run_config`: its input the message and the caller's mark, the shared keys it changed compared with the thread's state as the run started). Each sub-agent type runs on its own runner (`App(name=child_app(app_name))`, the type's agent its root, `_agent_plugin_chain`: the main chain configured for a sub-agent, no memory index, no summary, `RunControlPlugin` and `SubAgentOutcomePlugin`; every plugin's per-call state keyed by invocation) over the manager's session service, on a child session per instance (`child_session_id`: `<conversation id>/<instance>`, the conversation id's `%` and `/` percent-encoded; an inheriting instance's gets the conversation's events copied once, at its first run, `task_tool.inherited_events`), under an app no conversation list reads. On Deep Agents (`workflow/deepagents/task_tool.py::build_task_tool`) each type's graph is built on its own, and a run `astream`s it in its task with `var_child_runnable_config` cleared, so its chunks reach its own loop alone, never its parent's stream; an inheriting run's history is the parent's messages with Deep Agents' summary event applied (`SummarizationMiddleware._apply_event_to_messages`, private: `tests/workflow/deepagents/test_compact.py` pins it), and `ForeignReasoningMiddleware(kind, agent=...)` leaves out the reasoning of AI messages another agent wrote. A native ADK YAML app keeps transferring (chat-mode sub-agents); a task-mode agent in one is refused at validation, since ADK runs its delegation outside the tool pipeline and keeps the call open across turns. With `SubAgentPolicy(follow_ups=True)` every agent with sub-agents also gets `message_agent`, `stop_agent` and `check_agents` beside `task` (`workflow/agents/follow_ups.py::call_follow_up_tool` over `Delegations.message`/`stop`/`check`; ADK's `FollowUpTool`, Deep Agents' `build_follow_up_tools`; an own tool of one of their names fails the build, a Deep Agents MCP tool of one is skipped): `message_agent` continues an idle instance, steers a running one (before its next step; a run already stopping or finished is waited for, then the message follows the instance up or is refused; one being closed is refused as closed at once) or, with `interrupt` (refused, nothing cancelled, when no follow-up could start; an agent's keeps the turn's run it checked for), replaces its run (the user's interrupt is the user's stop); `stop_agent` cancels a running run by its parent (the instance idle; only the user's stop makes one `stopped`) and, with `close`, closes it and its descendants; a message steered to a run and not in its transcript when it ends goes to the instance's next run (`RunControl.stored`/`unstored`: ADK counts one stored as its child-session append returns, Deep Agents once the model call after it holds it); a run that did not complete fully names its open tasks in its envelope (`open_tasks`); a run whose parent's run was stopped by its control ends `cancelled` by its parent, not `interrupted`. +- **Sub-agents delegate and return**: on both backends a sub-agent run is a call of its parent's `task` tool (the framework's: `tools/_core/delegation.py` declares it, `workflow/agents/delegate.py` runs it) that returns in the same turn; only the root replies to the user (a sub-agent's `TEXT` carries `metadata["subagent"]`, and the CLI shows it as the events box's status line, under its run's name: `researcher-2 › …`; `/agents` picks among a conversation's instances), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the types the calling run may start, `Delegations.offered`: its own sub-agents, then, with `SubAgentPolicy.spawn_sources` holding `"agent"` and the run's depth below `max_spawn_depth`, the types whose `AgentConfig.spawnable_by` names `"agent"`, `workflow/agents/spawn.py`; a free type, in no `sub_agents` list, is never the root; `task` is offered for each run, ADK declaring it per request and Deep Agents rewriting a sub-agent's per model call, and a run offered nothing has none) and a brief (`workflow/agents/brief.py`: `title`, `objective`, `deliverable`, `constraints`, `known`, `done_when`), its schema and description the same on both backends (`task_parameters`, `task_description`: a line per type with its description, "The <name> agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both, through `Delegations.start` (a `StartRequest`, the one entry for a first run): it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents <id>`, never written to the conversation. It ends as the `RunAnswer` says: its last text (a reply that also called a tool included; none at all, an empty result shown `No answer`), `refused` or `partial` by the outcome mark, `failed` for an error or a raise (one recoverable `ERROR`, `<instance> failed: <reason>`, or the hook's own words, `RunFailed`: an overflow's; its result the text it wrote before it failed: a failed model call is the hook's `RunAnswer.error`, `failure_reason`, its warning's code `RunAnswer.error_code`, the error's type, and `RunFailed` carries `text=`); and the call's result is the run's envelope as JSON (`workflow/agents/envelope.py`), shown by `show_as_delegation`. A cancel of the caller's task stops the run's task first and ends the run `interrupted`. Each run works under its `RunControl` (`workflow/agents/control.py`, `AgentRun.control`), with its type's `AgentConfig.limits` over the policy's (`SubAgentPolicy.limits`, `DEFAULT_LIMITS`: 100 model calls): `Delegations.cancel(run_id, by=, error=)` cancels the run alone (its parent, the user or a limit), and the hook, seeing its own cancel (`own_cancel`), stops the run as a stopped turn's (ADK: its abort signal, its open calls sealed in its child session; Deep Agents: its stream closed) and returns what it has: the run ends `cancelled` with `cancelled_by` and that text, `partial`, while its siblings and the turn go on; the turn's own cancel still wins (`interrupted`). Past its `timeout` (counted from when its hook starts, `timing`) the run is cancelled by its limit (`time limit reached`); each model call is counted before it is made (`RunControlPlugin` in each sub-agent chain, `RunControlMiddleware` on each sub-agent's model side) and the last allowed one gets `STEP_LIMIT_NOTE` after its last message, its tools still declared (Claude refuses tool calls in a request that defines no tools); its answer's calls are dropped, never run, so the run completes `partial`, `step limit reached`; each call's tokens are counted after it, with what the run's other calls used (`RunControl(side_tokens=)`: its tools' side calls and its summaries, the ledger's rows of the run that are no agent step, `UsageLedger.by_purpose(run=)`), so the limit is the run's total as its usage record counts it, and past `max_tokens` an answer that makes tool calls is the run's last, its calls dropped, `cancelled` by its limit (`token limit reached`), while one that makes none ends the run as it would, `completed`, its result whole (a model that reports no usage counts none of its own). A turn starts at most `max_runs_per_turn` runs, at any depth (`sessions.runs_this_turn`): a call past it is the error result, no run started; `task`'s description says so (`limit_sentences`). At most `max_active` runs of a conversation work at once, at any depth (`workflow/agents/slots.py::SlotPool`, one per conversation, `Delegations.slots`; the root takes no slot): a run takes a slot right before its hook and its time limit start and gives it back at its end, however it ends; one that finds none waits `queued` (an `AGENT_RUN` and its record say so, then `running`), not counted against its `timeout`. A run lends its slot while it waits on its children (one lend for all it waits on at once; the child that ends last hands its slot straight back, so the tree in progress goes on ahead of the runs that have not started) or on the user (`waiting_on_user`: `input_required`, `queued` once answered while it waits for its slot back, then `running`, in `request_user_input` and in the permission engine from before its one-prompt lock until after it: a run waiting for a slot while holding the lock would hold every other run's prompt; a prompt no one can be shown, no input callback or its turn ended, lends nothing: `can_request_user_input`), so nested fan-out never deadlocks; a cancel, queued or lending, leaves no waiter in the heap and no slot taken. A message steered to a working run (`RunControl.steer`, through `Delegations.control(run)`) is added after its last message, as the user's, before its next model call, and stays in its transcript (ADK: appended to its child session, the run's later events stamped after it so a durable store reads them back in order; Deep Agents: added to its state); a sub-agent run's task message is never trimmed, on ADK neither by the fit guard nor by the overflow handler's retry, whatever was steered after it. A dialog whose run is stopped is withdrawn, the turn going on (`MessageProcessor`). `AgentConfig.inherit_context` sets what a run sees: False (the default) its task alone, True its parent's conversation too, read once as the run starts (the conversation after any summary; Deep Agents' less the message that called `task`, which ADK's copy keeps), before the task message, which then ends with `INHERITED_CONTEXT_NOTE` (whose conversation it reads, which message is its task); `validate_agent_graph` refuses a value that is not True or False, `inherit_context=True` on the root, on an agent with sub-agents and below another sub-agent. On ADK (`workflow/adk/task_tool.py::TaskTool`) every config-built agent is built on its own, with no ADK `sub_agents`, so ADK offers none `transfer_to_agent`, and gets ADK's identity line ("You are an agent. Your internal name is …"); a delegating agent has one `TaskTool`. A sub-agent is an instance that outlives its run: `idle` when the run ends, its next run a follow-up (`Delegations.follow_up`, through the same hook with `AgentRun.follow_up`, the message as written and no history), one run per instance at a time; a run's end leaves its instance `stopped` (once the user stopped it: its run cancelled by the user, or an idle one; only the user continues it), `closed` (`AgentConfig.continuable` False, or past `SubAgentPolicy.max_open`: the oldest idle one) or `idle`, `Delegations.close` closes an idle or stopped one and its descendants, and `AGENT_INSTANCE` carries a change without a run; the user controls any instance of the open conversation through the manager (`run_instance`: a follow-up as a turn of its own, its Ctrl+C the user's stop; `stop_instance`, `close_instance`, `steer_instance`; `tell_root`: a notice turn of the root, marked as a job's) and the CLI's `/agents` picker, `/agent stop|close <id>` and `/agent <id>`'s view (`cli/agent_view.py`: a line typed there is the instance's next run or a steer of the run that works, Ctrl+C the user's stop, `/back` the root's notice); on ADK a follow-up continues the instance's child session, the calls an earlier run left open answered first (`left_open_by`, from the instance's record), on Deep Agents the instance's own checkpointer thread (`instance_run_config`: its input the message and the caller's mark, the shared keys it changed compared with the thread's state as the run started). Each sub-agent type runs on its own runner (`App(name=child_app(app_name))`, the type's agent its root, `_agent_plugin_chain`: the main chain configured for a sub-agent, no memory index, no summary, `RunControlPlugin` and `SubAgentOutcomePlugin`; every plugin's per-call state keyed by invocation) over the manager's session service, on a child session per instance (`child_session_id`: `<conversation id>/<instance>`, the conversation id's `%` and `/` percent-encoded; an inheriting instance's gets the conversation's events copied once, at its first run, `task_tool.inherited_events`), under an app no conversation list reads. On Deep Agents (`workflow/deepagents/task_tool.py::build_task_tool`) each type's graph is built on its own, and a run `astream`s it in its task with `var_child_runnable_config` cleared, so its chunks reach its own loop alone, never its parent's stream; an inheriting run's history is the parent's messages with Deep Agents' summary event applied (`SummarizationMiddleware._apply_event_to_messages`, private: `tests/workflow/deepagents/test_compact.py` pins it), and `ForeignReasoningMiddleware(kind, agent=...)` leaves out the reasoning of AI messages another agent wrote. A native ADK YAML app keeps transferring (chat-mode sub-agents); a task-mode agent in one is refused at validation, since ADK runs its delegation outside the tool pipeline and keeps the call open across turns. With `SubAgentPolicy(follow_ups=True)` every agent that can have sub-agents (`can_have_children`: its own, or types it may start at run time) also gets `message_agent`, `stop_agent` and `check_agents` beside `task` (`workflow/agents/follow_ups.py::call_follow_up_tool` over `Delegations.message`/`stop`/`check`; ADK's `FollowUpTool`, Deep Agents' `build_follow_up_tools`; an own tool of one of their names fails the build, a Deep Agents MCP tool of one is skipped): `message_agent` continues an idle instance, steers a running one (before its next step; a run already stopping or finished is waited for, then the message follows the instance up or is refused; one being closed is refused as closed at once) or, with `interrupt` (refused, nothing cancelled, when no follow-up could start; an agent's keeps the turn's run it checked for), replaces its run (the user's interrupt is the user's stop); `stop_agent` cancels a running run by its parent (the instance idle; only the user's stop makes one `stopped`) and, with `close`, closes it and its descendants; a message steered to a run and not in its transcript when it ends goes to the instance's next run (`RunControl.stored`/`unstored`: ADK counts one stored as its child-session append returns, Deep Agents once the model call after it holds it); a run that did not complete fully names its open tasks in its envelope (`open_tasks`); a run whose parent's run was stopped by its control ends `cancelled` by its parent, not `interrupted`. - **Token usage**: every model call the framework makes is one `LLM_USAGE`, on both backends, side calls included (`generate_simple`: `summarize`'s, `purpose` `tool`; `on_session_end`'s, `memory_extraction`, outside any turn; an app's own, `side_call`, or what its caller names with `workflow/usage.py::side_call`), its counts normalized where it is made (`normalized_tokens`: `prompt_tokens` every input token, cache reads and writes included; `completion_tokens` every output token, thinking included; ADK's read by its model's provider kind, `adk_usage_event`/`adk_tokens`, since Gemini and ADK's Claude adapter keep the thinking apart from the candidates and OpenAI's count it inside, an agent of no known kind read as apart; Deep Agents' by LangChain's one convention, `langchain_tokens`; the raw log's usage records alike), and timed (`latency_ms`: on ADK from the request to the answer, `workflow/adk/call_clock.py`'s plugins marking the answer's `custom_metadata`; on Deep Agents by the turn's `RunCallback`, which marks the answer's `response_metadata["agentic_cli"]`, beside the outcome mark; a side call, a summary and the overflow retry around their own request; no adapter sends either mark). Each is recorded in its conversation's ledger (`UsageLedger`; `BaseWorkflowManager.usage`/`usage_of`, in memory for the manager's life: a backend switch's new manager starts afresh, as with `agent_runs`) where it is made, before `on_event` (the event processors, ADK's summarizer, as soon as its call answers, Deep Agents' `RunCallback`, `_report_side_call`), under the run it is made in and its conversation's turn while one runs (as the manager counts them, `/compact` and job notices included: not `SessionInfo.turns`; none in another conversation's turn or from a task its turn outlived, which `_report_side_call` reports to no one); a sub-agent run's `AGENT_RUN` end carries what it used, by model (`metadata["usage"]`, `RunRecord.usage`). The CLI's status bar sums the events it sees (the open conversation's total, on any backend); `/status` shows the ledger by agent. LangGraph (deprecated) records no ledger. - **Tool registration**: Use `@register_tool(category=..., capabilities=..., description=...)` decorator. `capabilities=` is required — pass `EXEMPT` for tools that need no permission check or a list of `Capability(name, target_arg=...)` tuples the engine matches against rules. Tools are auto-discovered via the global `ToolRegistry`. A tool in `AgentConfig.tools` that the registry did not issue is denied at every call; building the agents names it once (`tool_not_registered`, per agent and tool: `BaseWorkflowManager._name_unregistered`): a plain callable, a `FunctionTool`/`StructuredTool` judged by the function it runs (as the gates unwrap it), an app's own tool class; ADK's own tool objects excepted (a built-in runs inside the model). `outside_content=True` (or a function of the call's arguments) declares that a call brings content from outside the user and the project into the conversation (a page, a document, a program's output): once the gate allows one, a memory write in that conversation is approved per call (see Permissions); an application's tools are unmarked unless they declare it, and a variant must declare the same flag as its tool. - **Async tools never block the event loop**: a synchronous tool runs on a worker thread on both backends; an async tool runs on the event loop itself, where a blocking call (DNS, a connect, a file lock's wait, a sleep, a subprocess wait, PDF parsing, page conversion, embedding) freezes the whole app, Ctrl+C included. An async tool runs its slow work with `asyncio.to_thread`. `tests/tools/test_async_tools_never_block.py` lists every async tool (the registry's, the factories' service-bound variants, Deep Agents' skill tools), so a new one fails until it is listed, and calls each through the loop guard (`tests/loop_guard.py`). diff --git a/README.md b/README.md index bc8a4828..fd25457c 100644 --- a/README.md +++ b/README.md @@ -393,7 +393,8 @@ manager = DeepAgentsWorkflowManager( ``` What it supports: -- **Delegation through `task`**: a coordinator (an agent with `sub_agents`) +- **Delegation through `task`**: a coordinator (an agent with `sub_agents`, or + with types it may start at run time) gets the framework's `task` tool, as on ADK (see [Sub-agent context](#sub-agent-context)). Each sub-agent's graph runs apart from its coordinator's, in a task of its own, from the brief the @@ -1290,13 +1291,19 @@ configs = [coordinator, researcher, analyst] | `brief_required` | tuple[str, ...] | The brief fields a delegation to this agent must fill (default `("objective",)`; `title` and `objective` are always required): any of `deliverable`, `constraints`, `known`, `done_when`. A `task` call that leaves one empty starts no run, and its caller reads which. Not on the root | | `limits` | AgentLimits \| None | The agent's own per-run limits (`max_model_calls`, `timeout` in seconds, `max_tokens`), laid over the app's `SubAgentPolicy.limits` field by field: each of its runs works under them, and one past a limit ends (see [Sub-agent context](#sub-agent-context)). Not on the root | | `continuable` | bool | Whether an instance of this agent takes follow-ups after its run (`True`, the default) or is closed when its run ends (`False`, one-shot); see [Sub-agent context](#sub-agent-context). Not `False` on the root | +| `spawnable_by` | frozenset[str] \| None | Who may start this agent at run time besides its parent: a set of `"agent"` (another agent's `task` call), `"skill"` and `"user"`, each also enabled by the app's `SubAgentPolicy.spawn_sources`; `None` (the default): only its parent. One in no `sub_agents` list is a free type, never the root; see [Sub-agent context](#sub-agent-context). Not on the root | The agent graph is validated before anything is allocated — ahead of model discovery and service creation. Duplicate names, unknown `sub_agents` references, self-references, delegation cycles, a sub-agent shared by two parents, and **more than one root** raise `AgentGraphError` naming the offending agents. Exactly one agent may be unreferenced: the runner starts from -a single root, so agents under any other root would never run. +a single root, so agents under any other root would never run. An agent that +sets `spawnable_by` and is in no `sub_agents` list is a free type, started at +run time only, and no root however it is listed; the root may not set +`spawnable_by`, and a `spawnable_by` that is empty or names a source other +than `agent`, `skill` and `user` raises too (a free type the app's policy lets +no source start is a warning: `validate_agent_graph(configs, policy=...)`). `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 @@ -1314,7 +1321,8 @@ signatures, `async def` factories, and non-string results raise A sub-agent is a task its parent hands off and gets back in the same turn, on both backends. The parent calls the framework's `task` tool, the same on both: -`agent_type`, one of its own sub-agents, and a brief, `title` and `objective` +`agent_type`, one of its own sub-agents (or of the types it may start at run +time, below), and a brief, `title` and `objective` (required), `deliverable`, `constraints`, `known` (what the parent already knows that the task needs) and `done_when`. The sub-agent's run starts from its task message, the brief as sections (`# Task: <title>`, `## Objective`, …); it @@ -1417,8 +1425,37 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", a type that is not continuable), and new instances are numbered past the stored ones. Deleting the conversation deletes them, after the transcripts. +- **Starting agents at run time.** A type may also be started while the app + runs, by an agent's `task` call, when the app allows it twice: the type's + `spawnable_by={"agent"}` and the policy's + `subagents=SubAgentPolicy(spawn_sources={"agent"})` (off by default: + `spawnable_by` is unset and `spawn_sources` empty, so `task` lists the + caller's own sub-agents alone). `task` then lists, after + them, every type agents may start, each with its description, so a main + agent needs no `sub_agents` of its own; a type in no `sub_agents` list is a + free type, never the root. Such a run is a delegation like any other + (`helper-1`, `started_by: agent:root`, its envelope the call's result). + `max_spawn_depth` (1) says from how deep: a run at depth `d` (the root is + 0) may start one only while `d` is below it, so by default only the main + agent does, and `task`'s description then says "Sub-agents cannot start + sub-agents."; a run that may start nothing is offered no `task`, and the + configured tree keeps its own depth. An inheriting type is offered to the + main agent alone. + + ```python + coordinator = AgentConfig(name="coordinator", prompt="Hand self-contained " + "checks to fact_checker.") + fact_checker = AgentConfig(name="fact_checker", prompt="Check one claim.", + description="Checks one claim against sources.", + spawnable_by=frozenset({"agent"})) + manager = create_workflow_manager_from_settings( + [coordinator, fact_checker], settings, + subagents=SubAgentPolicy(spawn_sources={"agent"}), + ) + ``` - **The parent's tools.** With `subagents=SubAgentPolicy(follow_ups=True)` - every agent with sub-agents gets three more tools beside `task` (with the + every agent that can have sub-agents (its own, or types it may start at run + time) gets three more tools beside `task` (with the policy's defaults, `task` alone): `message_agent(agent, message, interrupt=false)` sends one of its sub-agents a message, which an idle one runs as a follow-up (the envelope comes back as `task`'s does) and a @@ -1469,8 +1506,10 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", the view first; a closed sub-agent's view has no prompt (`/back` only). The run's questions and a command's dialogs open one at a time, each waiting for the other ([Customizing the CLI](#customizing-the-cli)). -- **What the agent graph refuses.** `inherit_context` is for sub-agents only, and - only for the main agent's own sub-agents that have none of their own. A +- **What the agent graph refuses.** `inherit_context` is for sub-agents only, + and only for the main agent's own sub-agents that have none of their own. + `spawnable_by` is for sub-agents only, and names `agent`, `skill` or `user`. + A coordinator cannot have a tool of its own named `task` (nor, with `follow_ups`, one named `message_agent`, `stop_agent` or `check_agents`). Each raises `AgentGraphError` at startup. @@ -1608,6 +1647,7 @@ are `AgentConfig`'s, and an unknown one is an error: | `mcp_servers`, `skills` | As on `AgentConfig`: MCP servers (`name`, `transport`, `command`/`args` or `url`, ...) and skill names | | `sub_agents`, `inherit_context` | The agents it may delegate to, and what a sub-agent sees: `false` (its task alone, the default) or `true` (its parent's conversation too; see [Sub-agent context](#sub-agent-context)) | | `brief_required`, `limits`, `continuable` | As on `AgentConfig`: `brief_required: [objective, deliverable]`, `limits: {max_model_calls: 30, timeout: 600, max_tokens: 200000}` (each limit read as written), `continuable: false` (one-shot) | +| `spawnable_by` | Who may start it at run time, a list: `spawnable_by: [agent]` (read as a set; with no `sub_agents` naming it, a free type) | | `include_state_tools` | `true` by default: the plan and task tools are added | - **A tool is a name, resolved when the manager is built.** A bare name is diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index 6eb6c857..4aeb19e6 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -85,6 +85,7 @@ from agentic_cli.workflow.adk.tool_result_cap_plugin import ToolResultCapPlugin from agentic_cli.workflow.agents.delegate import AgentRun, RunAnswer, RunFailed, failure_reason from agentic_cli.workflow.agents.runs import own_plan_and_tasks +from agentic_cli.workflow.agents.spawn import can_have_children from agentic_cli.workflow.context import OVERFLOW_ERROR_CODE from agentic_cli.tools._core.delegation import ( FOLLOW_UP_CLASH_ERROR, @@ -488,7 +489,7 @@ def _build_agent( service_map: dict, *, root: bool, - types: "Mapping[str, AgentConfig] | None" = None, + delegates: bool = False, ) -> Agent: """Construct one ``LlmAgent`` from a config, on its own. @@ -496,10 +497,12 @@ def _build_agent( initialization resolved for it, built by the model factory. No agent has ADK ``sub_agents``, so ADK offers none of them - ``transfer_to_agent``. An agent that delegates (``types``: its - sub-agents, by name) gets the framework's ``task`` tool - (``adk/task_tool.py::TaskTool``), whose calls run each sub-agent on - that sub-agent type's own runner (``_run_agent``); with + ``transfer_to_agent``. An agent that delegates (``delegates``: it has + sub-agents, or may start types at run time, ``spawn.can_have_children``) + gets the framework's ``task`` tool (``adk/task_tool.py::TaskTool``), + which declares for each request what the run that asks may start, and + whose calls run each sub-agent on that type's own runner + (``_run_agent``); with ``SubAgentPolicy.follow_ups`` it also gets ``message_agent``, ``stop_agent`` and ``check_agents`` (``FollowUpTool``). Only the root's long-running tools are wrapped: a pending one would pause a @@ -517,14 +520,14 @@ def _build_agent( tools = self._assemble_agent_tools(config, service_map) if root: tools = self._wrap_long_running(tools) - if types: + if delegates: names = _tool_names(tools) if TASK_TOOL in names: raise AgentGraphError( 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, types, lambda: self._delegations)] + tools = [*tools, TaskTool(config.name, lambda: self._delegations, root=root)] 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: @@ -570,10 +573,13 @@ def _create_agents(self) -> Agent: # validates its own. graph, self._validated_graph = getattr(self, "_validated_graph", None), None if graph is None: - graph = validate_agent_graph(self._agent_configs, backend=self.backend_type) + graph = validate_agent_graph( + self._agent_configs, backend=self.backend_type, policy=self.subagent_policy + ) agents: dict[str, LlmAgent] = {} service_map = self._get_service_tool_map() + configs = list(graph.config_map.values()) from agentic_cli.config import SettingsContext @@ -581,15 +587,16 @@ def _create_agents(self) -> Agent: with SettingsContext(self._settings): for name in graph.build_order: config = graph.config_map[name] - types = {sub: graph.config_map[sub] for sub in config.sub_agents} + root = name == graph.root_name + delegates = can_have_children(config, configs, self.subagent_policy, root=root) agents[name] = self._build_agent( - config, service_map, root=name == graph.root_name, types=types + config, service_map, root=root, delegates=delegates ) logger.debug( "agent_created", name=name, - type="coordinator" if types else "leaf", - sub_agents=list(types), + type="coordinator" if delegates else "leaf", + sub_agents=list(config.sub_agents), ) self._agents = agents @@ -1175,7 +1182,7 @@ def _validate_agent_graph(self) -> AgentGraph | None: self._required_managers = self._detect_required_managers() return AgentGraph(config_map={}, build_order=(), root_name=root.name) self._validated_graph = validate_agent_graph( - self._agent_configs, backend=self.backend_type + self._agent_configs, backend=self.backend_type, policy=self.subagent_policy ) return self._validated_graph diff --git a/src/agentic_cli/workflow/adk/task_tool.py b/src/agentic_cli/workflow/adk/task_tool.py index 940d2eda..fc75555b 100644 --- a/src/agentic_cli/workflow/adk/task_tool.py +++ b/src/agentic_cli/workflow/adk/task_tool.py @@ -1,12 +1,18 @@ """ADK's ``task`` tool: the framework's delegation, as an ADK tool. -A delegating agent built from configs gets one ``TaskTool``, whatever its -sub-agents (its sub-agents are no ADK ``sub_agents``: each runs on a runner -of its own, ``GoogleADKWorkflowManager._run_agent``). Its declaration is the -framework's (``agents/brief.py``: ``task_parameters``, ``task_description``), -as Deep Agents' ``task``'s is, and a call hands its arguments, as the model -wrote them, to the manager's ``Delegations`` (``agents/delegate.py``): it -reads the brief, runs the sub-agent and returns the result envelope. +An agent built from configs that can have sub-agents (its own, or types it may +start at run time: ``agents/spawn.py::can_have_children``) gets one +``TaskTool``, whatever its sub-agents (they are no ADK ``sub_agents``: each +runs on a runner of its own, ``GoogleADKWorkflowManager._run_agent``). Its +declaration is the framework's, made for each request (ADK asks the tool for +it per model call, in the run's own context): what the run that asks may start +(``Delegations.task_offer``, ``agents/brief.py``'s ``task_parameters`` and +``task_description``), as Deep Agents' ``task``'s is, and none at all for a +run that may start nothing: ADK adds a tool to a request only for a +declaration, so the model is offered no ``task``, and a call of the name gets +ADK's answer for a tool it does not have. A call hands its arguments, as the +model wrote them, to the manager's ``Delegations`` (``agents/delegate.py``): +it reads the brief, runs the sub-agent and returns the result envelope. The call's result is the envelope as JSON text, which ADK stores as ``{"result": <text>}``: every model adapter sends that text whole (ADK's @@ -45,7 +51,7 @@ from __future__ import annotations import json -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Sequence from typing import TYPE_CHECKING, Any from google.adk.events import Event, EventActions @@ -57,8 +63,6 @@ from agentic_cli.workflow.agents.brief import ( follow_up_description, follow_up_parameters, - task_description, - task_parameters, ) from agentic_cli.workflow.agents.delegate import DelegationRequest from agentic_cli.workflow.agents.follow_ups import call_follow_up_tool @@ -69,7 +73,6 @@ from google.adk.tools.tool_context import ToolContext from agentic_cli.workflow.agents.delegate import Delegations - from agentic_cli.workflow.config import AgentConfig #: The state a run shares with its caller: the outside-content mark alone (a #: security mark: memory writes in a marked conversation are approved per @@ -79,32 +82,43 @@ class TaskTool(BaseTool): - """A delegating agent's ``task``, which starts a run of one of its sub-agents. + """An agent's ``task``, which starts a run of a type the calling run may start. + + Its ``description`` is the offer at the agent's first depth (the root's + 0, any other agent's 1); the declaration each request carries is the + offer for the run that asks. Args: - agent: The delegating agent's name. - types: Its sub-agents, by name: what ``agent_type`` may name. + agent: The agent's name. delegations: The manager's delegations, asked for at each call. + root: Whether the agent is the root. """ def __init__( self, agent: str, - types: Mapping[str, AgentConfig], delegations: Callable[[], Delegations], + *, + root: bool = True, ) -> None: - super().__init__(name=TASK_TOOL, description=task_description(types, delegations().policy)) + offer = delegations().task_offer(agent, 0 if root else 1, warn=True) + super().__init__( + name=TASK_TOOL, description=offer.description if offer is not None else "" + ) self._agent = agent - self._parameters = task_parameters(types) self._delegations = delegations if type(self) is TaskTool: bind_tool_identity(self, get_registry().get(TASK_TOOL)) - def _get_declaration(self) -> types.FunctionDeclaration: + def _get_declaration(self) -> types.FunctionDeclaration | None: + run = get_active_run() + offer = self._delegations().task_offer(self._agent, run.depth if run is not None else 0) + if offer is None: + return None return types.FunctionDeclaration( name=self.name, - description=self.description, - parameters_json_schema=self._parameters, + description=offer.description, + parameters_json_schema=offer.parameters, ) async def run_async(self, *, args: dict[str, Any], tool_context: "ToolContext") -> str: diff --git a/src/agentic_cli/workflow/agent_loader.py b/src/agentic_cli/workflow/agent_loader.py index a6b5f773..af95408e 100644 --- a/src/agentic_cli/workflow/agent_loader.py +++ b/src/agentic_cli/workflow/agent_loader.py @@ -23,6 +23,9 @@ brief_required: [objective, deliverable] # what a delegation must fill limits: {max_model_calls: 30, timeout: 600} # over the policy's, per field continuable: true # false: one-shot, closed when its run ends + - name: fact_checker + instruction: Check one claim. + spawnable_by: [agent] # in no sub_agents: a type agents start at run time A top-level bare list of agents (without the ``agents:`` key) is also accepted. Tool entries stay as strings here and are resolved to callables when the @@ -95,6 +98,8 @@ class AgentSpec(BaseModel): brief_required: list[str] | None = None limits: LimitsSpec | None = None continuable: bool = True + # None: only its parent starts it. + spawnable_by: list[str] | None = None class AgentsFile(BaseModel): @@ -171,6 +176,8 @@ def load_agents_from_yaml(path: str | Path) -> list[AgentConfig]: delegation["brief_required"] = tuple(spec.brief_required) if spec.limits is not None: delegation["limits"] = spec.limits.to_limits() + if spec.spawnable_by is not None: + delegation["spawnable_by"] = frozenset(spec.spawnable_by) configs.append( AgentConfig( name=spec.name, diff --git a/src/agentic_cli/workflow/agents/brief.py b/src/agentic_cli/workflow/agents/brief.py index ace22863..e87270a5 100644 --- a/src/agentic_cli/workflow/agents/brief.py +++ b/src/agentic_cli/workflow/agents/brief.py @@ -9,7 +9,8 @@ ``task_message`` lays a brief out as the first message of the run it starts (the system prompt stays the type's own); an inheriting type's ends with ``INHERITED_CONTEXT_NOTE``. ``task_parameters`` and ``task_description`` are -``task``'s schema and description, the same for both backends; +``task``'s schema and description, the same for both backends, made for the +types one run may start (``task_offer``, ``Delegations.offered``); ``follow_up_parameters`` and ``follow_up_description`` are the parent's other tools' (``message_agent``, ``stop_agent``, ``check_agents``). """ @@ -62,6 +63,9 @@ "this conversation: put in the brief everything it needs to know." ) +#: Added to ``task``'s limits when what a run starts could not start more. +DEPTH_SENTENCE = "Sub-agents cannot start sub-agents." + #: The parent's other tools' descriptions, by tool name. _PARENT_TOOL_DESCRIPTIONS = { "message_agent": ( @@ -278,7 +282,13 @@ def task_parameters(types: Mapping[str, AgentConfig]) -> dict[str, Any]: } -def task_description(types: Mapping[str, AgentConfig], policy: SubAgentPolicy) -> str: +def task_description( + types: Mapping[str, AgentConfig], + policy: SubAgentPolicy, + *, + depth_sentence: bool = False, + warn: bool = True, +) -> str: """``task``'s description, as the model reads it. What a delegation is (the sub-agent works on its own and returns its @@ -286,17 +296,50 @@ def task_description(types: Mapping[str, AgentConfig], policy: SubAgentPolicy) - sees (the brief alone, unless its type inherits the conversation), the limits in force (``limit_sentences``), and each of ``types`` with its description. A type without a description is offered as "The <name> - agent.", with one warning logged for it. + agent.", with one warning logged for it (none when ``warn`` is False). + ``depth_sentence`` ends the limits with ``DEPTH_SENTENCE``. """ paragraphs = [_DELEGATION, _WHAT_IT_SEES] limits = limit_sentences(policy) + if depth_sentence: + limits = [*limits, DEPTH_SENTENCE] if limits: paragraphs.append(" ".join(limits)) - lines = "\n".join(_type_line(name, config, warn=True) for name, config in types.items()) + lines = "\n".join(_type_line(name, config, warn=warn) for name, config in types.items()) paragraphs.append(f"The agents you can hand a task to:\n{lines}") return "\n\n".join(paragraphs) +@dataclass(frozen=True) +class TaskOffer: + """What ``task`` offers one run: the types it may start, the schema and the description.""" + + types: Mapping[str, AgentConfig] + parameters: dict[str, Any] + description: str + + +def task_offer( + types: Mapping[str, AgentConfig], + policy: SubAgentPolicy, + *, + depth_sentence: bool = False, + warn: bool = False, +) -> TaskOffer: + """The offer for ``types``: schema and description made together from the same types. + + ``warn`` logs a type without a description once; an offer made for each + run leaves it off. + """ + return TaskOffer( + types=dict(types), + parameters=task_parameters(types), + description=task_description( + types, policy, depth_sentence=depth_sentence, warn=warn + ), + ) + + def follow_up_description(name: str) -> str: """The description of the parent's tool ``name`` (``message_agent``, ``stop_agent`` or ``check_agents``), the same for both backends. diff --git a/src/agentic_cli/workflow/agents/delegate.py b/src/agentic_cli/workflow/agents/delegate.py index 8cff2595..8477d4f7 100644 --- a/src/agentic_cli/workflow/agents/delegate.py +++ b/src/agentic_cli/workflow/agents/delegate.py @@ -5,9 +5,15 @@ ``deepagents/task_tool.py::build_task_tool``) as a ``DelegationRequest``. ``delegate``: -- reads the brief against the caller's own sub-agents (``brief.read_brief``): - a brief that cannot start a run is the call's error result, and nothing - else happens (no run, no record, no event); +- reads the brief against what the calling run may start (``brief.read_brief``; + ``offered``: its own sub-agents, then, while the run's depth is below + ``max_spawn_depth``, the types agents start at run time, + ``agents/spawn.py``): a brief that cannot start a run is the call's error + result, and nothing else happens (no run, no record, no event); + +Then ``start``, the one entry for an instance's first run, whoever starts it +(a ``StartRequest``: the type, the brief, who starts it): + - counts the run against its turn's (``SubAgentPolicy.max_runs_per_turn``, runs at any depth: ``sessions.runs_this_turn``): a call past it is the error result ``RUNS_PER_TURN_ERROR`` says, and nothing else happens; @@ -111,7 +117,14 @@ from agentic_cli.constants import truncate from agentic_cli.logging import Loggers from agentic_cli.workflow import live_events -from agentic_cli.workflow.agents.brief import BriefError, read_brief, task_message +from agentic_cli.workflow.agents.brief import ( + Brief, + BriefError, + TaskOffer, + read_brief, + task_message, + task_offer, +) from agentic_cli.workflow.agents.control import PARENT_CAUSE, RunControl from agentic_cli.workflow.agents.envelope import ( CANCELLED_BY, @@ -143,6 +156,12 @@ run_title, ) from agentic_cli.workflow.agents.slots import NEW, Slot, SlotPool +from agentic_cli.workflow.agents.spawn import ( + AGENT_SOURCE, + depth_sentence_applies, + may_spawn, + spawnable, +) from agentic_cli.workflow.events import WorkflowEvent from agentic_cli.workflow.sessions import ( RunRef, @@ -262,6 +281,41 @@ class DelegationRequest: history: Callable[[], Any] | None = None +@dataclass(frozen=True) +class StartRequest: + """A first run of an agent type, as whoever starts it hands it over. + + Who may start the type is the asker's to check (``Delegations.offered`` + for a ``task`` call); ``Delegations.start`` runs what it is given. + + Attributes: + agent_type: The type to run: one of the manager's agent types. + brief: The run's brief (a title and an objective at least). + started_by: Who starts it: ``agent:<instance>`` (``agent:root`` for + the root), ``skill:<name>`` or ``user``. + caller: The run that starts it; None for the root, or the user. + call_id: The caller's tool call; None for the user's start. + conversation: The conversation; None: the active turn's. + state: The caller's shared state (the outside-content mark), which + the run starts from. + history: Called once, only when the type inherits its parent's + conversation: that conversation, as the backend reads it. + counted: Whether the run counts toward its turn's runs + (``SubAgentPolicy.max_runs_per_turn``); False for a run the + user starts. + """ + + agent_type: str + brief: Brief + started_by: str + caller: RunRef | None = None + call_id: str | None = None + conversation: SessionRef | None = None + state: Mapping[str, Any] = field(default_factory=dict) + history: Callable[[], Any] | None = None + counted: bool = True + + @dataclass(frozen=True) class AgentRun: """What the backend hook is asked to run. @@ -491,7 +545,8 @@ class Delegations: runs: The manager's runs, which name and record each run. policy: How the manager's sub-agents run. types: Every agent type, by name: a caller may start its own - sub-agents (``AgentConfig.sub_agents``). + sub-agents (``AgentConfig.sub_agents``) and, as the policy + allows, the types agents may start at run time (``offered``). hook: Runs one run (``BaseWorkflowManager._run_agent``). ledgers: The manager's usage ledgers: a run's end carries what it used, by model, and its token limit counts its side calls @@ -558,37 +613,104 @@ def sub_agents(self, agent: str) -> dict[str, AgentConfig]: names = caller.sub_agents if caller is not None else () return {name: self._types[name] for name in names if name in self._types} + def offered(self, caller_agent: str, depth: int) -> dict[str, AgentConfig]: + """The types a run of ``caller_agent`` at ``depth`` may start with ``task``. + + Its own sub-agents in their order, then, while ``depth`` is below + ``max_spawn_depth`` and the caller does not inherit its parent's + conversation, the types agents may start at run time + (``spawnable``), those not already its own, in config order. An + inheriting type is offered to the root (depth 0) alone: only the + root's own sub-agents inherit. + """ + offered = self.sub_agents(caller_agent) + caller = self._types.get(caller_agent) + if caller is None or caller.inherit_context or not may_spawn(depth, self.policy): + return offered + for name in spawnable(list(self._types.values()), self.policy, AGENT_SOURCE): + config = self._types[name] + if name not in offered and (depth == 0 or not config.inherit_context): + offered[name] = config + return offered + + def task_offer( + self, caller_agent: str, depth: int, *, warn: bool = False + ) -> TaskOffer | None: + """What ``task`` offers a run of ``caller_agent`` at ``depth``; None when it may start nothing. + + Both backends declare ``task`` from this: the schema and description + of ``offered``'s types, with the sentence that sub-agents cannot + start sub-agents when what the run starts could not. + """ + types = self.offered(caller_agent, depth) + if not types: + return None + own = self._types[caller_agent].sub_agents + return task_offer( + types, self.policy, + depth_sentence=depth_sentence_applies(types, own, depth, self.policy), + warn=warn, + ) + async def delegate(self, request: DelegationRequest) -> Delegated: """Run the sub-agent ``request`` asks for, to its end; its envelope. - A brief that cannot start a run, or a call past the runs its turn - may start, is the error result, and nothing else happens. 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. + A brief that cannot start a run is the error result, and nothing + else happens; otherwise it ends in ``start``, started by the + calling run. """ + depth = request.caller.depth if request.caller is not None else 0 try: - config, brief = read_brief(request.arguments, self.sub_agents(request.caller_agent)) + config, brief = read_brief( + request.arguments, self.offered(request.caller_agent, depth) + ) except BriefError as error: - return Delegated(result={"success": False, "error": str(error)}, state={}, run=None) - refused = self._past_runs_per_turn(config.name) - if refused is not None: - return refused - count_run_this_turn() - conversation = get_active_turn() - await self._number_past_stored(conversation) - ref = self._runs.run_for(conversation, request.caller, request.call_id, config.name) - self._emit(WorkflowEvent.agent_run( - ref, RUN_STARTED, call_id=request.call_id, title=run_title(brief.title), - brief=brief.fields(), started_by=started_by(request.caller), mode=BLOCKING, - inherit_context=config.inherit_context, continuable=config.continuable, + return _refused(str(error)) + return await self.start(StartRequest( + agent_type=config.name, brief=brief, started_by=started_by(request.caller), + caller=request.caller, call_id=request.call_id, state=request.state, + history=request.history, )) - return await self._run( - ref, config, conversation, request.call_id, - message=task_message(brief, inherit=config.inherit_context), - state=request.state, - history=request.history if config.inherit_context else None, + + async def start(self, request: StartRequest) -> Delegated: + """Run a first run of ``request.agent_type`` to its end; its envelope. + + A call past the runs its turn may start (when ``request.counted``) is + the error result, and nothing else happens. Otherwise the run is named + (its instance ``<type>-<n>``, numbered past the stored instances, and + its run ``<instance>#1``, under the caller's run) and starts with its + ``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. + + Raises: + KeyError: ``request.agent_type`` is not one of the manager's types. + """ + config = self._types[request.agent_type] + conversation = ( + request.conversation if request.conversation is not None else get_active_turn() ) + with _as_turn(conversation): + if request.counted: + refused = self._past_runs_per_turn(config.name) + if refused is not None: + return refused + count_run_this_turn() + await self._number_past_stored(conversation) + ref = self._runs.run_for(conversation, request.caller, request.call_id, config.name) + brief = request.brief + self._emit(WorkflowEvent.agent_run( + ref, RUN_STARTED, call_id=request.call_id, title=run_title(brief.title), + brief=brief.fields(), started_by=request.started_by, mode=BLOCKING, + inherit_context=config.inherit_context, continuable=config.continuable, + )) + return await self._run( + ref, config, conversation, request.call_id, + message=task_message(brief, inherit=config.inherit_context), + state=request.state, + history=request.history if config.inherit_context else None, + ) async def follow_up( self, request: FollowUpRequest, *, _reserved: list[bool] | None = None diff --git a/src/agentic_cli/workflow/agents/policy.py b/src/agentic_cli/workflow/agents/policy.py index 12c3d875..f3e5ded2 100644 --- a/src/agentic_cli/workflow/agents/policy.py +++ b/src/agentic_cli/workflow/agents/policy.py @@ -15,6 +15,11 @@ import math from dataclasses import dataclass, fields, replace +#: Who may start an agent type at run time: an agent's ``task`` call, a skill +#: an agent loads, the user. A run records it as ``agent:<instance>``, +#: ``skill:<name>`` or ``user``. +SPAWN_SOURCES = ("agent", "skill", "user") + def _check_count(owner: str, name: str, value: object, *, optional: bool) -> None: """Refuse ``value`` unless it is a positive int (or None, when ``optional``). @@ -107,9 +112,16 @@ class SubAgentPolicy: max_open: How many sub-agent instances a conversation keeps open (``idle`` or ``stopped``) between their runs; past it, as a run ends, the oldest idle one (by its last run's end) is closed. - follow_ups: Whether every agent with sub-agents gets + follow_ups: Whether every agent that can have sub-agents gets ``message_agent``, ``stop_agent`` and ``check_agents`` beside ``task``; False, ``task`` alone. + spawn_sources: Who may start an agent type at run time: a type whose + ``spawnable_by`` names a source this set holds may be started by + it. Empty by default (nothing is started at run time); a set, + list or tuple is kept as a frozenset. + max_spawn_depth: A run at depth ``d`` (the root's is 0) may start an + agent type at run time while ``d`` is below this; the configured + tree keeps its depth. """ max_active: int = 4 @@ -117,6 +129,8 @@ class SubAgentPolicy: limits: AgentLimits = DEFAULT_LIMITS max_open: int = 20 follow_ups: bool = False + spawn_sources: frozenset[str] = frozenset() + max_spawn_depth: int = 1 def __post_init__(self) -> None: _check_count("SubAgentPolicy", "max_active", self.max_active, optional=False) @@ -130,6 +144,20 @@ def __post_init__(self) -> None: f"SubAgentPolicy.limits must be an AgentLimits, not {self.limits!r}." ) _check_count("SubAgentPolicy", "max_open", self.max_open, optional=False) + object.__setattr__(self, "spawn_sources", _sources(self.spawn_sources)) + _check_count("SubAgentPolicy", "max_spawn_depth", self.max_spawn_depth, optional=False) + + +def _sources(value: object) -> frozenset[str]: + """``value`` as a frozenset of sources, or a ``ValueError`` naming it.""" + if isinstance(value, (set, frozenset, list, tuple)) and all( + isinstance(item, str) and item in SPAWN_SOURCES for item in value + ): + return frozenset(value) + allowed = ", ".join(repr(source) for source in SPAWN_SOURCES) + raise ValueError( + f"SubAgentPolicy.spawn_sources has {value!r}: each source must be one of {allowed}." + ) def as_policy(subagents: object) -> SubAgentPolicy: diff --git a/src/agentic_cli/workflow/agents/spawn.py b/src/agentic_cli/workflow/agents/spawn.py new file mode 100644 index 00000000..73a7776c --- /dev/null +++ b/src/agentic_cli/workflow/agents/spawn.py @@ -0,0 +1,89 @@ +"""What may start an agent type at run time, and which agents are built with ``task``. + +An app opts in twice: per source, in ``SubAgentPolicy.spawn_sources`` (an +agent's ``task`` call, a skill an agent loads, the user), and per type, in +``AgentConfig.spawnable_by``. ``spawnable`` is the types one source may +start; ``may_spawn`` says whether a run at a depth may start one +(``SubAgentPolicy.max_spawn_depth``, the root's depth being 0); and +``can_have_children`` says whether an agent is built with ``task`` (and, with +follow-ups, the tools and the roster that go with it): it has static +sub-agents, or it may start types at run time. Imports no backend. +""" + +from __future__ import annotations + +from collections.abc import Collection, Mapping, Sequence +from typing import TYPE_CHECKING + +from agentic_cli.workflow.agents.policy import SPAWN_SOURCES + +if TYPE_CHECKING: + from agentic_cli.workflow.agents.policy import SubAgentPolicy + from agentic_cli.workflow.config import AgentConfig + +AGENT_SOURCE, SKILL_SOURCE, USER_SOURCE = SPAWN_SOURCES + + +def spawnable( + configs: Sequence[AgentConfig], policy: SubAgentPolicy, source: str +) -> tuple[str, ...]: + """The types ``source`` may start at run time, in config order. + + ``source`` must be one the policy enables, and the type must name it in + its ``spawnable_by``. + """ + if source not in policy.spawn_sources: + return () + return tuple( + config.name + for config in configs + if config.spawnable_by is not None and source in config.spawnable_by + ) + + +def may_spawn(depth: int, policy: SubAgentPolicy) -> bool: + """Whether a run at ``depth`` (the root's is 0) may start a type at run time.""" + return depth < policy.max_spawn_depth + + +def can_have_children( + config: AgentConfig, + configs: Sequence[AgentConfig], + policy: SubAgentPolicy, + *, + root: bool, +) -> bool: + """Whether ``config`` is built with ``task``: static sub-agents, or types it may start. + + An agent may start types at run time when it does not inherit its + parent's conversation, some type is spawnable by agents, and it is the + root or runs below the root may start one too (``max_spawn_depth`` of 2 + or more). + """ + if config.sub_agents: + return True + return ( + not config.inherit_context + and bool(spawnable(configs, policy, AGENT_SOURCE)) + and (root or policy.max_spawn_depth >= 2) + ) + + +def depth_sentence_applies( + offered: Mapping[str, AgentConfig], + own: Collection[str], + depth: int, + policy: SubAgentPolicy, +) -> bool: + """Whether ``task``'s description says sub-agents cannot start sub-agents. + + It does when ``offered`` holds a type started at run time (one not in + ``own``, the caller's static sub-agents), what that run starts would + reach ``max_spawn_depth``, and no offered type has static sub-agents of + its own. + """ + return ( + any(name not in own for name in offered) + and not may_spawn(depth + 1, policy) + and not any(config.sub_agents for config in offered.values()) + ) diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index 6ba87c61..db4e7eef 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -69,6 +69,7 @@ RUN_END_STATUSES, AgentRuns, ) +from agentic_cli.workflow.agents.spawn import can_have_children from agentic_cli.workflow.usage import ( PURPOSE_MEMORY_EXTRACTION, PURPOSE_SIDE_CALL, @@ -369,7 +370,10 @@ def _get_state_tools(self) -> list[Callable]: return [] # the backend's plan and task tools def _validate_agent_graph(self) -> AgentGraph: - return validate_agent_graph(self._agent_configs, backend=self.backend_type) + return validate_agent_graph( + self._agent_configs, backend=self.backend_type, + policy=self.subagent_policy, + ) async def _do_initialize(self) -> None: self._engine = object() # build the backend's agents or graph @@ -1800,12 +1804,17 @@ def _rosters(self) -> Rosters: def _roster_wanted(self, root: str) -> bool: """Whether ``root``'s requests carry the roster of its sub-agents. - Only a root that can continue them does (it has ``message_agent``: - sub-agents and the policy's ``follow_ups``); without the tool it could - do nothing with an open instance. + Only a root that can continue them does (it has ``message_agent``: it + can have sub-agents, its own or types started at run time, and the + policy's ``follow_ups``); without the tool it could do nothing with an + open instance. """ config = next((c for c in self._agent_configs if c.name == root), None) - return config is not None and bool(config.sub_agents) and self.subagent_policy.follow_ups + return ( + config is not None + and self.subagent_policy.follow_ups + and can_have_children(config, self._agent_configs, self.subagent_policy, root=True) + ) def _roster_now(self) -> str: """The roster the turn's conversation carries, taken the first time it is diff --git a/src/agentic_cli/workflow/config.py b/src/agentic_cli/workflow/config.py index aa158ca8..9cd43c4d 100644 --- a/src/agentic_cli/workflow/config.py +++ b/src/agentic_cli/workflow/config.py @@ -5,13 +5,20 @@ from typing import Callable, Any, TYPE_CHECKING from agentic_cli.workflow.agents.brief import BRIEF_FIELDS -from agentic_cli.workflow.agents.policy import AgentLimits +from agentic_cli.logging import Loggers +from agentic_cli.workflow.agents.policy import ( + SPAWN_SOURCES, + AgentLimits, + SubAgentPolicy, + as_policy, +) if TYPE_CHECKING: from agentic_cli.config import BaseSettings from agentic_cli.workflow.model_settings import ModelSettings from agentic_cli.workflow.mcp import MCPServerConfig +logger = Loggers.workflow() #: The brief fields a delegation must fill unless an agent asks for more. _DEFAULT_BRIEF_REQUIRED = ("objective",) @@ -73,6 +80,13 @@ class AgentConfig: continuable: Whether an instance of this agent takes follow-ups after its run. True (the default) keeps it ``idle`` for the next; False closes it when its run ends. Only on sub-agents. + spawnable_by: Who may start this type at run time (a subset of + ``SPAWN_SOURCES``: ``agent``, ``skill``, ``user``; a list or + tuple is read as one), which the app's ``SubAgentPolicy`` + must allow too. None (the default): only its parent in + ``sub_agents`` starts it. A type that sets it and is in no + ``sub_agents`` list is a free type: no root, started at run time + only. Only on sub-agents. """ name: str @@ -89,6 +103,7 @@ class AgentConfig: brief_required: tuple[str, ...] = _DEFAULT_BRIEF_REQUIRED limits: AgentLimits | None = None continuable: bool = True + spawnable_by: frozenset[str] | None = None def get_prompt(self, settings: "BaseSettings | None" = None) -> str: """Get the prompt string, calling the factory if the prompt is callable. @@ -190,15 +205,22 @@ class AgentGraph: config_map: Agent name → config. build_order: Names ordered so every agent follows its sub-agents. root_name: The agent the runner starts from. + free_types: The agent types that set ``spawnable_by`` and are in no + ``sub_agents`` list, in config order: built like any sub-agent, + started at run time only, never the root. """ config_map: dict[str, AgentConfig] build_order: tuple[str, ...] root_name: str + free_types: tuple[str, ...] = () def validate_agent_graph( - configs: list[AgentConfig], backend: str = "adk" + configs: list[AgentConfig], + backend: str = "adk", + *, + policy: SubAgentPolicy | None = None, ) -> AgentGraph: """Validate an agent graph and return it in dependency (topological) order. @@ -211,7 +233,10 @@ def validate_agent_graph( 5. no delegation cycle; 6. no agent is a sub-agent of two parents — ADK agents hold a single ``parent_agent``, so a shared child is a tree the backend cannot build; - 7. exactly one root; + 7. exactly one root among the agents that are not free types: each + agent's ``spawnable_by`` is checked first (None, or a non-empty set, + list or tuple of ``SPAWN_SOURCES``), a free type is one that sets it + and is in no ``sub_agents`` list, and the root may not set it; 8. each agent's ``inherit_context`` is True or False; 9. the root does not set ``inherit_context``: it has no parent's conversation; @@ -225,9 +250,14 @@ def validate_agent_graph( objective), ``limits`` and ``continuable`` (beyond True): it is never delegated to. + A free type that no source ``policy`` enables can start is warned of + (``subagent_type_unreachable``), once for each validation. + Args: configs: The declared agents. backend: Backend name, used only in error messages. + policy: The app's sub-agent policy (None: ``SubAgentPolicy()``); + only the free types' warning reads it. Returns: The validated graph plus a build order in which every agent comes after @@ -235,7 +265,9 @@ def validate_agent_graph( Raises: AgentGraphError: With the offending agent name(s) in the message. + TypeError: ``policy`` is neither a ``SubAgentPolicy`` nor None. """ + policy = as_policy(policy) if not configs: raise AgentGraphError("No agents configured: at least one AgentConfig is required.") @@ -284,12 +316,27 @@ def validate_agent_graph( ) order = _topological_order(config_map) - # The root is the agent nobody delegates to. Selecting "first config with - # sub_agents" made the root depend on declaration order (listing a - # sub-coordinator before its parent promoted the child to root) and - # silently accepted a forest: only one root is ever run, so every other - # tree — and every agent under it — was unreachable. - roots = [c.name for c in configs if c.name not in parents] + _check_spawnable_by(configs) + free = tuple( + c.name for c in configs if c.spawnable_by is not None and c.name not in parents + ) + # The root is the agent nobody delegates to that is no free type. + # Selecting "first config with sub_agents" made the root depend on + # declaration order (listing a sub-coordinator before its parent promoted + # the child to root) and silently accepted a forest: only one root is ever + # run, so every other tree — and every agent under it — was unreachable. + roots = [c.name for c in configs if c.name not in parents and c.name not in free] + if not roots: + if len(free) == 1: + raise AgentGraphError( + f"Agent {free[0]!r} is the root agent and cannot set spawnable_by: " + "only a sub-agent type is started at run time." + ) + raise AgentGraphError( + f"Agent graph has no root: every agent nobody delegates to ({', '.join(free)}) " + "sets spawnable_by, which makes it a type started at run time. Leave " + "spawnable_by off the agent the runner starts from." + ) if len(roots) > 1: raise AgentGraphError( f"Agent graph has {len(roots)} roots: {', '.join(sorted(roots))}. " @@ -299,7 +346,50 @@ def validate_agent_graph( ) _check_inherit_context(config_map, roots[0]) _check_delegation_fields(config_map, roots[0]) - return AgentGraph(config_map=config_map, build_order=order, root_name=roots[0]) + _warn_unreachable([config_map[name] for name in free], policy) + return AgentGraph( + config_map=config_map, build_order=order, root_name=roots[0], free_types=free + ) + + +def _check_spawnable_by(configs: list[AgentConfig]) -> None: + """Each agent's ``spawnable_by`` is None, or a non-empty set, list or tuple of sources. + + Raises: + AgentGraphError: Naming the agent, the value and what to change. + """ + allowed = ", ".join(repr(source) for source in SPAWN_SOURCES) + for config in configs: + value = config.spawnable_by + if value is None: + continue + if isinstance(value, (set, frozenset, list, tuple)) and not value: + raise AgentGraphError( + f"Agent {config.name!r} has an empty spawnable_by: name at least one " + "source, or leave it out for a type only its parent starts." + ) + if not isinstance(value, (set, frozenset, list, tuple)) or not all( + isinstance(item, str) and item in SPAWN_SOURCES for item in value + ): + raise AgentGraphError( + f"Agent {config.name!r} has spawnable_by {value!r}: each source must be " + f"one of {allowed}." + ) + + +def _warn_unreachable(free: list[AgentConfig], policy: SubAgentPolicy) -> None: + """Log each free type that no source the policy enables can start. + + An app may define types it enables per install, so this is a warning. + """ + for config in free: + if not set(config.spawnable_by or ()) & policy.spawn_sources: + logger.warning( + "subagent_type_unreachable", + agent=config.name, + spawnable_by=sorted(config.spawnable_by or ()), + spawn_sources=sorted(policy.spawn_sources), + ) def _check_inherit_context(config_map: dict[str, AgentConfig], root: str) -> None: diff --git a/src/agentic_cli/workflow/deepagents/agent_builder.py b/src/agentic_cli/workflow/deepagents/agent_builder.py index 1cd8937d..03999d7d 100644 --- a/src/agentic_cli/workflow/deepagents/agent_builder.py +++ b/src/agentic_cli/workflow/deepagents/agent_builder.py @@ -3,16 +3,18 @@ Every agent is its own graph, built apart from the others, on the manager's checkpointer (a sub-agent's runs are on a thread of its instance's own, which its follow-ups continue); a tree built without a checkpointer compiles its -sub-agents with none. An agent with -sub-agents gets the framework's ``task`` tool (``task_tool.build_task_tool``) -among its tools (with ``SubAgentPolicy.follow_ups``, also the parent's other -tools, ``task_tool.build_follow_up_tools``): a call hands the brief to the -manager's ``Delegations``, which runs the sub-agent's graph apart from the caller's stream -(``DeepAgentsWorkflowManager._run_agent``) and answers with the result -envelope. Only the configured sub-agents are offered: there is no automatic -general-purpose sub-agent, and none of Deep Agents' file tools. ``graphs``, -when given, is filled with every agent's graph by name: what the manager runs -a sub-agent on. +sub-agents with none. An agent with sub-agents, its own or types it may start +at run time (``spawn.can_have_children``), gets the framework's ``task`` tool +(``task_tool.build_task_tool``) among its tools (the root's offer fixed when +it is built, a sub-agent's rewritten for each model call by +``RunControlMiddleware``; with ``SubAgentPolicy.follow_ups``, also the +parent's other tools, ``task_tool.build_follow_up_tools``): a call hands the +brief to the manager's ``Delegations``, which runs the sub-agent's graph apart +from the caller's stream (``DeepAgentsWorkflowManager._run_agent``) and +answers with the result envelope. Only the configured sub-agents are offered: +there is no automatic general-purpose sub-agent, and none of Deep Agents' file +tools. ``graphs``, when given, is filled with every agent's graph by name: +what the manager runs a sub-agent on. Every stack, outermost first: ``InterruptedCallsMiddleware`` (answers a tool call a cancelled turn or a crash left without a result, before each run, as @@ -61,6 +63,7 @@ from agentic_cli.models import CacheMechanism from agentic_cli.tools._core.delegation import FOLLOW_UP_CLASH_ERROR, FOLLOW_UP_TOOLS, TASK_TOOL from agentic_cli.tools.registry import ToolDefinition, identify_tool +from agentic_cli.workflow.agents.spawn import can_have_children from agentic_cli.workflow.config import AgentConfig, AgentGraphError from agentic_cli.workflow.deepagents.middleware import ( ActiveToolCallMiddleware, @@ -118,11 +121,13 @@ def build_agent_tree( delegations: "Callable[[], Delegations] | None" = None, graphs: "dict[str, CompiledStateGraph] | None" = None, roster: Callable[[], str] | None = None, + root: str | None = None, ) -> "CompiledStateGraph": """Build every agent, each on its own, and return the root. Validates nothing: the manager runs ``validate_agent_graph`` first, so - ``configs`` is a tree with one root (the agent nobody delegates to). + ``configs`` holds one root (the agent nobody delegates to that is no + free type) and the free types, which are built as any sub-agent is. Args: configs: The agents. @@ -166,8 +171,9 @@ def build_agent_tree( snapshots: the root's summarization calls it when it writes a summary, before the request that carries the summary is sent. delegations: The manager's delegations (``BaseWorkflowManager._delegations``): - given, an agent with sub-agents gets the ``task`` tool, which - hands each call to them, and every agent but the root + given, an agent that can have sub-agents (its own, or types it may + start at run time) gets the ``task`` tool, which hands each call + to them, and every agent but the root ``RunControlMiddleware``, which keeps a run's limits. Without it no agent delegates (a tree a unit test builds alone). graphs: Filled, when given, with every agent's graph, by name. @@ -175,6 +181,9 @@ def build_agent_tree( (``""`` for none): given, the root's stack has ``RosterMiddleware`` and its summarization counts it (the manager passes it only for a root that continues its sub-agents). No other agent gets one. + root: The root's name (the validated graph's ``AgentGraph.root_name``). + None: the first agent nobody delegates to that sets no + ``spawnable_by``. Raises: AgentGraphError: A delegating agent's own tools include one named @@ -182,7 +191,11 @@ def build_agent_tree( """ config_map = {config.name: config for config in configs} delegated = {sub for config in configs for sub in config.sub_agents} - root = next(config.name for config in configs if config.name not in delegated) + if root is None: + root = next( + config.name for config in configs + if config.name not in delegated and config.spawnable_by is None + ) def build(name: str) -> "CompiledStateGraph": config = config_map[name] @@ -209,16 +222,13 @@ def build(name: str) -> "CompiledStateGraph": (name, middleware) for middleware in model_side if isinstance(middleware, ReportingSummarizationMiddleware) ) - follows = ( - bool(config.sub_agents) and delegations is not None - and delegations().policy.follow_ups - ) - own = _own_tools( - config, tools.get(name, []), delegates=bool(config.sub_agents), follows=follows + delegates = delegations is not None and can_have_children( + config, configs, delegations().policy, root=name == root ) - if config.sub_agents and delegations is not None: - types = {sub: config_map[sub] for sub in config.sub_agents} - own = [*own, build_task_tool(name, types, delegations)] + follows = delegates and delegations is not None and delegations().policy.follow_ups + own = _own_tools(config, tools.get(name, []), delegates=delegates, follows=follows) + if delegates and delegations is not None: + own = [*own, build_task_tool(name, delegations, root=name == root)] if follows: own = [*own, *build_follow_up_tools(delegations)] return create_agent( diff --git a/src/agentic_cli/workflow/deepagents/manager.py b/src/agentic_cli/workflow/deepagents/manager.py index 11bb6caf..b1726877 100644 --- a/src/agentic_cli/workflow/deepagents/manager.py +++ b/src/agentic_cli/workflow/deepagents/manager.py @@ -235,7 +235,9 @@ def _get_state_tools(self) -> list: def _validate_agent_graph(self) -> AgentGraph: """Reject an unbuildable agent graph before anything is allocated.""" - return validate_agent_graph(self._agent_configs, backend=self.backend_type) + return validate_agent_graph( + self._agent_configs, backend=self.backend_type, policy=self.subagent_policy + ) def _manages_context(self) -> bool: """Every agent is summarized by its own context numbers.""" @@ -312,6 +314,7 @@ async def _do_initialize(self) -> None: roster=self._roster_now if roster_wanted else None, delegations=lambda: self._delegations, graphs=graphs, + root=root, ) self._agent_graphs = graphs self._root_summarization = summarizers.get(root) diff --git a/src/agentic_cli/workflow/deepagents/middleware.py b/src/agentic_cli/workflow/deepagents/middleware.py index 6adbe7f3..8a68f8f0 100644 --- a/src/agentic_cli/workflow/deepagents/middleware.py +++ b/src/agentic_cli/workflow/deepagents/middleware.py @@ -70,6 +70,7 @@ from agentic_cli.logging import Loggers from agentic_cli.models import ProviderKind from agentic_cli.paths import resolve_path +from agentic_cli.tools._core.delegation import TASK_TOOL from agentic_cli.tools.registry import ToolDefinition, get_registry, identify_tool from agentic_cli.workflow.agents.control import STEP_LIMIT_NOTE from agentic_cli.workflow.agents.outcome import ( @@ -85,6 +86,7 @@ from agentic_cli.workflow.permissions.capabilities import _CapabilityExempt from agentic_cli.workflow.service_registry import PERMISSION_ENGINE, get_service from agentic_cli.workflow.sessions import ( + RunRef, ToolCallRef, get_active_run, get_active_turn, @@ -1136,12 +1138,17 @@ class RunControlMiddleware(AgentMiddleware): that reports no usage counts none of its own; - on the run's last call (``RunControl.final_call``: its step limit's, or one past its token limit that makes calls) the answer's tool calls - are dropped (``without_calls``), so the agent ends with that answer. - - The summarization inside it counts the note; the outcome middleware - outside it 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. + are dropped (``without_calls``), so the agent ends with that answer; + - the framework's ``task`` the request offers (found by identity, never an + app's own tool of that name) is the run's: its description and schema + are what the run may start (``Delegations.task_offer``, by the run's + depth), or the tool is left out when it may start nothing, as ADK + declares one per request. + + The summarization inside it counts the note and the rewritten tools; the + outcome middleware outside it 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. Args: delegations: The manager's delegations, asked at each call for the @@ -1167,6 +1174,9 @@ async def awrap_model_call( request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]], ) -> Any: + run = get_active_run() + if run is not None: + request = self._with_task_offered(request, run) control = self._control() if control is None: return await handler(request) @@ -1185,6 +1195,36 @@ async def awrap_model_call( response = _mapped(response, without_calls) return response + def _with_task_offered(self, request: ModelRequest, run: RunRef) -> ModelRequest: + """``request`` with the framework's ``task`` as ``run`` is offered it. + + The request it was given is not changed: the tool is replaced by a + copy with the offer's description and schema, or left out when the run + may start nothing. A request that offers no framework ``task`` is + returned as it is. The graph's tool node runs the tool it was built + with, by name, and LangChain checks no call against a dict schema, so + a call of a type the copy lists reaches ``Delegations.delegate``. + """ + framework = get_registry().get(TASK_TOOL) + tools = list(request.tools) + index = next( + ( + i for i, tool in enumerate(tools) + if isinstance(tool, BaseTool) and identify_tool(tool) is framework + ), + None, + ) + if index is None: + return request + offer = self._delegations().task_offer(run.agent, run.depth) + if offer is None: + del tools[index] + else: + tools[index] = tools[index].model_copy( + update={"description": offer.description, "args_schema": offer.parameters} + ) + return request.override(tools=tools) + def with_note(messages: list[AnyMessage], note: str) -> list[AnyMessage]: """``messages`` with ``note`` after the last, as the user's. diff --git a/src/agentic_cli/workflow/deepagents/task_tool.py b/src/agentic_cli/workflow/deepagents/task_tool.py index a4df3de5..1c6e457f 100644 --- a/src/agentic_cli/workflow/deepagents/task_tool.py +++ b/src/agentic_cli/workflow/deepagents/task_tool.py @@ -1,10 +1,15 @@ """Deep Agents' ``task`` tool: the framework's delegation, as a LangChain tool. -``build_task_tool`` makes a delegating agent's ``task``. Its schema and its -description are the framework's (``agents/brief.py``: ``task_parameters``, -``task_description``), as ADK's ``TaskTool``'s are, and a call hands its -arguments, as the model wrote them, to the manager's ``Delegations`` -(``agents/delegate.py``): it reads the brief, runs the sub-agent +``build_task_tool`` makes the ``task`` of an agent that can have sub-agents +(its own, or types it may start at run time: ``agents/spawn.py``). Its +schema and its description are the framework's, made for the types the run +that calls it may start (``Delegations.task_offer``: ``agents/brief.py``'s +``task_parameters`` and ``task_description``), as ADK's ``TaskTool``'s are: +the root's are fixed when it is built (depth 0), a sub-agent's are rewritten +for each of its model calls (``RunControlMiddleware``), and a call from a run +that may start nothing gets the answer for a tool it does not have. A call +hands its arguments, as the model wrote them, to the manager's +``Delegations`` (``agents/delegate.py``): it reads the brief, runs the sub-agent (``DeepAgentsWorkflowManager._run_agent``, apart from this agent's stream) and returns the result envelope. The call is answered with the envelope as JSON (unescaped, as ADK's), one ``ToolMessage``, and the shared state the run @@ -43,21 +48,24 @@ from langgraph.prebuilt import ToolRuntime from langgraph.types import Command +from agentic_cli.logging import Loggers from agentic_cli.tools._core.delegation import FOLLOW_UP_TOOLS, TASK_TOOL from agentic_cli.tools.registry import bind_tool_identity, get_registry from agentic_cli.workflow.agents.brief import ( follow_up_description, follow_up_parameters, - task_description, task_parameters, ) from agentic_cli.workflow.agents.delegate import DelegationRequest from agentic_cli.workflow.agents.follow_ups import call_follow_up_tool +from agentic_cli.workflow.deepagents.middleware import error_tool_message from agentic_cli.workflow.sessions import get_active_run +from agentic_cli.workflow.tool_errors import unknown_tool_result if TYPE_CHECKING: from agentic_cli.workflow.agents.delegate import Delegations - from agentic_cli.workflow.config import AgentConfig + +logger = Loggers.workflow() #: The state a run shares with its caller (``state.AgentCliState``): the #: outside-content mark alone, which starts from the caller's and comes back @@ -67,20 +75,34 @@ def build_task_tool( - agent: str, types: Mapping[str, AgentConfig], delegations: Callable[[], Delegations] + agent: str, delegations: Callable[[], Delegations], *, root: bool = True ) -> StructuredTool: - """``agent``'s ``task`` tool, which starts a run of one of ``types``. + """``agent``'s ``task`` tool, which starts a run of a type the calling run may start. + + Its schema and description are the offer at the agent's first depth (the + root's 0, any other agent's 1), made once with the warnings; a + sub-agent's are rewritten for each model call. Args: agent: The delegating agent's name. - types: Its sub-agents, by name: what ``agent_type`` may name. delegations: The manager's delegations, asked for at each call. + root: Whether the agent is the root. """ + offer = delegations().task_offer(agent, 0 if root else 1, warn=True) async def task(runtime: ToolRuntime, **arguments: Any) -> Command: state = runtime.state + caller = get_active_run() + if not delegations().offered(agent, caller.depth if caller is not None else 0): + # A run that may start nothing is offered no task: a call of the + # name gets the answer for a tool it does not have, as on ADK. + logger.info("tool_not_found", tool=TASK_TOOL, agent=agent) + others = [tool.name for tool in runtime.tools or () if tool.name != TASK_TOOL] + call = {"name": TASK_TOOL, "args": arguments, "id": runtime.tool_call_id} + answer = error_tool_message(unknown_tool_result(TASK_TOOL, others), call) + return Command(update={"messages": [answer]}) delegated = await delegations().delegate(DelegationRequest( - caller=get_active_run(), + caller=caller, caller_agent=agent, call_id=runtime.tool_call_id, arguments=arguments, @@ -97,8 +119,8 @@ async def task(runtime: ToolRuntime, **arguments: Any) -> Command: tool = StructuredTool.from_function( coroutine=task, name=TASK_TOOL, - description=task_description(types, delegations().policy), - args_schema=task_parameters(types), + description=offer.description if offer is not None else "", + args_schema=offer.parameters if offer is not None else task_parameters({}), infer_schema=False, ) bind_tool_identity(tool, get_registry().get(TASK_TOOL)) diff --git a/tests/workflow/deepagents/test_agent_builder.py b/tests/workflow/deepagents/test_agent_builder.py index f34b1a8a..589057fc 100644 --- a/tests/workflow/deepagents/test_agent_builder.py +++ b/tests/workflow/deepagents/test_agent_builder.py @@ -190,6 +190,39 @@ async def test_the_root_is_the_agent_nobody_delegates_to(self, created): assert created["coordinator"]["checkpointer"] is not None assert len(coordinator.requests) == 1 and researcher.requests == [] + async def test_a_free_type_listed_first_is_no_root(self, created): + helper = AgentConfig(name="helper", prompt="p", spawnable_by=frozenset({"agent"})) + coordinator = ScriptedChat(script=[ai("Hello.")]) + free = ScriptedChat(script=[]) + + root = _tree( + [helper, COORDINATOR, RESEARCHER], + {"helper": free, "coordinator": coordinator, "researcher": ScriptedChat()}, + checkpointer=InMemorySaver(), + ) + await _turn(root) + + assert len(coordinator.requests) == 1 and free.requests == [] + # Built as a sub-agent is: a run's control in its stack. + assert RunControlMiddleware in [type(m) for m in created["helper"]["middleware"]] + + async def test_the_root_given_is_the_root(self, created): + coordinator = ScriptedChat(script=[ai("Hello.")]) + other = ScriptedChat(script=[]) + alone = AgentConfig(name="alone", prompt="p") + + root = _tree( + [alone, COORDINATOR, RESEARCHER], + {"alone": other, "coordinator": coordinator, "researcher": ScriptedChat()}, + checkpointer=InMemorySaver(), root="coordinator", + ) + await _turn(root) + + assert len(coordinator.requests) == 1 and other.requests == [] + assert RunControlMiddleware not in [ + type(m) for m in created["coordinator"]["middleware"] + ] + async def test_a_single_agent_is_its_own_root(self, created): solo = ScriptedChat(script=[ai("Hi.")]) saver = InMemorySaver() diff --git a/tests/workflow/deepagents/test_run_control_middleware.py b/tests/workflow/deepagents/test_run_control_middleware.py index 5481cd57..bdb8e7b7 100644 --- a/tests/workflow/deepagents/test_run_control_middleware.py +++ b/tests/workflow/deepagents/test_run_control_middleware.py @@ -1,29 +1,39 @@ """Deep Agents: a sub-agent run's limits at its model calls (``RunControlMiddleware``). -What the middleware does to a request and an answer, alone. Whole turns, on +What the middleware does to a request and an answer, alone: a run's limits, and the +``task`` its request offers (what the run may start). Whole turns, on both backends, are in the contract suite (``TestTheStepLimit``, ``TestTheTokenLimit``). """ from __future__ import annotations +import json from types import SimpleNamespace import pytest +from structlog.testing import capture_logs pytest.importorskip("deepagents") +from langchain.agents.middleware import ModelRequest # noqa: E402 from langchain_core.messages import AIMessage, HumanMessage, ToolMessage # noqa: E402 +from langchain_core.tools import StructuredTool # noqa: E402 +from agentic_cli.workflow.agents import AgentRuns, SubAgentPolicy # noqa: E402 from agentic_cli.workflow.agents.control import STEP_LIMIT_NOTE, RunControl # noqa: E402 +from agentic_cli.workflow.agents.delegate import Delegations # noqa: E402 from agentic_cli.workflow.agents.envelope import TOKEN_LIMIT_ERROR # noqa: E402 from agentic_cli.workflow.agents.policy import AgentLimits # noqa: E402 +from agentic_cli.workflow.config import AgentConfig # noqa: E402 from agentic_cli.workflow.deepagents.middleware import ( # noqa: E402 RunControlMiddleware, with_note, without_calls, ) -from agentic_cli.workflow.sessions import RunRef # noqa: E402 +from agentic_cli.workflow.deepagents.task_tool import build_task_tool # noqa: E402 +from agentic_cli.workflow.sessions import RunRef, reset_active_run, set_active_run # noqa: E402 +from agentic_cli.workflow.tool_errors import unknown_tool_result # noqa: E402 CALL = {"name": "lookup", "args": {"q": "X"}, "id": "r1", "type": "tool_call"} @@ -168,3 +178,103 @@ async def handler(request): await middleware.awrap_model_call(SimpleNamespace(messages=update["messages"]), handler) assert control.unstored() == [] + + +# -- task, offered for each model call what the run may start ------------------------- + + +def _hook(): + async def hook(run): # pragma: no cover - no run starts here + raise AssertionError("no run starts") + + return hook + + +def _offering(policy: SubAgentPolicy): + """A researcher's task, an own tool, the middleware and the delegations, under ``policy``.""" + configs = [ + AgentConfig(name="coordinator", prompt="p", sub_agents=["researcher"]), + AgentConfig(name="researcher", prompt="p", description="Finds facts."), + AgentConfig(name="helper", prompt="p", description="Helps.", + spawnable_by=frozenset({"agent"})), + ] + made = Delegations(runs=AgentRuns(), policy=policy, + types={c.name: c for c in configs}, hook=_hook()) + task = build_task_tool("researcher", lambda: made, root=False) + lookup = StructuredTool.from_function(lambda q="": "42", name="lookup", description="Look up.") + return made, task, lookup, RunControlMiddleware(lambda: made) + + +def _request(tools: list) -> ModelRequest: + return ModelRequest( + model=None, messages=[HumanMessage("# Task: Find X.")], system_message=None, + tool_choice=None, tools=tools, response_format=None, state={}, runtime=None, + ) + + +async def _offered(middleware, request: ModelRequest, run: RunRef | None) -> list: + """The tools ``request`` offers once the middleware has it, in ``run``.""" + seen: list = [] + + async def handler(sent): + seen.append(list(sent.tools)) + return AIMessage("Done.") + + token = set_active_run(run) + try: + await middleware.awrap_model_call(request, handler) + finally: + reset_active_run(token) + (tools,) = seen + return tools + + +DEEPER = SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=2) + + +async def test_a_runs_task_offers_what_the_run_may_start(): + made, task, lookup, middleware = _offering(DEEPER) + request = _request([lookup, task]) + + tools = await _offered(middleware, request, REF) + + assert [tool.name for tool in tools] == ["lookup", "task"] + offer = made.task_offer("researcher", 1) + assert (tools[1].description, tools[1].args_schema) == (offer.description, offer.parameters) + assert tools[1].args_schema["properties"]["agent_type"]["enum"] == ["helper"] + assert request.tools == [lookup, task] # the request it was given is as it was + + +async def test_a_run_that_may_start_nothing_is_offered_no_task(): + _, task, lookup, middleware = _offering(DEEPER) + deep = RunRef(agent="researcher", instance="researcher-2", run="researcher-2#1", + parent_run="helper-1#1", depth=2) + + assert await _offered(middleware, _request([lookup, task]), deep) == [lookup] + + +async def test_an_apps_own_tool_named_task_is_left_alone(): + _, _, lookup, middleware = _offering(SubAgentPolicy()) + own = StructuredTool.from_function(lambda: "mine", name="task", description="An app's own.") + + assert await _offered(middleware, _request([lookup, own]), REF) == [lookup, own] + + +async def test_the_roots_calls_keep_their_task(): + _, task, lookup, middleware = _offering(DEEPER) + + assert await _offered(middleware, _request([lookup, task]), None) == [lookup, task] + + +async def test_a_task_call_by_a_run_offered_nothing_is_logged_at_info(): + """The model's mistake, as at the permission gate: nothing over the prompt.""" + _, task, lookup, _ = _offering(SubAgentPolicy()) + runtime = SimpleNamespace(state={}, tools=[lookup, task], tool_call_id="t1") + + with capture_logs() as logs: + result = await task.coroutine(runtime, agent_type="researcher") + + (message,) = result.update["messages"] + assert message.status == "error" + assert json.loads(message.content) == unknown_tool_result("task", ["lookup"]) + assert [(log["log_level"], log["event"]) for log in logs] == [("info", "tool_not_found")] diff --git a/tests/workflow/test_adk_delegation.py b/tests/workflow/test_adk_delegation.py index 365b6787..d9be9ceb 100644 --- a/tests/workflow/test_adk_delegation.py +++ b/tests/workflow/test_adk_delegation.py @@ -52,6 +52,7 @@ from google.adk.apps import App # noqa: E402 from google.adk.events import Event # noqa: E402 from google.adk.models.anthropic_llm import AnthropicLlm # noqa: E402 +from google.adk.models.llm_request import LlmRequest # noqa: E402 from google.adk.sessions import InMemorySessionService # noqa: E402 from google.adk.tools import BaseTool, LongRunningFunctionTool # noqa: E402 from google.adk.tools.agent_tool import AgentTool # noqa: E402 @@ -87,12 +88,15 @@ follow_up_parameters, task_message, ) +from agentic_cli.workflow.agents.delegate import Delegations # noqa: E402 from agentic_cli.workflow.agents.envelope import read_envelope # noqa: E402 +from agentic_cli.workflow.agents.runs import AgentRuns # noqa: E402 from agentic_cli.workflow.config import AgentConfig, AgentGraphError # noqa: E402 from agentic_cli.workflow.context import context_budget # noqa: E402 from agentic_cli.workflow.events import EventType # noqa: E402 from agentic_cli.workflow.permissions import EXEMPT # noqa: E402 from agentic_cli.workflow.permissions.prompt import DENY_CHOICE # noqa: E402 +from agentic_cli.workflow.sessions import RunRef, reset_active_run, set_active_run # noqa: E402 from tests.workflow.adk.fakes import FakeAPI, anthropic_message, http_library # noqa: E402 from tests.workflow.test_manager_models import route # noqa: E402 from tests.workflow.test_skills import _make_skill # noqa: E402 @@ -1187,7 +1191,7 @@ class Delegate(TaskTool): manager = manager_for(team()) await manager.initialize_services() try: - tool = Delegate("coordinator", {"researcher": team()[1]}, lambda: manager._delegations) + tool = Delegate("coordinator", lambda: manager._delegations) finally: await manager.cleanup() # A subclass may run anything: only an exact TaskTool is bound. @@ -1199,6 +1203,81 @@ async def test_an_apps_agent_tool_is_denied(self, project): assert _denied(await _gate(AgentTool(stranger))) +class TestTaskDeclaredPerRun: + """``TaskTool`` declares, for each request, what the run that asks may + start (``Delegations.task_offer``, by its depth): nothing at all once it + may start nothing.""" + + @staticmethod + def tools(policy: SubAgentPolicy) -> tuple[Delegations, TaskTool, TaskTool]: + configs = [ + AgentConfig(name="coordinator", prompt="p", sub_agents=["researcher"]), + AgentConfig(name="researcher", prompt="p", description="Finds facts."), + AgentConfig(name="helper", prompt="p", description="Helps.", + spawnable_by=frozenset({"agent"})), + ] + + async def hook(run): # pragma: no cover - no run starts here + raise AssertionError("no run starts") + + made = Delegations(runs=AgentRuns(), policy=policy, + types={c.name: c for c in configs}, hook=hook) + return (made, TaskTool("coordinator", lambda: made), + TaskTool("researcher", lambda: made, root=False)) + + @staticmethod + def declared(tool: TaskTool, depth: int | None) -> types.FunctionDeclaration | None: + """``tool``'s declaration in a run at ``depth`` (None: the root's own request).""" + run = None if depth is None else RunRef( + agent="researcher", instance="researcher-1", run="researcher-1#1", + parent_run=None, depth=depth, + ) + token = set_active_run(run) + try: + return tool._get_declaration() + finally: + reset_active_run(token) + + def test_the_roots_own_request_is_offered_what_depth_0_may_start(self): + made, root, _ = self.tools(SubAgentPolicy(spawn_sources={"agent"})) + + declared = self.declared(root, None) + + offer = made.task_offer("coordinator", 0) + assert (declared.name, declared.description, declared.parameters_json_schema) == ( + TASK_TOOL, offer.description, offer.parameters, + ) + assert offer.parameters["properties"]["agent_type"]["enum"] == ["researcher", "helper"] + assert root.description == offer.description + + def test_a_sub_agents_request_is_its_runs(self): + made, _, researcher = self.tools( + SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=2) + ) + + declared = self.declared(researcher, 1) + + assert declared.parameters_json_schema == made.task_offer("researcher", 1).parameters + assert declared.parameters_json_schema["properties"]["agent_type"]["enum"] == ["helper"] + + def test_a_run_that_may_start_nothing_is_declared_no_task(self): + _, _, researcher = self.tools(SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=2)) + + assert self.declared(researcher, 2) is None + # Built at its first depth (1): what that run is offered. + assert "- helper: Helps." in researcher.description + + def test_the_default_policy_declares_its_own_sub_agents(self): + made, root, _ = self.tools(SubAgentPolicy()) + + declared = self.declared(root, None) + + assert declared.parameters_json_schema["properties"]["agent_type"]["enum"] == [ + "researcher" + ] + assert declared.description == made.task_offer("coordinator", 0).description + + # --- jobs ----------------------------------------------------------------------------- @@ -1393,6 +1472,20 @@ async def test_a_skill_toolsets_tools_are_its_static_list(self, tmp_path): t.name for t in toolset._tools } + def test_a_tool_declared_none_is_not_offered(self): + """``TaskTool`` declares no ``task`` to a run that may start nothing: + ADK adds a tool to a request only for a declaration, so the model is + offered none and a call of the name finds no tool (ADK's stand-in).""" + + class Undeclared(_Probe): + def _get_declaration(self): + return None + + request = LlmRequest() + request.append_tools([Undeclared()]) + + assert (request.tools_dict, request.config.tools) == ({}, None) + def test_a_base_tool_is_made_from_its_name_and_description(self): parameters = inspect.signature(BaseTool.__init__).parameters assert {"name", "description"} <= set(parameters) diff --git a/tests/workflow/test_agent_brief.py b/tests/workflow/test_agent_brief.py index f5c32be3..864bfbbc 100644 --- a/tests/workflow/test_agent_brief.py +++ b/tests/workflow/test_agent_brief.py @@ -22,14 +22,17 @@ from agentic_cli.workflow.agents import brief as brief_module from agentic_cli.workflow.agents.brief import ( BRIEF_FIELDS, + DEPTH_SENTENCE, INHERITED_CONTEXT_NOTE, Brief, BriefError, + TaskOffer, follow_up_description, follow_up_parameters, read_brief, task_description, task_message, + task_offer, task_parameters, ) from agentic_cli.workflow.agents.policy import SubAgentPolicy @@ -336,6 +339,42 @@ def sentences(policy: SubAgentPolicy) -> list[str]: assert paragraphs[3].startswith("The agents you can hand a task to:") assert seen == [policy] + def test_the_depth_sentence_follows_the_limits(self, logged): + text = task_description(TYPES, SubAgentPolicy(), depth_sentence=True) + assert DEPTH_SENTENCE == "Sub-agents cannot start sub-agents." + assert text.split("\n\n")[2] == ( + "At most 4 sub-agents work at once; more calls in one response wait for a free " + "slot. At most 20 runs per turn. Sub-agents cannot start sub-agents." + ) + assert text.replace(" Sub-agents cannot start sub-agents.", "") == ( + task_description(TYPES, SubAgentPolicy()) + ) + + def test_it_can_be_made_without_a_warning(self, logged): + text = task_description({"notes": NOTES}, SubAgentPolicy(), warn=False) + assert text.endswith(": The notes agent.") + assert logged == [] + + +class TestTaskOffer: + """What ``task`` offers one run: the types, the schema and the description, + made together from the same types.""" + + def test_its_parts(self, logged): + offer = task_offer(TYPES, SubAgentPolicy(max_active=2)) + + assert offer == TaskOffer( + types=TYPES, parameters=task_parameters(TYPES), + description=task_description(TYPES, SubAgentPolicy(max_active=2)), + ) + assert logged == [] # made per run: it warns only when asked + + def test_with_the_depth_sentence_and_the_warning(self, logged): + offer = task_offer({"notes": NOTES}, SubAgentPolicy(), depth_sentence=True, warn=True) + + assert DEPTH_SENTENCE in offer.description + assert [e["event"] for e in logged] == ["subagent_without_description"] + AGENT_ID = "The sub-agent's id, such as researcher-2." diff --git a/tests/workflow/test_agent_delegate.py b/tests/workflow/test_agent_delegate.py index 637d6979..e67df250 100644 --- a/tests/workflow/test_agent_delegate.py +++ b/tests/workflow/test_agent_delegate.py @@ -41,7 +41,14 @@ SubAgentPolicy, ) from agentic_cli.workflow.agents import delegate as delegate_module -from agentic_cli.workflow.agents.brief import INHERITED_CONTEXT_NOTE, Brief, task_message +from agentic_cli.workflow.agents.brief import ( + DEPTH_SENTENCE, + INHERITED_CONTEXT_NOTE, + Brief, + task_description, + task_message, + task_parameters, +) from agentic_cli.workflow.agents.delegate import ( RUNS_PER_TURN_ERROR, AgentRun, @@ -50,6 +57,7 @@ FollowUpRequest, RunAnswer, RunFailed, + StartRequest, started_by, waiting_on_user, ) @@ -3708,3 +3716,383 @@ async def test_neither_blocks_the_event_loop(self): assert await made.close_by_user(CONVERSATION, "researcher-1") == ["researcher-1"] await asyncio.wait_for(turn.task, 5) + + +# -- what a run may start: its own sub-agents, and the types started at run time ------- + +HELPER = AgentConfig(name="helper", prompt="p", description="Helps.", + spawnable_by=frozenset({"agent"})) +NOTER = AgentConfig(name="noter", prompt="p", description="Notes.", inherit_context=True, + spawnable_by=frozenset({"agent"})) +ASKED = AgentConfig(name="asked", prompt="p", description="Answers.", + spawnable_by=frozenset({"user"})) +PLANNER = AgentConfig(name="planner", prompt="p", description="Plans.", sub_agents=["leaf"], + spawnable_by=frozenset({"agent"})) +SPAWNING = {**TYPES, "helper": HELPER, "noter": NOTER, "asked": ASKED} +AGENTS = SubAgentPolicy(spawn_sources={"agent", "user"}) +HELP = {"agent_type": "helper", "title": "Help", "objective": "Help with X."} + + +def at(depth: int, agent: str = "middle") -> RunRef: + """A run of ``agent`` at ``depth``.""" + return RunRef(agent=agent, instance=f"{agent}-1", run=f"{agent}-1#1", parent_run=None, + depth=depth) + + +class TestWhatARunMayStart: + """``offered``: a run's own sub-agents in their order, then, while the + run's depth is below ``max_spawn_depth`` and it does not inherit, the + types agents may start at run time; an inheriting one only for the + root.""" + + def test_with_the_default_policy_its_own_sub_agents(self): + made = delegations(answering()[0], types=SPAWNING) + assert list(made.offered("coordinator", 0)) == ["researcher", "middle", "reader"] + assert list(made.offered("middle", 1)) == ["leaf"] + assert made.offered("researcher", 1) == {} + assert made.offered("coordinator", 0) == made.sub_agents("coordinator") + + def test_the_root_its_own_then_the_run_time_types_in_config_order(self): + made = delegations(answering()[0], types=SPAWNING, policy=AGENTS) + offered = made.offered("coordinator", 0) + assert list(offered) == ["researcher", "middle", "reader", "helper", "noter"] + assert offered["helper"] is HELPER + + def test_past_the_depth_its_own_alone(self): + made = delegations(answering()[0], types=SPAWNING, policy=AGENTS) + assert list(made.offered("middle", 1)) == ["leaf"] + assert made.offered("researcher", 1) == {} + + def test_below_the_root_no_inheriting_type(self): + deeper = SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=3) + made = delegations(answering()[0], types=SPAWNING, policy=deeper) + assert list(made.offered("middle", 1)) == ["leaf", "helper"] + assert list(made.offered("researcher", 2)) == ["helper"] + assert made.offered("researcher", 3) == {} + + def test_an_inheriting_run_starts_none(self): + deeper = SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=3) + made = delegations(answering()[0], types=SPAWNING, policy=deeper) + assert made.offered("reader", 1) == {} + assert made.offered("noter", 1) == {} + + def test_a_type_that_is_its_own_too_is_offered_once_in_its_place(self): + types = {**SPAWNING, "researcher": AgentConfig( + name="researcher", prompt="p", spawnable_by=frozenset({"agent"}))} + made = delegations(answering()[0], types=types, policy=AGENTS) + assert list(made.offered("coordinator", 0)) == [ + "researcher", "middle", "reader", "helper", "noter", + ] + + def test_an_unknown_agent_starts_none(self): + made = delegations(answering()[0], types=SPAWNING, policy=AGENTS) + assert made.offered("nobody", 0) == {} + + +#: A lead whose own sub-agent has none, and the types agents may start. +LEAD = AgentConfig(name="lead", prompt="p", sub_agents=["researcher"]) +LED = {"lead": LEAD, "researcher": TYPES["researcher"], "helper": HELPER, "noter": NOTER} + + +class TestTheTaskOffer: + """``task_offer``: what ``task`` declares for a run, or None when it offers nothing.""" + + def test_the_schema_and_description_of_what_the_run_may_start(self): + made = delegations(answering()[0], types=LED, policy=AGENTS) + + offer = made.task_offer("lead", 0) + + assert list(offer.types) == ["researcher", "helper", "noter"] + assert offer.parameters == task_parameters(offer.types) + assert offer.description == task_description(offer.types, AGENTS, depth_sentence=True) + + def test_none_when_it_offers_nothing(self): + made = delegations(answering()[0], types=SPAWNING, policy=AGENTS) + assert made.task_offer("researcher", 1) is None + assert made.task_offer("middle", 1) is not None + + def test_the_default_policy_says_what_it_said(self): + made = delegations(answering()[0], types=LED) + offer = made.task_offer("lead", 0) + assert offer.description == task_description(made.sub_agents("lead"), SubAgentPolicy()) + assert DEPTH_SENTENCE not in offer.description + + @pytest.mark.parametrize("policy, types, caller, depth, says", [ + # What the root starts may start nothing: it says so. + (AGENTS, LED, "lead", 0, True), + # One level more: what it starts may. + (SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=2), LED, "lead", 0, False), + # A run one level above the limit. + (SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=2), LED, "researcher", 1, True), + # Its own sub-agents alone: no run-time type, no sentence. + (AGENTS, SPAWNING, "middle", 1, False), + # A type it offers has sub-agents of its own: that one may start them. + (AGENTS, SPAWNING, "coordinator", 0, False), + (AGENTS, {**LED, "planner": PLANNER, "leaf": TYPES["leaf"]}, "lead", 0, False), + ]) + def test_the_depth_sentence(self, policy, types, caller, depth, says): + made = delegations(answering()[0], types=types, policy=policy) + assert (DEPTH_SENTENCE in made.task_offer(caller, depth).description) is says + + +class TestTheOffersWarning: + """``task_offer`` warns of a type without a description only when asked + (a build asks, a per-request offer does not).""" + + @staticmethod + def logged(warn: bool) -> list[str]: + from structlog.testing import capture_logs + + types = { + "lead": AgentConfig(name="lead", prompt="p", sub_agents=["notes"]), + "notes": AgentConfig(name="notes", prompt="p"), + } + made = delegations(answering()[0], types=types) + with capture_logs() as logs: + assert made.task_offer("lead", 0, warn=warn) is not None + return [log["event"] for log in logs] + + def test_when_asked(self): + assert self.logged(True) == ["subagent_without_description"] + + def test_not_by_default(self): + assert self.logged(False) == [] + + +class TestADelegationToATypeStartedAtRunTime: + async def test_the_root_starts_one(self): + hook, asked = answering("Helped.") + runs = AgentRuns() + + result, events = await delegated( + delegations(hook, runs=runs, types=SPAWNING, policy=AGENTS), request(HELP) + ) + + assert result.result == { + "success": True, "agent": "helper-1", "run": "helper-1#1", + "status": RUN_COMPLETED, "partial": False, "result": "Helped.", "error": None, + } + (run,) = asked + assert (run.ref.depth, run.ref.parent_run, run.config) == (1, None, HELPER) + assert events[0].metadata["started_by"] == "agent:root" + (instance,) = runs.instances(CONVERSATION) + assert (instance.instance, instance.parent, instance.depth) == ("helper-1", "root", 1) + + async def test_one_the_policy_does_not_let_agents_start_is_unknown(self): + hook, asked = answering() + made = delegations(hook, types=SPAWNING, policy=SubAgentPolicy(spawn_sources={"user"})) + + result, events = await delegated(made, request(HELP)) + + assert result.result == { + "success": False, + "error": "Unknown agent_type 'helper': the agents you can delegate to are " + "researcher, middle, reader.", + } + assert (asked, events) == ([], []) + + async def test_past_the_depth_it_is_unknown(self): + hook, asked = answering() + made = delegations(hook, types=SPAWNING, policy=AGENTS) + + result, events = await delegated( + made, request(HELP, caller=at(1), caller_agent="middle", call_id="m1") + ) + + assert result.result["error"] == ( + "Unknown agent_type 'helper': the agents you can delegate to are leaf." + ) + assert (asked, events) == ([], []) + + async def test_a_run_above_the_depth_starts_one_a_level_down(self): + hook, asked = answering() + deeper = SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=2) + made = delegations(hook, types=SPAWNING, policy=deeper) + + result, events = await delegated( + made, request(HELP, caller=at(1, "researcher"), caller_agent="researcher") + ) + + assert result.result["agent"] == "helper-1" + (run,) = asked + assert (run.ref.depth, run.ref.parent_run) == (2, "researcher-1#1") + assert events[0].metadata["started_by"] == "agent:researcher-1" + + +# -- one entry for a first run: start ------------------------------------------------- + +def start_request(agent_type: str = "researcher", **fields: Any) -> StartRequest: + return StartRequest( + agent_type=agent_type, + brief=fields.pop("brief", Brief(title="Find X", objective="Find X.")), + started_by=fields.pop("started_by", "skill:find"), call_id=fields.pop("call_id", "c1"), + **fields, + ) + + +async def started(made: Delegations, asked: StartRequest) -> tuple[Any, list[WorkflowEvent]]: + """``made.start(asked)`` in a turn of ``CONVERSATION`` (its span open); its result, and + what it reported.""" + live = LiveEvents() + out: dict[str, Any] = {} + + async def source(): + token = set_active_turn(CONVERSATION) + scope = open_turn_scope() + try: + with live_events.reporting(live): + out["result"] = await made.start(asked) + out["counted"] = runs_this_turn() + finally: + close_turn_scope(scope) + reset_active_turn(token) + if False: # pragma: no cover + yield + + events = [item async for item in merged(source(), live)] + return out, events + + +class TestStart: + """``start``: a first run of a type, whoever starts it, run as a + delegation's: numbered, reported with who started it, run to its end.""" + + async def test_runs_the_type_to_its_end_and_says_who_started_it(self): + hook, asked = answering() + runs = AgentRuns() + + out, events = await started(delegations(hook, runs=runs), start_request()) + + assert out["result"].result == { + "success": True, "agent": "researcher-1", "run": "researcher-1#1", + "status": RUN_COMPLETED, "partial": False, "result": "X is 42.", "error": None, + } + (run,) = asked + assert run.message == task_message(Brief(title="Find X", objective="Find X.")) + assert (run.ref, run.history, run.follow_up) == (RESEARCHER, None, False) + assert events[0].metadata == { + "status": RUN_STARTED, "agent": "researcher", "partial": False, "call_id": "c1", + "title": "Find X", "brief": {"title": "Find X", "objective": "Find X."}, + "started_by": "skill:find", "mode": "blocking", + "inherit_context": False, "continuable": True, + } + assert out["counted"] == 1 + (record,) = runs.records(CONVERSATION) + assert record.started_by == "skill:find" + + async def test_under_the_run_that_starts_it(self): + hook, asked = answering() + + await started(delegations(hook), start_request( + "leaf", caller=at(1), started_by="agent:middle-1", call_id="m1", + )) + + (run,) = asked + assert (run.ref.instance, run.ref.depth, run.ref.parent_run) == ( + "leaf-1", 2, "middle-1#1" + ) + + async def test_one_not_counted_is_not_refused_past_the_runs_a_turn_may_start(self): + hook, asked = answering() + made = delegations(hook, policy=SubAgentPolicy(max_runs_per_turn=1)) + live = LiveEvents() + results: list[Any] = [] + + async def source(): + token = set_active_turn(CONVERSATION) + scope = open_turn_scope() + try: + with live_events.reporting(live): + results.append(await made.start(start_request(call_id="c1"))) + results.append(await made.start(start_request(call_id="c2"))) + results.append(await made.start(start_request( + call_id="c3", started_by="user", counted=False, + ))) + results.append(runs_this_turn()) + finally: + close_turn_scope(scope) + reset_active_turn(token) + if False: # pragma: no cover + yield + + async for _ in merged(source(), live): + pass + + first, refused, uncounted, counted = results + assert first.result["status"] == RUN_COMPLETED + assert refused.result == { + "success": False, "error": RUNS_PER_TURN_ERROR.format(limit=1), + } + assert (uncounted.result["status"], uncounted.result["agent"]) == ( + RUN_COMPLETED, "researcher-2" + ) + assert counted == 1 + assert len(asked) == 2 + + async def test_numbered_past_the_stored(self): + hook, _ = answering() + stored, asked = storing({"researcher": 4}) + + out, _ = await started(delegations(hook, stored=stored), start_request()) + + assert out["result"].result["agent"] == "researcher-5" + assert asked == [CONVERSATION] + + async def test_an_inheriting_type_reads_its_history_once(self): + hook, asked = answering() + read: list[int] = [] + + def history() -> list[str]: + read.append(1) + return ["the conversation"] + + await started(delegations(hook), start_request( + "reader", brief=Brief(title="Read", objective="Read it."), history=history, + )) + + (run,) = asked + assert (run.history, read) == (["the conversation"], [1]) + assert run.message.endswith(INHERITED_CONTEXT_NOTE) + + async def test_a_fresh_type_never_reads_it(self): + hook, asked = answering() + + def history() -> list[str]: + raise AssertionError("a fresh run read the conversation") + + await started(delegations(hook), start_request(history=history)) + + assert asked[0].history is None + + async def test_its_state_is_the_runs_and_its_conversation_the_one_named(self): + hook, asked = answering() + other = SessionRef("app", "u", "other") + + await started(delegations(hook), start_request( + conversation=other, state={"outside_content": "web_fetch"}, + )) + + (run,) = asked + assert (run.conversation, run.state) == (other, {"outside_content": "web_fetch"}) + + async def test_a_type_that_is_no_type_is_a_key_error(self): + hook, asked = answering() + + with pytest.raises(KeyError): + await delegations(hook).start(start_request("nobody")) + assert asked == [] + + def test_its_fields_and_defaults(self): + made = StartRequest(agent_type="researcher", brief=Brief(title="T", objective="O"), + started_by="user") + assert (made.caller, made.call_id, made.conversation, made.state, made.history, + made.counted) == (None, None, None, {}, None, True) + + +async def test_a_start_blocks_no_event_loop(): + hook, _ = answering() + + with no_blocking_calls(): + out, events = await started(delegations(hook), start_request()) + + assert out["result"].result["status"] == RUN_COMPLETED diff --git a/tests/workflow/test_agent_loader.py b/tests/workflow/test_agent_loader.py index d89a9e7e..9543ac33 100644 --- a/tests/workflow/test_agent_loader.py +++ b/tests/workflow/test_agent_loader.py @@ -12,8 +12,9 @@ create_workflow_manager_from_yaml, load_agents_from_yaml, ) -from agentic_cli.workflow.agents.policy import AgentLimits +from agentic_cli.workflow.agents.policy import AgentLimits, SubAgentPolicy from agentic_cli.workflow.base_manager import BaseWorkflowManager +from agentic_cli.workflow.config import AgentGraphError, validate_agent_graph def _write(tmp_path: Path, text: str, name: str = "agents.yaml") -> Path: @@ -133,6 +134,7 @@ def test_defaults(self, tmp_path): assert cfg.brief_required == ("objective",) assert cfg.limits is None assert cfg.continuable is True + assert cfg.spawnable_by is None def test_a_sub_agents_inherit_context(self, tmp_path): path = _write( @@ -234,6 +236,60 @@ def test_an_unknown_limit_is_rejected(self, tmp_path): assert "agents.0.limits.steps" in message assert "Extra inputs are not permitted" in message + def test_a_type_started_at_run_time(self, tmp_path): + # Listed before the root: a free type is never the root. + path = _write( + tmp_path, + """ + agents: + - name: helper + instruction: Help. + spawnable_by: [agent, user] + - name: coordinator + instruction: Lead. + sub_agents: [researcher] + - name: researcher + instruction: Find facts. + spawnable_by: [skill] + """, + ) + configs = load_agents_from_yaml(path) + found = {c.name: c.spawnable_by for c in configs} + assert found == { + "helper": frozenset({"agent", "user"}), "coordinator": None, + "researcher": frozenset({"skill"}), + } + graph = validate_agent_graph( + configs, policy=SubAgentPolicy(spawn_sources={"agent", "user", "skill"}) + ) + assert (graph.root_name, graph.free_types) == ("coordinator", ("helper",)) + + def test_spawnable_by_is_a_list(self, tmp_path): + path = _write( + tmp_path, "agents:\n - name: a\n instruction: hi\n spawnable_by: agent\n" + ) + with pytest.raises(ValidationError) as exc: + load_agents_from_yaml(path) + message = str(exc.value) + assert "agents.0.spawnable_by" in message and "valid list" in message + + def test_a_source_spawnable_by_does_not_name_is_the_graphs_to_refuse(self, tmp_path): + path = _write( + tmp_path, + """ + agents: + - name: coordinator + instruction: Lead. + sub_agents: [researcher] + - name: researcher + instruction: Find facts. + spawnable_by: [agents] + """, + ) + configs = load_agents_from_yaml(path) + with pytest.raises(AgentGraphError, match="'researcher' has spawnable_by frozenset"): + validate_agent_graph(configs) + def test_brief_required_is_a_list(self, tmp_path): path = _write( tmp_path, diff --git a/tests/workflow/test_agent_policy.py b/tests/workflow/test_agent_policy.py index 4156b311..75fc5834 100644 --- a/tests/workflow/test_agent_policy.py +++ b/tests/workflow/test_agent_policy.py @@ -19,6 +19,7 @@ from agentic_cli.workflow import agents from agentic_cli.workflow.agents.policy import ( DEFAULT_LIMITS, + SPAWN_SOURCES, AgentLimits, SubAgentPolicy, as_policy, @@ -87,9 +88,9 @@ def test_the_defaults(self): assert policy.max_open == 20 assert policy.follow_ups is False - def test_max_open_and_follow_ups_come_last(self): + def test_max_open_and_follow_ups_come_after_the_first_ones(self): # Appended: a positional SubAgentPolicy(...) written before them still binds. - assert [f.name for f in dataclasses.fields(SubAgentPolicy)][-2:] == [ + assert [f.name for f in dataclasses.fields(SubAgentPolicy)][3:5] == [ "max_open", "follow_ups", ] assert SubAgentPolicy(max_open=3).max_open == 3 @@ -141,6 +142,57 @@ def test_its_own_limits_replace_the_default_limits_whole(self): assert kept == AgentLimits(max_model_calls=100, timeout=60) +class TestRunTimeStarts: + """``spawn_sources``: who may start an agent type at run time (none by + default); ``max_spawn_depth``: from how deep a run may start one.""" + + def test_the_defaults(self): + policy = SubAgentPolicy() + assert policy.spawn_sources == frozenset() + assert policy.max_spawn_depth == 1 + + def test_the_sources(self): + assert SPAWN_SOURCES == ("agent", "skill", "user") + + def test_they_come_after_follow_ups(self): + # Appended: a positional SubAgentPolicy(...) written before them still binds. + assert [f.name for f in dataclasses.fields(SubAgentPolicy)][-2:] == [ + "spawn_sources", "max_spawn_depth", + ] + + @pytest.mark.parametrize("given", [{"agent", "user"}, ["user", "agent"], ("agent", "user"), + frozenset({"agent", "user"})]) + def test_a_set_list_or_tuple_of_sources_is_kept_as_a_frozenset(self, given): + policy = SubAgentPolicy(spawn_sources=given) + assert policy.spawn_sources == frozenset({"agent", "user"}) + assert type(policy.spawn_sources) is frozenset + hash(policy) # still hashable, as a frozen dataclass + + def test_every_source_may_be_named(self): + assert SubAgentPolicy(spawn_sources=SPAWN_SOURCES).spawn_sources == frozenset(SPAWN_SOURCES) + + @pytest.mark.parametrize("value", [{"agents"}, ["agent", "tool"], {1}, "agent", None, True]) + def test_a_source_that_is_not_one_of_the_three_is_refused(self, value): + with pytest.raises(ValueError) as exc: + SubAgentPolicy(spawn_sources=value) + assert str(exc.value) == ( + f"SubAgentPolicy.spawn_sources has {value!r}: each source must be one of " + "'agent', 'skill', 'user'." + ) + + def test_a_depth_is_kept(self): + assert SubAgentPolicy(max_spawn_depth=3).max_spawn_depth == 3 + + @pytest.mark.parametrize("value", [0, -1, 1.0, None, "2", True]) + def test_max_spawn_depth_is_a_count(self, value): + with pytest.raises(ValueError) as exc: + SubAgentPolicy(max_spawn_depth=value) + assert str(exc.value) == f"SubAgentPolicy.max_spawn_depth must be a positive int, not {value!r}." + + def test_policies_with_the_same_sources_are_equal(self): + assert SubAgentPolicy(spawn_sources=["agent"]) == SubAgentPolicy(spawn_sources={"agent"}) + + class TestAsPolicy: def test_none_is_the_default_policy(self): assert as_policy(None) == SubAgentPolicy() diff --git a/tests/workflow/test_agent_spawn.py b/tests/workflow/test_agent_spawn.py new file mode 100644 index 00000000..93b1923b --- /dev/null +++ b/tests/workflow/test_agent_spawn.py @@ -0,0 +1,94 @@ +"""What may start an agent type at run time (``workflow/agents/spawn.py``). + +``spawnable`` is the types one source may start: the policy enables the +source (``SubAgentPolicy.spawn_sources``) and the type names it +(``AgentConfig.spawnable_by``). ``may_spawn`` says whether a run at a depth +may start one (``max_spawn_depth``), and ``can_have_children`` whether an +agent is built with ``task``: static sub-agents, or types it may start. +""" + +from __future__ import annotations + +import pytest + +from agentic_cli.workflow.agents.policy import SubAgentPolicy +from agentic_cli.workflow.agents.spawn import ( + AGENT_SOURCE, + SKILL_SOURCE, + USER_SOURCE, + can_have_children, + may_spawn, + spawnable, +) +from agentic_cli.workflow.config import AgentConfig + +LEAD = AgentConfig(name="lead", prompt="p", sub_agents=["researcher"]) +RESEARCHER = AgentConfig(name="researcher", prompt="p") +HELPER = AgentConfig(name="helper", prompt="p", spawnable_by=frozenset({"agent", "user"})) +SKILLED = AgentConfig(name="skilled", prompt="p", spawnable_by=frozenset({"skill"})) +READER = AgentConfig(name="reader", prompt="p", spawnable_by=frozenset({"agent"}), + inherit_context=True) +CONFIGS = [LEAD, RESEARCHER, HELPER, SKILLED, READER] +EVERY = SubAgentPolicy(spawn_sources={"agent", "skill", "user"}) + + +class TestTheSources: + def test_their_names(self): + assert (AGENT_SOURCE, SKILL_SOURCE, USER_SOURCE) == ("agent", "skill", "user") + + +class TestSpawnable: + def test_none_with_the_default_policy(self): + for source in ("agent", "skill", "user"): + assert spawnable(CONFIGS, SubAgentPolicy(), source) == () + + def test_the_types_that_name_a_source_the_policy_enables_in_config_order(self): + assert spawnable(CONFIGS, EVERY, "agent") == ("helper", "reader") + assert spawnable(CONFIGS, EVERY, "skill") == ("skilled",) + assert spawnable(CONFIGS, EVERY, "user") == ("helper",) + + def test_a_source_the_policy_leaves_out_starts_none(self): + policy = SubAgentPolicy(spawn_sources={"user"}) + assert spawnable(CONFIGS, policy, "agent") == () + assert spawnable(CONFIGS, policy, "user") == ("helper",) + + def test_a_static_sub_agent_that_names_one_is_spawnable_too(self): + writer = AgentConfig(name="writer", prompt="p", spawnable_by=["agent"]) + assert spawnable([LEAD, writer], EVERY, "agent") == ("writer",) + + +class TestMaySpawn: + @pytest.mark.parametrize("depth, limit, may", [ + (0, 1, True), (1, 1, False), (1, 2, True), (2, 2, False), (5, 9, True), + ]) + def test_below_the_limit_only(self, depth, limit, may): + assert may_spawn(depth, SubAgentPolicy(max_spawn_depth=limit)) is may + + +class TestCanHaveChildren: + def test_an_agent_with_sub_agents_can(self): + assert can_have_children(LEAD, CONFIGS, SubAgentPolicy(), root=True) + middle = AgentConfig(name="middle", prompt="p", sub_agents=["leaf"]) + assert can_have_children(middle, CONFIGS, SubAgentPolicy(), root=False) + + def test_by_default_one_without_cannot(self): + assert not can_have_children(RESEARCHER, CONFIGS, SubAgentPolicy(), root=False) + solo = AgentConfig(name="solo", prompt="p") + assert not can_have_children(solo, [solo], SubAgentPolicy(), root=True) + + def test_the_root_can_when_agents_may_start_a_type(self): + solo = AgentConfig(name="solo", prompt="p") + assert can_have_children(solo, [solo, HELPER], EVERY, root=True) + assert not can_have_children(solo, [solo, SKILLED], EVERY, root=True) + assert not can_have_children( + solo, [solo, HELPER], SubAgentPolicy(spawn_sources={"user"}), root=True + ) + + def test_a_sub_agent_can_only_when_runs_below_the_root_may_start_one(self): + assert not can_have_children(RESEARCHER, CONFIGS, EVERY, root=False) + deeper = SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=2) + assert can_have_children(RESEARCHER, CONFIGS, deeper, root=False) + + def test_an_inheriting_agent_never_can(self): + deeper = SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=3) + assert not can_have_children(READER, CONFIGS, deeper, root=False) diff --git a/tests/workflow/test_subagent_config.py b/tests/workflow/test_subagent_config.py index 42588a27..732ea54e 100644 --- a/tests/workflow/test_subagent_config.py +++ b/tests/workflow/test_subagent_config.py @@ -1,4 +1,4 @@ -"""A sub-agent type's delegation fields: ``brief_required``, ``limits`` and ``continuable``. +"""A sub-agent type's delegation fields: ``brief_required``, ``limits``, ``continuable`` and ``spawnable_by``. ``brief_required`` names the brief fields a delegation to the type must fill (the title and the objective are always needed); ``limits`` are the type's @@ -8,6 +8,11 @@ ``brief_required`` names brief fields, ``limits`` is an ``AgentLimits``, ``continuable`` is True or False, and the root sets none, since it is never delegated to. + +``spawnable_by`` names who may start the type at run time: a type that sets +it and is in no ``sub_agents`` list is a free type, never the root, and +``validate_agent_graph`` checks its sources, refuses it on the root and warns +of a free type the policy lets no source start. """ from __future__ import annotations @@ -16,8 +21,14 @@ import pytest -from agentic_cli.workflow.agents.policy import AgentLimits -from agentic_cli.workflow.config import AgentConfig, AgentGraphError, validate_agent_graph +from agentic_cli.workflow import config as config_module +from agentic_cli.workflow.agents.policy import AgentLimits, SubAgentPolicy +from agentic_cli.workflow.config import ( + AgentConfig, + AgentGraph, + AgentGraphError, + validate_agent_graph, +) def team(**fields: dict[str, object]) -> list[AgentConfig]: @@ -43,7 +54,11 @@ def test_an_instance_takes_follow_ups_by_default(self): def test_they_follow_inherit_context(self): # Appended: a positional AgentConfig(...) written before them still binds. names = [f.name for f in dataclasses.fields(AgentConfig)] - assert names[-4:] == ["inherit_context", "brief_required", "limits", "continuable"] + assert names[-5:] == ["inherit_context", "brief_required", "limits", "continuable", + "spawnable_by"] + + def test_only_its_parent_starts_it_by_default(self): + assert AgentConfig(name="a", prompt="p").spawnable_by is None def test_they_are_kept(self): limits = AgentLimits(timeout=60) @@ -142,3 +157,228 @@ def test_the_inherit_context_checks_come_first(self): configs = team(lead={"inherit_context": True, "limits": AgentLimits(timeout=1)}) with pytest.raises(AgentGraphError, match="inherit_context"): validate_agent_graph(configs) + + +@pytest.fixture +def logged(monkeypatch) -> list[dict]: + """Every log call of ``workflow/config.py``, with its level.""" + events: list[dict] = [] + + class Recorder: + def __getattr__(self, level: str): + def log(event: str, **fields) -> None: + events.append({"event": event, "log_level": level, **fields}) + + return log + + monkeypatch.setattr(config_module, "logger", Recorder()) + return events + + +AGENTS = SubAgentPolicy(spawn_sources={"agent"}) + + +def with_free(*free: AgentConfig, first: bool = False) -> list[AgentConfig]: + """``team()``'s lead and its sub-agents, with ``free`` before them (``first``) or after.""" + return [*free, *team()] if first else [*team(), *free] + + +class TestFreeTypes: + """A type that sets ``spawnable_by`` and is in no ``sub_agents`` list is a + free type: started at run time only, so it is no root.""" + + def test_a_free_type_is_no_second_root(self): + graph = validate_agent_graph( + with_free(AgentConfig(name="helper", prompt="p", spawnable_by=frozenset({"agent"}))), + policy=AGENTS, + ) + assert (graph.root_name, graph.free_types) == ("lead", ("helper",)) + + def test_listed_before_the_root_it_is_still_no_root(self): + graph = validate_agent_graph( + with_free(AgentConfig(name="helper", prompt="p", spawnable_by={"agent"}), first=True), + policy=AGENTS, + ) + assert (graph.root_name, graph.free_types) == ("lead", ("helper",)) + + def test_free_types_are_in_config_order_and_built_with_the_rest(self): + graph = validate_agent_graph( + [AgentConfig(name="b", prompt="p", spawnable_by=["agent"]), *team(), + AgentConfig(name="a", prompt="p", spawnable_by=("agent", "user"))], + policy=SubAgentPolicy(spawn_sources={"agent", "user"}), + ) + assert graph.free_types == ("b", "a") + assert {"a", "b"} <= set(graph.build_order) and set(graph.config_map) >= {"a", "b"} + + def test_a_free_type_may_have_sub_agents_of_its_own(self): + configs = with_free( + AgentConfig(name="planner", prompt="p", sub_agents=["checker"], + spawnable_by={"agent"}), + AgentConfig(name="checker", prompt="p"), + ) + graph = validate_agent_graph(configs, policy=AGENTS) + assert (graph.root_name, graph.free_types) == ("lead", ("planner",)) + assert graph.build_order.index("checker") < graph.build_order.index("planner") + + def test_a_sub_agent_may_be_started_at_run_time_too(self): + # In a sub_agents list: its parent's, and no free type. + graph = validate_agent_graph(team(writer={"spawnable_by": {"agent"}}), policy=AGENTS) + assert (graph.root_name, graph.free_types) == ("lead", ()) + + def test_without_spawnable_by_a_second_unreferenced_agent_is_still_a_second_root(self): + with pytest.raises(AgentGraphError, match="2 roots"): + validate_agent_graph(with_free(AgentConfig(name="helper", prompt="p"))) + + def test_two_roots_among_the_rest_are_still_refused(self): + with pytest.raises(AgentGraphError, match="2 roots: lead, other"): + validate_agent_graph( + with_free(AgentConfig(name="other", prompt="p"), + AgentConfig(name="helper", prompt="p", spawnable_by={"agent"})), + policy=AGENTS, + ) + + def test_a_free_inheriting_type_with_sub_agents_is_refused(self): + configs = with_free( + AgentConfig(name="reader", prompt="p", sub_agents=["checker"], + inherit_context=True, spawnable_by={"agent"}), + AgentConfig(name="checker", prompt="p"), + ) + with pytest.raises(AgentGraphError, match="'reader' set inherit_context=True and have"): + validate_agent_graph(configs, policy=AGENTS) + + def test_a_free_inheriting_type_without_sub_agents_is_valid(self): + configs = with_free(AgentConfig( + name="reader", prompt="p", inherit_context=True, spawnable_by={"agent"}, + )) + graph = validate_agent_graph(configs, policy=AGENTS) + assert (graph.root_name, graph.free_types) == ("lead", ("reader",)) + + def test_a_free_types_own_sub_agent_does_not_inherit(self): + configs = with_free( + AgentConfig(name="planner", prompt="p", sub_agents=["reader"], spawnable_by={"agent"}), + AgentConfig(name="reader", prompt="p", inherit_context=True), + ) + with pytest.raises(AgentGraphError, match="'reader' set inherit_context=True below"): + validate_agent_graph(configs, policy=AGENTS) + + def test_a_free_type_may_set_what_a_delegation_sets(self): + configs = with_free(AgentConfig( + name="helper", prompt="p", spawnable_by={"agent"}, continuable=False, + limits=AgentLimits(timeout=60), brief_required=("objective", "deliverable"), + )) + assert validate_agent_graph(configs, policy=AGENTS).free_types == ("helper",) + + def test_a_graph_has_no_free_types_by_default(self): + assert validate_agent_graph(team()).free_types == () + assert AgentGraph(config_map={}, build_order=(), root_name="r").free_types == () + + +class TestSpawnableBy: + """What ``spawnable_by`` may hold, and that the root sets none.""" + + @pytest.mark.parametrize("value", [{"agent"}, ["skill", "user"], ("agent", "skill", "user"), + frozenset({"user"})]) + def test_a_set_list_or_tuple_of_sources(self, value): + assert validate_agent_graph(team(writer={"spawnable_by": value})).root_name == "lead" + + @pytest.mark.parametrize("value", [{"agents"}, ["agent", "tool"], "agent", True, {1}]) + def test_a_source_that_is_not_one_of_the_three_is_refused(self, value): + with pytest.raises(AgentGraphError) as exc: + validate_agent_graph(team(writer={"spawnable_by": value})) + assert str(exc.value) == ( + f"Agent 'writer' has spawnable_by {value!r}: each source must be one of " + "'agent', 'skill', 'user'." + ) + + @pytest.mark.parametrize("value", [frozenset(), set(), [], ()]) + def test_an_empty_one_is_refused(self, value): + with pytest.raises(AgentGraphError) as exc: + validate_agent_graph(with_free(AgentConfig(name="helper", prompt="p", + spawnable_by=value))) + assert str(exc.value) == ( + "Agent 'helper' has an empty spawnable_by: name at least one source, or leave it " + "out for a type only its parent starts." + ) + + def test_the_root_cannot_set_it(self): + # The agent nobody delegates to, the only one: the root, whatever it sets. + with pytest.raises(AgentGraphError) as exc: + validate_agent_graph(team(lead={"spawnable_by": {"agent"}}), policy=AGENTS) + assert str(exc.value) == ( + "Agent 'lead' is the root agent and cannot set spawnable_by: only a sub-agent " + "type is started at run time." + ) + + def test_a_single_agent_cannot_set_it(self): + with pytest.raises(AgentGraphError, match="'solo' is the root agent and cannot set"): + validate_agent_graph( + [AgentConfig(name="solo", prompt="p", spawnable_by={"user"})], policy=AGENTS + ) + + def test_with_every_unreferenced_agent_free_there_is_no_root(self): + configs = [ + AgentConfig(name="helper", prompt="p", spawnable_by={"agent"}), + *team(lead={"spawnable_by": {"agent"}}), + ] + with pytest.raises(AgentGraphError) as exc: + validate_agent_graph(configs, policy=AGENTS) + assert str(exc.value) == ( + "Agent graph has no root: every agent nobody delegates to (helper, lead) sets " + "spawnable_by, which makes it a type started at run time. Leave spawnable_by off " + "the agent the runner starts from." + ) + + def test_the_values_are_checked_before_the_root(self): + # A bad source on a sub-agent is named, not the shape of the tree. + with pytest.raises(AgentGraphError, match="'writer' has spawnable_by"): + validate_agent_graph(team(writer={"spawnable_by": {"bogus"}}, + lead={"spawnable_by": {"agent"}})) + + +class TestAFreeTypeNoSourceCanStart: + """A free type the policy lets no source start is warned of, once for each + validation: an app may enable its sources per install.""" + + def test_is_a_warning_naming_it(self, logged): + configs = with_free(AgentConfig(name="helper", prompt="p", spawnable_by={"skill", "user"})) + + graph = validate_agent_graph(configs, policy=AGENTS) + + assert graph.free_types == ("helper",) + assert logged == [{ + "event": "subagent_type_unreachable", "log_level": "warning", "agent": "helper", + "spawnable_by": ["skill", "user"], "spawn_sources": ["agent"], + }] + + def test_with_the_default_policy_every_free_type_is(self, logged): + validate_agent_graph(with_free( + AgentConfig(name="a", prompt="p", spawnable_by={"agent"}), + AgentConfig(name="b", prompt="p", spawnable_by={"user"}), + )) + assert [(e["event"], e["agent"]) for e in logged] == [ + ("subagent_type_unreachable", "a"), ("subagent_type_unreachable", "b"), + ] + + def test_one_a_source_can_start_is_not(self, logged): + validate_agent_graph( + with_free(AgentConfig(name="helper", prompt="p", spawnable_by={"agent", "user"})), + policy=AGENTS, + ) + assert logged == [] + + def test_each_validation_says_so_again(self, logged): + # A model switch validates the same configs once more: a warning each time. + configs = with_free(AgentConfig(name="helper", prompt="p", spawnable_by={"user"})) + + validate_agent_graph(configs, policy=AGENTS) + validate_agent_graph(configs, policy=AGENTS) + + assert [e["event"] for e in logged] == ["subagent_type_unreachable"] * 2 + + def test_a_sub_agent_its_parent_starts_is_not(self, logged): + validate_agent_graph(team(writer={"spawnable_by": {"user"}}), policy=AGENTS) + assert logged == [] + + def test_the_policy_must_be_a_policy(self): + with pytest.raises(TypeError, match="subagents must be a SubAgentPolicy or None"): + validate_agent_graph(team(), policy={"spawn_sources": {"agent"}}) diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 9825b857..21dbeff2 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -53,6 +53,7 @@ import anthropic import httpx import pytest +from structlog.testing import capture_logs from agentic_cli.config import BaseSettings from agentic_cli.constants import TOOL_SUMMARY_MAX_LENGTH, truncate @@ -493,6 +494,7 @@ class Crew: _instance_mark: Callable[[str], Awaitable[str]] | None = None _models: Callable[[str], list[str]] | None = None _opening: Callable[[str, int], list[str]] | None = None + _declared: Callable[[str, str, int], dict[str, Any] | None] | None = None #: The turns ``start`` started: one a failed test left running is stopped #: before its manager is cleaned up (the cleanup waits for its turn). started: list["asyncio.Task[Any]"] = field(default_factory=list) @@ -595,6 +597,13 @@ def tool_names(self, agent: str, call: int = 0) -> list[str]: assert self._tool_names is not None return self._tool_names(agent, call) + def declared(self, agent: str, tool: str = "task", call: int = 0) -> dict[str, Any] | None: + """How ``agent``'s model request ``call`` offered ``tool``: its + ``description`` and ``parameters`` (its JSON schema), as sent; None + when the request did not offer it.""" + assert self._declared is not None + return self._declared(agent, tool, call) + def message_count(self, agent: str, call: int = 0) -> int: """How many messages ``agent``'s model request ``call`` held, its system prompt aside.""" assert self._message_count is not None @@ -723,6 +732,13 @@ def tool_names(name: str, call: int) -> list[str]: body = [body for sent, body in claude.sent if sent == name][call] return [tool["name"] for tool in body.get("tools", [])] + def declared(name: str, tool: str, call: int) -> dict[str, Any] | None: + body = [body for sent, body in claude.sent if sent == name][call] + found = next((t for t in body.get("tools", []) if t["name"] == tool), None) + if found is None: + return None + return {"description": found["description"], "parameters": found["input_schema"]} + def message_count(name: str, call: int) -> int: return len([body for sent, body in claude.sent if sent == name][call]["messages"]) @@ -767,7 +783,7 @@ def opening(name: str, call: int) -> list[str]: "adk", manager, manager.session_ref(SESSION, USER), results_read, requests, result_ids, answers, last_message, bodies, tool_names, message_count, state, marked, _call_results=call_results, _instance_mark=instance_mark, _models=models, - _opening=opening, + _opening=opening, _declared=declared, ) @@ -841,6 +857,12 @@ def bodies(name: str) -> list[str]: def tool_names(name: str, call: int) -> list[str]: return models.chats[name].tool_names(call) + def declared(name: str, tool: str, call: int) -> dict[str, Any] | None: + found = next((t for t in models.chats[name].bound[call] if t["name"] == tool), None) + if found is None: + return None + return {"description": found["description"], "parameters": found["parameters"]} + def message_count(name: str, call: int) -> int: return len(models.chats[name].conversation(call)) @@ -887,7 +909,7 @@ def opening(name: str, call: int) -> list[str]: "deepagents", manager, manager.session_ref(SESSION, USER), results_read, requests, result_ids, answers, last_message, bodies, tool_names, message_count, state, marked, _call_results=call_results, _instance_mark=instance_mark, _models=built_models, - _opening=opening, + _opening=opening, _declared=declared, ) @@ -6088,3 +6110,353 @@ async def test_the_notice_writes_the_held_mark_before_the_root_answers(self, mak assert before is False assert any(e.type is EventType.ERROR for e in events) assert await crew.marked() is True + + +# -- types started at run time ------------------------------------------------------- + +#: Agents may start a type at run time: from the root alone (``max_spawn_depth`` 1). +SPAWNING = SubAgentPolicy(spawn_sources={"agent"}) + + +def helper(**fields: Any) -> AgentConfig: + """A free type agents may start: ``spawnable_by`` set, in no ``sub_agents`` list.""" + return agent("helper", spawnable_by=fields.pop("spawnable_by", frozenset({"agent"})), + description="Helps with one thing.", **fields) + + +def spawn_team(**fields: Any) -> list[AgentConfig]: + """``team()`` and the helper agents may start, which looks things up.""" + return [*team(), helper(tools=(contract_lookup,), **fields)] + + +class TestATypeStartedAtRunTime: + async def test_the_root_starts_one(self, make_crew): + crew = make_crew( + spawn_team(), subagents=SPAWNING, + coordinator=[calls(delegate("helper", "Help with X.", "c1")), says("Done.")], + helper=[says("Helped.")], + ) + + with no_blocking_calls(): + events = await crew.turn() + + assert envelope_read(crew.results_read("coordinator")["c1"]) == { + "success": True, "agent": "helper-1", "run": "helper-1#1", + "status": RUN_COMPLETED, "partial": False, "result": "Helped.", "error": None, + } + (record,) = crew.records() + assert (record.ref.instance, record.ref.depth, record.ref.parent_run, + record.started_by) == ("helper-1", 1, None, "agent:root") + (instance,) = crew.manager.agent_runs.instances(crew.conversation) + assert (instance.agent, instance.parent, instance.depth, instance.status) == ( + "helper", "root", 1, INSTANCE_IDLE + ) + assert [e.metadata["status"] for e in runs_of(events)] == [RUN_STARTED, RUN_COMPLETED] + + async def test_the_roots_task_lists_it_and_its_requests_carry_none(self, make_crew): + crew = make_crew( + spawn_team(), subagents=SPAWNING, + coordinator=[calls(delegate("helper", "Help with X.", "c1")), says("Done.")], + helper=[says("Helped.")], + ) + + await crew.turn() + + declared = crew.declared("coordinator") + assert agent_types(declared) == ["researcher", "helper"] + assert declared["description"].split("\n\n")[2:] == [ + SPAWN_LIMITS, + "The agents you can hand a task to:\n- researcher: The researcher.\n" + "- helper: Helps with one thing.", + ] + # At the depth limit (1): what the root starts is offered no task. + assert crew.tool_names("helper") == ["contract_lookup"] + + async def test_one_level_down_it_starts_another_whose_requests_carry_no_task( + self, make_crew + ): + crew = make_crew( + spawn_team(), subagents=SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=2), + coordinator=[calls(delegate("helper", "Help with X.", "c1")), says("Done.")], + # helper-1, then helper-2 (the same type's script), then helper-1 again. + helper=[calls(delegate("helper", "Help more.", "h1")), says("Helped more."), + says("Helped.")], + ) + + await crew.turn() + + assert [(r.ref.instance, r.ref.depth, r.ref.parent_run, r.started_by) + for r in crew.records()] == [ + ("helper-1", 1, None, "agent:root"), + ("helper-2", 2, "helper-1#1", "agent:helper-1"), + ] + assert envelope_read(crew.results_read("helper", 2)["h1"])["result"] == "Helped more." + assert crew.tool_names("helper", 0) == ["contract_lookup", "task"] + assert agent_types(crew.declared("helper", call=0)) == ["helper"] + assert SPAWN_LIMITS in crew.declared("helper", call=0)["description"] + assert crew.tool_names("helper", 1) == ["contract_lookup"] + # What the root starts may start more: no depth sentence there. + assert "Sub-agents cannot start" not in crew.declared("coordinator")["description"] + + async def test_a_run_past_the_depth_that_calls_task_gets_the_unknown_tool_answer( + self, make_crew + ): + crew = make_crew( + spawn_team(), subagents=SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=2), + coordinator=[calls(delegate("helper", "Help with X.", "c1")), says("Done.")], + helper=[calls(delegate("helper", "Help more.", "h1")), + calls(delegate("helper", "And more.", "h2")), says("Could not."), + says("Helped.")], + ) + + await crew.turn() + + assert json.loads(crew.results_read("helper", 2)["h2"]) == { + "success": False, + "error": "task failed: ValueError: Tool 'task' not found.\n" + "Available tools: contract_lookup", + } + assert [r.ref.instance for r in crew.records()] == ["helper-1", "helper-2"] + + +class TestATypeNotOffered: + """What a run is not offered it cannot start: a call naming it is an + unknown type, and no run starts.""" + + @pytest.mark.parametrize("sources, starts", [({"agent", "user"}, True), ({"user"}, False)]) + async def test_only_while_the_policy_lets_agents_start_it(self, make_crew, sources, starts): + crew = make_crew( + spawn_team(spawnable_by=frozenset({"agent", "user"})), + subagents=SubAgentPolicy(spawn_sources=sources), + coordinator=[calls(delegate("helper", "Help with X.", "c1")), says("Done.")], + helper=[says("Helped.")], + ) + + events = await crew.turn() + + read = json.loads(crew.results_read("coordinator")["c1"]) + if starts: + assert (read["status"], read["agent"]) == (RUN_COMPLETED, "helper-1") + else: + assert read == { + "success": False, + "error": "Unknown agent_type 'helper': the agents you can delegate to are " + "researcher.", + } + assert (runs_of(events), crew.records(), crew.requests("helper")) == ([], [], 0) + + async def test_past_the_depth_while_a_static_tree_delegates_at_every_level(self, make_crew): + crew = make_crew( + [agent("coordinator", sub_agents=("researcher",)), + agent("researcher", sub_agents=("checker",)), + agent("checker", tools=(contract_lookup,)), + helper()], + subagents=SPAWNING, + coordinator=[calls(delegate("helper", "Help.", "c1")), + calls(delegate("researcher", "Find X.", "c2")), says("Done.")], + researcher=[calls(delegate("helper", "Help.", "r1")), + calls(delegate("checker", "Check X.", "r2")), says("X is 42.")], + checker=[says("Checked.")], + helper=[says("Helped.")], + ) + + await crew.turn() + + assert envelope_read(crew.results_read("coordinator", 1)["c1"])["agent"] == "helper-1" + assert json.loads(crew.results_read("researcher", 1)["r1"]) == { + "success": False, + "error": "Unknown agent_type 'helper': the agents you can delegate to are checker.", + } + assert [(r.ref.instance, r.ref.depth, r.status) for r in crew.records()] == [ + ("helper-1", 1, RUN_COMPLETED), ("researcher-1", 1, RUN_COMPLETED), + ("checker-1", 2, RUN_COMPLETED), + ] + assert crew.requests("helper") == 1 + + +class TestAFreeTypeListedFirst: + """A free type is never the root, wherever it is listed: the turn starts at + the agent nobody delegates to that is no free type, on both backends.""" + + async def test_in_the_configs(self, make_crew): + crew = make_crew( + [helper(tools=(contract_lookup,)), *team()], subagents=SPAWNING, + coordinator=[says("Hello.")], helper=[says("[never asked]")], + ) + + events = await crew.turn() + + assert crew.manager.root_agent_name == "coordinator" + assert (crew.requests("coordinator"), crew.requests("helper")) == (1, 0) + assert [e.content for e in events if e.type is EventType.TEXT] == ["Hello."] + + async def test_in_agent_yaml(self, make_crew, project): + from agentic_cli.workflow.agent_loader import load_agents_from_yaml + + path = project / "agents.yaml" + path.write_text( + "agents:\n" + " - name: helper\n instruction: You are helper.\n" + " description: Helps with one thing.\n include_state_tools: false\n" + " spawnable_by: [agent]\n" + " - name: coordinator\n instruction: You are coordinator.\n" + " include_state_tools: false\n sub_agents: [researcher]\n" + " - name: researcher\n instruction: You are researcher.\n" + " include_state_tools: false\n", + encoding="utf-8", + ) + crew = make_crew( + load_agents_from_yaml(path), subagents=SPAWNING, + coordinator=[says("Hello.")], helper=[says("[never asked]")], + ) + + await crew.turn() + + assert crew.manager.root_agent_name == "coordinator" + assert (crew.requests("coordinator"), crew.requests("helper")) == (1, 0) + + +#: ``task``'s declaration for ``team()``'s coordinator, as both backends send it +#: with the default policy: what an app that starts no type at run time keeps. +TEAM_TASK = { + "description": ( + "Hand a task to a sub-agent. The sub-agent works on it on its own, with its own " + "tools, and returns its result to you as this call's result; the user does not see " + "it, so tell the user what it means yourself. Several task calls in one response " + "run in parallel.\n\n" + "A sub-agent sees only the brief you write, unless its line below says it sees this " + "conversation: put in the brief everything it needs to know.\n\n" + "At most 4 sub-agents work at once; more calls in one response wait for a free " + "slot. At most 20 runs per turn.\n\n" + "The agents you can hand a task to:\n- researcher: The researcher." + ), + "parameters": { + "type": "object", + "properties": { + "agent_type": { + "type": "string", "enum": ["researcher"], + "description": "The agent to hand the task to:\n- researcher: The researcher.", + }, + "title": { + "type": "string", + "description": "A few words naming the task, shown to the user while it runs.", + }, + "objective": {"type": "string", "description": "What the sub-agent is to do."}, + "deliverable": {"type": "string", "description": "What to return and in what form."}, + "constraints": {"type": "string", "description": "Limits on how to do it."}, + "known": { + "type": "string", + "description": ( + "What you already know that the sub-agent needs: facts found, decisions " + "made, file paths and URLs, what was tried." + ), + }, + "done_when": {"type": "string", "description": "The criteria for the task to be done."}, + }, + "required": ["agent_type", "title", "objective"], + }, +} +#: The limits paragraph of ``task``'s description when what a run starts may start none. +SPAWN_LIMITS = ( + "At most 4 sub-agents work at once; more calls in one response wait for a free slot. " + "At most 20 runs per turn. Sub-agents cannot start sub-agents." +) + + +def agent_types(declared: dict[str, Any] | None) -> list[str]: + """The types a ``task`` declaration offers.""" + assert declared is not None + return declared["parameters"]["properties"]["agent_type"]["enum"] + + +class TestTheDefaultPolicyKeepsTask: + """With nothing started at run time, ``task`` is what it was, byte for byte.""" + + async def test_its_schema_and_description(self, make_crew): + crew = make_crew(team(), coordinator=[says("Hi.")]) + + await crew.turn() + + assert crew.declared("coordinator") == TEAM_TASK + + async def test_with_a_free_type_no_source_may_start(self, make_crew): + crew = make_crew(spawn_team(), coordinator=[says("Hi.")]) + + await crew.turn() + + assert crew.declared("coordinator") == TEAM_TASK + + +DEEPER = SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=2) + + +class TestTheOfferIsTheRuns: + """What a model is offered is its run's offer, not the one its agent was + built with: a type that runs at several depths.""" + + async def test_a_run_below_the_depth_it_was_built_for_is_offered_less(self, make_crew): + crew = make_crew( + [*team(), + agent("checker", tools=(contract_lookup,)), + agent("planner", sub_agents=("checker",), spawnable_by=frozenset({"agent"}))], + subagents=DEEPER, + coordinator=[calls(delegate("planner", "Plan X.", "c1")), says("Done.")], + # planner-1 (depth 1), then planner-2 (depth 2), then planner-1 again. + planner=[calls(delegate("planner", "Plan more.", "p1")), says("Planned more."), + says("Planned.")], + ) + + await crew.turn() + + assert [r.ref.instance for r in crew.records()] == ["planner-1", "planner-2"] + # Depth 1: its own checker, then the types agents may start. + assert agent_types(crew.declared("planner", call=0)) == ["checker", "planner"] + # Depth 2 may start none: its own sub-agent alone, and no depth sentence for it. + deep = crew.declared("planner", call=1) + assert agent_types(deep) == ["checker"] + assert "- planner:" not in deep["description"] + assert "Sub-agents cannot start" not in deep["description"] + + async def test_the_missing_description_is_warned_of_at_build_and_not_for_each_call( + self, make_crew + ): + crew = make_crew( + [*team(), agent("helper", tools=(contract_lookup,), description="", + spawnable_by=frozenset({"agent"}))], + subagents=DEEPER, + coordinator=[calls(delegate("helper", "Help with X.", "c1")), says("Done.")], + helper=[calls(delegate("helper", "Help more.", "h1")), says("Helped more."), + says("Helped.")], + ) + + with capture_logs() as logs: + await crew.turn() + + assert crew.requests("helper") == 3 and crew.requests("coordinator") == 2 + # One for each agent built with task (the coordinator, the researcher and the + # helper: each offers the helper), at build; none for a request. + 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): + crew = make_crew( + [agent("coordinator", tools=(contract_whoami,)), helper()], + subagents=SubAgentPolicy(follow_ups=True, spawn_sources={"agent"}), + coordinator=[calls(delegate("helper", "Help with X.", "c1")), says("Asked."), + says("Listed.")], + helper=[says("Helped.")], + ) + await crew.turn() + assert crew.tool_names("coordinator") == [ + "contract_whoami", "task", "message_agent", "stop_agent", "check_agents", + ] + + await crew.manager.load_session(SESSION, user_id=USER) + await crew.turn("And now?") + + assert crew.opening("coordinator", -1) == [ + roster("- helper-1 (helper, idle): Help with X. — Helped."), "Go.", + ]