diff --git a/CHANGELOG.md b/CHANGELOG.md index 76b44eb6..3bb6f790 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -575,6 +575,46 @@ the start of the entry's title. ### Added +- **The built-in `general_purpose` type: `SubAgentPolicy.general_purpose`, on + both backends.** With `general_purpose=True` (False by default; True with + no `spawn_sources` is a `ValueError`: "SubAgentPolicy.general_purpose needs + spawn_sources: with none, nothing could start it."), every source the + policy enables may start `general_purpose`, a type the app does not + configure: an agent's `task` lists it after the app's types ("- + general_purpose: A general-purpose agent with your own tools (but not the + ones that start agents) and your model, for a self-contained task no other + agent fits."), a skill may name it (`agent: general_purpose`), and the user + may start it (`/agent new general_purpose `). Its run has the + tools, MCP servers, skills and model of the type that started it (the + caller's type for `task` and a skill, the main agent for the user; the + type's own model, never a run's model choice), the framework's system + prompt, a fresh context and the plan's tools, and it starts no agent: no + `task`, none of the parent's tools, and a skill it loads that names an + agent is refused. `task`'s `tools` narrows it against its spawner's tools; + its `model` is refused (it has no model choices). Each backend builds one + for every type that may start it, at initialization (the main agent, and + with `max_spawn_depth` 2 or more every type that does not inherit when + agents may start types, and every type with skills when skills may), with + MCP connections of its own (ADK: an agent and a runner of its own, + connecting at first use; Deep Agents: a graph of its own, whose MCP + sessions open at initialization, so a server that cannot start is a notice + for it too, naming its spawner in `metadata["spawner"]`, and one that never + answers is waited for once more per spawner), built again by a model + switch and released with the others; a main agent with no sub-agents gets + `task` for it alone when agents may start it. Its instances are `general_purpose-`, and the + records keep the type each was made for (`InstanceRecord.based_on`, from + the run's start, `WorkflowEvent.agent_run(based_on=)`; records written + before it read None), so its follow-ups, the user's and after a restart, + run as its first run did (one whose type no longer makes one is refused as + a type that is gone), and its view shows that type's model and context. + While the policy enables it, an app's agent of that name is refused + (`AgentGraphError`: "An agent named 'general_purpose' clashes with the + built-in general_purpose type, which this app's SubAgentPolicy + enables."). `agentic_cli.workflow.agents.spawn` (provisional): + `GENERAL_PURPOSE`, `GENERAL_PURPOSE_PROMPT`, `GENERAL_PURPOSE_DESCRIPTION`, + `general_purpose_config`, `general_purpose_spawners`, `root_type`; the + manager's delegations' `general_purpose` and `config_for(agent_type, + based_on=)`. - **`/agent new `: you start a sub-agent, and its view opens on its first run.** A type whose `spawnable_by` names `"user"`, in an app whose policy's `spawn_sources` names it too diff --git a/CLAUDE.md b/CLAUDE.md index 5623a846..3192c034 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -38,7 +38,7 @@ agentic-cli/ │ │ ├── builtin_commands.py # /help (by category; /help : its usage and examples), /status (the main agent's context rows: context_budget, in a sub-agent's view the instance's, AgentView.context_rows; why the workflow did not start: app.workflow_error; tokens by agent: the main agent, each sub-agent with its runs, the side calls by purpose, from the manager's usage ledger), /models (ModelsCommand: the list, each model's facts and sources, Status for an entry left out, the providers in use; /models searches the full listings; refresh), /sessions (every installed backend's, a Backend column; --delete= on the backend that keeps it, --backend= for an id two keep; on the memory store NOT_KEPT, no table, --delete refused), /resume [] (sessions; refused on the memory store), /jobs (resume: finished jobs; in a sub-agent's view JOBS_WAIT: they wait for /back), /compact [focus] (refused in a sub-agent's view: COMPACT_IN_VIEW), /new [backend] (an unknown backend or a missing extra refused: check_backend), ... │ │ ├── agents_command.py # /agents: the open conversation's sub-agent instances (agent_runs.instances under workflow.session_ref(app.session_id)) in a picker (a Dialog with one ChoiceField, as /resume's: `picker`), each followed by the ones it started (id · type · status · title), Enter opening the view of the one picked (app.open_agent_view); /agent opens its view (open_agent_view: cli/agent_view.py), /agent new starts one and opens its view (app.start_agent; the objective the rest of the line as typed; NEW_USAGE without one; AGENT_USAGE names it), /agent stop and /agent close are the user's stop and close (stop_instance, close_instance, the app's conversation named), each saying what it did or why not (NO_SUCH_AGENT, ALREADY_TEXT), nothing tried on records not read; /agents (its panel: tokens in/out from the usage ledger, usage_of, live for a running run; time): one instance (every run of it) or run (type, parent, title, the instance's Model and Tools when its delegation gave them, NO_OWN_TOOLS for none; each run's status and time, its brief's other fields (a follow-up's message in their place), its result's first lines, its own last plan and tasks, its error, its tokens by model); the records are the conversation's, kept beside it in its store and loaded with it (`workflow.load_agents`, asked by /agents too: a conversation resumed after a restart lists its runs before its first turn; a store that cannot be read is said, and the runs held shown), a run from before a restart showing its record's tokens by model (its usage, no call count); a module of its own, as /memory's │ │ ├── dialogs.py # One dialog at a time on a session: serialize_dialogs (BaseCLIApp.session's setter wraps a real session's six dialog methods, whoever calls them: the framework's commands, an app's own, a question's dialog) and dialog_lock(ui) (the message processor holds it around a question's dialog; a task may take it again) make a sub-agent view's run (outside the input handler) asking while a command's dialog is open, or the reverse, wait instead of raising (thinking-prompt raises on a second dialog: a permission prompt would be a denial the user never saw); a stand-in whose methods are mocks is left as it is -│ │ ├── agent_view.py # A sub-agent's view (provisional; open_view/leave_view behind BaseCLIApp.open_agent_view/leave_agent_view, /back: BackCommand): entering prints VIEW_RULE ("── researcher-2 · researcher · idle ──") and a recap (title, its first brief's objective, its last run's status, its result's first lines, its tokens: instance_tokens, each run's from the usage ledger or its record), the prompt "> " (none for a closed one: read-only, READ_ONLY) and WorkflowController.view_segment (its status, its ctx: its last own step's prompt against its own trigger, its model choice's for an instance on one, its tokens); AgentView.take: a line steers the run that works (steer_instance, STEERED) or starts the instance's next run in a task of its own (ConversationCore.run_instance on the view's own MessageProcessor), outside the input handler, so the prompt takes the lines that steer it (thinking-prompt takes none while a handler runs); bind_ctrl_c: Ctrl+C stops that run (AgentView.stop: the user's stop) through a prompt_toolkit binding on the session's application, active only while it works; AgentView.interrupt (at exit): the manager's interrupt_instance, then the view's tasks cancelled; a line typed before the run ends waits for it inside the view (a stop says the cancel once), and one typed while the workflow is down is the next run all the same (its start retries); leave_view (/back): waits for the run, retries a workflow that is down, BACK_RULE, the prompt and bar back, then one notice turn (ConversationCore.tell_root, view_notice, TELLING) when a run the user started there ended since the main agent last heard, then the finished jobs that waited (job_auto_resume); start_view (/agent new, BaseCLIApp.start_agent): a view open first left (leave_view), the start (ConversationCore.start_instance → MessageProcessor.process_start) in a task of its own on a MessageProcessor of its own, the view opened on the instance its run's start names (opens) holding that task (AgentView.adopt) and processor, so its first run streams, steers and stops there; Ctrl+C before it opened stops the run, no view; in a view /compact is refused (COMPACT_IN_VIEW), /jobs resume waits (JOBS_WAIT), /status shows its context_rows, /new and /resume leave it first +│ │ ├── agent_view.py # A sub-agent's view (provisional; open_view/leave_view behind BaseCLIApp.open_agent_view/leave_agent_view, /back: BackCommand): entering prints VIEW_RULE ("── researcher-2 · researcher · idle ──") and a recap (title, its first brief's objective, its last run's status, its result's first lines, its tokens: instance_tokens, each run's from the usage ledger or its record), the prompt "> " (none for a closed one: read-only, READ_ONLY) and WorkflowController.view_segment (its status, its ctx: its last own step's prompt against its own trigger, its model choice's for an instance on one, a general_purpose one's its spawner's (based_on), its tokens); AgentView.take: a line steers the run that works (steer_instance, STEERED) or starts the instance's next run in a task of its own (ConversationCore.run_instance on the view's own MessageProcessor), outside the input handler, so the prompt takes the lines that steer it (thinking-prompt takes none while a handler runs); bind_ctrl_c: Ctrl+C stops that run (AgentView.stop: the user's stop) through a prompt_toolkit binding on the session's application, active only while it works; AgentView.interrupt (at exit): the manager's interrupt_instance, then the view's tasks cancelled; a line typed before the run ends waits for it inside the view (a stop says the cancel once), and one typed while the workflow is down is the next run all the same (its start retries); leave_view (/back): waits for the run, retries a workflow that is down, BACK_RULE, the prompt and bar back, then one notice turn (ConversationCore.tell_root, view_notice, TELLING) when a run the user started there ended since the main agent last heard, then the finished jobs that waited (job_auto_resume); start_view (/agent new, BaseCLIApp.start_agent): a view open first left (leave_view), the start (ConversationCore.start_instance → MessageProcessor.process_start) in a task of its own on a MessageProcessor of its own, the view opened on the instance its run's start names (opens) holding that task (AgentView.adopt) and processor, so its first run streams, steers and stops there; Ctrl+C before it opened stops the run, no view; in a view /compact is refused (COMPACT_IN_VIEW), /jobs resume waits (JOBS_WAIT), /status shows its context_rows, /new and /resume leave it first │ │ ├── memory_command.py # /memory: the list (a picker like /resume's), one memory (Delete, History), /memory , history (Restore), inbox (Accept/Discard/Skip), stale; proposals_line; Enter's button is Close or Skip, and Delete acts only on the memory as shown │ │ ├── workflow_controller.py # WorkflowController (lazy/background init; subagents=: the SubAgentPolicy every manager it builds gets, a switch_backend's too; the session store of every manager of the run, store, fixed at its first start; the backend it runs, backend: the settings' orchestrator at its first start, then switch_backend's (a conversation on another backend, new or opened: the new manager started first on the run's services lent, given over by the old one and published at once, the old one released in the controller's task, a cancel stops only the wait; a failed start or give leaves the old one with its services; while down, a manager a failed reinitialization kept lends its services to the next build, _lender, and is released once they are given); reinitialize, a model switch, always in place; the status bar names the main agent's model, or in a sub-agent's view what view_segment says of the instance, the jobs segment kept) │ │ ├── session_resume.py # What /resume shows: the picker (picker: each row's backend once one is another's; PickedConversation, the id a str naming its backend), the "Resumed:" line ("Resumed on :" on another backend), the replay of the last 10 messages @@ -51,7 +51,7 @@ agentic-cli/ │ │ ├── waiting_jobs.py # Which finished jobs wait to be told in the open conversation: one rule (JobRecord.awaiting_resume, then its own, no conversation's, or a gone conversation's: can_resume, then the other installed backends' readers, opens_anywhere: one another backend keeps is not gone, its job waits for it) for the deliveries, ↻N and the startup line │ │ └── usage_tracker.py # Token usage / status bar: ctx = the main agent's last prompt over its context_trigger (a call with a purpose, a sub-agent's, a summary's or a side call's, never moves it); the token segment the open conversation's total, every call of its turns; format_usage: /status's rows by agent and /agents 's tokens by model │ ├── workflow/ -│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none), and _agent_tool_names, what a task call's tools may name (the agent's own tools by the names its model sees, KEPT_TOOLS left out; the base's: its configured tools; ADK and Deep Agents add MCP and skill tools; ADK raises delegate.ToolsUnlistedError for a toolset it could not list, which Delegations answers TOOLS_UNLISTED_ERROR); _run_models: a run's maps of each agent's model and numbers, its type's its model choice's when it runs on one; the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), start_instance (a turn: Delegations.start_by_user, the user's new instance, parent root, depth 1, started_by user, counted toward no turn's runs; a type the user may not start or a blank objective one ERROR; a conversation not yet stored stored first, _keep_conversation: ADK's session with one state-only event, Deep Agents' index row, titled from the objective with no turns; an inheriting type's copy of the conversation from _inherited_history, the backend's hook: ADK's session's root-visible events, Deep Agents' root messages, summary applied; its first event the run's start), both streamed by _users_run (the run in a task of its own; _UsersRunEvents notes the run as its start is reported and until_started awaits that one future, so a stop before the consumer read it, or before the run started, stops it by the user as it starts, before its hook is entered), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', each config's model_choices as its model would be, with its model_settings, into _choice_models by (agent, choice), choice_models, then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built, and _compute_choice_budgets (each model choice's, context_budget(agent, model=choice)): each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) +│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none), and _agent_tool_names, what a task call's tools may name (the agent's own tools by the names its model sees, KEPT_TOOLS left out; the base's: its configured tools; ADK and Deep Agents add MCP and skill tools; ADK raises delegate.ToolsUnlistedError for a toolset it could not list, which Delegations answers TOOLS_UNLISTED_ERROR); _run_models: a run's maps of each agent's model and numbers, its type's its model choice's when it runs on one, a general_purpose run's its spawner's (based_on; _general_model: the spawner's resolved model named general_purpose); the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), start_instance (a turn: Delegations.start_by_user, the user's new instance, parent root, depth 1, started_by user, counted toward no turn's runs; a type the user may not start or a blank objective one ERROR; a conversation not yet stored stored first, _keep_conversation: ADK's session with one state-only event, Deep Agents' index row, titled from the objective with no turns; an inheriting type's copy of the conversation from _inherited_history, the backend's hook: ADK's session's root-visible events, Deep Agents' root messages, summary applied; its first event the run's start), both streamed by _users_run (the run in a task of its own; _UsersRunEvents notes the run as its start is reported and until_started awaits that one future, so a stop before the consumer read it, or before the run started, stops it by the user as it starts, before its hook is entered), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', each config's model_choices as its model would be, with its model_settings, into _choice_models by (agent, choice), choice_models, then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built, and _compute_choice_budgets (each model choice's, context_budget(agent, model=choice)): each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) │ │ ├── factory.py # create_workflow_manager_from_settings (_BACKENDS: orchestrator → "module:Class" + extra, imported when chosen; orchestrator=: another backend than the settings'; session_store=: the store a manager is built for, BaseWorkflowManager.session_store, the settings' by default; subagents=: the SubAgentPolicy the manager gets, checked before a backend is imported); orchestrator_of; check_backend (an unknown name, a missing extra) │ │ ├── session_readers.py # SessionReader: a backend's stored conversations read without its manager (list/info/exists/delete/aclose, rows naming the backend; delete deletes what the manager's does, ADK's sub-agent transcripts and records with the conversation), opened from the settings and a store (open_session_reader: the backend's own session code, adk/sessions.py::open_sessions and deepagents/sessions.py::open_sessions, imported on a worker thread; no agents, models or services; a sqlite store not made yet reads empty and is not made, Deep Agents not even imported for it; a database without its backend's tables, looked at read-only, reads empty, nothing written to it: no table, no journal mode); none for the memory store or LangGraph; ImportError (the install hint) for a missing extra; reader_backends │ │ ├── service_registry.py # get_service/require_service + ContextVar registry; the registry keys and KNOWN_SERVICE_KEYS, read from services.py's table @@ -84,9 +84,9 @@ agentic-cli/ │ │ │ ├── capabilities.py # Capability, EXEMPT │ │ │ ├── matchers.py # PathMatcher, URLMatcher, ShellMatcher, StringGlobMatcher │ │ │ └── rules.py, store.py, prompt.py (build_request(run=): a sub-agent's prompt opens with its run; is_permission_request: by its perm- id) -│ │ ├── agents/ # Sub-agents: runs.py: the RUN_* statuses (a working run's: RUN_QUEUED, RUN_RUNNING, RUN_INPUT_REQUIRED, RUN_WORKING_STATUSES; a record says running from its start), INSTANCE_RUNNING/IDLE/STOPPED/CLOSED and INSTANCE_STATUSES, InstanceRecord (an instance: parent, depth, title, status, runs, continuable, and the tools and model its first run's start gave it, read as None from records without them), RunRecord (input: a follow-up's message as written, "" for a first run), AgentRuns (a manager's runs and instances by conversation: run_for names - and its first run #1 per (conversation, parent run, call id), a new one once it ended, and a start with no call (the user's) a new one each time; next_run: an instance's next run; instances/instance, kept from the events: a start makes or reopens the instance running, an end sets its status from instance_status, AGENT_INSTANCE a change without a run; number_from: past the instances a conversation's store keeps, a count never lowered; observe records AGENT_RUN under the turn it is reported in; interrupt_open; a record's usage: what the run used, by model, from its end event or the ledger; its plan and tasks: the run's own last, from its end event; RECORDS_VERSION, export (a conversation's records as JSON-safe data: v, saved, numbered, instances, runs) and restore (replaces them; a run found working ends interrupted, INTERRUPTED_ERROR, at the later of its start and saved, its instance idle, closed for a type that is not continuable; each run's end order stored (end), any time or field that does not read ValueError; counters never below an instance kept; ValueError for another version or records that do not read, nothing changed), stored_instance_ids (the instances stored records name; None for none), AgentRuns(on_change=): told each change, never by restore), run_title, result_head, run_instance and run_number (the one reader of a run id: researcher-2#1's instance and number), run_label (how a dialog names a run: researcher-2 (researcher, run 1)), SUBAGENT_ERROR_PREFIX (ADK's old words for a failed delegation, kept for callers), show_as_delegation(result, envelope) (a delegation's TOOL_RESULT shown alike on both backends: the result's first line, or Failed: ; metadata["result"] the envelope); a record's brief, started_by, mode and cancelled_by; delegate.py: Delegations (delegate(DelegationRequest) → Delegated and follow_up(FollowUpRequest) → Delegated: the one place a run starts and ends, on both backends (a follow-up is the instance's next run through the same hook, AgentRun.follow_up: refused as an error result, no run, for an unknown or not-yours instance (NOT_YOURS_ERROR, YOURS, NO_SUB_AGENTS), a closed one (CLOSED_ERROR), one the user stopped when an agent sends it (STOPPED_ERROR), a running one (RUNNING_ERROR), one whose type the app no longer has (TYPE_GONE_ERROR) and a blank message (NO_MESSAGE_ERROR); an agent's counts toward max_runs_per_turn, the user's (started_by USER) does not; a run's end carries the status it leaves its instance in: stopped for the user's cancel, closed for a type that is not continuable or the oldest idle one past max_open, else idle; close(conversation, instance, reason=): an idle or stopped instance and its descendants, AGENT_INSTANCE closed; open_calls=: the manager's OpenCalls, whose stop recorded for an instance is taken when the instance is left closed (its end, close, max_open, or a turn that stops a one-shot run), so its calls are freed; max_open ranks by AgentRuns.end_order, the order ends were recorded in, never the clock): the brief read against what the calling run may start (offered(agent, depth): its own sub-agents, then, while may_spawn, the types agents may start at run time, an inheriting one for the root alone; task_offer: task's TaskOffer for that run, None for nothing; types: every agent type by name, read-only, what a skill's start checks against), its tools and model against the type's own (read_choices, tool_names= asked only for a call naming tools), then start(StartRequest, its tools= and model= carried to AgentRun.tools/.model and RunControl.tools, and said by its start: every run of the instance keeps them, a follow-up one whose type lost them refused, CHOICE_GONE_ERROR) (also start_by_user's, /agent new's: a type startable_by_user, spawnable for "user", else user_start_refused's USER_START_ERROR, NO_USER_TYPES_ERROR or NO_OBJECTIVE_ERROR as the error result; no caller or call, started_by USER, counted False, titled run_title(objective)), the one entry for a first run (counted unless the user's, started_by as given; who may start the type is the asker's to check), the run named (a turn's first run past the instances its conversation's store keeps: stored=, asked once per conversation per turn, again after a failed or stopped ask), its AGENT_RUN start and end observed and reported, the backend's hook (RunHook: AgentRun → RunAnswer) run in a task of its own with the run active and no tool call, the end by the answer (completed, partial for a cut or the step limit, refused, failed for an error or a raise, with one recoverable ERROR failed: , or RunFailed's own words, its result the text the run wrote before it failed (RunFailed(text=); a failed model call the hook's RunAnswer.error, failure_reason, with error_code its type, the warning's code), cancelled by its control with what the hook had), interrupted on its turn's cancel, which wins; the envelope as the result; each run under its RunControl, the type's limits over the policy's, kept while it works: control(run), cancel(run_id, by=, error=), the run alone; a call past max_runs_per_turn the error result RUNS_PER_TURN_ERROR, no run; the stored instances asked under a lock per conversation; forget(conversation): a deleted one's slots, unread messages, waiting closes and asks; each run in a working slot of its conversation's SlotPool, slots(conversation): policy.max_active slots, made on first use and kept, the root taking none: taken right before its hook and its time limit, queued then running while it waits for one, given back at its end, straight back to a caller that waits on it alone; a caller that delegates lends its slot while it waits for its children), DelegationRequest, StartRequest, FollowUpRequest, AgentRun (control, follow_up), RunAnswer, RunFailed, started_by, waiting_on_user (a sub-agent run waiting on the user: input_required, its slot lent, queued while its take-back waits for a slot, then running; nested waits once; request_user_input and the permission engine); records.py: RecordsWriter (each conversation's records written to its store as they change: changed, one write at a time per conversation taking the records as it starts, so changes made meanwhile go together in the next; flush, flush_all, discard (a delete's: what waits dropped, the write under way waited for); a failed write warned once per conversation, subagent_records_not_saved, never raised); slots.py: SlotPool (acquire(priority): a free slot, else a future in a heap by priority, RETURNING before NEW, then arrival; release; lent(slot, on_wait=): the slot lent while its run waits, nested lends once, taken back at RETURNING after (on_wait called when that has to wait), at most one take-back waiting for a slot and none once it is held (a wait that starts while one is queued takes it over, and one handed the slot withdraws any queued since), nothing taken back after a cancel, so a tool's caught timeout around a question leaves its run working without a slot, input_required until its next question is answered (running again, still without a slot) or its end; hand_back(slot, to): a child's slot to its parent waiting on it alone; free, waiting; a cancelled waiter leaves the heap, one handed a slot as it is cancelled hands it on; not asyncio.Semaphore), Slot (held, lent), RETURNING, NEW; control.py: RunControl (one run's: tools, the type's own tools it may use, and keeps(name): one of them or of KEPT_TOOLS, the state and delegation tools, what both backends filter by; cancel(by=, error=) its task, the first cancel winning, own_cancel for the hook that takes it and returns, finish: the hook's work ended, no cancel after it (ADK's state read loses no answer), timing: the time limit while the hook runs; model_call/at_step_limit/final_call: the step limit, STEP_LIMIT_NOTE on the last allowed call; used: the token limit, against its own calls and side_tokens (its side calls and summaries, from the ledger), an answer past it that makes calls the run's last, cancelled by it, one that makes none its result (calls=); model_call once final stays final; a cancel leaves a task its turn is cancelling alone; steer/take_steering), STEP_LIMIT_NOTE; outcome.py: a sub-agent's refused or cut answer (outcome_of, the refusal notice as Deep Agents 0.7.34 words it, cut_off, cut_off_warning, OPENAI_REFUSAL_PREFIX: how ADK's OpenAI adapters word a refusal); policy.py: SubAgentPolicy (max_active, max_runs_per_turn, limits, max_open, follow_ups, spawn_sources: of SPAWN_SOURCES, kept as a frozenset, max_spawn_depth) and AgentLimits (max_model_calls, timeout, max_tokens; over: a type's limits over the policy's, field by field, None taking the base's), DEFAULT_LIMITS (100 model calls), frozen and checked as they are made (a ValueError naming the field), as_policy (the one reading of a subagents= argument: a TypeError for anything but a policy or None); brief.py: BRIEF_FIELDS, Brief, BriefError, read_brief (a task call's agent type and brief, against the types its caller may start: the error texts), read_choices (its tools, some of the type's own, and its model, one of its model_choices: TOOLS_ERROR, NO_TOOLS_ERROR, MODEL_ERROR, NO_MODEL_CHOICES_ERROR), task_message (a run's first message, a section per filled field; an inheriting type's ends with INHERITED_CONTEXT_NOTE), task_parameters and task_description (task's schema and description, the same for both backends: tools always, TOOLS_DESCRIPTION, model when a type offered has choices, MODEL_DESCRIPTION, and a type's line its "model choices: , "; limit_sentences: the limits it states, "At most sub-agents work at once; more calls in one response wait for a free slot. At most runs per turn.", then DEPTH_SENTENCE, "Sub-agents cannot start sub-agents.", when no run the call starts may start one; warn=False for a description made per run), TaskOffer and task_offer (both, for the types one run may start); envelope.py: envelope (a delegation run's result: success only for completed, a one-line error, cancelled_by for a cancelled run), read_envelope (a dict or its JSON text, else None; never raises), view_notice (`VIEW_NOTICE`: what the root is told once the user worked with an instance), the limit and interrupted error texts; `Delegations.message` (an idle instance's follow-up; a running one's run steered, or with `interrupt` cancelled by its parent and followed up; one run per instance, so of two messages to one idle instance in one answer the first runs and the second is steered into it), `stop` (a running instance's run cancelled by its parent, the instance idle; `close` closes it and its descendants, a running one's at its run's end), `check`, `steer(conversation, run, message)`, `stop_by_user`/`close_by_user` (`STOPPED_BY_USER_ERROR`, `CLOSED_BY_USER`: a running run cancelled by the user and waited for), `stop_cause(run)` and `cancel(..., conversation=)`; a message steered to a run that its transcript does not hold when it ends (`RunControl.unstored`) is kept for the instance's next run; a run whose parent's run its control stopped ends `cancelled` by its parent (`its parent's run was stopped`); a run that did not complete fully names its open tasks in its envelope (`envelope(open_tasks=)`, `open_task_descriptions`) and a cancelled run keeps its plan and tasks; `SubAgentPolicy.follow_ups`; brief.py: `follow_up_description`/`follow_up_parameters` (the parent's tools' texts); follow_ups.py: `call_follow_up_tool` (a message_agent, stop_agent or check_agents call as the run in progress); spawn.py: spawnable (the types a source may start at run time: the policy's spawn_sources and the type's spawnable_by), may_spawn (depth below max_spawn_depth), can_have_children (who is built with task, and with follow_ups the parent's tools and the roster: sub-agents, or a type agents may start while the root or runs below it may), depth_sentence_applies, AGENT_SOURCE/SKILL_SOURCE/USER_SOURCE; no backend imports; roster.py: roster_text (the main agent's open sub-agents, newest first, one line each, ROSTER_OPEN/ROSTER_HEADER/ROSTER_CLOSE, at most ROSTER_MAX characters in whole lines, "" for none open), Rosters (a snapshot per conversation, as MemoryIndex: now, forget, clear; the root's own instances, parent root) +│ │ ├── agents/ # Sub-agents: runs.py: the RUN_* statuses (a working run's: RUN_QUEUED, RUN_RUNNING, RUN_INPUT_REQUIRED, RUN_WORKING_STATUSES; a record says running from its start), INSTANCE_RUNNING/IDLE/STOPPED/CLOSED and INSTANCE_STATUSES, InstanceRecord (an instance: parent, depth, title, status, runs, continuable, and the tools and model its first run's start gave it, and a general_purpose one's based_on, read as None from records without them), RunRecord (input: a follow-up's message as written, "" for a first run), AgentRuns (a manager's runs and instances by conversation: run_for names - and its first run #1 per (conversation, parent run, call id), a new one once it ended, and a start with no call (the user's) a new one each time; next_run: an instance's next run; instances/instance, kept from the events: a start makes or reopens the instance running, an end sets its status from instance_status, AGENT_INSTANCE a change without a run; number_from: past the instances a conversation's store keeps, a count never lowered; observe records AGENT_RUN under the turn it is reported in; interrupt_open; a record's usage: what the run used, by model, from its end event or the ledger; its plan and tasks: the run's own last, from its end event; RECORDS_VERSION, export (a conversation's records as JSON-safe data: v, saved, numbered, instances, runs) and restore (replaces them; a run found working ends interrupted, INTERRUPTED_ERROR, at the later of its start and saved, its instance idle, closed for a type that is not continuable; each run's end order stored (end), any time or field that does not read ValueError; counters never below an instance kept; ValueError for another version or records that do not read, nothing changed), stored_instance_ids (the instances stored records name; None for none), AgentRuns(on_change=): told each change, never by restore), run_title, result_head, run_instance and run_number (the one reader of a run id: researcher-2#1's instance and number), run_label (how a dialog names a run: researcher-2 (researcher, run 1)), SUBAGENT_ERROR_PREFIX (ADK's old words for a failed delegation, kept for callers), show_as_delegation(result, envelope) (a delegation's TOOL_RESULT shown alike on both backends: the result's first line, or Failed: ; metadata["result"] the envelope); a record's brief, started_by, mode and cancelled_by; delegate.py: Delegations (delegate(DelegationRequest) → Delegated and follow_up(FollowUpRequest) → Delegated: the one place a run starts and ends, on both backends (a follow-up is the instance's next run through the same hook, AgentRun.follow_up: refused as an error result, no run, for an unknown or not-yours instance (NOT_YOURS_ERROR, YOURS, NO_SUB_AGENTS), a closed one (CLOSED_ERROR), one the user stopped when an agent sends it (STOPPED_ERROR), a running one (RUNNING_ERROR), one whose type the app no longer has (TYPE_GONE_ERROR) and a blank message (NO_MESSAGE_ERROR); an agent's counts toward max_runs_per_turn, the user's (started_by USER) does not; a run's end carries the status it leaves its instance in: stopped for the user's cancel, closed for a type that is not continuable or the oldest idle one past max_open, else idle; close(conversation, instance, reason=): an idle or stopped instance and its descendants, AGENT_INSTANCE closed; open_calls=: the manager's OpenCalls, whose stop recorded for an instance is taken when the instance is left closed (its end, close, max_open, or a turn that stops a one-shot run), so its calls are freed; max_open ranks by AgentRuns.end_order, the order ends were recorded in, never the clock): the brief read against what the calling run may start (offered(agent, depth): its own sub-agents, then, while may_spawn, the types agents may start at run time, an inheriting one for the root alone, general_purpose last made for the caller's type (config_for(agent_type, based_on=), general_purpose: one per spawner type); task_offer: task's TaskOffer for that run, None for nothing; types: every agent type by name, read-only, what a skill's start checks against), its tools and model against the type's own (read_choices, tool_names= asked only for a call naming tools), then start(StartRequest, its tools= and model= carried to AgentRun.tools/.model and RunControl.tools, and general_purpose's based_on= to AgentRun.based_on, and said by its start: every run of the instance keeps them, a follow-up one whose type lost them refused, CHOICE_GONE_ERROR) (also start_by_user's, /agent new's: a type startable_by_user, spawnable for "user", else user_start_refused's USER_START_ERROR, NO_USER_TYPES_ERROR or NO_OBJECTIVE_ERROR as the error result; no caller or call, started_by USER, counted False, titled run_title(objective)), the one entry for a first run (counted unless the user's, started_by as given; who may start the type is the asker's to check), the run named (a turn's first run past the instances its conversation's store keeps: stored=, asked once per conversation per turn, again after a failed or stopped ask), its AGENT_RUN start and end observed and reported, the backend's hook (RunHook: AgentRun → RunAnswer) run in a task of its own with the run active and no tool call, the end by the answer (completed, partial for a cut or the step limit, refused, failed for an error or a raise, with one recoverable ERROR failed: , or RunFailed's own words, its result the text the run wrote before it failed (RunFailed(text=); a failed model call the hook's RunAnswer.error, failure_reason, with error_code its type, the warning's code), cancelled by its control with what the hook had), interrupted on its turn's cancel, which wins; the envelope as the result; each run under its RunControl, the type's limits over the policy's, kept while it works: control(run), cancel(run_id, by=, error=), the run alone; a call past max_runs_per_turn the error result RUNS_PER_TURN_ERROR, no run; the stored instances asked under a lock per conversation; forget(conversation): a deleted one's slots, unread messages, waiting closes and asks; each run in a working slot of its conversation's SlotPool, slots(conversation): policy.max_active slots, made on first use and kept, the root taking none: taken right before its hook and its time limit, queued then running while it waits for one, given back at its end, straight back to a caller that waits on it alone; a caller that delegates lends its slot while it waits for its children), DelegationRequest, StartRequest, FollowUpRequest, AgentRun (control, follow_up), RunAnswer, RunFailed, started_by, waiting_on_user (a sub-agent run waiting on the user: input_required, its slot lent, queued while its take-back waits for a slot, then running; nested waits once; request_user_input and the permission engine); records.py: RecordsWriter (each conversation's records written to its store as they change: changed, one write at a time per conversation taking the records as it starts, so changes made meanwhile go together in the next; flush, flush_all, discard (a delete's: what waits dropped, the write under way waited for); a failed write warned once per conversation, subagent_records_not_saved, never raised); slots.py: SlotPool (acquire(priority): a free slot, else a future in a heap by priority, RETURNING before NEW, then arrival; release; lent(slot, on_wait=): the slot lent while its run waits, nested lends once, taken back at RETURNING after (on_wait called when that has to wait), at most one take-back waiting for a slot and none once it is held (a wait that starts while one is queued takes it over, and one handed the slot withdraws any queued since), nothing taken back after a cancel, so a tool's caught timeout around a question leaves its run working without a slot, input_required until its next question is answered (running again, still without a slot) or its end; hand_back(slot, to): a child's slot to its parent waiting on it alone; free, waiting; a cancelled waiter leaves the heap, one handed a slot as it is cancelled hands it on; not asyncio.Semaphore), Slot (held, lent), RETURNING, NEW; control.py: RunControl (one run's: tools, the type's own tools it may use, and keeps(name): one of them or of KEPT_TOOLS, the state and delegation tools, what both backends filter by; cancel(by=, error=) its task, the first cancel winning, own_cancel for the hook that takes it and returns, finish: the hook's work ended, no cancel after it (ADK's state read loses no answer), timing: the time limit while the hook runs; model_call/at_step_limit/final_call: the step limit, STEP_LIMIT_NOTE on the last allowed call; used: the token limit, against its own calls and side_tokens (its side calls and summaries, from the ledger), an answer past it that makes calls the run's last, cancelled by it, one that makes none its result (calls=); model_call once final stays final; a cancel leaves a task its turn is cancelling alone; steer/take_steering), STEP_LIMIT_NOTE; outcome.py: a sub-agent's refused or cut answer (outcome_of, the refusal notice as Deep Agents 0.7.34 words it, cut_off, cut_off_warning, OPENAI_REFUSAL_PREFIX: how ADK's OpenAI adapters word a refusal); policy.py: SubAgentPolicy (max_active, max_runs_per_turn, limits, max_open, follow_ups, spawn_sources: of SPAWN_SOURCES, kept as a frozenset, max_spawn_depth, general_purpose: the built-in type, a ValueError without a source) and AgentLimits (max_model_calls, timeout, max_tokens; over: a type's limits over the policy's, field by field, None taking the base's), DEFAULT_LIMITS (100 model calls), frozen and checked as they are made (a ValueError naming the field), as_policy (the one reading of a subagents= argument: a TypeError for anything but a policy or None); brief.py: BRIEF_FIELDS, Brief, BriefError, read_brief (a task call's agent type and brief, against the types its caller may start: the error texts), read_choices (its tools, some of the type's own, and its model, one of its model_choices: TOOLS_ERROR, NO_TOOLS_ERROR, MODEL_ERROR, NO_MODEL_CHOICES_ERROR), task_message (a run's first message, a section per filled field; an inheriting type's ends with INHERITED_CONTEXT_NOTE), task_parameters and task_description (task's schema and description, the same for both backends: tools always, TOOLS_DESCRIPTION, model when a type offered has choices, MODEL_DESCRIPTION, and a type's line its "model choices: , "; limit_sentences: the limits it states, "At most sub-agents work at once; more calls in one response wait for a free slot. At most runs per turn.", then DEPTH_SENTENCE, "Sub-agents cannot start sub-agents.", when no run the call starts may start one; warn=False for a description made per run), TaskOffer and task_offer (both, for the types one run may start); envelope.py: envelope (a delegation run's result: success only for completed, a one-line error, cancelled_by for a cancelled run), read_envelope (a dict or its JSON text, else None; never raises), view_notice (`VIEW_NOTICE`: what the root is told once the user worked with an instance), the limit and interrupted error texts; `Delegations.message` (an idle instance's follow-up; a running one's run steered, or with `interrupt` cancelled by its parent and followed up; one run per instance, so of two messages to one idle instance in one answer the first runs and the second is steered into it), `stop` (a running instance's run cancelled by its parent, the instance idle; `close` closes it and its descendants, a running one's at its run's end), `check`, `steer(conversation, run, message)`, `stop_by_user`/`close_by_user` (`STOPPED_BY_USER_ERROR`, `CLOSED_BY_USER`: a running run cancelled by the user and waited for), `stop_cause(run)` and `cancel(..., conversation=)`; a message steered to a run that its transcript does not hold when it ends (`RunControl.unstored`) is kept for the instance's next run; a run whose parent's run its control stopped ends `cancelled` by its parent (`its parent's run was stopped`); a run that did not complete fully names its open tasks in its envelope (`envelope(open_tasks=)`, `open_task_descriptions`) and a cancelled run keeps its plan and tasks; `SubAgentPolicy.follow_ups`; brief.py: `follow_up_description`/`follow_up_parameters` (the parent's tools' texts); follow_ups.py: `call_follow_up_tool` (a message_agent, stop_agent or check_agents call as the run in progress); spawn.py: spawnable (the types a source may start at run time: the policy's spawn_sources and the type's spawnable_by, then GENERAL_PURPOSE with the policy's general_purpose), 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; the general-purpose type never), depth_sentence_applies, AGENT_SOURCE/SKILL_SOURCE/USER_SOURCE, general_purpose_config (the built-in type made for a spawner type: its tools, MCP servers, skills and model, GENERAL_PURPOSE_PROMPT, GENERAL_PURPOSE_DESCRIPTION), general_purpose_spawners (the types one is built for), root_type; no backend imports; roster.py: roster_text (the main agent's open sub-agents, newest first, one line each, ROSTER_OPEN/ROSTER_HEADER/ROSTER_CLOSE, at most ROSTER_MAX characters in whole lines, "" for none open), Rosters (a snapshot per conversation, as MemoryIndex: now, forget, clear; the root's own instances, parent root) │ │ ├── adk/ # ADK orchestrator -│ │ │ ├── manager.py # GoogleADKWorkflowManager (the agents built from configs or, adk_config_path, by ADK from a native YAML (library-only: no BaseCLIApp starts one; loaded once per manager at the first _validate_agent_graph (_native_root: the settings' keys exported first; a retry, a model switch and a start after cleanup build on the same tree, whose toolsets the closed runner left reusable), its agents' models resolved leniently in _resolve_extra_models, the base's hook, its registered tools' services detected; configs passed with it ignored, adk_native_configs_ignored): the only difference; _do_initialize builds the app from the tree alone, _build_app → ADKBuild, through the hooks _plugin_chain (the whole chain, top to bottom, its head _init_plugins), _compaction_config (None for a root without a budget), _context_cache_config, _agent_model_refs; the event processor built from the build; a config-built agent's prompt as an instruction provider, sent as written: no `{name}` state injection; _compact_turn: ADK's compaction once, in the base's compact turn; supports_compact False once built for a root without a budget (_no_compact_support says why); the job resume hooks: _conversation_exists (the session read without its events, num_recent_events=0), _deliver_job_notice (the notice, for every app); _run_config: the agents' synchronous tools run in ADK's tool thread pool, 8 workers; _run_and_stream: a run that fails yields the turn's one ERROR, last, none after an ERROR already yielded, and keeps the record of its calls that returned for the next turn (OpenCalls.failed; _answer_left_open forgets it once its answers are stored); the agents: _create_agents builds each config's agent on its own (_agents, by name; no ADK sub_agents), a delegating one with a TaskTool (its own tool named task: AgentGraphError); a runner per sub-agent type (_agent_runners: NoAfterTurnCompactionRunner on App(name=child_app(app_name), root_agent=the type's agent, plugins=_agent_plugin_chain(agent), the app's context cache, no compaction) over the session service, closed with the main runner by _detach_backend, rebuilt by every initialization); a runner per (type, model choice) too (_variant_runners over _variant_agents: the type's agent built on the choice, _build_agent(model=), its chain _agent_plugin_chain(agent, model=, budget=), every plugin reading the choice's model, kind and numbers under the type's name), closed and rebuilt alike; _agent_tool_names: the built agent's tools by name, an MCP toolset's listed when first asked and kept for the build; _run_agent, the base's hook: the runner of run.model's choice or the type's, its processor on _run_models' maps, the raw log told the choice (_chosen_model); the instance's child session (_child_session: a first run makes it from run.state and an inheriting instance's copied events, once; never one the store keeps, whose instance numbering goes past: ADK's create_session refuses it, and the run fails; a follow-up takes the stored session, answers the calls an earlier run left open there (left_open_by) and passes the caller's mark when it holds none; one the store lost is made as a first run's), _stored_instances (the base's hook: the highest instance number of each type the conversation's child sessions keep), the type's runner on the task message (a follow-up's own message) with an abort signal set before it is closed, a run-mode ADKEventProcessor, the raw log's records reported as they come (_report_raw_log); a model's failure raised as the provider's (_plugin_cause), an overflow RunFailed, a reply that is no answer RunAnswer(error=), the shared keys it changed read back) +│ │ │ ├── manager.py # GoogleADKWorkflowManager (the agents built from configs or, adk_config_path, by ADK from a native YAML (library-only: no BaseCLIApp starts one; loaded once per manager at the first _validate_agent_graph (_native_root: the settings' keys exported first; a retry, a model switch and a start after cleanup build on the same tree, whose toolsets the closed runner left reusable), its agents' models resolved leniently in _resolve_extra_models, the base's hook, its registered tools' services detected; configs passed with it ignored, adk_native_configs_ignored): the only difference; _do_initialize builds the app from the tree alone, _build_app → ADKBuild, through the hooks _plugin_chain (the whole chain, top to bottom, its head _init_plugins), _compaction_config (None for a root without a budget), _context_cache_config, _agent_model_refs; the event processor built from the build; a config-built agent's prompt as an instruction provider, sent as written: no `{name}` state injection; _compact_turn: ADK's compaction once, in the base's compact turn; supports_compact False once built for a root without a budget (_no_compact_support says why); the job resume hooks: _conversation_exists (the session read without its events, num_recent_events=0), _deliver_job_notice (the notice, for every app); _run_config: the agents' synchronous tools run in ADK's tool thread pool, 8 workers; _run_and_stream: a run that fails yields the turn's one ERROR, last, none after an ERROR already yielded, and keeps the record of its calls that returned for the next turn (OpenCalls.failed; _answer_left_open forgets it once its answers are stored); the agents: _create_agents builds each config's agent on its own (_agents, by name; no ADK sub_agents), a delegating one with a TaskTool (its own tool named task: AgentGraphError); a runner per sub-agent type (_agent_runners: NoAfterTurnCompactionRunner on App(name=child_app(app_name), root_agent=the type's agent, plugins=_agent_plugin_chain(agent), the app's context cache, no compaction) over the session service, closed with the main runner by _detach_backend, rebuilt by every initialization); a runner per (type, model choice) too (_variant_runners over _variant_agents: the type's agent built on the choice, _build_agent(model=), its chain _agent_plugin_chain(agent, model=, budget=), every plugin reading the choice's model, kind and numbers under the type's name), closed and rebuilt alike; _general_agents/_general_runners: the built-in general_purpose type's agent and runner per spawner type (Delegations.general_purpose, no delegation tools), picked by run.based_on; _agent_tool_names: the built agent's tools by name, an MCP toolset's listed when first asked and kept for the build; _run_agent, the base's hook: the runner of run.model's choice or the type's, its processor on _run_models' maps, the raw log told the choice (_chosen_model); the instance's child session (_child_session: a first run makes it from run.state and an inheriting instance's copied events, once; never one the store keeps, whose instance numbering goes past: ADK's create_session refuses it, and the run fails; a follow-up takes the stored session, answers the calls an earlier run left open there (left_open_by) and passes the caller's mark when it holds none; one the store lost is made as a first run's), _stored_instances (the base's hook: the highest instance number of each type the conversation's child sessions keep), the type's runner on the task message (a follow-up's own message) with an abort signal set before it is closed, a run-mode ADKEventProcessor, the raw log's records reported as they come (_report_raw_log); a model's failure raised as the provider's (_plugin_cause), an overflow RunFailed, a reply that is no answer RunAnswer(error=), the shared keys it changed read back) │ │ │ ├── build.py # ADKBuild (root, reply_agents, plugins, compaction, cache, models); load_native_root (from_config at validation; what ADK cannot load, wrapped as AgentGraphError naming the file, ADK's error the cause; a root that is not an LlmAgent, a name used twice in the tree and a task-mode agent refused, AgentGraphError naming it; ensure_direct_anthropic); what the run reads of any tree: reply_agents (the root and the chat-mode agents it can transfer to), own_after_tool_agents (left out by the cap) │ │ │ ├── task_tool.py # TaskTool: the framework's task on ADK (a BaseTool; declared for each request what the run that asks may start, Delegations.task_offer by get_active_run's depth, the root's own requests 0: task_parameters' JSON schema, parameters_json_schema, and task_description; None, no task declared, for a run offered nothing; its description attribute the offer at its first depth, warned of once; bound to the task declaration, an exact TaskTool only): a call → Delegations.delegate, the run's shared-key changes written to the caller's state, the envelope returned as JSON text (ADK's OpenAI Responses adapter sends only a dict's result); SHARED_KEYS (the outside-content mark alone); inherited_events (an inheriting run's history: the session's root-visible events, copied); FollowUpTool (with follow_ups: message_agent, stop_agent, check_agents, each an exact FollowUpTool bound to its declaration, the result as JSON text; an own tool of one of their names fails the build) │ │ │ ├── skill_tool.py # SkillLoadTool: load_skill for an agent with a skill that names an agent type (a LoadSkillTool with ADK's declaration, bound by make_skill_toolset as ADK's is): such a skill → SkillAgents.start, its result JSON text as task's, the mark from and back to the caller's state, an inheriting type given inherited_events; any other skill as ADK loads it; imported by make_skill_toolset only @@ -113,8 +113,8 @@ agentic-cli/ │ │ │ ├── call_clock.py # Every model call timed: CallClock (a clock per call, under its EventActions, held through an error until the answer a later plugin gives; the raw log keeps one too), CallSentPlugin (last: starts it as the request goes out), CallLatencyPlugin (second, after MainAgentPlugin: marks the answer, custom_metadata[LATENCY_KEY], which the event processor reads, call_latency; an answer already marked keeps its mark: mark_latency, the overflow retry's); no adapter sends it │ │ │ └── plugins.py # LLM traffic logging (raw_llm_logging): requests as sent (SentRequestLoggingPlugin, after the fit guard); each record names its agent's model (chosen=: a run's model choice's), the agent and its sub-agent run (the active run); latency per model call (call_clock.CallClock: a clock under the call's EventActions, as the fit guard keeps its copies); usage records go to the file only (the stream's LLM_USAGE is the event processor's), counted as the stream's (adk_usage_event, by the agent's kind: kinds); the summary call and the overflow retry are not logged on ADK (a follow-up) │ │ ├── deepagents/ # Deep Agents orchestrator (deepagents extra); imports neither adk/ nor langgraph/ -│ │ │ ├── manager.py # DeepAgentsWorkflowManager (turns, sessions, the release hooks: the agents and MCP sessions, the checkpointer and index; _agent_tool_names: each agent's own tools as built, _own_tool_names; MCP, skills, the job resume hooks (_conversation_exists, _deliver_job_notice), _compact_turn; _run_agent, the base's hook: the type's graph (_agent_graphs), or its model choice's (_variant_graphs, built from Variant(config, chat_model, resolved, budget) per (type, choice)), its processor and RunCallback on _run_models' maps, astreamed in the run's task with var_child_runnable_config cleared, so its chunks reach its own loop alone, through a run-mode processor and a RunCallback of its own; the answer the last AIMessage with text, its outcome mark, the shared keys it changed by Deep Agents' _is_unchanged rule (copied), an overflow RunFailed) -│ │ │ ├── agent_builder.py # build_agent_tree: one create_agent per AgentConfig, each on its own, through build_agent (one agent's graph, root= explicit; variants=: Variant, a sub-agent type on another model and its numbers, its graphs in variant_graphs=) (graphs=: kept by name for _run_agent; every agent compiled on the manager's checkpointer, a tree built without one compiling its sub-agents with none); root=: the graph's root (a free type listed first is no root); each agent can_have_children says gets task from task_tool.build_task_tool (delegations=), its own tool named task an AgentGraphError; every sub-agent's RunControlMiddleware (delegations=), inside its SubAgentOutcomeMiddleware +│ │ │ ├── manager.py # DeepAgentsWorkflowManager (turns, sessions, the release hooks: the agents and MCP sessions, the checkpointer and index; _agent_tool_names: each agent's own tools as built, _own_tool_names; MCP, skills, the job resume hooks (_conversation_exists, _deliver_job_notice), _compact_turn; _run_agent, the base's hook: the type's graph (_agent_graphs), or its model choice's (_variant_graphs, built from Variant(config, chat_model, resolved, budget) per (type, choice)), a general_purpose run on its spawner's (_general_graphs: a Variant with tools and prompt of its own, _agent_tools; its MCP notice names the spawner), its processor and RunCallback on _run_models' maps, astreamed in the run's task with var_child_runnable_config cleared, so its chunks reach its own loop alone, through a run-mode processor and a RunCallback of its own; the answer the last AIMessage with text, its outcome mark, the shared keys it changed by Deep Agents' _is_unchanged rule (copied), an overflow RunFailed) +│ │ │ ├── agent_builder.py # build_agent_tree: one create_agent per AgentConfig, each on its own, through build_agent (one agent's graph, root= explicit; variants=: Variant, a sub-agent type on another model and its numbers, its graphs in variant_graphs=) (graphs=: kept by name for _run_agent; every agent compiled on the manager's checkpointer, a tree built without one compiling its sub-agents with none); root=: the graph's root (a free type listed first is no root); each agent can_have_children says gets task from task_tool.build_task_tool (delegations=), its own tool named task an AgentGraphError; general=/general_graphs=: the built-in general_purpose type's Variant per spawner, no task; every sub-agent's RunControlMiddleware (delegations=), inside its SubAgentOutcomeMiddleware │ │ │ ├── middleware.py # InterruptedCallsMiddleware (each call recorded and answered as the active run's; a call id the agent's state holds renamed as the answer arrives, awrap_model_call outside the model side, fresh_call_id; a call answered by a result of its id between its answer and the next), PermissionMiddleware, ToolResultCapMiddleware, ToolCallErrorMiddleware, ActiveToolCallMiddleware (each call the active tool call around its tool), ForeignReasoningMiddleware, ContextOverflowMiddleware, MemoryIndexMiddleware (the root's memory index first in the first human message of each request), RosterMiddleware (outside it: the root's roster of its open sub-agents, after the index), SubAgentOutcomeMiddleware (outermost on every sub-agent's model side: a refused or cut final answer rewritten, its reasoning kept, and marked, response_metadata["agentic_cli"]["outcome"], beside the other marks; a call that raises passes), RunControlMiddleware (inside it: a sub-agent run's control at its model calls, Delegations.control of the active run: a narrowed run's request offers its tools and KEPT_TOOLS only (RunControl.keeps), and its awrap_tool_call answers a call of any other unknown_tool_result, before the gate; the messages steered to it added to its state before each call, abefore_model; the call counted and the last allowed one given STEP_LIMIT_NOTE, with_note, its tools still bound; each answer's usage, langchain_tokens, to used; the run's last answer's tool calls dropped, without_calls; the framework's task among the request's tools, by identity, given the schema and description the run is offered, Delegations.task_offer by its depth, or left out when it is offered nothing); mark_latency/answer_latency: the run callback's mark of how long a call took, response_metadata["agentic_cli"]["latency_ms"]; only the gate has a synchronous tool or model wrapper (it denies the sync tool call), the rest wrap with the async ones (`InterruptedCallsMiddleware.before_agent` is a node hook, synchronous, run on async turns too): turns run through `astream`, and a synchronous run of a graph fails at the first without a sync wrapper, LangChain's NotImplementedError │ │ │ ├── tools.py # to_langchain_tools: a callable → StructuredTool whose .func/.coroutine is it │ │ │ ├── task_tool.py # build_task_tool: the framework's task on Deep Agents (a StructuredTool over what a run at the agent's first depth is offered, task_offer: the root's fixed, a sub-agent's rewritten per call by RunControlMiddleware; bound to the task declaration; a call by a run offered nothing answered unknown_tool_result, as ADK answers a tool it did not declare): a call → Delegations.delegate, whose shared-key change (the outside-content mark) and envelope (JSON, the ToolMessage) come back as one Command; SHARED_KEYS; inherited_messages (an inheriting run's history: the state's messages, the summary event applied, less the message that called task); build_follow_up_tools (with follow_ups: message_agent, stop_agent, check_agents, each a StructuredTool bound to its declaration, answering as task does); start_skill_run (a load_skill of a skill that names an agent type: SkillAgents.start, answered as task is, one Command) @@ -158,7 +158,7 @@ agentic-cli/ │ │ ├── adk/state_tools.py # ADK-native plan/task tools (ToolContext.state) │ │ ├── langgraph/state_tools.py # LangGraph-library plan/task tools (Command/InjectedState): Deep Agents and LangGraph │ │ ├── skills/ # Agent Skills: SkillStore, the ADK toolset (toolset.py: make_skill_toolset(agents=), ADK's load_skill replaced by adk/skill_tool.py's SkillLoadTool for an agent with a skill that names an agent type, where the app lets a skill start one) -│ │ │ ├── agents.py # A skill that starts an agent: SKILL_AGENT_KEY (the frontmatter's top-level agent), skill_agent, skill_started_by (skill:); SkillAgents(agent, delegations, root=): starts (the key counts only with "skill" in spawn_sources: otherwise it is ignored and the skill loads as instructions, ADK's own toolset kept), check as the agent is built (skill_agent_ignored, or skill_agent_not_startable, warning, once per agent and skill though ADK builds an agent for each model choice; the app still starts), start at a load (the type one of the app's, spawnable for "skill", may_spawn at the loading run's depth, none by an inheriting agent nor, below the root, of an inheriting type, and the skill's instructions not empty; else SKILL_AGENT_ERROR, no run): Delegations.start (the brief the skill's name and body, counted, no tools or model), the envelope with "skill" +│ │ │ ├── agents.py # A skill that starts an agent: SKILL_AGENT_KEY (the frontmatter's top-level agent), skill_agent, skill_started_by (skill:); SkillAgents(agent, delegations, root=): starts (the key counts only with "skill" in spawn_sources: otherwise it is ignored and the skill loads as instructions, ADK's own toolset kept), check as the agent is built (skill_agent_ignored, or skill_agent_not_startable, warning, once per agent and skill though ADK builds an agent for each model choice; the app still starts), start at a load (the type one of the app's, spawnable for "skill", may_spawn at the loading run's depth, none by an inheriting agent nor, below the root, of an inheriting type, and the skill's instructions not empty; else SKILL_AGENT_ERROR, no run): Delegations.start (the brief the skill's name and body, counted, no tools or model), the envelope with "skill" (general_purpose: made for the loading agent's type, based_on; a general-purpose agent's own loads start none) │ │ │ └── langchain_tools.py # make_skill_tools: list_skills/load_skill/load_skill_resource for Deep Agents (agents=: a skill that names an agent type starts it, workflow/deepagents/task_tool.py::start_skill_run, from the call's injected runtime) │ │ ├── jobs/ # Long-running jobs: JobManager, backends (a spec pinned at submit: a subprocess job runs where it was submitted; one on a backend that does not survive a restart, in-process, is claimed at submit and runs only in its submitter, FAILED if still queued at close; JobRecord.started_by: the sub-agent instance whose call submitted it), job_* tools │ │ │ └── resume.py # job_result_payload, JOB_NOTICE_HEADER, job_notice_ask (a sub-agent's job named: JOB_NOTICE_ASK_FOR): what a finished job tells the agent @@ -256,7 +256,7 @@ Workflow: - **Tool error handling**: All tools return `{"success": bool, ...}` dicts. Never raise `ToolError`. An exception that still escapes a tool is a bug, but it costs one call rather than the turn: on ADK, `workflow/adk/tool_error_plugin.py::ToolErrorPlugin` turns it into an error dict; on Deep Agents, `workflow/deepagents/middleware.py::ToolCallErrorMiddleware`, inside the permission gate, gives the same result, `{"success": false, "error": " failed: : "}` cut to 500 characters (both use `workflow/tool_errors.py`). A call to a tool name the agent does not have gets ADK's own text, its first two lines (`unknown_tool_result`: "nope failed: ValueError: Tool 'nope' not found." and the agent's tools by name), logged `tool_not_found` at info (the model's mistake): on ADK the permission gate lets ADK's stand-in through (`is_unknown_tool`: a bare `BaseTool` described "Tool not found", which runs nothing; contract-tested) and `ToolErrorPlugin` answers its lookup error; on Deep Agents the gate answers it. It catches `Exception`, never `BaseException`, so cancelling still cancels (google-adk 2.15 hands a cancelled call's `CancelledError` to `ToolErrorPlugin` for cleanup, ignoring the answer: it answers nothing and logs `tool_cancelled` at debug, no warning). `task` raises nothing into it: a sub-agent's model or run failing (its summary or overflow included: its own tools' errors are results already) fails the run, whose envelope its parent reads (`error`: the provider's reason; on ADK out of ADK's plugin wrapper), reported at once through the turn's live events as one recoverable `ERROR`, ` failed: `, the run's: the coordinator carries on. A sub-agent's overflow (still too long after its summary or trim) fails its run, on both backends, in the words of ADK's overflow handler, `: the request no longer fits 's context window.` with `error_code` `CONTEXT_OVERFLOW` (`context.py::subagent_overflow_message`): ADK's `OverflowPlugin` answers the run's model call with it, Deep Agents' manager raises it (`RunFailed`). A refusal is no exception here (the framework adds no `ModelRefusalMiddleware`): a sub-agent whose final answer a model refused ends its run `refused`, and its parent reads, as its envelope's result, Deep Agents 0.7.34's notice ("The subagent stopped because a model refused the request. … Retrying the same request is unlikely to succeed; rephrase it or continue without it."), on both backends and whichever deepagents the pin installs (0.7.28 has no notice of its own; 0.7.34+ finds no refusal block left to word again); an answer cut at the output limit keeps its text, followed by `[cut off at the output limit]`, and its run ends `completed` and `partial`, with one recoverable warning ("'s answer was cut off at the output limit"); the answer's thoughts or reasoning are kept. ADK's `SubAgentOutcomePlugin` and Deep Agents' `SubAgentOutcomeMiddleware` rewrite and mark the answer, by `workflow/agents/outcome.py`. On ADK the plugin reads the answer's `finish_reason` (Claude's `refusal` and a Chat Completions `content_filter` arrive as `SAFETY`, `max_tokens` and `length` as `MAX_TOKENS`, Gemini's as themselves), the `error_code` ADK sets on an answer with no content (a Gemini prompt's `block_reason`), the `reason` an `OTHER` stop names in its JSON error message (ADK's OpenAI Responses adapter's `incomplete_details`, `content_filter` among them) and a text part `OpenAI refusal: ` (that adapter's refusal, and `OpenAICompatibleLlm`'s of a Chat Completions `refusal`, which ADK's class drops). On Deep Agents the middleware reads `response_metadata`'s `stop_reason` (ChatAnthropic), `finish_reason` (ChatOpenAI, ChatGoogleGenerativeAI), `incomplete_details.reason` (the Responses API) and `prompt_feedback.block_reason` (a Gemini prompt block), and a refusal the answer holds (a refusal block, standard or `non_standard`, or `additional_kwargs["refusal"]`). The root's own answers reach the user as their model gave them: on ADK a root's refusal with no answer (Claude's, Gemini's) is still the turn's one `ERROR` (" returned no answer"), and a root on OpenRouter or an OpenAI-compatible server replies "OpenAI refusal: ". On both backends the root's own failure leaves the run: the turn's one `ERROR`. A gate or error result goes back as the call's `ToolMessage` with `status="error"`. LangGraph's `ToolNode` runs with `handle_tool_errors=True`. - **Tool result cap**: every tool result passes `workflow/tool_output.py::cap_tool_result` (registered, MCP and skill tools, `job_result`, a delegation's envelope on either backend, and the envelope a view's notice carries: `BaseWorkflowManager._user_ran` keeps `instance_result` capped): one over `tool_result_max_chars` is cut to its shape and as much of its head and tail as fits (the kept length is bisected, since JSON escapes vary), with a note (under `truncated`, or appended to a string) pointing at its full output in `./.{app_name}/tool-output/`, written for `read_file` to page by lines (lines over 2,000 characters split). A string that holds a JSON object (`json_object`: a delegation's envelope, which both task tools write unescaped, `ensure_ascii=False`; a framework tool's dict in a Deep Agents `ToolMessage`) is cut as that dict and given back as its JSON text, so the parent reads JSON still, on both backends. On ADK, `workflow/adk/tool_result_cap_plugin.py::ToolResultCapPlugin` is registered after `InterruptedCallsPlugin`, since ADK stops at the first `after_tool_callback` that returns a value, and it leaves out an agent with `after_tool_callback`s of its own (a native YAML app's, `build.own_after_tool_agents`), which ADK would skip once the cap answered. ADK's Claude and OpenAI Responses adapters send only a result's `content`, else its `result`, so the plugin also puts the note there (`_note_where_sent`). On Deep Agents, `ToolResultCapMiddleware` sits between the permission gate and `ToolCallErrorMiddleware`, so an error result is capped too, and reads a `ToolMessage` (its text cut by the cap's string rule, text blocks joined into the first) and each `ToolMessage` of a `Command`. A call of the framework's `read_file` (by identity, as each gate resolves tools) on a saved output is cut without a second save. Saving never fails the call (`tool_output_not_saved` warns once per folder, then debug), and a cap that raises leaves the result uncut (`tool_result_cap_failed` at warning, its traceback at debug). - **Summarizing on ADK (main agent only)**: every app's App (a native ADK YAML app's too, when its root's model has a context budget) has ADK's `EventsCompactionConfig` with `workflow/adk/compaction.py::AgentCliSummarizer` at the root's trigger (`context_budget`, as on Deep Agents); ADK checks before every agent's model call, and `MainAgentPlugin` (the first plugin) records the running agent in a ContextVar, so the summarizer writes only for the root (a sub-agent's run, on its type's runner, has no compaction config at all: a sub-agent compacting the shared session lost its brief and looped, 100 requests in one turn, offline). The summarizer picks its own range before paying for anything (`summary_range`: the newest `keep` tokens and the current turn kept, a cut only where a user turn starts, never parting a call from its result, long-running calls excepted since ADK re-injects them, nor leaving a kept event stamped inside the range; none for a saving under 20% of the trigger, the seed left out of it), writes on the root's own model (`_simple_model(SUMMARY_MAX_TOKENS, agent=root)`, thinking off) with `workflow/summary_prompt.py`, the rendering sized to that model's window (the middle cut, `MIDDLE_OMITTED`, the seed kept whole), and returns **user-role** text starting `SUMMARY_PREFIX` (a model-role first message is one Claude refuses), which the fit guard folds, after the memory index and the roster when the request has them, into the next user text (`fold_summary`), so no request holds two user messages in a row. `last_kept_turns` and `last_error` are for its callers: a manual summarizer warns of nothing itself. It reports through the turn's live events (`_run_and_stream` iterates the runner through `live_events.merged` under `reporting(live)`); any failure is one recoverable `ERROR` a turn, never raised to ADK. `NoAfterTurnCompactionRunner` overrides ADK's private `Runner._run_post_invocation_compaction` (contract-tested), so the prompt never waits for a summary after the answer. `FitGuardPlugin` is the last plugin (but `SentRequestLoggingPlugin`, which logs a request as sent, and `CallSentPlugin`, which starts the call's clock) and `OverflowPlugin` the one before it (`MemoryIndexPlugin`, when the root has a memory tool and `memory_index_enabled` is on, the one before that: it puts the conversation's memory index snapshot first in the root's requests, never in the session): the guard leaves a request's oldest turns out when it is over its agent's budget (keeping the newest turn and what opens the conversation, the memory index, the roster of the root's open sub-agents (`RosterPlugin`, before `MemoryIndexPlugin`, for a root with `message_agent`), then a summary: `protected_head`; in a sub-agent type's chain also the run's task message and its instance's brief, `brief_of`) and keeps each request as it came in (`request_as_seen`: one copy per model call, under the call's `EventActions`, which ADK passes to all three of its callbacks: each sub-agent run is an invocation of its own on a child session, but two runs of one type share that type's runner and its plugins, and a run drops only what its own cancelled calls left, as it ends), and the overflow handler, on a provider's overflow, summarizes now (the root, through `compact_session`, ADK's private `_run_compaction_for_token_threshold_config`; `_summarize_now` returns `WrittenSummary(text, kept_turns)`, and the retry is the index, the roster, the summary and those turns) or trims to half the budget (a sub-agent, or nothing to summarize), builds the retry from the guard's copy without the context cache, retries once on the agent's `canonical_model`, then answers the root with `LlmResponse(error_code="CONTEXT_OVERFLOW")`, never model text (ADK would store it as the reply), which `ADKEventProcessor` maps to the turn's `ERROR`; a retry that fails otherwise propagates, and `_run_and_stream` unwraps ADK's plugin-manager `RuntimeError` to the provider's error; a sub-agent's call that still does not fit is answered with an error response too, `CONTEXT_OVERFLOW` and `subagent_overflow_message`, which its run's processor keeps as the run's failure: the run ends `failed` with those words (`RunFailed`), its parent reads them in the envelope, and the user is warned once, by the framework's delegation (`agents/delegate.py`), as on Deep Agents. A native ADK YAML app gets all of it: only the building of its agents differs (`workflow/adk/build.py`). Its chat-mode sub-agents keep transferring, and an agent the root transfers to replies to the user (`build.reply_agents`: its text is the reply, recent_messages reads it, its overflow is the turn's clear error, its calls write the outside-content mark); the summary and the memory index stay the root's, so such an agent is trimmed by the fit guard, not summarized. An agent's own callbacks (a native app's) run after every plugin, and only when none answered: its before-model callbacks see the request after the fit guard, and the cap leaves out an agent with after-tool callbacks. A main agent whose model does not resolve through the catalog has no budget and no summary. -- **Sub-agents delegate and return**: on both backends a sub-agent run is a call of its parent's `task` tool (the framework's: `tools/_core/delegation.py` declares it, `workflow/agents/delegate.py` runs it) that returns in the same turn; only the root replies to the user (a sub-agent's `TEXT` carries `metadata["subagent"]`, and the CLI shows it as the events box's status line, under its run's name: `researcher-2 › …`; `/agents` picks among a conversation's instances), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the types the calling run may start, `Delegations.offered`: its own sub-agents, then, with `SubAgentPolicy.spawn_sources` holding `"agent"` and the run's depth below `max_spawn_depth`, the types whose `AgentConfig.spawnable_by` names `"agent"`, `workflow/agents/spawn.py`; a free type, in no `sub_agents` list, is never the root; `task` is offered for each run, ADK declaring it per request and Deep Agents rewriting a sub-agent's per model call, and a run offered nothing has none) and a brief (`workflow/agents/brief.py`: `title`, `objective`, `deliverable`, `constraints`, `known`, `done_when`), then `tools` (some of the type's own tools, `_agent_tool_names`: the run is offered only those and the tools every run keeps, `RunControl.keeps`, ADK's `RunControlPlugin` and Deep Agents' `RunControlMiddleware` filtering its requests and answering a call of another `unknown_tool_result`) and `model` (one of `AgentConfig.model_choices`, offered only when a type has some: the run is on the type's agent built on that choice at initialization, ADK a runner and Deep Agents a graph per (type, choice), resolved and budgeted with the rest, `_run_models`), its schema and description the same on both backends (`task_parameters`, `task_description`: a line per type with its description, "The agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both, through `Delegations.start` (a `StartRequest`, the one entry for a first run): it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents `, never written to the conversation. It ends as the `RunAnswer` says: its last text (a reply that also called a tool included; none at all, an empty result shown `No answer`), `refused` or `partial` by the outcome mark, `failed` for an error or a raise (one recoverable `ERROR`, ` failed: `, or the hook's own words, `RunFailed`: an overflow's; its result the text it wrote before it failed: a failed model call is the hook's `RunAnswer.error`, `failure_reason`, its warning's code `RunAnswer.error_code`, the error's type, and `RunFailed` carries `text=`); and the call's result is the run's envelope as JSON (`workflow/agents/envelope.py`), shown by `show_as_delegation`. A cancel of the caller's task stops the run's task first and ends the run `interrupted`. Each run works under its `RunControl` (`workflow/agents/control.py`, `AgentRun.control`), with its type's `AgentConfig.limits` over the policy's (`SubAgentPolicy.limits`, `DEFAULT_LIMITS`: 100 model calls): `Delegations.cancel(run_id, by=, error=)` cancels the run alone (its parent, the user or a limit), and the hook, seeing its own cancel (`own_cancel`), stops the run as a stopped turn's (ADK: its abort signal, its open calls sealed in its child session; Deep Agents: its stream closed) and returns what it has: the run ends `cancelled` with `cancelled_by` and that text, `partial`, while its siblings and the turn go on; the turn's own cancel still wins (`interrupted`). Past its `timeout` (counted from when its hook starts, `timing`) the run is cancelled by its limit (`time limit reached`); each model call is counted before it is made (`RunControlPlugin` in each sub-agent chain, `RunControlMiddleware` on each sub-agent's model side) and the last allowed one gets `STEP_LIMIT_NOTE` after its last message, its tools still declared (Claude refuses tool calls in a request that defines no tools); its answer's calls are dropped, never run, so the run completes `partial`, `step limit reached`; each call's tokens are counted after it, with what the run's other calls used (`RunControl(side_tokens=)`: its tools' side calls and its summaries, the ledger's rows of the run that are no agent step, `UsageLedger.by_purpose(run=)`), so the limit is the run's total as its usage record counts it, and past `max_tokens` an answer that makes tool calls is the run's last, its calls dropped, `cancelled` by its limit (`token limit reached`), while one that makes none ends the run as it would, `completed`, its result whole (a model that reports no usage counts none of its own). A turn starts at most `max_runs_per_turn` runs, at any depth (`sessions.runs_this_turn`): a call past it is the error result, no run started; `task`'s description says so (`limit_sentences`). At most `max_active` runs of a conversation work at once, at any depth (`workflow/agents/slots.py::SlotPool`, one per conversation, `Delegations.slots`; the root takes no slot): a run takes a slot right before its hook and its time limit start and gives it back at its end, however it ends; one that finds none waits `queued` (an `AGENT_RUN` and its record say so, then `running`), not counted against its `timeout`. A run lends its slot while it waits on its children (one lend for all it waits on at once; the child that ends last hands its slot straight back, so the tree in progress goes on ahead of the runs that have not started) or on the user (`waiting_on_user`: `input_required`, `queued` once answered while it waits for its slot back, then `running`, in `request_user_input` and in the permission engine from before its one-prompt lock until after it: a run waiting for a slot while holding the lock would hold every other run's prompt; a prompt no one can be shown, no input callback or its turn ended, lends nothing: `can_request_user_input`), so nested fan-out never deadlocks; a cancel, queued or lending, leaves no waiter in the heap and no slot taken. A message steered to a working run (`RunControl.steer`, through `Delegations.control(run)`) is added after its last message, as the user's, before its next model call, and stays in its transcript (ADK: appended to its child session, the run's later events stamped after it so a durable store reads them back in order; Deep Agents: added to its state); a sub-agent run's task message is never trimmed, on ADK neither by the fit guard nor by the overflow handler's retry, whatever was steered after it. A dialog whose run is stopped is withdrawn, the turn going on (`MessageProcessor`). `AgentConfig.inherit_context` sets what a run sees: False (the default) its task alone, True its parent's conversation too, read once as the run starts (the conversation after any summary; Deep Agents' less the message that called `task`, which ADK's copy keeps), before the task message, which then ends with `INHERITED_CONTEXT_NOTE` (whose conversation it reads, which message is its task); `validate_agent_graph` refuses a value that is not True or False, `inherit_context=True` on the root, on an agent with sub-agents and below another sub-agent. On ADK (`workflow/adk/task_tool.py::TaskTool`) every config-built agent is built on its own, with no ADK `sub_agents`, so ADK offers none `transfer_to_agent`, and gets ADK's identity line ("You are an agent. Your internal name is …"); a delegating agent has one `TaskTool`. A sub-agent is an instance that outlives its run: `idle` when the run ends, its next run a follow-up (`Delegations.follow_up`, through the same hook with `AgentRun.follow_up`, the message as written and no history), one run per instance at a time; a run's end leaves its instance `stopped` (once the user stopped it: its run cancelled by the user, or an idle one; only the user continues it), `closed` (`AgentConfig.continuable` False, or past `SubAgentPolicy.max_open`: the oldest idle one) or `idle`, `Delegations.close` closes an idle or stopped one and its descendants, and `AGENT_INSTANCE` carries a change without a run; the user controls any instance of the open conversation through the manager (`run_instance`: a follow-up as a turn of its own, its Ctrl+C the user's stop; `start_instance`: the user's new instance, `/agent new`, the same; `stop_instance`, `close_instance`, `steer_instance`; `tell_root`: a notice turn of the root, marked as a job's) and the CLI's `/agents` picker, `/agent stop|close `, `/agent new ` and `/agent `'s view (`cli/agent_view.py`: a line typed there is the instance's next run or a steer of the run that works, Ctrl+C the user's stop, `/back` the root's notice); on ADK a follow-up continues the instance's child session, the calls an earlier run left open answered first (`left_open_by`, from the instance's record), on Deep Agents the instance's own checkpointer thread (`instance_run_config`: its input the message and the caller's mark, the shared keys it changed compared with the thread's state as the run started). Each sub-agent type runs on its own runner (`App(name=child_app(app_name))`, the type's agent its root, `_agent_plugin_chain`: the main chain configured for a sub-agent, no memory index, no summary, `RunControlPlugin` and `SubAgentOutcomePlugin`; every plugin's per-call state keyed by invocation) over the manager's session service, on a child session per instance (`child_session_id`: `/`, the conversation id's `%` and `/` percent-encoded; an inheriting instance's gets the conversation's events copied once, at its first run, `task_tool.inherited_events`), under an app no conversation list reads. On Deep Agents (`workflow/deepagents/task_tool.py::build_task_tool`) each type's graph is built on its own, and a run `astream`s it in its task with `var_child_runnable_config` cleared, so its chunks reach its own loop alone, never its parent's stream; an inheriting run's history is the parent's messages with Deep Agents' summary event applied (`SummarizationMiddleware._apply_event_to_messages`, private: `tests/workflow/deepagents/test_compact.py` pins it), and `ForeignReasoningMiddleware(kind, agent=...)` leaves out the reasoning of AI messages another agent wrote. A native ADK YAML app keeps transferring (chat-mode sub-agents); a task-mode agent in one is refused at validation, since ADK runs its delegation outside the tool pipeline and keeps the call open across turns. With `SubAgentPolicy(follow_ups=True)` every agent that can have sub-agents (`can_have_children`: its own, or types it may start at run time) also gets `message_agent`, `stop_agent` and `check_agents` beside `task` (`workflow/agents/follow_ups.py::call_follow_up_tool` over `Delegations.message`/`stop`/`check`; ADK's `FollowUpTool`, Deep Agents' `build_follow_up_tools`; an own tool of one of their names fails the build, a Deep Agents MCP tool of one is skipped): `message_agent` continues an idle instance, steers a running one (before its next step; a run already stopping or finished is waited for, then the message follows the instance up or is refused; one being closed is refused as closed at once) or, with `interrupt` (refused, nothing cancelled, when no follow-up could start; an agent's keeps the turn's run it checked for), replaces its run (the user's interrupt is the user's stop); `stop_agent` cancels a running run by its parent (the instance idle; only the user's stop makes one `stopped`) and, with `close`, closes it and its descendants; a message steered to a run and not in its transcript when it ends goes to the instance's next run (`RunControl.stored`/`unstored`: ADK counts one stored as its child-session append returns, Deep Agents once the model call after it holds it); a run that did not complete fully names its open tasks in its envelope (`open_tasks`); a run whose parent's run was stopped by its control ends `cancelled` by its parent, not `interrupted`. A skill whose frontmatter names a type (`agent: `, `tools/skills/agents.py`) starts a run of it when an agent loads it where the app lets a skill start an agent (`"skill"` in `spawn_sources`; otherwise the key is ignored, the skill loads as instructions and the build warns, `skill_agent_ignored`), on both backends (ADK: `adk/skill_tool.py::SkillLoadTool` in `load_skill`'s place; Deep Agents: `_SkillAnswers.load_skill`), when the type's `spawnable_by` holds `"skill"`, the skill has instructions and the loading run may start one (`may_spawn`): through `Delegations.start` (`started_by: skill:`, the loading run its parent, its task message the skill's body under its name, counted toward `max_runs_per_turn`), the call's result the envelope with `"skill"`, shown as a delegation; otherwise `{"success": false, "error": "The skill '' starts the agent '', which ."}`, no run, and a skill its agent's first run could not start is warned of as the agent is built (`skill_agent_not_startable`). +- **Sub-agents delegate and return**: on both backends a sub-agent run is a call of its parent's `task` tool (the framework's: `tools/_core/delegation.py` declares it, `workflow/agents/delegate.py` runs it) that returns in the same turn; only the root replies to the user (a sub-agent's `TEXT` carries `metadata["subagent"]`, and the CLI shows it as the events box's status line, under its run's name: `researcher-2 › …`; `/agents` picks among a conversation's instances), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the types the calling run may start, `Delegations.offered`: its own sub-agents, then, with `SubAgentPolicy.spawn_sources` holding `"agent"` and the run's depth below `max_spawn_depth`, the types whose `AgentConfig.spawnable_by` names `"agent"`, `workflow/agents/spawn.py`; a free type, in no `sub_agents` list, is never the root; `task` is offered for each run, ADK declaring it per request and Deep Agents rewriting a sub-agent's per model call, and a run offered nothing has none) and a brief (`workflow/agents/brief.py`: `title`, `objective`, `deliverable`, `constraints`, `known`, `done_when`), then `tools` (some of the type's own tools, `_agent_tool_names`: the run is offered only those and the tools every run keeps, `RunControl.keeps`, ADK's `RunControlPlugin` and Deep Agents' `RunControlMiddleware` filtering its requests and answering a call of another `unknown_tool_result`) and `model` (one of `AgentConfig.model_choices`, offered only when a type has some: the run is on the type's agent built on that choice at initialization, ADK a runner and Deep Agents a graph per (type, choice), resolved and budgeted with the rest, `_run_models`), its schema and description the same on both backends (`task_parameters`, `task_description`: a line per type with its description, "The agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both, through `Delegations.start` (a `StartRequest`, the one entry for a first run): it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents `, never written to the conversation. It ends as the `RunAnswer` says: its last text (a reply that also called a tool included; none at all, an empty result shown `No answer`), `refused` or `partial` by the outcome mark, `failed` for an error or a raise (one recoverable `ERROR`, ` failed: `, or the hook's own words, `RunFailed`: an overflow's; its result the text it wrote before it failed: a failed model call is the hook's `RunAnswer.error`, `failure_reason`, its warning's code `RunAnswer.error_code`, the error's type, and `RunFailed` carries `text=`); and the call's result is the run's envelope as JSON (`workflow/agents/envelope.py`), shown by `show_as_delegation`. A cancel of the caller's task stops the run's task first and ends the run `interrupted`. Each run works under its `RunControl` (`workflow/agents/control.py`, `AgentRun.control`), with its type's `AgentConfig.limits` over the policy's (`SubAgentPolicy.limits`, `DEFAULT_LIMITS`: 100 model calls): `Delegations.cancel(run_id, by=, error=)` cancels the run alone (its parent, the user or a limit), and the hook, seeing its own cancel (`own_cancel`), stops the run as a stopped turn's (ADK: its abort signal, its open calls sealed in its child session; Deep Agents: its stream closed) and returns what it has: the run ends `cancelled` with `cancelled_by` and that text, `partial`, while its siblings and the turn go on; the turn's own cancel still wins (`interrupted`). Past its `timeout` (counted from when its hook starts, `timing`) the run is cancelled by its limit (`time limit reached`); each model call is counted before it is made (`RunControlPlugin` in each sub-agent chain, `RunControlMiddleware` on each sub-agent's model side) and the last allowed one gets `STEP_LIMIT_NOTE` after its last message, its tools still declared (Claude refuses tool calls in a request that defines no tools); its answer's calls are dropped, never run, so the run completes `partial`, `step limit reached`; each call's tokens are counted after it, with what the run's other calls used (`RunControl(side_tokens=)`: its tools' side calls and its summaries, the ledger's rows of the run that are no agent step, `UsageLedger.by_purpose(run=)`), so the limit is the run's total as its usage record counts it, and past `max_tokens` an answer that makes tool calls is the run's last, its calls dropped, `cancelled` by its limit (`token limit reached`), while one that makes none ends the run as it would, `completed`, its result whole (a model that reports no usage counts none of its own). A turn starts at most `max_runs_per_turn` runs, at any depth (`sessions.runs_this_turn`): a call past it is the error result, no run started; `task`'s description says so (`limit_sentences`). At most `max_active` runs of a conversation work at once, at any depth (`workflow/agents/slots.py::SlotPool`, one per conversation, `Delegations.slots`; the root takes no slot): a run takes a slot right before its hook and its time limit start and gives it back at its end, however it ends; one that finds none waits `queued` (an `AGENT_RUN` and its record say so, then `running`), not counted against its `timeout`. A run lends its slot while it waits on its children (one lend for all it waits on at once; the child that ends last hands its slot straight back, so the tree in progress goes on ahead of the runs that have not started) or on the user (`waiting_on_user`: `input_required`, `queued` once answered while it waits for its slot back, then `running`, in `request_user_input` and in the permission engine from before its one-prompt lock until after it: a run waiting for a slot while holding the lock would hold every other run's prompt; a prompt no one can be shown, no input callback or its turn ended, lends nothing: `can_request_user_input`), so nested fan-out never deadlocks; a cancel, queued or lending, leaves no waiter in the heap and no slot taken. A message steered to a working run (`RunControl.steer`, through `Delegations.control(run)`) is added after its last message, as the user's, before its next model call, and stays in its transcript (ADK: appended to its child session, the run's later events stamped after it so a durable store reads them back in order; Deep Agents: added to its state); a sub-agent run's task message is never trimmed, on ADK neither by the fit guard nor by the overflow handler's retry, whatever was steered after it. A dialog whose run is stopped is withdrawn, the turn going on (`MessageProcessor`). `AgentConfig.inherit_context` sets what a run sees: False (the default) its task alone, True its parent's conversation too, read once as the run starts (the conversation after any summary; Deep Agents' less the message that called `task`, which ADK's copy keeps), before the task message, which then ends with `INHERITED_CONTEXT_NOTE` (whose conversation it reads, which message is its task); `validate_agent_graph` refuses a value that is not True or False, `inherit_context=True` on the root, on an agent with sub-agents and below another sub-agent. On ADK (`workflow/adk/task_tool.py::TaskTool`) every config-built agent is built on its own, with no ADK `sub_agents`, so ADK offers none `transfer_to_agent`, and gets ADK's identity line ("You are an agent. Your internal name is …"); a delegating agent has one `TaskTool`. A sub-agent is an instance that outlives its run: `idle` when the run ends, its next run a follow-up (`Delegations.follow_up`, through the same hook with `AgentRun.follow_up`, the message as written and no history), one run per instance at a time; a run's end leaves its instance `stopped` (once the user stopped it: its run cancelled by the user, or an idle one; only the user continues it), `closed` (`AgentConfig.continuable` False, or past `SubAgentPolicy.max_open`: the oldest idle one) or `idle`, `Delegations.close` closes an idle or stopped one and its descendants, and `AGENT_INSTANCE` carries a change without a run; the user controls any instance of the open conversation through the manager (`run_instance`: a follow-up as a turn of its own, its Ctrl+C the user's stop; `start_instance`: the user's new instance, `/agent new`, the same; `stop_instance`, `close_instance`, `steer_instance`; `tell_root`: a notice turn of the root, marked as a job's) and the CLI's `/agents` picker, `/agent stop|close `, `/agent new ` and `/agent `'s view (`cli/agent_view.py`: a line typed there is the instance's next run or a steer of the run that works, Ctrl+C the user's stop, `/back` the root's notice); on ADK a follow-up continues the instance's child session, the calls an earlier run left open answered first (`left_open_by`, from the instance's record), on Deep Agents the instance's own checkpointer thread (`instance_run_config`: its input the message and the caller's mark, the shared keys it changed compared with the thread's state as the run started). Each sub-agent type runs on its own runner (`App(name=child_app(app_name))`, the type's agent its root, `_agent_plugin_chain`: the main chain configured for a sub-agent, no memory index, no summary, `RunControlPlugin` and `SubAgentOutcomePlugin`; every plugin's per-call state keyed by invocation) over the manager's session service, on a child session per instance (`child_session_id`: `/`, the conversation id's `%` and `/` percent-encoded; an inheriting instance's gets the conversation's events copied once, at its first run, `task_tool.inherited_events`), under an app no conversation list reads. On Deep Agents (`workflow/deepagents/task_tool.py::build_task_tool`) each type's graph is built on its own, and a run `astream`s it in its task with `var_child_runnable_config` cleared, so its chunks reach its own loop alone, never its parent's stream; an inheriting run's history is the parent's messages with Deep Agents' summary event applied (`SummarizationMiddleware._apply_event_to_messages`, private: `tests/workflow/deepagents/test_compact.py` pins it), and `ForeignReasoningMiddleware(kind, agent=...)` leaves out the reasoning of AI messages another agent wrote. A native ADK YAML app keeps transferring (chat-mode sub-agents); a task-mode agent in one is refused at validation, since ADK runs its delegation outside the tool pipeline and keeps the call open across turns. With `SubAgentPolicy(follow_ups=True)` every agent that can have sub-agents (`can_have_children`: its own, or types it may start at run time) also gets `message_agent`, `stop_agent` and `check_agents` beside `task` (`workflow/agents/follow_ups.py::call_follow_up_tool` over `Delegations.message`/`stop`/`check`; ADK's `FollowUpTool`, Deep Agents' `build_follow_up_tools`; an own tool of one of their names fails the build, a Deep Agents MCP tool of one is skipped): `message_agent` continues an idle instance, steers a running one (before its next step; a run already stopping or finished is waited for, then the message follows the instance up or is refused; one being closed is refused as closed at once) or, with `interrupt` (refused, nothing cancelled, when no follow-up could start; an agent's keeps the turn's run it checked for), replaces its run (the user's interrupt is the user's stop); `stop_agent` cancels a running run by its parent (the instance idle; only the user's stop makes one `stopped`) and, with `close`, closes it and its descendants; a message steered to a run and not in its transcript when it ends goes to the instance's next run (`RunControl.stored`/`unstored`: ADK counts one stored as its child-session append returns, Deep Agents once the model call after it holds it); a run that did not complete fully names its open tasks in its envelope (`open_tasks`); a run whose parent's run was stopped by its control ends `cancelled` by its parent, not `interrupted`. A skill whose frontmatter names a type (`agent: `, `tools/skills/agents.py`) starts a run of it when an agent loads it where the app lets a skill start an agent (`"skill"` in `spawn_sources`; otherwise the key is ignored, the skill loads as instructions and the build warns, `skill_agent_ignored`), on both backends (ADK: `adk/skill_tool.py::SkillLoadTool` in `load_skill`'s place; Deep Agents: `_SkillAnswers.load_skill`), when the type's `spawnable_by` holds `"skill"`, the skill has instructions and the loading run may start one (`may_spawn`): through `Delegations.start` (`started_by: skill:`, the loading run its parent, its task message the skill's body under its name, counted toward `max_runs_per_turn`), the call's result the envelope with `"skill"`, shown as a delegation; otherwise `{"success": false, "error": "The skill '' starts the agent '', which ."}`, no run, and a skill its agent's first run could not start is warned of as the agent is built (`skill_agent_not_startable`). With `SubAgentPolicy.general_purpose` (it needs a source) every enabled source may also start the built-in `general_purpose` type (`spawn.GENERAL_PURPOSE`; `task` lists it last, a skill may name it, `/agent new` may start it): no config of the app's (one named so is refused at validation while it is on), but one made for the type that starts it (`general_purpose_config`: that type's tools, MCP servers, skills and own model, `GENERAL_PURPOSE_PROMPT`, the plan's tools, a fresh context; `Delegations.config_for(agent_type, based_on=)`), its spawner the caller's type for `task` and a skill, the root for the user (`StartRequest.based_on` → `AgentRun.based_on`, `InstanceRecord.based_on`, so its follow-ups and its runs after a restart are made for the same type); it starts no agent (`can_have_children` False: no `task`, no parent's tools; a skill it loads that names a type is refused), `task`'s `tools` narrows it against its spawner's tools (`_agent_tool_names()`), and it has no model choices. Each backend builds one per type that may start it (`general_purpose_spawners`: the root, and with `max_spawn_depth` 2 or more each type that does not inherit when `"agent"` is a source, and each type with skills when `"skill"` is; `Delegations.general_purpose`) at initialization, through the builder that builds a model choice's, with MCP connections of its own (ADK `_general_agents`/`_general_runners`, its chain reading the spawner's model, kind and numbers under `general_purpose`; Deep Agents `_general_graphs`, a `Variant` with its own tools and prompt), the hooks picking it by `run.based_on` (`_run_models`, `_general_model`: the spawner's resolved model named for `general_purpose`), released with the rest and built again by a model switch. - **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 a7cd2aa1..fdc62595 100644 --- a/README.md +++ b/README.md @@ -1305,6 +1305,8 @@ run time only, and no root however it is listed; the root may not set `spawnable_by`, and a `spawnable_by` that is empty or names a source other than `agent`, `skill` and `user` raises too (a free type the app's policy lets no source start is a warning: `validate_agent_graph(configs, policy=...)`). +An agent named `general_purpose` raises too while the policy enables the +built-in type of that name (`SubAgentPolicy(general_purpose=True)`). `model_choices` on the root, one that is no tuple or list of texts, and a choice named twice raise it too. `inherit_context=True` on the root, on an agent with sub-agents of its own or @@ -1444,7 +1446,8 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", 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. + main agent alone, and with the policy's `general_purpose` the built-in + general-purpose type is offered last (below). ```python coordinator = AgentConfig(name="coordinator", prompt="Hand self-contained " @@ -1511,6 +1514,32 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", Its body is all a fresh type's run reads (an inheriting type reads the conversation too), so write it as a task that stands on its own. +- **The general-purpose type.** `SubAgentPolicy(spawn_sources=..., general_purpose=True)` + adds a type the app does not configure, `general_purpose`, which every + source the policy enables may start: `task` lists it last ("A + general-purpose agent with your own tools (but not the ones that start + agents) and your model, for a self-contained task no other agent fits."), + a skill may name it (`agent: general_purpose`), and `/agent new + general_purpose ` starts one. Its run has the tools, MCP + servers, skills and model of the type that started it (the main agent's, + for the user's start), the framework's system prompt and a fresh context, + and starts no agent itself; `task`'s `tools` narrows it as any type, and + it has no model choices. One is built for each type that may start it + (the main agent, and with `max_spawn_depth` 2 or more each type that does + not inherit when agents may start types, and each type with skills when + skills may), with MCP connections of its own. Its instances + (`general_purpose-1`) keep the type that started them, so a follow-up runs + as the first run did. An agent of the app's named `general_purpose` is + refused while the policy enables it. + + ```python + manager = create_workflow_manager_from_settings( + [coordinator, researcher], settings, + subagents=SubAgentPolicy(spawn_sources={"agent", "user"}, general_purpose=True), + ) + # The coordinator's call: {"agent_type": "general_purpose", "title": "Tally it", + # "objective": "Count the TODO comments under src/ by file."} + ``` - **The parent's tools.** With `subagents=SubAgentPolicy(follow_ups=True)` every agent that can have sub-agents (its own, or types it may start at run time) gets three more tools beside `task` (with the diff --git a/src/agentic_cli/cli/agent_view.py b/src/agentic_cli/cli/agent_view.py index a7e024dc..c90a8fc2 100644 --- a/src/agentic_cli/cli/agent_view.py +++ b/src/agentic_cli/cli/agent_view.py @@ -583,21 +583,22 @@ def _runs_of(workflow: Any, conversation: "SessionRef", instance: str) -> list[" def _model(workflow: Any, record: "InstanceRecord") -> Any: """The model the instance runs on: its model choice's when it has one, else its - type's.""" + type's (a ``general_purpose`` one's, the type that started it: ``based_on``).""" if record.model is not None: return getattr(workflow, "choice_models", {}).get((record.agent, record.model)) - return getattr(workflow, "agent_models", {}).get(record.agent) + return getattr(workflow, "agent_models", {}).get(record.based_on or record.agent) def _budget(workflow: Any, record: "InstanceRecord") -> Any: - """The instance's context budget (its model choice's, when it has one). + """The instance's context budget (its model choice's, when it has one; a + ``general_purpose`` one's, the type that started it: ``based_on``). None when its manager manages none. """ try: if record.model is not None: return workflow.context_budget(record.agent, model=record.model) - return workflow.context_budget(record.agent) + return workflow.context_budget(record.based_on or record.agent) except (KeyError, RuntimeError, AttributeError): return None diff --git a/src/agentic_cli/tools/skills/agents.py b/src/agentic_cli/tools/skills/agents.py index c99db0ed..af4e76a1 100644 --- a/src/agentic_cli/tools/skills/agents.py +++ b/src/agentic_cli/tools/skills/agents.py @@ -21,6 +21,12 @@ agent is built: the app still starts, since a skill file can come from a user's folder. +A skill may name the built-in ``general_purpose`` type (with the policy's +``general_purpose``): its run is made for the loading agent's type, whose tools +and model it has. A general-purpose agent's own loads start no agent (it starts +none: ``spawn.can_have_children``), and its skills are not warned of: its +spawner's build warns of its own. + ``SkillAgents`` is one loading agent's: ADK's ``adk/skill_tool.py::SkillLoadTool`` and Deep Agents' ``task_tool.start_skill_run`` call it. Imports no backend. """ @@ -33,7 +39,12 @@ from agentic_cli.logging import Loggers from agentic_cli.workflow.agents.brief import Brief from agentic_cli.workflow.agents.delegate import Delegated, StartRequest -from agentic_cli.workflow.agents.spawn import SKILL_SOURCE, may_spawn, spawnable +from agentic_cli.workflow.agents.spawn import ( + GENERAL_PURPOSE, + SKILL_SOURCE, + may_spawn, + spawnable, +) from agentic_cli.workflow.sessions import get_active_run if TYPE_CHECKING: @@ -109,19 +120,25 @@ def starts(self, skill: Any) -> bool: and SKILL_SOURCE in self._delegations().policy.spawn_sources ) + def _general(self) -> bool: + """Whether this is a general-purpose agent's skill: it starts no agent.""" + return self._agent == GENERAL_PURPOSE and self._delegations().policy.general_purpose + def _reason(self, skill: Any, name: str, depth: int) -> str | None: """Why this agent's run at ``depth`` may not start the type ``name`` for ``skill``.""" delegations = self._delegations() types = delegations.types - config = types.get(name) - if config is None: - return UNKNOWN_TYPE policy = delegations.policy + config = delegations.config_for(name, based_on=self._agent) + if config is None and not (name == GENERAL_PURPOSE and policy.general_purpose): + return UNKNOWN_TYPE if name not in spawnable(list(types.values()), policy, SKILL_SOURCE): return NOT_FOR_SKILLS caller = types.get(self._agent) if ( - not may_spawn(depth, policy) + config is None # the general-purpose type, from an agent that may not start it + or self._general() + or not may_spawn(depth, policy) or (caller is not None and caller.inherit_context) or (depth > 0 and config.inherit_context) ): @@ -148,6 +165,8 @@ def refusal(self, skill: Any, depth: int) -> str | None: def check(self, skills: Sequence[Any]) -> None: """Warn, once per skill, of each that names an agent this agent's first run could not start, or that the app lets no skill start (the key is ignored).""" + if self._general(): + return for skill in skills: name = skill_agent(skill) if name is None or (self._agent, skill.name) in self._warned: @@ -187,6 +206,7 @@ async def start( brief=Brief(title=skill.name, objective=skill.instructions), started_by=skill_started_by(skill.name), caller=caller, call_id=call_id, state=state, history=history, counted=True, + based_on=self._agent if skill_agent(skill) == GENERAL_PURPOSE else None, )) if delegated.run is None: return delegated diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index f02a6827..50220861 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -257,6 +257,10 @@ class GoogleADKWorkflowManager(BaseWorkflowManager): #: runner of each, by (type, choice): what a run on a choice runs on. _variant_agents: "Mapping[tuple[str, str], LlmAgent]" = MappingProxyType({}) _variant_runners: "Mapping[tuple[str, str], Runner]" = MappingProxyType({}) + #: The built-in general-purpose type built for each type that may start it + #: (``Delegations.general_purpose``), and the runner of each, by that type. + _general_agents: "Mapping[str, LlmAgent]" = MappingProxyType({}) + _general_runners: "Mapping[str, Runner]" = MappingProxyType({}) def __init__( self, @@ -415,8 +419,8 @@ async def _agent_tool_names(self, agent: str) -> frozenset[str]: def _detach_backend(self) -> list[Closer]: """The runners and the agents, and the LLM logging plugin. - The conversation's runner and each sub-agent type's, and each of a - type's model choices': a runner closes + The conversation's runner and each sub-agent type's, each of a + type's model choices' and each general-purpose agent's: a runner closes its agent's toolsets (an MCP server stops with its toolset) and plugins; the session service it only flushes, so one a model switch keeps stays open. They close before the session service (the base @@ -428,6 +432,8 @@ def _detach_backend(self) -> list[Closer]: chosen_runners, self._variant_runners = ( self._variant_runners, MappingProxyType({}) ) + general_runners, self._general_runners = self._general_runners, MappingProxyType({}) + self._general_agents = MappingProxyType({}) self._variant_agents = MappingProxyType({}) self._agents = MappingProxyType({}) self._root_agent = None @@ -454,6 +460,15 @@ def _detach_backend(self) -> list[Closer]: ) for (name, choice), owned in chosen_runners.items() ), + *( + ( + f"runner general_purpose for {spawner}", + functools.partial( + self._aclose_owned, owned, f"runner general_purpose for {spawner}" + ), + ) + for spawner, owned in general_runners.items() + ), ] def _detach_store(self) -> list[Closer]: @@ -660,7 +675,10 @@ def _create_agents(self) -> Agent: itself. Every agent is kept by name (``_agents``): each sub-agent type gets a runner of its own (``_do_initialize``), and so does each of its model choices, an agent built once more on that model - (``_variant_agents``, by (type, choice)). + (``_variant_agents``, by (type, choice)), and the built-in + general-purpose type, one for each type that may start it + (``Delegations.general_purpose``: that type's tools, toolsets of its + own and model, no delegation tools; ``_general_agents``, by that type). Prompt factories are called under this manager's settings context (see ``AgentConfig.get_prompt``), so a prompt that reads settings sees the @@ -682,6 +700,7 @@ def _create_agents(self) -> Agent: agents: dict[str, LlmAgent] = {} variants: dict[tuple[str, str], LlmAgent] = {} + general: dict[str, LlmAgent] = {} # What this build's skill checks warned of: an agent built once more # for each model choice has skills of its own, and warns once. self._skill_warned: set[tuple[str, str]] = set() @@ -711,9 +730,15 @@ def _create_agents(self) -> Agent: type="coordinator" if delegates else "leaf", sub_agents=list(config.sub_agents), ) + # The general-purpose agent starts none (``delegates`` stays False). + for spawner, config in self._delegations.general_purpose.items(): + general[spawner] = self._build_agent( + config, service_map, root=False, model=self._general_model(spawner) + ) self._agents = agents self._variant_agents = variants + self._general_agents = general root_agent = agents[graph.root_name] logger.info("agents_created", root=root_agent.name, total=len(agents)) return root_agent @@ -1088,6 +1113,24 @@ async def _do_initialize(self) -> None: ) for key, agent in self._variant_agents.items() } + # And of each general-purpose agent: the chain on its spawner's model + # and numbers, under the name general_purpose. + self._general_runners = { + spawner: NoAfterTurnCompactionRunner( + app=App( + name=child_app(self.app_name), + root_agent=agent, + plugins=self._agent_plugin_chain( + agent, model=self._general_model(spawner), + budget=self._budgets.get(spawner), + ), + context_cache_config=build.cache, + events_compaction_config=None, + ), + session_service=self._session_service, + ) + for spawner, agent in self._general_agents.items() + } # A call's usage names its agent's own model and context numbers (the # default model stands in for an agent without one); only the agents # that reply write the reply, another's text is a sub-agent's work. @@ -1707,7 +1750,9 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: A run on a model choice (``run.model``) runs on the runner of its type built on that model (``_variant_runners``), its usage and context the - choice's (``_run_models``). + choice's (``_run_models``). A run of the built-in ``general_purpose`` + type (``run.based_on``) runs on the runner built for that type + (``_general_runners``), on that type's model. In the run's own task (``agents/delegate.py``): the child session (``child_app``, ``child_session_id``: the conversation's id and the @@ -1762,8 +1807,9 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: _, budgets = self._run_models(run) models, kinds = dict(build.models), self._agent_kinds() chosen = ( - self._choice_models[(run.ref.agent, run.model)] - if run.model is not None else None + self._general_model(run.based_on) if run.based_on is not None + else self._choice_models[(run.ref.agent, run.model)] if run.model is not None + else None ) if chosen is not None: models[run.ref.agent] = str(chosen.ref) @@ -1780,10 +1826,12 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: ) aborted = asyncio.Event() raised: BaseException | None = None - runner = ( - self._agent_runners[run.ref.agent] if chosen is None - else self._variant_runners[(run.ref.agent, run.model)] - ) + if run.based_on is not None: + runner = self._general_runners[run.based_on] + elif chosen is None: + runner = self._agent_runners[run.ref.agent] + else: + runner = self._variant_runners[(run.ref.agent, run.model)] key = (conversation, run.ref.run or "") if chosen is not None: self._chosen_runs[key] = chosen diff --git a/src/agentic_cli/workflow/agents/delegate.py b/src/agentic_cli/workflow/agents/delegate.py index 03741499..c0d3bde2 100644 --- a/src/agentic_cli/workflow/agents/delegate.py +++ b/src/agentic_cli/workflow/agents/delegate.py @@ -8,7 +8,8 @@ - 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``), then its tools against the type's own and its model + ``agents/spawn.py``, and the built-in ``general_purpose`` type made for the + caller's type when the policy enables it), then its tools against the type's own and its model against the type's choices (``brief.read_choices``): a brief that cannot start a run, tools that are not some of the type's own and a model that is none of its choices are the call's error result, and nothing else happens @@ -60,7 +61,10 @@ Every run of an instance has the tools and the model its first run's delegation gave it (``AgentRun.tools``, ``AgentRun.model``, kept in its ``InstanceRecord``); a follow-up to an instance whose type no longer has -them is refused (``CHOICE_GONE_ERROR``). +them is refused (``CHOICE_GONE_ERROR``). A ``general_purpose`` instance +also keeps the type it was made for (``AgentRun.based_on``, +``InstanceRecord.based_on``), whose tools and model it has; one whose type no +longer makes it is refused as a type that is gone (``TYPE_GONE_ERROR``). Each run works under its ``RunControl`` (``agents/control.py``, ``AgentRun.control``): its limits (its type's over the policy's), the time @@ -180,9 +184,13 @@ from agentic_cli.workflow.agents.slots import NEW, Slot, SlotPool from agentic_cli.workflow.agents.spawn import ( AGENT_SOURCE, + GENERAL_PURPOSE, USER_SOURCE, depth_sentence_applies, + general_purpose_config, + general_purpose_spawners, may_spawn, + root_type, spawnable, ) from agentic_cli.workflow.events import WorkflowEvent @@ -371,6 +379,11 @@ class StartRequest: later run of the instance keeps them. model: One of the type's ``model_choices``, as written, to run it on; None: the type's own model. Every later run keeps it. + based_on: For the built-in ``general_purpose`` type, the type it is + made for (``Delegations.config_for``): the caller's type for a + ``task`` call or a skill, the root for the user's start; its + tools and model are the run's. None (or any value, for another + type): none. """ agent_type: str @@ -384,6 +397,7 @@ class StartRequest: counted: bool = True tools: frozenset[str] | None = None model: str | None = None + based_on: str | None = None @dataclass(frozen=True) @@ -410,6 +424,9 @@ class AgentRun: model: The type's model choice it runs on, as ``model_choices`` writes it; the backend runs the type's agent built on it. None: the type's own model. + based_on: A run of the built-in ``general_purpose`` type: the type it + is made for (``config`` is ``general_purpose_config`` of it), + whose general-purpose agent the backend runs; None for any other. """ ref: RunRef @@ -422,6 +439,7 @@ class AgentRun: follow_up: bool = False tools: frozenset[str] | None = None model: str | None = None + based_on: str | None = None def __post_init__(self) -> None: if self.control is None: @@ -627,6 +645,8 @@ class Delegations: types: Every agent type, by name: a caller may start its own sub-agents (``AgentConfig.sub_agents``) and, as the policy allows, the types agents may start at run time (``offered``). + The built-in ``general_purpose`` type is no entry: it is made + for each of these types that may start it (``general_purpose``). 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 @@ -668,6 +688,12 @@ def __init__( self._stored = stored self._open_calls = open_calls self._tool_names = tool_names + # The general-purpose type made for each type that may start it, by + # the type's name: the one place those configs are made. + self._general: Mapping[str, AgentConfig] = MappingProxyType({ + name: general_purpose_config(self._types[name]) + for name in general_purpose_spawners(list(self._types.values()), policy) + }) # Each conversation's turn its stored instances were last read in # (its span, ``current_turn_scope``: held here, so no later turn's # can be the same object), and each conversation's lock, which a @@ -698,6 +724,31 @@ def types(self) -> Mapping[str, AgentConfig]: """Every agent type, by name, in config order (read-only): what ``start`` starts.""" return MappingProxyType(self._types) + @property + def general_purpose(self) -> Mapping[str, AgentConfig]: + """The general-purpose type made for each type that may start it, by that type's name. + + Empty unless the policy enables it (``general_purpose_spawners``); + the backends build their agents of it from this (read-only). + """ + return self._general + + def config_for(self, agent_type: str, *, based_on: str | None = None) -> AgentConfig | None: + """The config a run of ``agent_type`` has, else None. + + The app's config of that name; for the built-in ``general_purpose`` + type (when the policy enables it), the one made for ``based_on``, the + type that starts it: None for no ``based_on``, or one that may not + start it here. + """ + if self._is_general(agent_type): + return self._general.get(based_on) if based_on is not None else None + return self._types.get(agent_type) + + def _is_general(self, agent_type: str) -> bool: + """Whether ``agent_type`` is the built-in general-purpose type, and the policy enables it.""" + return self.policy.general_purpose and agent_type == GENERAL_PURPOSE + def sub_agents(self, agent: str) -> dict[str, AgentConfig]: """The types ``agent`` may start, by name, in its ``sub_agents``' order.""" caller = self._types.get(agent) @@ -719,7 +770,9 @@ def offered(self, caller_agent: str, depth: int) -> dict[str, AgentConfig]: 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] + config = self.config_for(name, based_on=caller_agent) + if config is None: + continue if name not in offered and (depth == 0 or not config.inherit_context): offered[name] = config return offered @@ -756,8 +809,9 @@ async def delegate(self, request: DelegationRequest) -> Delegated: config, brief = read_brief( request.arguments, self.offered(request.caller_agent, depth) ) + based_on = request.caller_agent if self._is_general(config.name) else None own = ( - await self._own_tools(config) + await self._own_tools(config, based_on=based_on) if request.arguments.get("tools") is not None else () ) tools, model = read_choices(request.arguments, config, own) @@ -766,7 +820,7 @@ async def delegate(self, request: DelegationRequest) -> Delegated: 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, tools=tools, model=model, + history=request.history, tools=tools, model=model, based_on=based_on, )) async def start(self, request: StartRequest) -> Delegated: @@ -782,9 +836,14 @@ async def start(self, request: StartRequest) -> Delegated: has stopped, and goes on. Raises: - KeyError: ``request.agent_type`` is not one of the manager's types. + KeyError: ``request.agent_type`` is not one of the manager's types + (the built-in ``general_purpose`` type: with no + ``request.based_on`` that may start it). """ - config = self._types[request.agent_type] + based_on = request.based_on if self._is_general(request.agent_type) else None + config = self.config_for(request.agent_type, based_on=based_on) + if config is None: + raise KeyError(request.agent_type) conversation = ( request.conversation if request.conversation is not None else get_active_turn() ) @@ -802,14 +861,14 @@ async def start(self, request: StartRequest) -> Delegated: brief=brief.fields(), started_by=request.started_by, mode=BLOCKING, inherit_context=config.inherit_context, continuable=config.continuable, tools=sorted(request.tools) if request.tools is not None else None, - model=request.model, + model=request.model, based_on=based_on, )) return await self._run( ref, config, conversation, request.call_id, message=task_message(brief, inherit=config.inherit_context), state=request.state, history=request.history if config.inherit_context else None, - tools=request.tools, model=request.model, + tools=request.tools, model=request.model, based_on=based_on, ) def startable_by_user(self) -> tuple[str, ...]: @@ -817,9 +876,17 @@ def startable_by_user(self) -> tuple[str, ...]: ``spawnable`` for ``"user"``: the policy's ``spawn_sources`` and the type's ``spawnable_by`` both name the user. An inheriting one too: its - parent is the root, whose conversation it reads. + parent is the root, whose conversation it reads. The built-in + ``general_purpose`` type only where it is made for the root. """ - return spawnable(list(self._types.values()), self.policy, USER_SOURCE) + names = spawnable(list(self._types.values()), self.policy, USER_SOURCE) + # The general-purpose type is made for the root: an app with no + # configured types (a native ADK app) has none to make it for. + return tuple( + name for name in names + if not self._is_general(name) + or self.config_for(name, based_on=root_type(self._types.values())) is not None + ) def user_start_refused(self, agent_type: str, objective: str) -> str | None: """Why the user may not start ``agent_type`` on ``objective``, else None. @@ -872,6 +939,8 @@ async def start_by_user( agent_type=agent_type, brief=Brief(title=run_title(objective), objective=objective), started_by=USER, conversation=conversation, state=dict(state or {}), history=history, counted=False, + # The user's spawner is the root. + based_on=root_type(self._types.values()) if self._is_general(agent_type) else None, )) async def follow_up( @@ -918,7 +987,9 @@ async def follow_up( return Delegated(result={"success": False, "error": error}, state={}, run=None) instance = self._runs.instance(conversation, request.instance) assert instance is not None - config = self._types[instance.agent] + based_on = instance.based_on if self._is_general(instance.agent) else None + config = self.config_for(instance.agent, based_on=based_on) + assert config is not None # _follow_up_refused answered otherwise if request.started_by != USER: if _reserved is None: refused = self._past_runs_per_turn(instance.agent) @@ -940,7 +1011,7 @@ async def follow_up( ref, config, conversation, request.call_id, message=request.message, state=request.state, history=None, follow_up=True, tools=frozenset(instance.tools) if instance.tools is not None else None, - model=instance.model, + model=instance.model, based_on=based_on, ) def close(self, conversation: SessionRef | None, instance: str, *, reason: str) -> list[str]: @@ -1428,9 +1499,11 @@ def _follow_up_refused( return STOPPED_ERROR.format(instance=found.instance) if found.status == INSTANCE_RUNNING and not running_ok: return RUNNING_ERROR.format(instance=found.instance) - if found.agent not in self._types: + config = self.config_for( + found.agent, based_on=found.based_on if self._is_general(found.agent) else None + ) + if config is None: return TYPE_GONE_ERROR.format(instance=found.instance, agent=found.agent) - config = self._types[found.agent] what = None if found.model is not None and found.model not in config.model_choices: what = f"the model {found.model}" @@ -1444,10 +1517,15 @@ def _follow_up_refused( ) return None - async def _own_tools(self, config: AgentConfig) -> Collection[str]: + async def _own_tools( + self, config: AgentConfig, *, based_on: str | None = None + ) -> Collection[str]: """The names of ``config``'s own tools: its backend's, else its configured tools'. + A general-purpose type's are its spawner's (``based_on``): the same + names, which the backend lists for that type. + The one place the backend's hook is asked. Raises: @@ -1457,7 +1535,7 @@ async def _own_tools(self, config: AgentConfig) -> Collection[str]: if self._tool_names is None: return configured_tool_names(config.tools) try: - return await self._tool_names(config.name) + return await self._tool_names(based_on if based_on is not None else config.name) except ToolsUnlistedError as error: raise BriefError( TOOLS_UNLISTED_ERROR.format(agent_type=config.name, error=error.reason) @@ -1479,10 +1557,11 @@ async def _instance_tools( record = self._runs.instance(conversation, instance) if record is None or record.tools is None: return None - config = self._types.get(record.agent) + based_on = record.based_on if self._is_general(record.agent) else None + config = self.config_for(record.agent, based_on=based_on) if config is None: return None - return frozenset(await self._own_tools(config)) + return frozenset(await self._own_tools(config, based_on=based_on)) async def _run( self, @@ -1497,12 +1576,13 @@ async def _run( follow_up: bool = False, tools: frozenset[str] | None = None, model: str | None = None, + based_on: str | None = None, ) -> Delegated: """Run ``ref``'s run, started and reported already, to its end; its envelope. What a first run and a follow-up share: the run's control, its task, the caller's slot lent while it waits. ``tools`` and ``model`` are - the instance's. + the instance's, ``based_on`` a general-purpose one's. """ control = RunControl( ref, self._limits(config), side_tokens=self._side_tokens(conversation, ref), @@ -1515,7 +1595,7 @@ async def _run( self._in_run( ref, config, conversation, call_id, control, message=message, state=state, history=history, follow_up=follow_up, - model=model, + model=model, based_on=based_on, ), name=f"agent run {ref.run}", ) @@ -1702,6 +1782,7 @@ async def _in_run( history: Callable[[], Any] | None, follow_up: bool, model: str | None = None, + based_on: str | None = None, ) -> RunAnswer: """The run, in its own task: the active run, and no tool call active. @@ -1727,6 +1808,7 @@ async def _in_run( follow_up=follow_up, tools=control.tools, model=model, + based_on=based_on, ) pool = self.slots(conversation) queued = pool.free == 0 diff --git a/src/agentic_cli/workflow/agents/policy.py b/src/agentic_cli/workflow/agents/policy.py index f3e5ded2..2763d952 100644 --- a/src/agentic_cli/workflow/agents/policy.py +++ b/src/agentic_cli/workflow/agents/policy.py @@ -122,6 +122,12 @@ class SubAgentPolicy: 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. + general_purpose: Whether the built-in ``general_purpose`` type is + one of the types started at run time (``agents/spawn.py``): its + spawner's own tools but the ones that start agents, its + spawner's model and the framework's system prompt, startable by + every source ``spawn_sources`` enables. False (the default): no + such type. True needs a source. """ max_active: int = 4 @@ -131,6 +137,7 @@ class SubAgentPolicy: follow_ups: bool = False spawn_sources: frozenset[str] = frozenset() max_spawn_depth: int = 1 + general_purpose: bool = False def __post_init__(self) -> None: _check_count("SubAgentPolicy", "max_active", self.max_active, optional=False) @@ -146,6 +153,16 @@ def __post_init__(self) -> None: _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) + if not isinstance(self.general_purpose, bool): + raise ValueError( + f"SubAgentPolicy.general_purpose must be True or False, not " + f"{self.general_purpose!r}." + ) + if self.general_purpose and not self.spawn_sources: + raise ValueError( + "SubAgentPolicy.general_purpose needs spawn_sources: with none, nothing could " + "start it." + ) def _sources(value: object) -> frozenset[str]: diff --git a/src/agentic_cli/workflow/agents/runs.py b/src/agentic_cli/workflow/agents/runs.py index 2a60e612..5863d648 100644 --- a/src/agentic_cli/workflow/agents/runs.py +++ b/src/agentic_cli/workflow/agents/runs.py @@ -205,6 +205,9 @@ class InstanceRecord: model: The model choice its first run's delegation ran it on, as the type writes it (``task``'s ``model``); None for the type's own model. Every run of it keeps it. + based_on: For an instance of the built-in ``general_purpose`` type, + the type that started it, whose tools and model it has; None for + any other. Every run of it keeps it. """ instance: str @@ -218,6 +221,7 @@ class InstanceRecord: continuable: bool = True tools: tuple[str, ...] | None = None model: str | None = None + based_on: str | None = None def own_plan_and_tasks(state: Mapping[str, Any]) -> tuple[str, list[dict[str, Any]]]: @@ -630,6 +634,7 @@ def _instance_of( continuable=bool(metadata.get("continuable", True)), tools=tuple(tools) if tools is not None else None, model=metadata.get("model"), + based_on=metadata.get("based_on"), ) return record @@ -748,9 +753,10 @@ def _instance_from(value: Any) -> InstanceRecord: runs=list(runs), continuable=_get(value, "continuable", bool), # Written since records first kept them: missing in older ones (all - # of the type's tools, its own model). + # of the type's tools, its own model, no general-purpose spawner). tools=_tools(value.get("tools")), model=_get_new(value, "model", str, _NONE), + based_on=_get_new(value, "based_on", str, _NONE), ) diff --git a/src/agentic_cli/workflow/agents/spawn.py b/src/agentic_cli/workflow/agents/spawn.py index 73a7776c..4a3200bc 100644 --- a/src/agentic_cli/workflow/agents/spawn.py +++ b/src/agentic_cli/workflow/agents/spawn.py @@ -7,12 +7,19 @@ (``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. +sub-agents, or it may start types at run time. + +With ``SubAgentPolicy.general_purpose`` every enabled source may also start +the built-in ``GENERAL_PURPOSE`` type: no config of the app's, but one made +for its spawner type (``general_purpose_config``: the spawner's own tools, +MCP servers, skills and model, the framework's prompt), which starts no +agent itself. Each backend builds one for every type that may start it +(``general_purpose_spawners``). Imports no backend. """ from __future__ import annotations -from collections.abc import Collection, Mapping, Sequence +from collections.abc import Collection, Iterable, Mapping, Sequence from typing import TYPE_CHECKING from agentic_cli.workflow.agents.policy import SPAWN_SOURCES @@ -23,6 +30,21 @@ AGENT_SOURCE, SKILL_SOURCE, USER_SOURCE = SPAWN_SOURCES +#: The built-in general-purpose type's name, its line in ``task``'s list of +#: types and its system prompt. +GENERAL_PURPOSE = "general_purpose" +GENERAL_PURPOSE_DESCRIPTION = ( + "A general-purpose agent with your own tools (but not the ones that start agents) and " + "your model, for a self-contained task no other agent fits." +) +GENERAL_PURPOSE_PROMPT = ( + "You are a general-purpose agent, started by another agent for one task. The task " + "message says what to do and what to return. Do it with the tools you have, then " + "answer with the result itself, in the form the task asks for: the agent that " + "started you reads only your final answer. If the task cannot be done, say why, " + "and give what you found." +) + def spawnable( configs: Sequence[AgentConfig], policy: SubAgentPolicy, source: str @@ -30,15 +52,19 @@ def spawnable( """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``. + its ``spawnable_by``. The built-in ``GENERAL_PURPOSE`` type comes last + when the policy enables it. """ if source not in policy.spawn_sources: return () - return tuple( + types = tuple( config.name for config in configs if config.spawnable_by is not None and source in config.spawnable_by ) + if policy.general_purpose and GENERAL_PURPOSE not in types: + return (*types, GENERAL_PURPOSE) + return types def may_spawn(depth: int, policy: SubAgentPolicy) -> bool: @@ -58,8 +84,10 @@ def can_have_children( 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). + or more). The built-in general-purpose type starts none. """ + if policy.general_purpose and config.name == GENERAL_PURPOSE: + return False if config.sub_agents: return True return ( @@ -87,3 +115,64 @@ def depth_sentence_applies( and not may_spawn(depth + 1, policy) and not any(config.sub_agents for config in offered.values()) ) + + +def root_type(configs: Iterable[AgentConfig]) -> str | None: + """The root agent's name: the first config no other delegates to that is no free type.""" + configs = list(configs) + delegated = {sub for config in configs for sub in config.sub_agents} + for config in configs: + if config.name not in delegated and config.spawnable_by is None: + return config.name + return None + + +def general_purpose_spawners( + configs: Sequence[AgentConfig], policy: SubAgentPolicy +) -> tuple[str, ...]: + """The types a general-purpose agent is built for, in config order. + + None unless the policy enables the type. The root always (every source + starts from it: the user's start is the root's child). Below the root, + when ``max_spawn_depth`` is 2 or more, each type that does not inherit + and may start one: by ``task`` when agents may start types, or by a skill + it loads when it has skills and skills may. + """ + if not policy.general_purpose: + return () + root = root_type(configs) + deeper = policy.max_spawn_depth >= 2 + sources = policy.spawn_sources + return tuple( + config.name + for config in configs + if config.name == root + or ( + deeper + and not config.inherit_context + and (AGENT_SOURCE in sources or (SKILL_SOURCE in sources and config.skills)) + ) + ) + + +def general_purpose_config(spawner: AgentConfig) -> AgentConfig: + """The built-in general-purpose type made for ``spawner``. + + The spawner's own tools, MCP servers, skills, model and model settings + (not a model choice), the framework's prompt and description, the plan's + tools, a fresh context; no sub-agents and no model choices, so it starts + no agent. Its lists are its own. + """ + from agentic_cli.workflow.config import AgentConfig + + return AgentConfig( + name=GENERAL_PURPOSE, + prompt=GENERAL_PURPOSE_PROMPT, + description=GENERAL_PURPOSE_DESCRIPTION, + tools=list(spawner.tools), + mcp_servers=list(spawner.mcp_servers), + skills=list(spawner.skills), + model=spawner.model, + model_settings=spawner.model_settings, + include_state_tools=True, + ) diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index f87fb9d2..f741d8ab 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -73,7 +73,7 @@ RUN_STARTED, AgentRuns, ) -from agentic_cli.workflow.agents.spawn import can_have_children +from agentic_cli.workflow.agents.spawn import GENERAL_PURPOSE, can_have_children from agentic_cli.workflow.usage import ( PURPOSE_MEMORY_EXTRACTION, PURPOSE_SIDE_CALL, @@ -1402,7 +1402,10 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: its type's tools (``run.control.tools``) is offered only those and the tools every run keeps (``KEPT_TOOLS``), and a call of another is answered as one of a tool the agent does not have - (``unknown_tool_result``). + (``unknown_tool_result``). A run of the built-in ``general_purpose`` + type (``run.based_on``: the type it is made for) runs on the + general-purpose agent built for that type (``Delegations.general_purpose``), + on that type's own model (``_general_model``). Raises: NotImplementedError: This backend runs no sub-agent. @@ -1418,20 +1421,37 @@ def _run_models( Those of the manager's, except that a run on a model choice (``run.model``) has its type's entries the choice's: its backend's event processing, usage and overflow messages then name and count - the model the run went to, under the type's name. + the model the run went to, under the type's name. A run of the + built-in ``general_purpose`` type (``run.based_on``) has its entry + the model and numbers of the type it is made for. Raises: KeyError: ``run.model`` is not one of its type's model choices. """ - if run.model is None: + if run.model is None and run.based_on is None: return self._resolved_models, self._budgets - key = (run.ref.agent, run.model) - models = {**self._resolved_models, run.ref.agent: self._choice_models[key]} + models = dict(self._resolved_models) budgets = dict(self._budgets) - if key in self._choice_budgets: - budgets[run.ref.agent] = self._choice_budgets[key] + if run.based_on is not None: + models[run.ref.agent] = self._general_model(run.based_on) + if run.based_on in self._budgets: + budgets[run.ref.agent] = self._budgets[run.based_on] + if run.model is not None: + key = (run.ref.agent, run.model) + models[run.ref.agent] = self._choice_models[key] + if key in self._choice_budgets: + budgets[run.ref.agent] = self._choice_budgets[key] return models, budgets + def _general_model(self, spawner: str) -> "ResolvedModel": + """The model of the general-purpose agent made for the type ``spawner``. + + ``spawner``'s own resolved model (never a run's model choice), named + for ``general_purpose``: a backend keys an agent's own reasoning and + its usage by that name. + """ + return dataclasses.replace(self._resolved_models[spawner], agent=GENERAL_PURPOSE) + async def _agent_tool_names(self, agent: str) -> frozenset[str]: """The names a ``task`` call's ``tools`` may give for ``agent`` (a backend hook). diff --git a/src/agentic_cli/workflow/config.py b/src/agentic_cli/workflow/config.py index ba840526..2cd479ff 100644 --- a/src/agentic_cli/workflow/config.py +++ b/src/agentic_cli/workflow/config.py @@ -13,6 +13,7 @@ SubAgentPolicy, as_policy, ) +from agentic_cli.workflow.agents.spawn import GENERAL_PURPOSE if TYPE_CHECKING: from agentic_cli.config import BaseSettings @@ -235,7 +236,8 @@ def validate_agent_graph( Checks, in order, so the first failure is the most fundamental: 1. at least one agent; - 2. no duplicate agent names; + 2. no duplicate agent names, and, with the policy's ``general_purpose``, + none named ``general_purpose``, the built-in type's name; 3. every ``sub_agents`` entry resolves to a configured agent; 4. no agent lists itself as a sub-agent; 5. no delegation cycle; @@ -267,7 +269,7 @@ def validate_agent_graph( 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. + the free types' warning and the built-in type's name read it. Returns: The validated graph plus a build order in which every agent comes after @@ -292,6 +294,11 @@ def validate_agent_graph( f"Duplicate agent name(s): {', '.join(sorted(set(duplicates)))}. " "Agent names must be unique." ) + if policy.general_purpose and GENERAL_PURPOSE in config_map: + raise AgentGraphError( + f"An agent named {GENERAL_PURPOSE!r} clashes with the built-in {GENERAL_PURPOSE} " + "type, which this app's SubAgentPolicy enables." + ) missing = [ f"{config.name} -> {sub}" diff --git a/src/agentic_cli/workflow/deepagents/agent_builder.py b/src/agentic_cli/workflow/deepagents/agent_builder.py index 59f1eee5..8fae41e8 100644 --- a/src/agentic_cli/workflow/deepagents/agent_builder.py +++ b/src/agentic_cli/workflow/deepagents/agent_builder.py @@ -11,12 +11,15 @@ 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: +answers with the result envelope. Only the app's agent types are offered (and +the framework's own ``general_purpose`` type, when the app's policy enables it): +there is no automatic general-purpose sub-agent of Deep Agents', and none of its +file tools. ``graphs``, when given, is filled with every agent's graph by name: what the manager runs a sub-agent on. A sub-agent type's model choices are built once more each (``Variant``, ``variants=``): the type's graph on -another model, filled into ``variant_graphs`` by key. +another model, filled into ``variant_graphs`` by key. The general-purpose agent +made for a type (``spawn.general_purpose_config``) is a ``Variant`` too, with +tools and a prompt of its own (``general``, filling ``general_graphs``). Every stack, outermost first: ``InterruptedCallsMiddleware`` (answers a tool call a cancelled turn or a crash left without a result, before each run, as @@ -108,20 +111,26 @@ class Variant: """One more graph of a sub-agent type, on another model (a model choice's). - Built as the type's own is, with its tools and prompt, but its model - side from ``resolved`` and its summarization from ``budget``. + Built as the type's own is, with its tools and prompt (or its own: the + general-purpose agent's), but its model side from ``resolved`` and its + summarization from ``budget``. Attributes: config: The type. chat_model: The chat model of the choice. resolved: The choice's resolved model (None: a unit test's, with no model side). budget: The choice's context numbers; None: computed from ``resolved``. + tools: Its tools; None: the type's (``build_agent_tree``'s ``tools``). A + type in no ``configs`` (the general-purpose one) has its own. + prompt: Its system prompt; None: the type's. """ config: AgentConfig chat_model: "BaseChatModel" resolved: "ResolvedModel | None" budget: ContextBudget | None = None + tools: "list[BaseTool] | None" = None + prompt: str | None = None def build_agent_tree( @@ -147,6 +156,8 @@ def build_agent_tree( root: str | None = None, variants: "Mapping[Hashable, Variant] | None" = None, variant_graphs: "dict[Hashable, CompiledStateGraph] | None" = None, + general: "Mapping[str, Variant] | None" = None, + general_graphs: "dict[str, CompiledStateGraph] | None" = None, ) -> "CompiledStateGraph": """Build every agent, each on its own, and return the root. @@ -214,6 +225,13 @@ def build_agent_tree( model, resolved model and budget, with the type's tools and prompt, and filled into ``variant_graphs``. variant_graphs: Filled, when given, with each variant's graph, by key. + general: The built-in general-purpose type made for each type that + may start it (``Delegations.general_purpose``), by that type's + name: each is built as a variant is, with the tools and prompt + of its own, and filled into ``general_graphs``. It starts no + agent (``can_have_children``), so it gets no ``task``. + general_graphs: Filled, when given, with each general-purpose + graph, by its spawner's name. Raises: AgentGraphError: A delegating agent's own tools include one named @@ -245,17 +263,27 @@ def build(name: str) -> "CompiledStateGraph": built = {name: build(name) for name in config_map} if graphs is not None: graphs.update(built) - for key, variant in (variants or {}).items(): + + def build_variant(variant: Variant) -> "CompiledStateGraph": name = variant.config.name - graph = build_agent( + return build_agent( variant.config, root=False, configs=configs, chat_model=variant.chat_model, - resolved=variant.resolved, tools=tools.get(name, []), prompt=prompts[name], + resolved=variant.resolved, + tools=variant.tools if variant.tools is not None else tools.get(name, []), + prompt=variant.prompt if variant.prompt is not None else prompts[name], settings=settings, checkpointer=checkpointer, bound=bound, budget=variant.budget, open_calls=open_calls, marks=marks, delegations=delegations, ) + + for key, variant in (variants or {}).items(): + graph = build_variant(variant) if variant_graphs is not None: variant_graphs[key] = graph + for spawner, variant in (general or {}).items(): + graph = build_variant(variant) + if general_graphs is not None: + general_graphs[spawner] = graph return built[root] diff --git a/src/agentic_cli/workflow/deepagents/manager.py b/src/agentic_cli/workflow/deepagents/manager.py index 6721e771..b2add4dd 100644 --- a/src/agentic_cli/workflow/deepagents/manager.py +++ b/src/agentic_cli/workflow/deepagents/manager.py @@ -115,6 +115,7 @@ from langgraph.checkpoint.base import BaseCheckpointSaver from langgraph.graph.state import CompiledStateGraph + from agentic_cli.models import ResolvedModel from agentic_cli.workflow.agents.policy import SubAgentPolicy from agentic_cli.workflow.sessions import SessionInfo, SessionRef @@ -197,6 +198,9 @@ def __init__( # Each sub-agent type's graph on each of its model choices, by (type, # choice): what a run on a choice runs on. self._variant_graphs: dict[tuple[str, str], CompiledStateGraph] = {} + # The built-in general-purpose type's graph for each type that may start + # it, by that type's name: what a run of it runs on. + self._general_graphs: dict[str, CompiledStateGraph] = {} # Each agent's own tools' names as its model sees them (its tools, skill # tools and MCP tools), the framework's state and delegation tools left # out: what a task call's `tools` may name. @@ -278,17 +282,10 @@ async def _do_initialize(self) -> None: } tools: dict[str, list[BaseTool]] = {} for config in self._agent_configs: - own = to_langchain_tools(self._build_tools(config, service_map)) - # Skill tools before MCP tools: an MCP tool named like one is skipped. - if config.skills: - skill_tools, instruction = self._skill_tools(config, own) - own = [*own, *skill_tools] - prompts[config.name] = _with_instruction( - prompts[config.name], instruction - ) - if config.mcp_servers: - own = await self._with_mcp_tools(config, own) - tools[config.name] = own + tools[config.name], prompts[config.name] = await self._agent_tools( + config, service_map, prompts[config.name], + model=self._resolved_models[config.name], + ) self._own_tool_names = { name: frozenset(t.name for t in own if t.name not in KEPT_TOOLS) for name, own in tools.items() @@ -314,6 +311,31 @@ async def _do_initialize(self) -> None: if config.name != root for choice in config.model_choices } + # The general-purpose agent of each type that may start one: its + # spawner's tools and MCP servers (sessions of its own), its prompt, + # its spawner's model and numbers. + general_graphs: dict[str, CompiledStateGraph] = {} + general: dict[str, Variant] = {} + for spawner, config in self._delegations.general_purpose.items(): + model = self._general_model(spawner) + # Deep Agents opens MCP sessions at initialization (ADK connects at + # first use), so each general-purpose agent starts its spawner's + # servers once more here: one that never answers is waited for once + # more per spawner, and one that cannot start is a notice for it too. + own, prompt = await self._agent_tools( + config, service_map, config.get_prompt(self._settings), model=model, + spawner=spawner, + ) + general[spawner] = Variant( + config=config, + chat_model=build_chat_model( + model, settings=self._settings, app_name=self.app_name + ), + resolved=model, + budget=self._budgets.get(spawner), + tools=own, + prompt=prompt, + ) self._root = build_agent_tree( self._agent_configs, chat_models={ @@ -345,9 +367,12 @@ async def _do_initialize(self) -> None: root=root, variants=variants, variant_graphs=variant_graphs, + general=general, + general_graphs=general_graphs, ) self._agent_graphs = graphs self._variant_graphs = variant_graphs + self._general_graphs = general_graphs self._root_summarization = summarizers.get(root) logger.info( @@ -388,8 +413,39 @@ async def _open_session_store(self) -> None: self._checkpointer, self._checkpointer_cm = saver, connections self._sessions = CheckpointSessions(saver, store, backfill=kind != "memory") + async def _agent_tools( + self, + config: AgentConfig, + service_map: dict[str, Callable], + prompt: str, + *, + model: "ResolvedModel", + spawner: str | None = None, + ) -> tuple[list[BaseTool], str]: + """``config``'s tools as its model sees them, and its prompt with its skills' instruction. + + Its registered tools, then its skill tools (before the MCP tools: an + MCP tool named like one is skipped), then its MCP servers' tools, + opened now on sessions of this agent's own. ``model`` is the model it + runs on (the provider its skill tools are worded for): the + general-purpose agent's is its spawner's, and ``spawner`` names that + type for the notices about its MCP servers. + """ + own = to_langchain_tools(self._build_tools(config, service_map)) + if config.skills: + skill_tools, instruction = self._skill_tools(config, own, model=model) + own = [*own, *skill_tools] + prompt = _with_instruction(prompt, instruction) + if config.mcp_servers: + own = await self._with_mcp_tools(config, own, spawner=spawner) + return own, prompt + def _skill_tools( - self, config: AgentConfig, tools: list[BaseTool] + self, + config: AgentConfig, + tools: list[BaseTool], + *, + model: "ResolvedModel | None" = None, ) -> tuple[list[BaseTool], str]: """``config``'s skills as skill tools, and the instruction its prompt gets. @@ -413,7 +469,7 @@ def _skill_tools( skills = SkillStore(self._settings.skills_dirs or []).resolve(config.skills) skill_tools, instruction = make_skill_tools( skills, - provider=self._resolved_models[config.name].record.kind, + provider=(model if model is not None else self._resolved_models[config.name]).record.kind, # The base validated the graph before this build, so the root is set. agents=SkillAgents( config.name, lambda: self._delegations, @@ -426,14 +482,19 @@ def _skill_tools( return skill_tools, instruction async def _with_mcp_tools( - self, config: AgentConfig, tools: list[BaseTool] + self, config: AgentConfig, tools: list[BaseTool], *, spawner: str | None = None ) -> list[BaseTool]: """``tools`` and the tools of ``config``'s MCP servers, opened now. A server that cannot start, and a tool whose name is taken, become - notices for the next turn; the agent runs without them. + notices for the next turn; the agent runs without them. A + general-purpose agent's notices name its ``spawner`` too + (``metadata["spawner"]``), since every type that may start one has an + agent of that name. """ - loaded, unavailable = await self._mcp.start(config.name, config.mcp_servers) + loaded, unavailable = await self._mcp.start( + config.name, config.mcp_servers, spawner=spawner + ) kept, skipped = without_clashes(config.name, tools, loaded) for message, code in [ *((message, "mcp_unavailable") for message in unavailable), @@ -441,6 +502,8 @@ async def _with_mcp_tools( ]: notice = WorkflowEvent.error(message, error_code=code, recoverable=True) notice.metadata["agent"] = config.name + if spawner is not None: + notice.metadata["spawner"] = spawner self._pending_notices.append(notice) return [*tools, *kept] @@ -466,6 +529,7 @@ def _detach_backend(self) -> list[Closer]: self._root = None self._agent_graphs = {} self._variant_graphs = {} + self._general_graphs = {} self._root_summarization = None self._own_tool_names = {} self._pending_notices = [] @@ -832,7 +896,9 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: A run on a model choice (``run.model``) runs on its type's graph built on that model (``_variant_graphs``), its usage and context the - choice's (``_run_models``). + choice's (``_run_models``). A run of the built-in ``general_purpose`` + type (``run.based_on``) runs on the graph built for that type + (``_general_graphs``), on that type's model. In the run's own task (``agents/delegate.py``), apart from its caller's stream: the graph is streamed with the run's own config, @@ -884,11 +950,14 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: conversation = run.conversation if conversation is None: raise RuntimeError("A sub-agent run runs in a conversation's turn.") - # A run on a model choice runs on its type's graph built on that model. - graph = ( - self._agent_graphs[run.ref.agent] if run.model is None - else self._variant_graphs[(run.ref.agent, run.model)] - ) + # A run on a model choice runs on its type's graph built on that model; + # a general-purpose run on the graph built for the type it is made for. + if run.based_on is not None: + graph = self._general_graphs[run.based_on] + elif run.model is None: + graph = self._agent_graphs[run.ref.agent] + else: + graph = self._variant_graphs[(run.ref.agent, run.model)] models, budgets = self._run_models(run) task_id = f"agentic-cli-task-{uuid.uuid4().hex}" # A first run's message is its instance's brief, which its summaries keep. diff --git a/src/agentic_cli/workflow/deepagents/mcp_tools.py b/src/agentic_cli/workflow/deepagents/mcp_tools.py index 7c9f7164..b6112db5 100644 --- a/src/agentic_cli/workflow/deepagents/mcp_tools.py +++ b/src/agentic_cli/workflow/deepagents/mcp_tools.py @@ -91,19 +91,22 @@ def __init__(self) -> None: self._identities = ToolRegistry() async def start( - self, agent: str, servers: Sequence[MCPServerConfig] + self, agent: str, servers: Sequence[MCPServerConfig], *, spawner: str | None = None ) -> tuple[list[BaseTool], list[str]]: """Open ``agent``'s servers, at once, and load their tools. Args: agent: The agent the sessions are for. servers: Its servers, in order. + spawner: For a general-purpose agent, the type it is made for, + which its notices and log lines name too. Returns: The tools, server by server, filtered, prefixed and bound; and a notice for each server that could not start (none started within its ``timeout``, or ``STARTUP_TIMEOUT``). """ + who = f"'{agent}' (for '{spawner}')" if spawner is not None else f"'{agent}'" owners = [self._open(agent, server) for server in servers] outcomes = await asyncio.gather( *(self._started(owner, server) for owner, server in zip(owners, servers)) @@ -115,11 +118,12 @@ async def start( logger.warning( "mcp_server_unavailable", agent=agent, + spawner=spawner, server=server.name, reason=outcome, ) notices.append( - f"MCP server '{server.name}' is unavailable, so agent '{agent}' " + f"MCP server '{server.name}' is unavailable, so agent {who} " f"runs without its tools: {outcome}" ) continue diff --git a/src/agentic_cli/workflow/events.py b/src/agentic_cli/workflow/events.py index be1f97dc..c79ee42d 100644 --- a/src/agentic_cli/workflow/events.py +++ b/src/agentic_cli/workflow/events.py @@ -217,6 +217,7 @@ def agent_run( continuable: bool | None = None, tools: Sequence[str] | None = None, model: str | None = None, + based_on: str | None = None, ) -> "WorkflowEvent": """Create a sub-agent run's event: its start, or how it ended (``AGENT_RUN``). @@ -224,7 +225,8 @@ def agent_run( ``started`` (with its ``title``, its ``brief``, who it was ``started_by`` and its ``mode``; a first run of an instance also says whether the instance ``inherit_context`` and is ``continuable``, - and the ``tools`` and ``model`` its delegation gave it; a follow-up's + and the ``tools`` and ``model`` its delegation gave it, and a general-purpose + run the type it is ``based_on``; a follow-up's start carries its ``input``, the message as written), then one end status (``completed``, ``failed``, ``refused``, ``cancelled``, ``interrupted``: the constants of ``workflow/agents/runs.py``) with the first of its ``result``, its @@ -262,6 +264,9 @@ def agent_run( of them); None for all of them. model: A first run's start: the model choice it runs on, as the type writes it; None for the type's own model. + based_on: A first run's start of the built-in ``general_purpose`` + type: the type that started it, whose tools and model it has + (``agents/spawn.py::general_purpose_config``); None for any other. """ metadata: dict[str, Any] = {"status": status, "agent": ref.agent, "partial": partial} if title is not None: @@ -298,6 +303,8 @@ def agent_run( metadata["tools"] = list(tools) if model is not None: metadata["model"] = model + if based_on is not None: + metadata["based_on"] = based_on return cls( type=EventType.AGENT_RUN, content=f"{ref.instance} {status}", diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index ebff358b..f9af0007 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -1207,3 +1207,32 @@ async def test_it_blocks_no_event_loop(self, make_crew): await typed(app, "/agent new helper Help.", "/back") assert said(app.session, "add_response") == ["Helped.", "Noted."] + + +class TestAGeneralPurposeInstancesView: + async def test_it_says_the_model_and_context_of_the_type_that_started_it(self, make_crew): + """A ``general_purpose`` instance runs on its spawner type's model: its view + names that model, and its context is that model's.""" + from agentic_cli.workflow.agents import SubAgentPolicy + + crew = make_crew( + [agent("coordinator", model=SMALL_MODEL)], models=SMALL_ENTRY, + subagents=SubAgentPolicy(spawn_sources={"agent"}, general_purpose=True), + coordinator=[calls(delegate("general_purpose", "Sum it up.", "c1")), says("Done.")], + general_purpose=[says("Summed.", usage=(900, 30))], + ) + app = await app_on(crew) + + await typed(app, "Sum it up.", "/agent general_purpose-1") + bar = status(app) + await typed(app, "/status") + + (panel,) = app.session.add_rich.call_args.args + rows = dict(rows_of(panel.renderable)) + budget = crew.manager.context_budget("coordinator") + assert rows["Sub-agent"] == "general_purpose-1 (general_purpose, idle)" + assert (rows["Model"], rows["Summarize At"]) == (SMALL_MODEL, format_tokens(budget.trigger)) + assert UsageTracker( + last_prompt_tokens=900, context_trigger=budget.trigger, + window_known=budget.window_known, + ).format_context() in bar diff --git a/tests/tools/test_skill_agents.py b/tests/tools/test_skill_agents.py index fd582db6..61c41a71 100644 --- a/tests/tools/test_skill_agents.py +++ b/tests/tools/test_skill_agents.py @@ -368,3 +368,68 @@ async def source(): "success": False, "error": RUNS_PER_TURN_ERROR.format(limit=1), } assert len(asked) == 1 + + +class TestTheGeneralPurposeType: + """A skill may name ``general_purpose``: with the policy's ``general_purpose`` + and ``"skill"`` among its sources, the load starts one made for the + loading agent's type. A general-purpose agent's own loads start none.""" + + GENERAL = SubAgentPolicy(spawn_sources={"skill"}, general_purpose=True) + + async def test_it_starts_one_made_for_the_loading_agents_type(self, tmp_path, logged): + from agentic_cli.workflow.agents.spawn import general_purpose_config + + hook, asked = answering("Found it.") + runs = AgentRuns() + delegations = made(hook, policy=self.GENERAL, runs=runs) + agents = SkillAgents("lead", lambda: delegations, root=True) + skill = make_skill(tmp_path, "research", "agent: general_purpose\n") + + agents.check([skill]) + out, events = await loaded(agents, skill) + + assert logged == [] + assert out["result"].result["agent"] == "general_purpose-1" + (run,) = asked + assert (run.config, run.based_on) == (general_purpose_config(TYPES["lead"]), "lead") + assert events[0].metadata["based_on"] == "lead" + assert runs.instance(CONVERSATION, "general_purpose-1").based_on == "lead" + + @pytest.mark.parametrize("policy, reason", [ + (SKILLS, "is not one of this app's agent types"), + (SubAgentPolicy(spawn_sources={"agent"}, general_purpose=True), + "this app does not let a skill start"), + ], ids=["off", "not-for-skills"]) + def test_with_the_type_off_or_not_for_skills_it_is_refused(self, tmp_path, policy, reason): + skill = make_skill(tmp_path, "research", "agent: general_purpose\n") + agents = SkillAgents("lead", lambda: made(policy=policy), root=True) + + assert agents.refusal(skill, 0) == ( + f"The skill 'research' starts the agent 'general_purpose', which {reason}." + ) + + @pytest.mark.parametrize("named", ["helper", "general_purpose"]) + def test_a_general_purpose_agent_starts_none_and_is_not_warned_of( + self, tmp_path, logged, named + ): + deeper = SubAgentPolicy(spawn_sources={"skill"}, max_spawn_depth=3, general_purpose=True) + skill = make_skill(tmp_path, "research", f"agent: {named}\n") + agents = SkillAgents("general_purpose", lambda: made(policy=deeper), root=False) + + agents.check([skill]) + + assert logged == [] + assert agents.refusal(skill, 1) == ( + f"The skill 'research' starts the agent '{named}', which cannot be started " + "here: sub-agents cannot start sub-agents." + ) + + def test_past_the_depth_it_is_refused_as_any_type(self, tmp_path): + skill = make_skill(tmp_path, "research", "agent: general_purpose\n") + agents = SkillAgents("middle", lambda: made(policy=self.GENERAL), root=False) + + assert agents.refusal(skill, 1) == ( + "The skill 'research' starts the agent 'general_purpose', which cannot be started " + "here: sub-agents cannot start sub-agents." + ) diff --git a/tests/workflow/adk/test_plugin_chain.py b/tests/workflow/adk/test_plugin_chain.py index 8ec270de..27971a52 100644 --- a/tests/workflow/adk/test_plugin_chain.py +++ b/tests/workflow/adk/test_plugin_chain.py @@ -224,6 +224,47 @@ async def test_a_model_choices_runner_has_its_types_chain_on_the_choices_numbers assert (manager._variant_runners, manager._variant_agents) == ({}, {}) +async def test_a_general_purpose_runner_has_a_sub_agents_chain_on_its_spawners_model(project): + """With the policy's ``general_purpose``, each type that may start it has a + general-purpose agent of its own and its runner: the spawner's model, a + sub-agent's chain reading that model's numbers, kind and reference under + ``general_purpose``, and no delegation tool, and the release empties the maps (that it closes the + runner, and the MCP server with it, is ``test_adk_mcp_lifecycle.py``'s).""" + spawner_model = "claude-haiku-4-5" + manager = GoogleADKWorkflowManager( + agent_configs=[ + AgentConfig(name="lead", prompt="Lead.", sub_agents=["helper"], model=spawner_model), + AgentConfig(name="helper", prompt="Help.", description="Helps."), + ], + settings=_settings(extras=True), + subagents=SubAgentPolicy(spawn_sources={"agent"}, general_purpose=True), + ) + + try: + await manager.initialize_services() + runner = manager._general_runners["lead"] + agent = runner.app.root_agent + plugins = {plugin.name: plugin for plugin in runner.app.plugins} + budget = manager.context_budget("lead") + assert set(manager._general_runners) == set(manager._general_agents) == {"lead"} + assert manager._general_agents["lead"] is agent + assert (agent.name, agent.model.model) == ("general_purpose", spawner_model) + assert [p.name for p in runner.app.plugins] == [ + p.name for p in manager._agent_runners["helper"].app.plugins + ] + assert plugins["fit_guard"]._budgets["general_purpose"] == budget + assert plugins["context_overflow"]._budgets["general_purpose"] == budget + assert plugins["context_overflow"]._models["general_purpose"] == ( + f"anthropic:{spawner_model}" + ) + assert "task" not in {getattr(tool, "name", "") for tool in agent.tools} + assert "general_purpose" not in manager._agent_runners + finally: + await manager.cleanup() + + assert (manager._general_runners, manager._general_agents) == ({}, {}) + + async def test_a_main_agent_that_continues_its_sub_agents_gets_the_roster(project): """With the policy's ``follow_ups`` the main agent has ``message_agent``: its chain carries the roster, before the memory index; a sub-agent type's diff --git a/tests/workflow/deepagents/test_agent_builder.py b/tests/workflow/deepagents/test_agent_builder.py index f08e1dd1..7f670a11 100644 --- a/tests/workflow/deepagents/test_agent_builder.py +++ b/tests/workflow/deepagents/test_agent_builder.py @@ -720,3 +720,49 @@ def spy(*args, **kwargs): ) assert [tool.name for tool in variant["tools"]] == ["save_plan"] assert RunControlMiddleware in [type(m) for m in variant["middleware"]] + + +class TestTheGeneralPurposeAgent: + """The general-purpose agent made for a type (``general``): built as a + variant is, with its own tools and prompt, a sub-agent's stack, and no + ``task`` even where a sub-agent of the app's would get one.""" + + async def test_its_own_tools_and_prompt_and_no_task(self, monkeypatch): + from agentic_cli.workflow.agents.spawn import general_purpose_config + + made: list[dict] = [] + real = agent_builder.create_agent + + def spy(*args, **kwargs): + made.append(kwargs) + return real(*args, **kwargs) + + monkeypatch.setattr(agent_builder, "create_agent", spy) + chat = ScriptedChat(script=[ai("Summed.")]) + general_graphs: dict = {} + deeper = SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=2, + general_purpose=True) + + _tree( + [COORDINATOR, RESEARCHER], + {"coordinator": ScriptedChat(), "researcher": ScriptedChat()}, + policy=deeper, checkpointer=InMemorySaver(), + general={"coordinator": Variant( + config=general_purpose_config(COORDINATOR), chat_model=chat, resolved=None, + tools=to_langchain_tools([save_plan]), prompt="Its own prompt.", + )}, + general_graphs=general_graphs, + ) + await general_graphs["coordinator"].ainvoke( + {"messages": [HumanMessage("# Task: Sum it up.")]}, + {"configurable": {"thread_id": "g"}}, + ) + + assert len(chat.requests) == 1 + *_, built = made + assert [m["name"] for m in made] == ["coordinator", "researcher", "general_purpose"] + assert (built["model"], built["system_prompt"]) == (chat, "Its own prompt.") + assert [tool.name for tool in built["tools"]] == ["save_plan"] + # A sub-agent of the app's at this depth gets task; the general-purpose one does not. + assert "task" in [tool.name for tool in made[1]["tools"]] + assert RunControlMiddleware in [type(m) for m in built["middleware"]] diff --git a/tests/workflow/deepagents/test_mcp.py b/tests/workflow/deepagents/test_mcp.py index 30d42d54..4d099068 100644 --- a/tests/workflow/deepagents/test_mcp.py +++ b/tests/workflow/deepagents/test_mcp.py @@ -637,6 +637,41 @@ async def test_an_unreachable_server_leaves_the_agent_without_its_tools( assert [e.content for e in of(first, EventType.TEXT)] == ["Without it."] assert of(second, EventType.ERROR) == [] + async def test_a_general_purpose_agents_notice_names_its_spawner( + self, ctx, servers, monkeypatch + ): + """Each type that may start the general-purpose type has an agent of it with + sessions of its own, so a server that cannot start is a notice for it too, + which says whose spawner it is.""" + from agentic_cli.workflow.agents import SubAgentPolicy + + scripted(monkeypatch, lead=[ai("Hello.")], general_purpose=[]) + manager = DeepAgentsWorkflowManager( + agent_configs=[AgentConfig( + name="lead", prompt="Lead.", include_state_tools=False, + mcp_servers=[servers("broken", env={"MCP_TEST_FAIL": "no licence"})], + )], + settings=ctx.settings, model="gemini-2.5-flash", + subagents=SubAgentPolicy(spawn_sources={"agent"}, general_purpose=True), + ) + try: + events = await turn(manager) + finally: + await manager.cleanup() + + notices = of(events, EventType.ERROR) + assert [(n.metadata["agent"], n.metadata.get("spawner")) for n in notices] == [ + ("lead", None), ("general_purpose", "lead"), + ] + assert all(n.metadata["error_code"] == "mcp_unavailable" for n in notices) + assert notices[0].content.startswith( + "MCP server 'broken' is unavailable, so agent 'lead' runs without its tools: " + ) + assert notices[1].content.startswith( + "MCP server 'broken' is unavailable, so agent 'general_purpose' (for 'lead') " + "runs without its tools: " + ) + @pytest.mark.parametrize("rename, configs, taken_by", [ ("add=read_file", lambda server: [_researcher(server, tools=[read_file])], "the agent already has a tool of that name"), @@ -872,8 +907,8 @@ async def counted_exit(*exc): real_start = MCPSessions.start started = asyncio.Event() - async def start_then_hang(self, agent, configs): - loaded = await real_start(self, agent, configs) + async def start_then_hang(self, agent, configs, **kwargs): + loaded = await real_start(self, agent, configs, **kwargs) started.set() await asyncio.Event().wait() return loaded diff --git a/tests/workflow/test_adk_mcp_lifecycle.py b/tests/workflow/test_adk_mcp_lifecycle.py index 351d9492..527a13e6 100644 --- a/tests/workflow/test_adk_mcp_lifecycle.py +++ b/tests/workflow/test_adk_mcp_lifecycle.py @@ -29,8 +29,10 @@ from tests.workflow.adk.fakes import FakeAPI, anthropic_message # noqa: E402 from tests.workflow.test_manager_models import route # noqa: E402 from tests.workflow.test_subagents_contract import ( # noqa: E402,F401 - fixtures + ADK_MCP_WARNINGS, CHOICE, FOLLOWING, + GENERAL, agent, backend, calls, @@ -315,3 +317,38 @@ async def test_a_model_choices_runner_is_released_with_the_backend( assert alive(pid_dir) == [], "a server outlived cleanup()" assert getattr(manager, "_variant_graphs", {}) == {} assert dict(getattr(manager, "_variant_runners", {})) == {} + + +@ADK_MCP_WARNINGS +async def test_a_general_purpose_agents_runner_is_released_with_the_backend( + make_crew, backend, pid_dir +): + """A type with an MCP server that starts the built-in general-purpose type: + its agent has a server of its own (ADK: a toolset of its runner's; Deep + Agents: sessions of its own), which a model switch and cleanup stop.""" + server = MCPServerConfig( + name="atlas", command=sys.executable, args=[str(SERVER)], timeout=30, + env={"MCP_TEST_PID_DIR": str(pid_dir)}, tool_name_prefix="atlas", + ) + crew = make_crew( + [agent("coordinator", mcp_servers=[server])], subagents=GENERAL, + coordinator=[calls(delegate("general_purpose", "Find X.", "c1")), says("Done.")], + general_purpose=[says("X is 42.")], + ) + manager = crew.manager + try: + await crew.turn() + assert len(manager._general_graphs if backend == "deepagents" + else manager._general_runners) == 1 + # The spawner's own server and the general-purpose agent's. + assert len(alive(pid_dir)) == 2 + + await manager.reinitialize(model="claude-opus-4-7", preserve_sessions=True) + if backend == "adk": + assert alive(pid_dir) == [] # no runner of the old build is left open + finally: + await manager.cleanup() + + assert alive(pid_dir) == [], "a server outlived cleanup()" + assert getattr(manager, "_general_graphs", {}) == {} + assert dict(getattr(manager, "_general_runners", {})) == {} diff --git a/tests/workflow/test_agent_delegate.py b/tests/workflow/test_agent_delegate.py index bbee2cf4..279d6a2f 100644 --- a/tests/workflow/test_agent_delegate.py +++ b/tests/workflow/test_agent_delegate.py @@ -69,6 +69,7 @@ TOKEN_LIMIT_ERROR, ) from agentic_cli.workflow.agents.outcome import CUT, REFUSAL_ERROR, REFUSED +from agentic_cli.workflow.agents.spawn import general_purpose_config from agentic_cli.workflow.config import AgentConfig from agentic_cli.workflow.events import EventType, WorkflowEvent from agentic_cli.workflow.interrupts import OpenCalls @@ -4650,3 +4651,227 @@ def test_its_refusals_say_why_before_any_run(self): "You cannot start 'nobody' here. Types you can start: asked, reads." ) assert made.user_start_refused("asked", " ") == "A new agent needs an objective." + + +# -- the built-in general-purpose type --------------------------------------------------- + +#: Every source may start the general-purpose type; runs from the root alone. +GENERAL = SubAgentPolicy(spawn_sources={"agent", "skill", "user"}, general_purpose=True) +#: The same, and one level more: a type the root starts may start one too. +GENERAL_DEEPER = SubAgentPolicy( + spawn_sources={"agent", "skill", "user"}, max_spawn_depth=2, general_purpose=True +) +#: A lead with tools of its own, its sub-agent, and a free type agents may start. +TOOLED = AgentConfig(name="lead", prompt="p", sub_agents=["researcher"], + tools=[contract_tool, "web_fetch"]) +GENERAL_TYPES = {"lead": TOOLED, "researcher": TYPES["researcher"], "helper": HELPER} +SUM_UP = {"agent_type": "general_purpose", "title": "Sum up", "objective": "Sum it up."} +#: The line ``task`` offers it by. +GENERAL_LINE = ( + "- general_purpose: A general-purpose agent with your own tools (but not the ones that " + "start agents) and your model, for a self-contained task no other agent fits." +) + + +class TestTheGeneralPurposeType: + """``general_purpose``: offered last to a run that may start a type, made + for the caller's type (``general_purpose_config``, ``based_on``), which its + run, its start, its instance and every later run of it keep.""" + + def test_offered_last_made_for_its_caller(self): + made = delegations(answering()[0], types=GENERAL_TYPES, policy=GENERAL) + + offered = made.offered("lead", 0) + + assert list(offered) == ["researcher", "helper", "general_purpose"] + assert offered["general_purpose"] == general_purpose_config(TOOLED) + assert made.task_offer("lead", 0).description.endswith(GENERAL_LINE) + + def test_not_offered_with_the_policy_off_or_past_the_depth(self): + made = delegations(answering()[0], types=GENERAL_TYPES, policy=AGENTS) + assert "general_purpose" not in made.offered("lead", 0) + on = delegations(answering()[0], types=GENERAL_TYPES, policy=GENERAL) + assert on.offered("researcher", 1) == {} + + def test_a_type_one_level_down_is_offered_its_own(self): + made = delegations(answering()[0], types=GENERAL_TYPES, policy=GENERAL_DEEPER) + + offered = made.offered("helper", 1) + + assert list(offered) == ["helper", "general_purpose"] + assert offered["general_purpose"] == general_purpose_config(HELPER) + + def test_its_own_runs_start_nothing(self): + made = delegations(answering()[0], types=GENERAL_TYPES, policy=GENERAL_DEEPER) + assert made.offered("general_purpose", 1) == {} + assert made.task_offer("general_purpose", 1) is None + + def test_one_for_each_type_that_may_start_it(self): + assert delegations(answering()[0], types=GENERAL_TYPES, policy=GENERAL).general_purpose \ + == {"lead": general_purpose_config(TOOLED)} + deeper = delegations(answering()[0], types=GENERAL_TYPES, policy=GENERAL_DEEPER) + assert list(deeper.general_purpose) == ["lead", "researcher", "helper"] + assert delegations(answering()[0], types=GENERAL_TYPES).general_purpose == {} + + def test_config_for(self): + made = delegations(answering()[0], types=GENERAL_TYPES, policy=GENERAL) + assert made.config_for("researcher") is TYPES["researcher"] + assert made.config_for("general_purpose", based_on="lead") == ( + general_purpose_config(TOOLED) + ) + # No spawner, or one that may not start it here. + assert made.config_for("general_purpose") is None + assert made.config_for("general_purpose", based_on="helper") is None + assert made.config_for("nobody") is None + off = delegations(answering()[0], types=GENERAL_TYPES, policy=AGENTS) + assert off.config_for("general_purpose", based_on="lead") is None + + async def test_the_root_starts_one_with_its_own_tools_and_model(self): + hook, asked = answering("Summed.") + runs = AgentRuns() + made = delegations(hook, runs=runs, types=GENERAL_TYPES, policy=GENERAL) + + result, events = await delegated(made, request(SUM_UP, caller_agent="lead")) + + assert result.result == { + "success": True, "agent": "general_purpose-1", "run": "general_purpose-1#1", + "status": RUN_COMPLETED, "partial": False, "result": "Summed.", "error": None, + } + (run,) = asked + assert (run.config, run.based_on, run.tools, run.model) == ( + general_purpose_config(TOOLED), "lead", None, None, + ) + assert (run.ref.depth, run.ref.parent_run) == (1, None) + start = runs_of_status(events, RUN_STARTED)[0] + assert (start.metadata["based_on"], start.metadata["started_by"]) == ("lead", "agent:root") + instance = runs.instance(CONVERSATION, "general_purpose-1") + assert (instance.agent, instance.based_on) == ("general_purpose", "lead") + + async def test_its_tools_narrow_against_its_spawners(self): + hook, asked = answering() + tools_asked: list[str] = [] + made = delegations(hook, types=GENERAL_TYPES, policy=GENERAL, + tool_names=own_tools({"lead": {"lookup", "fetch"}}, tools_asked)) + + await delegated(made, request({**SUM_UP, "tools": ["lookup"]}, caller_agent="lead")) + refused, _ = await delegated(made, request( + {**SUM_UP, "tools": ["write_file"]}, caller_agent="lead", call_id="c2", + )) + + assert asked[0].tools == frozenset({"lookup"}) + assert tools_asked == ["lead", "lead"] + assert refused.result == { + "success": False, + "error": "The tools for 'general_purpose' must be some of its own: fetch, lookup.", + } + + async def test_a_model_is_refused(self): + hook, asked = answering() + made = delegations(hook, types=GENERAL_TYPES, policy=GENERAL) + + result, events = await delegated( + made, request({**SUM_UP, "model": "fast"}, caller_agent="lead") + ) + + assert result.result == { + "success": False, "error": "'general_purpose' has no model choices; leave model out.", + } + assert (asked, events) == ([], []) + + async def test_a_follow_up_and_a_restored_instance_run_on_the_same_spawners(self): + hook, asked = answering() + runs = AgentRuns() + made = delegations(hook, runs=runs, types=GENERAL_TYPES, policy=GENERAL) + await turned(lambda: made.delegate(request(SUM_UP, caller_agent="lead"))) + + followed, _ = await turned(lambda: made.follow_up(follow("general_purpose-1"))) + again = AgentRuns() + again.restore(CONVERSATION, runs.export(CONVERSATION)) + restarted = delegations(hook, runs=again, types=GENERAL_TYPES, policy=GENERAL) + resumed, _ = await turned(lambda: restarted.follow_up(users("general_purpose-1"))) + + assert [r.result["run"] for r in (followed, resumed)] == [ + "general_purpose-1#2", "general_purpose-1#3", + ] + assert [(run.config, run.based_on) for run in asked[1:]] == [ + (general_purpose_config(TOOLED), "lead"), + ] * 2 + + @pytest.mark.parametrize("policy", [AGENTS, SubAgentPolicy( + spawn_sources={"agent"}, general_purpose=True, + )], ids=["off", "on"]) + async def test_a_follow_up_the_app_no_longer_allows_is_refused(self, policy): + hook, asked = answering() + runs = AgentRuns() + made = delegations(hook, runs=runs, types=GENERAL_TYPES, policy=GENERAL) + await turned(lambda: made.delegate(request(SUM_UP, caller_agent="lead"))) + again = AgentRuns() + again.restore(CONVERSATION, runs.export(CONVERSATION)) + # The type off, or its spawner gone. + types = GENERAL_TYPES if policy is AGENTS else { + "boss": AgentConfig(name="boss", prompt="p"), "helper": HELPER, + } + restarted = delegations(hook, runs=again, types=types, policy=policy) + + result, events = await turned(lambda: restarted.follow_up(users("general_purpose-1"))) + + assert result.result == { + "success": False, + "error": "general_purpose-1's type 'general_purpose' is not one of this app's agents.", + } + assert (events, len(asked)) == ([], 1) + + async def test_the_user_starts_one_on_the_roots(self): + hook, asked = answering() + made = delegations(hook, types=GENERAL_TYPES, policy=GENERAL) + + assert made.startable_by_user() == ("general_purpose",) + out, events = await users_start(made, "general_purpose", "Sum it up.") + + assert out["result"].result["agent"] == "general_purpose-1" + assert (asked[0].config, asked[0].based_on) == (general_purpose_config(TOOLED), "lead") + assert events[0].metadata["based_on"] == "lead" + + async def test_a_start_request_names_its_spawner(self): + hook, asked = answering() + made = delegations(hook, types=GENERAL_TYPES, policy=GENERAL_DEEPER) + + await started(made, start_request("general_purpose", based_on="helper")) + + assert (asked[0].config, asked[0].based_on) == (general_purpose_config(HELPER), "helper") + + async def test_without_a_spawner_that_may_start_it_start_has_no_such_type(self): + made = delegations(answering()[0], types=GENERAL_TYPES, policy=GENERAL) + with pytest.raises(KeyError): + await made.start(start_request("general_purpose")) + with pytest.raises(KeyError): + await made.start(start_request("general_purpose", based_on="helper")) + + async def test_based_on_is_the_general_purpose_types_alone(self): + hook, asked = answering() + runs = AgentRuns() + made = delegations(hook, runs=runs, types=GENERAL_TYPES, policy=GENERAL) + + _, events = await started(made, start_request("researcher", based_on="lead")) + + assert asked[0].based_on is None + assert "based_on" not in events[0].metadata + assert runs.instance(CONVERSATION, "researcher-1").based_on is None + + async def test_with_no_configured_types_the_user_may_not_start_it(self): + """A native ADK app has no configs: no root, so no type to make it for.""" + made = delegations(answering()[0], types={}, policy=GENERAL) + + assert made.startable_by_user() == () + result = await made.start_by_user(CONVERSATION, "general_purpose", "Sum it up.") + assert result.result == { + "success": False, "error": "This app lets you start no agent types.", + } + assert made.offered("anyone", 0) == {} + + def test_the_fields_default_to_none(self): + made = StartRequest(agent_type="researcher", brief=Brief(title="T", objective="O"), + started_by="user") + run = AgentRun(ref=RESEARCHER, config=TYPES["researcher"], message="m", + conversation=None, state={}) + assert (made.based_on, run.based_on) == (None, None) diff --git a/tests/workflow/test_agent_policy.py b/tests/workflow/test_agent_policy.py index 75fc5834..08c4b398 100644 --- a/tests/workflow/test_agent_policy.py +++ b/tests/workflow/test_agent_policy.py @@ -156,7 +156,7 @@ def test_the_sources(self): 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:] == [ + assert [f.name for f in dataclasses.fields(SubAgentPolicy)][5:7] == [ "spawn_sources", "max_spawn_depth", ] @@ -193,6 +193,36 @@ def test_policies_with_the_same_sources_are_equal(self): assert SubAgentPolicy(spawn_sources=["agent"]) == SubAgentPolicy(spawn_sources={"agent"}) +class TestTheGeneralPurposeType: + """``general_purpose``: the built-in general-purpose type, off by default, + and only with a source that could start it.""" + + def test_it_is_off_by_default_and_comes_last(self): + assert SubAgentPolicy().general_purpose is False + # Appended: a positional SubAgentPolicy(...) written before it still binds. + assert [f.name for f in dataclasses.fields(SubAgentPolicy)][-1] == "general_purpose" + + @pytest.mark.parametrize("sources", [{"agent"}, {"skill"}, {"user"}]) + def test_any_source_lets_it_on(self, sources): + assert SubAgentPolicy(spawn_sources=sources, general_purpose=True).general_purpose is True + + def test_with_no_source_it_is_refused(self): + with pytest.raises(ValueError) as exc: + SubAgentPolicy(general_purpose=True) + assert str(exc.value) == ( + "SubAgentPolicy.general_purpose needs spawn_sources: with none, nothing could " + "start it." + ) + + @pytest.mark.parametrize("value", [1, 0, None, "yes"]) + def test_it_is_true_or_false(self, value): + with pytest.raises(ValueError) as exc: + SubAgentPolicy(spawn_sources={"agent"}, general_purpose=value) + assert str(exc.value) == ( + f"SubAgentPolicy.general_purpose must be True or False, not {value!r}." + ) + + class TestAsPolicy: def test_none_is_the_default_policy(self): assert as_policy(None) == SubAgentPolicy() diff --git a/tests/workflow/test_agent_run_event.py b/tests/workflow/test_agent_run_event.py index e2b112ff..4505a982 100644 --- a/tests/workflow/test_agent_run_event.py +++ b/tests/workflow/test_agent_run_event.py @@ -112,6 +112,14 @@ def test_no_tools_or_model_unless_given(self): assert "tools" not in event.metadata and "model" not in event.metadata + def test_a_general_purpose_runs_start_carries_its_spawner_type(self): + ref = RunRef("general_purpose", "general_purpose-1", "general_purpose-1#1", None, 1) + + event = WorkflowEvent.agent_run(ref, "started", title="Sum it up.", based_on="lead") + + assert event.metadata["based_on"] == "lead" + assert "based_on" not in WorkflowEvent.agent_run(ref, "started").metadata + def test_a_follow_ups_start_carries_its_input(self): second = RunRef("researcher", "researcher-1", "researcher-1#2", None, 1) diff --git a/tests/workflow/test_agent_runs.py b/tests/workflow/test_agent_runs.py index caf77b4e..39ef60f8 100644 --- a/tests/workflow/test_agent_runs.py +++ b/tests/workflow/test_agent_runs.py @@ -472,6 +472,17 @@ def test_a_first_runs_start_keeps_the_tools_and_model_it_was_given(self): record = runs.instance(ONE, "researcher-1") assert (record.tools, record.model) == (("lookup", "fetch"), "fast") + def test_a_first_runs_start_keeps_its_spawner_type(self): + runs = AgentRuns() + ref = runs.run_for(ONE, None, "c1", "general_purpose") + + in_turn(ONE, lambda: runs.observe(WorkflowEvent.agent_run( + ref, RUN_STARTED, title="Sum it up.", call_id="c1", based_on="lead", + ))) + + record = runs.instance(ONE, "general_purpose-1") + assert (record.agent, record.based_on) == ("general_purpose", "lead") + def test_a_follow_ups_start_changes_neither(self): runs = AgentRuns() ref = runs.run_for(ONE, None, "c1", "researcher") @@ -799,7 +810,7 @@ def test_its_shape(self): "instance": "researcher-1", "agent": "researcher", "parent": "root", "depth": 1, "inherit_context": False, "title": "researcher work", "status": INSTANCE_IDLE, "runs": ["researcher-1#1"], "continuable": True, - "tools": None, "model": None, + "tools": None, "model": None, "based_on": None, }], "runs": [{ "run": "researcher-1#1", "agent": "researcher", "instance": "researcher-1", @@ -920,9 +931,37 @@ def test_records_written_before_tools_and_model_read_them_as_none(self): assert {(i.tools, i.model) for i in again.instances(ONE)} == {(None, None)} + def test_a_spawner_type_is_kept_and_read_back(self): + runs = AgentRuns() + ref = started(runs, ONE, "c1", "general_purpose") + in_turn(ONE, lambda: runs.observe(WorkflowEvent.agent_run( + runs.run_for(ONE, None, "c2", "general_purpose"), RUN_STARTED, title="More.", + call_id="c2", based_on="lead", + ))) + ended(runs, ONE, ref) + + data = json.loads(json.dumps(runs.export(ONE))) + + assert [i["based_on"] for i in data["instances"]] == [None, "lead"] + again = AgentRuns() + again.restore(ONE, data) + assert [i.based_on for i in again.instances(ONE)] == [None, "lead"] + + def test_records_written_before_a_spawner_type_read_it_as_none(self): + runs = AgentRuns() + a_conversation(runs) + data = json.loads(json.dumps(runs.export(ONE))) + for instance in data["instances"]: + del instance["based_on"] + again = AgentRuns() + + assert again.restore(ONE, data) == ["writer-1#1"] + + assert {i.based_on for i in again.instances(ONE)} == {None} + @pytest.mark.parametrize("field, value", [ ("tools", "lookup"), ("tools", [1]), ("tools", {"lookup": True}), ("model", 3), - ("model", ["fast"]), + ("model", ["fast"]), ("based_on", 1), ("based_on", ["lead"]), ]) def test_tools_or_a_model_that_do_not_read_are_records_it_cannot_read( self, field, value diff --git a/tests/workflow/test_agent_spawn.py b/tests/workflow/test_agent_spawn.py index 93b1923b..6a4e9a76 100644 --- a/tests/workflow/test_agent_spawn.py +++ b/tests/workflow/test_agent_spawn.py @@ -2,9 +2,12 @@ ``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. +(``AgentConfig.spawnable_by``), then the built-in ``general_purpose`` when +the policy enables it. ``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. +``general_purpose_config`` is the general-purpose type made for one spawner +type, and ``general_purpose_spawners`` the types one is made for. """ from __future__ import annotations @@ -14,10 +17,16 @@ from agentic_cli.workflow.agents.policy import SubAgentPolicy from agentic_cli.workflow.agents.spawn import ( AGENT_SOURCE, + GENERAL_PURPOSE, + GENERAL_PURPOSE_DESCRIPTION, + GENERAL_PURPOSE_PROMPT, SKILL_SOURCE, USER_SOURCE, can_have_children, + general_purpose_config, + general_purpose_spawners, may_spawn, + root_type, spawnable, ) from agentic_cli.workflow.config import AgentConfig @@ -92,3 +101,131 @@ def test_a_sub_agent_can_only_when_runs_below_the_root_may_start_one(self): 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) + + +#: The general-purpose type on, for every source. +GENERAL = SubAgentPolicy(spawn_sources={"agent", "skill", "user"}, general_purpose=True) + + +class TestTheGeneralPurposeType: + def test_its_name_line_and_prompt(self): + assert GENERAL_PURPOSE == "general_purpose" + assert GENERAL_PURPOSE_DESCRIPTION == ( + "A general-purpose agent with your own tools (but not the ones that start " + "agents) and your model, for a self-contained task no other agent fits." + ) + assert GENERAL_PURPOSE_PROMPT == ( + "You are a general-purpose agent, started by another agent for one task. The task " + "message says what to do and what to return. Do it with the tools you have, then " + "answer with the result itself, in the form the task asks for: the agent that " + "started you reads only your final answer. If the task cannot be done, say why, " + "and give what you found." + ) + + @pytest.mark.parametrize("source", ["agent", "skill", "user"]) + def test_spawnable_appends_it_for_each_source_the_policy_enables(self, source): + assert spawnable(CONFIGS, GENERAL, source)[-1] == GENERAL_PURPOSE + only = SubAgentPolicy(spawn_sources={source}, general_purpose=True) + assert spawnable([LEAD, RESEARCHER], only, source) == (GENERAL_PURPOSE,) + others = [s for s in ("agent", "skill", "user") if s != source] + assert all(spawnable([LEAD, RESEARCHER], only, other) == () for other in others) + + def test_not_unless_the_policy_enables_it(self): + assert GENERAL_PURPOSE not in spawnable(CONFIGS, EVERY, "agent") + + def test_the_root_can_have_children_for_it_alone(self): + solo = AgentConfig(name="solo", prompt="p") + agents = SubAgentPolicy(spawn_sources={"agent"}, general_purpose=True) + assert can_have_children(solo, [solo], agents, root=True) + users = SubAgentPolicy(spawn_sources={"user"}, general_purpose=True) + assert not can_have_children(solo, [solo], users, root=True) + + def test_it_never_has_children_itself(self): + deeper = SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=3, general_purpose=True) + made = general_purpose_config(RESEARCHER) + assert not can_have_children(made, CONFIGS, deeper, root=False) + # An app's own agent of that name, with the built-in type off, is any agent. + own = AgentConfig(name=GENERAL_PURPOSE, prompt="p", sub_agents=["researcher"]) + assert can_have_children(own, CONFIGS, EVERY, root=False) + + +class TestGeneralPurposeConfig: + def test_the_spawners_tools_servers_skills_and_model_with_its_own_prompt(self): + from agentic_cli.workflow.mcp import MCPServerConfig + from agentic_cli.workflow.model_settings import ModelSettings + + def lookup() -> dict: + return {"success": True} + + server = MCPServerConfig(name="atlas", command="atlas") + settings = ModelSettings(temperature=0.2) + spawner = AgentConfig( + name="lead", prompt="Lead.", tools=[lookup, "write_file"], mcp_servers=[server], + skills=["/skills/research"], model="fast", model_settings=settings, + sub_agents=["researcher"], include_state_tools=False, description="The lead.", + ) + + made = general_purpose_config(spawner) + + assert (made.name, made.prompt, made.description) == ( + GENERAL_PURPOSE, GENERAL_PURPOSE_PROMPT, GENERAL_PURPOSE_DESCRIPTION, + ) + assert (made.tools, made.mcp_servers, made.skills) == ( + [lookup, "write_file"], [server], ["/skills/research"], + ) + assert (made.model, made.model_settings) == ("fast", settings) + assert (made.sub_agents, made.model_choices, made.spawnable_by) == ([], (), None) + assert (made.inherit_context, made.continuable, made.include_state_tools) == ( + False, True, True, + ) + assert (made.limits, made.brief_required) == (None, ("objective",)) + + def test_its_lists_are_its_own(self): + spawner = AgentConfig(name="lead", prompt="Lead.", tools=["write_file"]) + made = general_purpose_config(spawner) + made.tools.append("read_file") + assert spawner.tools == ["write_file"] + + def test_not_from_a_spawner_on_a_model_choice(self): + researcher = AgentConfig(name="researcher", prompt="p", model="strong", + model_choices=("fast",)) + assert general_purpose_config(researcher).model == "strong" + + +class TestRootType: + def test_the_agent_nobody_delegates_to_that_is_no_free_type(self): + assert root_type([HELPER, RESEARCHER, LEAD]) == "lead" + + def test_none_for_none(self): + assert root_type([HELPER]) is None + + +class TestGeneralPurposeSpawners: + """The types a general-purpose agent is built for: the root whenever the + type is on; another type when runs below the root may start one (its + ``task``, or a skill it loads) and it does not inherit.""" + + def test_none_unless_the_policy_enables_it(self): + assert general_purpose_spawners(CONFIGS, EVERY) == () + + @pytest.mark.parametrize("source", ["agent", "skill", "user"]) + def test_the_root_alone_at_the_default_depth(self, source): + policy = SubAgentPolicy(spawn_sources={source}, general_purpose=True) + assert general_purpose_spawners(CONFIGS, policy) == ("lead",) + + def test_deeper_every_type_that_does_not_inherit_for_agents(self): + policy = SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=2, general_purpose=True) + assert general_purpose_spawners(CONFIGS, policy) == ( + "lead", "researcher", "helper", "skilled", + ) + + def test_deeper_for_skills_only_the_types_with_skills(self): + with_skills = AgentConfig(name="skilled", prompt="p", skills=["/s/research"], + spawnable_by=frozenset({"skill"})) + configs = [LEAD, RESEARCHER, with_skills] + policy = SubAgentPolicy(spawn_sources={"skill"}, max_spawn_depth=2, general_purpose=True) + assert general_purpose_spawners(configs, policy) == ("lead", "skilled") + + def test_deeper_for_the_user_the_root_alone(self): + policy = SubAgentPolicy(spawn_sources={"user"}, max_spawn_depth=2, general_purpose=True) + assert general_purpose_spawners(CONFIGS, policy) == ("lead",) diff --git a/tests/workflow/test_resource_ownership.py b/tests/workflow/test_resource_ownership.py index 924b3be2..a450739d 100644 --- a/tests/workflow/test_resource_ownership.py +++ b/tests/workflow/test_resource_ownership.py @@ -143,6 +143,23 @@ async def close(self) -> None: assert order == ["runner", "runner", "session_service"] assert dict(mgr._agent_runners) == {} + async def test_each_general_purpose_runner_is_closed_too(self): + order: list[str] = [] + + class Service: + async def close(self) -> None: + order.append("session_service") + + mgr = _manager(Service()) + mgr._runner = _Runner(order) + mgr._general_runners = {"lead": _Runner(order), "helper": _Runner(order)} + mgr._general_agents = {"lead": object(), "helper": object()} + + await mgr.cleanup() + + assert order == ["runner", "runner", "runner", "session_service"] + assert (dict(mgr._general_runners), dict(mgr._general_agents)) == ({}, {}) + async def test_cleanup_closes_it_before_the_session_service(self): order: list[str] = [] @@ -349,6 +366,27 @@ async def test_partial_initialization_is_rolled_back(self): finally: ctx.__exit__(None, None, None) + async def test_a_failed_initialization_closes_the_general_purpose_runners(self): + mgr, created, state, ctx = _real_manager() + runner = _Runner() + real = mgr._do_initialize + + async def _do_init(): + mgr._general_runners = {"a": runner} + mgr._general_agents = {"a": object()} + await real() + + mgr._do_initialize = _do_init + try: + state["boom"] = True + with pytest.raises(RuntimeError, match="backend init failed"): + await mgr.initialize_services() + + assert runner.closes == 1, "the general-purpose runner leaked" + assert (dict(mgr._general_runners), dict(mgr._general_agents)) == ({}, {}) + finally: + ctx.__exit__(None, None, None) + async def test_manager_can_be_initialized_after_a_failure(self): mgr, created, state, ctx = _real_manager() try: @@ -666,6 +704,16 @@ async def test_cleanup_closes_them_with_the_checkpointer(self): assert (mcp.closes, connection.closes) == (1, 1) + async def test_cleanup_drops_the_general_purpose_graphs_and_closes_their_sessions(self): + connection, mcp = _CountedConnection(), _CountedMCP() + mgr = _deepagents_manager(connection, mcp) + mgr._general_graphs = {"a": object()} + + await mgr.cleanup() + + assert mgr._general_graphs == {} + assert (mcp.closes, connection.closes) == (1, 1) + async def test_a_release_that_keeps_the_checkpointer_still_closes_them(self): connection, mcp = _CountedConnection(), _CountedMCP() mgr = _deepagents_manager(connection, mcp) @@ -820,6 +868,18 @@ async def test_a_failed_initialization_is_rolled_back(self, deepagents_manager): assert mgr.is_initialized is False assert mgr.services == {} + async def test_a_failed_initialization_drops_the_general_purpose_graphs( + self, deepagents_manager + ): + mgr, created, state = deepagents_manager + state["boom"] = True + mgr._general_graphs = {"a": object()} + + with pytest.raises(RuntimeError, match="backend init failed"): + await mgr.initialize_services() + + assert mgr._general_graphs == {} + async def test_it_can_be_initialized_after_a_failure(self, deepagents_manager): mgr, created, state = deepagents_manager state["boom"] = True diff --git a/tests/workflow/test_subagent_config.py b/tests/workflow/test_subagent_config.py index 8a726a0a..7c252d02 100644 --- a/tests/workflow/test_subagent_config.py +++ b/tests/workflow/test_subagent_config.py @@ -439,3 +439,36 @@ def test_a_free_type_may_set_them(self): name="helper", prompt="p", spawnable_by={"agent"}, model_choices=("fast",), )) assert validate_agent_graph(configs, policy=AGENTS).free_types == ("helper",) + + +class TestTheGeneralPurposeName: + """With the built-in ``general_purpose`` type on, no agent of the app's may + take its name; with it off, the name is any agent's.""" + + GENERAL = SubAgentPolicy(spawn_sources={"agent"}, general_purpose=True) + + #: The root named so, and a sub-agent named so. + NAMED = { + "root": {"lead": {"name": "general_purpose"}}, + "sub-agent": {"lead": {"sub_agents": ["researcher", "general_purpose"]}, + "writer": {"name": "general_purpose"}}, + } + + @pytest.mark.parametrize("named", NAMED.values(), ids=NAMED.keys()) + def test_an_agent_of_that_name_is_refused_while_it_is_on(self, named): + with pytest.raises(AgentGraphError) as exc: + validate_agent_graph(team(**named), policy=self.GENERAL) + assert str(exc.value) == ( + "An agent named 'general_purpose' clashes with the built-in general_purpose " + "type, which this app's SubAgentPolicy enables." + ) + + def test_with_it_off_the_name_is_any_agents(self): + graph = validate_agent_graph(team(**self.NAMED["sub-agent"]), policy=AGENTS) + assert "general_purpose" in graph.config_map + + def test_the_names_are_checked_for_duplicates_first(self): + configs = [*team(), AgentConfig(name="writer", prompt="p"), + AgentConfig(name="general_purpose", prompt="p")] + with pytest.raises(AgentGraphError, match="Duplicate agent name"): + validate_agent_graph(configs, policy=self.GENERAL) diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index ffb4d692..0355eb40 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -28,7 +28,8 @@ version goes), and ``written_no_more`` makes a manager write no more records, as a killed process writes none. Each agent's prompt is ``You are .``, by which ADK's fake API tells the -agents apart. +agents apart (the built-in ``general_purpose`` type by the framework's prompt, +``prompt_of``); ``Crew.system`` reads a request's system prompt. ``make_crew(..., models={...})`` adds ``models`` entries to the settings: an agent on a model with a small window (``SMALL_MODEL``) has its long transcript @@ -82,6 +83,7 @@ from agentic_cli.workflow.agents.delegate import Delegated, FollowUpRequest, started_by from agentic_cli.workflow.agents.roster import ROSTER_CLOSE, ROSTER_HEADER, ROSTER_MAX, ROSTER_OPEN from agentic_cli.workflow.agents.slots import SlotPool +from agentic_cli.workflow.agents.spawn import GENERAL_PURPOSE, GENERAL_PURPOSE_PROMPT from agentic_cli.workflow.agents.envelope import ( INTERRUPTED_ERROR, STEP_LIMIT_ERROR, @@ -237,7 +239,10 @@ def calls(*made: Call, text: str = "", usage: tuple[int, int] | None = None) -> def prompt_of(name: str) -> str: - """The prompt of the agent ``name``: how ADK's fake API knows whose request it is.""" + """The prompt of the agent ``name``: how ADK's fake API knows whose request it is + (the built-in ``general_purpose`` type's is the framework's).""" + if name == GENERAL_PURPOSE: + return GENERAL_PURPOSE_PROMPT return f"You are {name}." @@ -503,6 +508,7 @@ class Crew: _opening: Callable[[str, int], list[str]] | None = None _declared: Callable[[str, str, int], dict[str, Any] | None] | None = None _sent_models: Callable[[str], list[str]] | None = None + _system: Callable[[str, int], str] | None = None #: The turns ``start`` started: one a failed test left running is stopped #: before its manager is cleaned up (the cleanup waits for its turn). started: list["asyncio.Task[Any]"] = field(default_factory=list) @@ -553,6 +559,11 @@ def sent_models(self, agent: str) -> list[str]: assert self._sent_models is not None return self._sent_models(agent) + def system(self, agent: str, call: int = 0) -> str: + """The system prompt ``agent``'s model request ``call`` held, as text.""" + assert self._system is not None + return self._system(agent, call) + def opening(self, agent: str, call: int = -1) -> list[str]: """The text blocks of the first user message ``agent``'s model request ``call`` held, in order: what opens its conversation (the main @@ -793,11 +804,17 @@ def opening(name: str, call: int) -> list[str]: return [content] return [block["text"] for block in content if block.get("type") == "text"] + def system(name: str, call: int) -> str: + held = [body for sent, body in claude.sent if sent == name][call].get("system") or "" + if isinstance(held, list): + return "\n".join(block.get("text", "") for block in held) + return held + return Crew( "adk", manager, manager.session_ref(SESSION, USER), results_read, requests, result_ids, answers, last_message, bodies, tool_names, message_count, state, marked, _call_results=call_results, _instance_mark=instance_mark, _models=models, - _opening=opening, _declared=declared, _sent_models=models, + _opening=opening, _declared=declared, _sent_models=models, _system=system, ) @@ -933,6 +950,7 @@ def opening(name: str, call: int) -> list[str]: _call_results=call_results, _instance_mark=instance_mark, _models=built_models, _opening=opening, _declared=declared, _sent_models=lambda name: list(models.chats[name].sent_models), + _system=lambda name, call: models.chats[name].system_prompt(call) or "", ) @@ -1121,7 +1139,9 @@ async def make_crew(backend, project, monkeypatch): """``make_crew(team, *, subagents=None, store="memory", **scripts)``: ``team``'s manager on ``backend``, with the sub-agent policy ``subagents`` and the session store ``store`` (``"memory"`` or ``"sqlite"``) and the settings' - ``models`` entries, each agent answering from its script (an agent without one has none); every manager + ``models`` entries, each agent answering from its script (an agent without one has none; + the built-in ``general_purpose`` type's, ``general_purpose=[...]``, when the policy enables + it); every manager made is cleaned up after the test.""" SEEN.clear() BLOCKING["started"] = asyncio.Event() @@ -1133,6 +1153,9 @@ def make( store: str = "memory", models: dict[str, Any] | None = None, **scripts: list[Step], ) -> Crew: complete = {config.name: list(scripts.get(config.name, ())) for config in team} + if GENERAL_PURPOSE in scripts or (subagents is not None and subagents.general_purpose): + # The built-in type: no config of the team's, but an agent of its own. + complete[GENERAL_PURPOSE] = list(scripts.get(GENERAL_PURPOSE, ())) complete[SIDE_CALLS] = list(scripts.get(SIDE_CALLS, ())) complete[SUMMARIES] = list(scripts.get(SUMMARIES, ())) build = _adk_crew if backend == "adk" else _deepagents_crew @@ -7809,3 +7832,424 @@ async def test_it_blocks_no_event_loop(self, make_crew): events = await user_start(crew, "reader", "Find the code.") assert runs_of(events)[-1].metadata["result"] == "The code is 7." + + +# -- the built-in general-purpose type ------------------------------------------------- + +#: Agents may start the built-in general-purpose type: from the root alone. +GENERAL = SubAgentPolicy(spawn_sources={"agent"}, general_purpose=True) +#: Its line in ``task``'s list of types. +GENERAL_LINE = ( + "- general_purpose: A general-purpose agent with your own tools (but not the ones that " + "start agents) and your model, for a self-contained task no other agent fits." +) +#: Its tools when its spawner is ``general_team()``'s coordinator: the +#: coordinator's own and the plan's tools (on for it), no delegation tool. +GENERAL_TOOLS = [ + "contract_lookup", "contract_whoami", "save_plan", "get_plan", "save_tasks", "get_tasks", +] +GENERAL_1 = RunRef(agent=GENERAL_PURPOSE, instance="general_purpose-1", + run="general_purpose-1#1", parent_run=None, depth=1) + + +def general_team(**coordinator: Any) -> list[AgentConfig]: + """A coordinator with two tools of its own, and the researcher it delegates to.""" + return [ + agent("coordinator", sub_agents=("researcher",), + tools=(contract_lookup, contract_whoami), **coordinator), + agent("researcher", tools=(contract_lookup,)), + ] + + +class TestTheGeneralPurposeTypeOff: + async def test_the_default_policy_offers_no_such_type(self, make_crew): + crew = make_crew( + general_team(), coordinator=[calls(delegate("general_purpose", "Sum.", "c1")), + says("Done.")], + ) + + await crew.turn() + + assert agent_types(crew.declared("coordinator")) == ["researcher"] + assert json.loads(crew.results_read("coordinator", 1)["c1"]) == { + "success": False, + "error": "Unknown agent_type 'general_purpose': the agents you can delegate to are " + "researcher.", + } + + async def test_a_root_without_sub_agents_gets_no_task_unless_agents_may_start_it( + self, make_crew + ): + crew = make_crew( + [agent("solo", tools=(contract_lookup,))], + subagents=SubAgentPolicy(spawn_sources={"user"}, general_purpose=True), + solo=[says("Hi.")], + ) + + await crew.turn() + + assert crew.tool_names("solo") == ["contract_lookup"] + + async def test_an_agent_named_like_it_is_refused_while_it_is_on(self, make_crew): + from agentic_cli.workflow.config import AgentGraphError + + crew = make_crew( + [agent("coordinator", sub_agents=("general_purpose",)), agent("general_purpose")], + subagents=GENERAL, + ) + + with pytest.raises(AgentGraphError) as exc: + await crew.turn() + + assert str(exc.value) == ( + "An agent named 'general_purpose' clashes with the built-in general_purpose type, " + "which this app's SubAgentPolicy enables." + ) + + +class TestTheGeneralPurposeType: + """``SubAgentPolicy.general_purpose``: a run that may start a type may start + the built-in ``general_purpose`` one, offered last, made for the caller's + type: that type's own tools (but ``task`` and the parent's other tools), + its model, the framework's prompt.""" + + async def test_the_root_starts_one_with_its_own_tools_model_and_prompt(self, make_crew): + crew = make_crew( + general_team(), subagents=GENERAL, + coordinator=[calls(delegate("general_purpose", "Sum it up.", "c1")), says("Done.")], + general_purpose=[calls(use("contract_lookup", "g1", q="x")), says("Summed.")], + ) + + with no_blocking_calls(): + events = await crew.turn() + + assert envelope_read(crew.results_read("coordinator")["c1"]) == { + "success": True, "agent": "general_purpose-1", "run": "general_purpose-1#1", + "status": RUN_COMPLETED, "partial": False, "result": "Summed.", "error": None, + } + assert crew.tool_names(GENERAL_PURPOSE) == GENERAL_TOOLS + assert json.loads(crew.results_read(GENERAL_PURPOSE, 1)["g1"]) == { + "success": True, "value": 42, + } + assert crew.system(GENERAL_PURPOSE).startswith(GENERAL_PURPOSE_PROMPT) + assert crew.sent_models(GENERAL_PURPOSE) == ["claude-sonnet-4-6"] * 2 + assert crew.sent_models("coordinator")[0] == "claude-sonnet-4-6" + declared = crew.declared("coordinator") + assert agent_types(declared) == ["researcher", "general_purpose"] + assert declared["description"].endswith( + "- researcher: The researcher.\n" + GENERAL_LINE + ) + assert SPAWN_LIMITS in declared["description"] + started = runs_of(events, RUN_STARTED)[0] + assert (started.run, started.metadata["based_on"]) == (GENERAL_1, "coordinator") + (instance,) = crew.manager.agent_runs.instances(crew.conversation) + assert (instance.agent, instance.based_on, instance.parent, instance.status) == ( + GENERAL_PURPOSE, "coordinator", "root", INSTANCE_IDLE + ) + (record,) = crew.records() + assert list(record.usage) == ["anthropic:claude-sonnet-4-6"] + + async def test_its_skills_start_no_agent(self, make_crew, project): + """The spawner's skills are its own too, but a load of one that starts an + agent is refused: a general-purpose agent starts none.""" + skill = make_skill(project.parent / "skills") + crew = make_crew( + [*general_team(skills=[skill]), helper(spawnable_by=frozenset({"skill"}))], + subagents=SubAgentPolicy(spawn_sources={"agent", "skill"}, general_purpose=True), + coordinator=[calls(delegate("general_purpose", "Research it.", "c1")), + says("Done.")], + general_purpose=[calls(load("research", "g1")), says("Could not.")], + ) + + await crew.turn() + + assert json.loads(crew.results_read(GENERAL_PURPOSE, 1)["g1"]) == refused_by_skill( + "helper", "cannot be started here: sub-agents cannot start sub-agents" + ) + assert [r.ref.instance for r in crew.records()] == ["general_purpose-1"] + + async def test_a_root_without_sub_agents_gets_task_for_it_alone(self, make_crew): + crew = make_crew( + [agent("solo", tools=(contract_lookup,))], subagents=GENERAL, + solo=[calls(delegate("general_purpose", "Look X up.", "c1")), says("Done.")], + general_purpose=[says("X is 42.")], + ) + + await crew.turn() + + assert crew.tool_names("solo") == ["contract_lookup", "task"] + assert agent_types(crew.declared("solo")) == ["general_purpose"] + assert crew.tool_names(GENERAL_PURPOSE) == [ + "contract_lookup", "save_plan", "get_plan", "save_tasks", "get_tasks", + ] + assert envelope_read(crew.results_read("solo")["c1"])["result"] == "X is 42." + + async def test_one_level_down_a_type_starts_one_with_its_tools_and_model(self, make_crew): + crew = make_crew( + [*general_team(), helper(tools=(contract_whoami,), model=CHOICE)], + subagents=SubAgentPolicy(spawn_sources={"agent"}, max_spawn_depth=2, + general_purpose=True), + coordinator=[calls(delegate("helper", "Help with X.", "c1")), says("Done.")], + helper=[calls(delegate("general_purpose", "Find who.", "h1")), says("Helped.")], + general_purpose=[says("You are helper-1's.")], + ) + + await crew.turn() + + assert agent_types(crew.declared("helper")) == ["helper", "general_purpose"] + assert crew.tool_names(GENERAL_PURPOSE) == [ + "contract_whoami", "save_plan", "get_plan", "save_tasks", "get_tasks", + ] + assert crew.sent_models(GENERAL_PURPOSE) == ["claude-haiku-4-5"] + assert crew.sent_models("coordinator")[0] == "claude-sonnet-4-6" + 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"), + ("general_purpose-1", 2, "helper-1#1", "agent:helper-1"), + ] + assert crew.manager.agent_runs.instance( + crew.conversation, "general_purpose-1" + ).based_on == "helper" + assert envelope_read(crew.results_read("helper", 1)["h1"])["result"] == ( + "You are helper-1's." + ) + + async def test_narrowed_to_some_of_its_spawners_tools(self, make_crew): + crew = make_crew( + general_team(), subagents=GENERAL, + coordinator=[calls(delegate("general_purpose", "Look X up.", "c1", + tools=["contract_lookup"])), says("Done.")], + general_purpose=[calls(use("contract_whoami", "g1")), says("Could not.")], + ) + + await crew.turn() + + assert crew.tool_names(GENERAL_PURPOSE) == NARROWED + assert json.loads(crew.results_read(GENERAL_PURPOSE, 1)["g1"]) == WHOAMI_NOT_FOUND + assert SEEN == [] + (instance,) = crew.manager.agent_runs.instances(crew.conversation) + assert instance.tools == ("contract_lookup",) + + @pytest.mark.parametrize("fields, error", [ + ({"tools": ["write_file"]}, + "The tools for 'general_purpose' must be some of its own: contract_lookup, " + "contract_whoami."), + ({"model": CHOICE}, "'general_purpose' has no model choices; leave model out."), + ], ids=["tools", "model"]) + async def test_what_it_cannot_take_starts_no_run(self, make_crew, fields, error): + crew = make_crew( + general_team(), subagents=GENERAL, + coordinator=[calls(delegate("general_purpose", "Look X up.", "c1", **fields)), + says("Done.")], + ) + + events = await crew.turn() + + assert json.loads(crew.results_read("coordinator", 1)["c1"]) == { + "success": False, "error": error, + } + assert (runs_of(events), crew.records(), crew.requests(GENERAL_PURPOSE)) == ([], [], 0) + + async def test_a_follow_up_runs_on_the_same_build_and_after_a_restart(self, make_crew): + following = SubAgentPolicy(follow_ups=True, spawn_sources={"agent"}, general_purpose=True) + first = make_crew( + general_team(), subagents=following, store="sqlite", + coordinator=[calls(delegate("general_purpose", "Find X.", "c1")), says("Asked."), + calls(message("general_purpose-1", "Now find Y.", "c2")), + says("Asked again.")], + general_purpose=[says("X is 42."), says("Y is 7.")], + ) + await first.turn() + await first.turn("Find Y too.") + await first.manager.cleanup() + second = make_crew( + general_team(), subagents=following, store="sqlite", + coordinator=[calls(message("general_purpose-1", "Now find Z.", "c3")), + says("Done.")], + general_purpose=[says("Z is 3.")], + ) + + await second.turn("And Z.") + + assert envelope_read(first.results_read("coordinator")["c2"])["result"] == "Y is 7." + assert envelope_read(second.results_read("coordinator")["c3"])["run"] == ( + "general_purpose-1#3" + ) + for crew in (first, second): + assert all( + crew.tool_names(GENERAL_PURPOSE, n) == GENERAL_TOOLS + for n in range(crew.requests(GENERAL_PURPOSE)) + ) + assert crew.system(GENERAL_PURPOSE).startswith(GENERAL_PURPOSE_PROMPT) + assert "Y is 7." in second.bodies(GENERAL_PURPOSE)[0] + (instance,) = second.manager.agent_runs.instances(second.conversation) + assert (instance.based_on, instance.runs) == ( + "coordinator", ["general_purpose-1#1", "general_purpose-1#2", "general_purpose-1#3"] + ) + + +class TestTheGeneralPurposeTypeStartsNone: + async def test_below_the_depth_limit_it_has_no_task_and_no_follow_up_tools(self, make_crew): + deep = SubAgentPolicy(follow_ups=True, spawn_sources={"agent"}, max_spawn_depth=3, + general_purpose=True) + crew = make_crew( + general_team(), subagents=deep, + coordinator=[calls(delegate("general_purpose", "Look X up.", "c1")), says("Done.")], + general_purpose=[says("X is 42.")], + ) + + await crew.turn() + + # The coordinator's own, the researcher it delegates to and the plan's tools: + # nothing that starts or follows an agent. + assert crew.tool_names(GENERAL_PURPOSE) == GENERAL_TOOLS + assert crew.tool_names("coordinator")[-4:] == [ + "task", "message_agent", "stop_agent", "check_agents", + ] + + async def test_with_the_default_policy_none_is_built(self, make_crew): + crew = make_crew(general_team(), coordinator=[says("Hi.")]) + + await crew.manager.initialize_services() + + manager = crew.manager + assert not any( + getattr(manager, name, None) + for name in ("_general_agents", "_general_runners", "_general_graphs") + ) + + +class TestTheGeneralPurposeTypeFromASkillAndTheUser: + async def test_a_skill_that_names_it_starts_one_made_for_the_loading_agent( + self, make_crew, project + ): + skill = make_skill(project.parent / "skills", agent_type="general_purpose") + crew = make_crew( + general_team(skills=[skill]), + subagents=SubAgentPolicy(spawn_sources={"skill"}, general_purpose=True), + coordinator=[calls(load("research", "c1")), says("Done.")], + general_purpose=[says("Found it.")], + ) + + events = await crew.turn() + + assert envelope_read(crew.results_read("coordinator")["c1"]) == { + "success": True, "agent": "general_purpose-1", "run": "general_purpose-1#1", + "status": RUN_COMPLETED, "partial": False, "result": "Found it.", "error": None, + "skill": "research", + } + assert crew.last_message(GENERAL_PURPOSE, 0) == RESEARCH_TASK + # The loading agent's tools, its skills' too. + assert crew.tool_names(GENERAL_PURPOSE) == [ + *GENERAL_TOOLS, "list_skills", "load_skill", "load_skill_resource", + ] + assert crew.system(GENERAL_PURPOSE).startswith(GENERAL_PURPOSE_PROMPT) + started = runs_of(events, RUN_STARTED)[0] + assert (started.metadata["started_by"], started.metadata["based_on"]) == ( + "skill:research", "coordinator" + ) + + async def test_the_user_starts_one_made_for_the_root(self, make_crew): + crew = make_crew( + general_team(), + subagents=SubAgentPolicy(spawn_sources={"user"}, general_purpose=True), + general_purpose=[calls(use("contract_whoami", "g1")), says("Summed.")], + ) + + events = await user_start(crew, "general_purpose", "Sum it up.") + + started, ended = runs_of(events) + assert events[0] is started + assert (started.run, started.metadata["started_by"], started.metadata["based_on"]) == ( + GENERAL_1, "user", "coordinator" + ) + assert ended.metadata["result"] == "Summed." + assert crew.tool_names(GENERAL_PURPOSE) == GENERAL_TOOLS + assert SEEN == [(GENERAL_1, "g1")] + assert crew.requests("coordinator") == 0 + assert crew.manager._delegations.startable_by_user() == ("general_purpose",) + + +#: The stdio MCP server the MCP tests start (``atlas_add``, ``atlas_lookup`` +#: here); each process records its pid. +MCP_SERVER = Path(__file__).parent / "deepagents" / "mcp_server.py" + + +def _alive(pid: int) -> bool: + import os + + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + return True + + +#: What ADK itself says as its MCP toolset connects and lists tools (its own +#: ``MCPTool`` class's deprecation, three experimental features it turns on): a +#: scenario with an MCP server on ADK filters exactly these. +ADK_MCP_WARNINGS = pytest.mark.filterwarnings( + "ignore:MCPTool class is deprecated:DeprecationWarning", + r"ignore:\[EXPERIMENTAL\] feature FeatureName\.(_MCP_GRACEFUL_ERROR_HANDLING" + r"|BASE_AUTHENTICATED_TOOL|JSON_SCHEMA_FOR_FUNC_DECL) is enabled:UserWarning", +) + + +class TestAGeneralPurposeAgentAcrossAModelSwitch: + """A general-purpose agent made for a type with an MCP server has + connections of its own: across a model switch (``reinitialize``) each + connection opens once and closes once, the spawner's own MCP tools keep + working, and a follow-up of the general-purpose instance runs on the new + build (its spawner's new model).""" + + @ADK_MCP_WARNINGS + async def test_each_connection_opens_and_closes_once(self, make_crew, project): + pytest.importorskip("mcp") + from agentic_cli.workflow.mcp import MCPServerConfig + + pids = project.parent / "server-pids" + pids.mkdir() + server = MCPServerConfig( + name="atlas", command=sys.executable, args=[str(MCP_SERVER)], timeout=30, + env={"MCP_TEST_PID_DIR": str(pids)}, tool_name_prefix="atlas", + ) + crew = make_crew( + general_team(mcp_servers=[server]), + subagents=SubAgentPolicy(follow_ups=True, spawn_sources={"agent"}, + general_purpose=True), + coordinator=[calls(use("atlas_add", "c0", a=1, b=2)), + calls(delegate("general_purpose", "Add 2 and 3.", "c1")), says("Asked."), + calls(use("atlas_add", "c2", a=3, b=4)), + calls(message("general_purpose-1", "Now 4 and 5.", "c3")), says("Done.")], + general_purpose=[calls(use("atlas_add", "g1", a=2, b=3)), says("5."), + calls(use("atlas_add", "g2", a=4, b=5)), says("9.")], + ) + + async def allow_once(request: UserInputRequest) -> str: + return ALLOW_ONCE_CHOICE + + crew.answer_with(allow_once) + opened = lambda: sorted(int(p.name) for p in pids.iterdir()) # noqa: E731 + try: + await crew.turn() + before = opened() + await crew.manager.reinitialize(model="claude-opus-4-7", preserve_sessions=True) + await crew.turn("Again.") + after = opened() + alive_after = [pid for pid in after if _alive(pid)] + finally: + await crew.manager.cleanup() + + # The spawner's and the general-purpose agent's, then each anew. + assert len(before) == 2 and len(after) == 4 + assert sorted(set(after) - set(before)) == alive_after + assert [pid for pid in after if _alive(pid)] == [] + assert ["3" in crew.results_read("coordinator", 1)["c0"], + "7" in crew.results_read("coordinator", -2)["c2"], + "5" in crew.results_read(GENERAL_PURPOSE, 1)["g1"], + "9" in crew.results_read(GENERAL_PURPOSE, -1)["g2"]] == [True] * 4 + assert crew.sent_models(GENERAL_PURPOSE) == [ + "claude-sonnet-4-6", "claude-sonnet-4-6", "claude-opus-4-7", "claude-opus-4-7", + ] + assert "5." in crew.bodies(GENERAL_PURPOSE)[2] + assert envelope_read(crew.results_read("coordinator")["c3"])["result"] == "9."