diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2e84146b..38ea75a5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -575,6 +575,48 @@ the start of the entry's title.
### Added
+- **The main agent's requests list its open sub-agents, when it can continue
+ them.** With `SubAgentPolicy(follow_ups=True)` a main agent with sub-agents
+ (it has `message_agent`) is told which of its own sub-agents are open: a
+ roster after the memory index, ``, the line `Your sub-agents in
+ this conversation (message_agent continues one):`, then one line per
+ idle, stopped or running instance, newest first, `- (,
+ ): ` and ` — `, then
+ ``; at most 2,000 characters, the oldest lines left out, never
+ cut (`agentic_cli.workflow.agents.roster`: `roster_text`, `ROSTER_OPEN`,
+ `ROSTER_CLOSE`, `ROSTER_HEADER`, `ROSTER_MAX`, provisional). It is a
+ snapshot per conversation, taken and dropped where the memory index's is
+ (the conversation opened, a summary written, `/compact`), so the head of
+ the request stays the same for prompt caching; the tool results and
+ notices in the conversation carry what changed since. On ADK it is a user
+ content of its own after the index (`RosterPlugin`): the fit guard never
+ drops it and folds the index, the roster and a summary into the first user
+ text, in that order, and the overflow retry keeps it; on Deep Agents the
+ text block after the index's in the first human message
+ (`RosterMiddleware`), counted by the summarization. With the policy's
+ defaults, and when every sub-agent is closed, there is none. A manager
+ reaches it through `_roster_wanted(root)` and `_roster_now()`;
+ `_forget_memory_index` drops it with the index's.
+- **A sub-agent instance's brief survives its growing transcript, on both
+ backends.** A follow-up's own message is not its instance's brief, so a
+ long transcript could lose the brief from the requests: on Deep Agents a
+ summary of the instance's thread stood for it, on ADK the fit guard could
+ leave it out of a follow-up's request. An instance's first run now marks
+ its message as the brief, and it is kept in every later request. On Deep
+ Agents the instance's own summarization (on its model, against its
+ budget) writes each summary that stands for the brief as a message that
+ opens with the brief's text (`summarization.brief_message`, `is_brief`,
+ `brief_of`); on ADK, where summaries stay the main agent's, the fit guard
+ and the overflow retry keep the brief whatever they leave out, the turns
+ after it joining it as the run's task message does (the event that set
+ `adk/sessions.py::BRIEF_KEY`, `agentic_cli.brief`, in the child session:
+ `fit_guard_plugin.brief_of`; `drop_turns(brief=)`). The difference is the
+ libraries': Deep Agents' summary also stands for a follow-up's own message
+ once it is older than what a summary keeps word for word, where ADK's
+ trim keeps it. An instance's summary that would stand for less than a fifth
+ of its trigger is not written (the brief restated in each summary can keep
+ a long brief near the trigger), as ADK's is not. The main agent's
+ summaries are unchanged.
- **A parent's tools that continue its sub-agents, `message_agent`,
`stop_agent` and `check_agents`, on both backends, with
`SubAgentPolicy(follow_ups=True)`.** Every agent with sub-agents gets them
diff --git a/CLAUDE.md b/CLAUDE.md
index 33c24c7b..34c70707 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -49,7 +49,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); 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 and the load mark dropped); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built: each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it))
+│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none); the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget and the load mark dropped); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built: each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete))
│ │ ├── 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
@@ -82,16 +82,17 @@ agentic-cli/
│ │ │ ├── capabilities.py # Capability, EXEMPT
│ │ │ ├── matchers.py # PathMatcher, URLMatcher, ShellMatcher, StringGlobMatcher
│ │ │ └── rules.py, store.py, prompt.py (build_request(run=): a sub-agent's prompt opens with its run; is_permission_request: by its perm- id)
-│ │ ├── agents/ # Sub-agents: runs.py: the RUN_* statuses (a working run's: RUN_QUEUED, RUN_RUNNING, RUN_INPUT_REQUIRED, RUN_WORKING_STATUSES; a record says running from its start), INSTANCE_RUNNING/IDLE/STOPPED/CLOSED and INSTANCE_STATUSES, InstanceRecord (an instance: parent, depth, title, status, runs, continuable), RunRecord (input: a follow-up's message as written, "" for a first run), AgentRuns (a manager's runs and instances by conversation: run_for names - and its first run #1 per (conversation, parent run, call id), a new one once it ended; next_run: an instance's next run; instances/instance, kept from the events: a start makes or reopens the instance running, an end sets its status from instance_status, AGENT_INSTANCE a change without a run; number_from: past the instances a conversation's store keeps, a count never lowered; observe records AGENT_RUN under the turn it is reported in; interrupt_open; a record's usage: what the run used, by model, from its end event or the ledger; its plan and tasks: the run's own last, from its end event; RECORDS_VERSION, export (a conversation's records as JSON-safe data: v, saved, numbered, instances, runs) and restore (replaces them; a run found working ends interrupted, INTERRUPTED_ERROR, at the later of its start and saved, its instance idle, closed for a type that is not continuable; each run's end order stored (end), any time or field that does not read ValueError; counters never below an instance kept; ValueError for another version or records that do not read, nothing changed), stored_instance_ids (the instances stored records name; None for none), AgentRuns(on_change=): told each change, never by restore), run_title, result_head, run_instance and run_number (the one reader of a run id: researcher-2#1's instance and number), run_label (how a dialog names a run: researcher-2 (researcher, run 1)), SUBAGENT_ERROR_PREFIX (ADK's old words for a failed delegation, kept for callers), show_as_delegation(result, envelope) (a delegation's TOOL_RESULT shown alike on both backends: the result's first line, or Failed: ; metadata["result"] the envelope); a record's brief, started_by, mode and cancelled_by; delegate.py: Delegations (delegate(DelegationRequest) → Delegated and follow_up(FollowUpRequest) → Delegated: the one place a run starts and ends, on both backends (a follow-up is the instance's next run through the same hook, AgentRun.follow_up: refused as an error result, no run, for an unknown or not-yours instance (NOT_YOURS_ERROR, YOURS, NO_SUB_AGENTS), a closed one (CLOSED_ERROR), one the user stopped when an agent sends it (STOPPED_ERROR), a running one (RUNNING_ERROR), one whose type the app no longer has (TYPE_GONE_ERROR) and a blank message (NO_MESSAGE_ERROR); an agent's counts toward max_runs_per_turn, the user's (started_by USER) does not; a run's end carries the status it leaves its instance in: stopped for the user's cancel, closed for a type that is not continuable or the oldest idle one past max_open, else idle; close(conversation, instance, reason=): an idle or stopped instance and its descendants, AGENT_INSTANCE closed; open_calls=: the manager's OpenCalls, whose stop recorded for an instance is taken when the instance is left closed (its end, close, max_open, or a turn that stops a one-shot run), so its calls are freed; max_open ranks by AgentRuns.end_order, the order ends were recorded in, never the clock): the brief read against the caller's own sub-agents, the run named (a turn's first run past the instances its conversation's store keeps: stored=, asked once per conversation per turn, again after a failed or stopped ask), its AGENT_RUN start and end observed and reported, the backend's hook (RunHook: AgentRun → RunAnswer) run in a task of its own with the run active and no tool call, the end by the answer (completed, partial for a cut or the step limit, refused, failed for an error or a raise, with one recoverable ERROR 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, FollowUpRequest, AgentRun (control, follow_up), RunAnswer, RunFailed, started_by, waiting_on_user (a sub-agent run waiting on the user: input_required, its slot lent, queued while its take-back waits for a slot, then running; nested waits once; request_user_input and the permission engine); records.py: RecordsWriter (each conversation's records written to its store as they change: changed, one write at a time per conversation taking the records as it starts, so changes made meanwhile go together in the next; flush, flush_all, discard (a delete's: what waits dropped, the write under way waited for); a failed write warned once per conversation, subagent_records_not_saved, never raised); slots.py: SlotPool (acquire(priority): a free slot, else a future in a heap by priority, RETURNING before NEW, then arrival; release; lent(slot, on_wait=): the slot lent while its run waits, nested lends once, taken back at RETURNING after (on_wait called when that has to wait), at most one take-back waiting for a slot and none once it is held (a wait that starts while one is queued takes it over, and one handed the slot withdraws any queued since), nothing taken back after a cancel, so a tool's caught timeout around a question leaves its run working without a slot, input_required until its next question is answered (running again, still without a slot) or its end; hand_back(slot, to): a child's slot to its parent waiting on it alone; free, waiting; a cancelled waiter leaves the heap, one handed a slot as it is cancelled hands it on; not asyncio.Semaphore), Slot (held, lent), RETURNING, NEW; control.py: RunControl (one run's: cancel(by=, error=) its task, the first cancel winning, own_cancel for the hook that takes it and returns, finish: the hook's work ended, no cancel after it (ADK's state read loses no answer), timing: the time limit while the hook runs; model_call/at_step_limit/final_call: the step limit, STEP_LIMIT_NOTE on the last allowed call; used: the token limit, against its own calls and side_tokens (its side calls and summaries, from the ledger), an answer past it that makes calls the run's last, cancelled by it, one that makes none its result (calls=); model_call once final stays final; a cancel leaves a task its turn is cancelling alone; steer/take_steering), STEP_LIMIT_NOTE; outcome.py: a sub-agent's refused or cut answer (outcome_of, the refusal notice as Deep Agents 0.7.34 words it, cut_off, cut_off_warning, OPENAI_REFUSAL_PREFIX: how ADK's OpenAI adapters word a refusal); policy.py: SubAgentPolicy (max_active, max_runs_per_turn, limits, max_open) and AgentLimits (max_model_calls, timeout, max_tokens; over: a type's limits over the policy's, field by field, None taking the base's), DEFAULT_LIMITS (100 model calls), frozen and checked as they are made (a ValueError naming the field), as_policy (the one reading of a subagents= argument: a TypeError for anything but a policy or None); brief.py: BRIEF_FIELDS, Brief, BriefError, read_brief (a task call's agent type and brief, against the types its caller may start: the error texts), task_message (a run's first message, a section per filled field; an inheriting type's ends with INHERITED_CONTEXT_NOTE), task_parameters and task_description (task's schema and description, the same for both backends; limit_sentences: the limits it states, "At most sub-agents work at once; more calls in one response wait for a free slot. At most runs per turn."); envelope.py: envelope (a delegation run's result: success only for completed, a one-line error, cancelled_by for a cancelled run), read_envelope (a dict or its JSON text, else None; never raises), 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_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)
+│ │ ├── agents/ # Sub-agents: runs.py: the RUN_* statuses (a working run's: RUN_QUEUED, RUN_RUNNING, RUN_INPUT_REQUIRED, RUN_WORKING_STATUSES; a record says running from its start), INSTANCE_RUNNING/IDLE/STOPPED/CLOSED and INSTANCE_STATUSES, InstanceRecord (an instance: parent, depth, title, status, runs, continuable), RunRecord (input: a follow-up's message as written, "" for a first run), AgentRuns (a manager's runs and instances by conversation: run_for names - and its first run #1 per (conversation, parent run, call id), a new one once it ended; next_run: an instance's next run; instances/instance, kept from the events: a start makes or reopens the instance running, an end sets its status from instance_status, AGENT_INSTANCE a change without a run; number_from: past the instances a conversation's store keeps, a count never lowered; observe records AGENT_RUN under the turn it is reported in; interrupt_open; a record's usage: what the run used, by model, from its end event or the ledger; its plan and tasks: the run's own last, from its end event; RECORDS_VERSION, export (a conversation's records as JSON-safe data: v, saved, numbered, instances, runs) and restore (replaces them; a run found working ends interrupted, INTERRUPTED_ERROR, at the later of its start and saved, its instance idle, closed for a type that is not continuable; each run's end order stored (end), any time or field that does not read ValueError; counters never below an instance kept; ValueError for another version or records that do not read, nothing changed), stored_instance_ids (the instances stored records name; None for none), AgentRuns(on_change=): told each change, never by restore), run_title, result_head, run_instance and run_number (the one reader of a run id: researcher-2#1's instance and number), run_label (how a dialog names a run: researcher-2 (researcher, run 1)), SUBAGENT_ERROR_PREFIX (ADK's old words for a failed delegation, kept for callers), show_as_delegation(result, envelope) (a delegation's TOOL_RESULT shown alike on both backends: the result's first line, or Failed: ; metadata["result"] the envelope); a record's brief, started_by, mode and cancelled_by; delegate.py: Delegations (delegate(DelegationRequest) → Delegated and follow_up(FollowUpRequest) → Delegated: the one place a run starts and ends, on both backends (a follow-up is the instance's next run through the same hook, AgentRun.follow_up: refused as an error result, no run, for an unknown or not-yours instance (NOT_YOURS_ERROR, YOURS, NO_SUB_AGENTS), a closed one (CLOSED_ERROR), one the user stopped when an agent sends it (STOPPED_ERROR), a running one (RUNNING_ERROR), one whose type the app no longer has (TYPE_GONE_ERROR) and a blank message (NO_MESSAGE_ERROR); an agent's counts toward max_runs_per_turn, the user's (started_by USER) does not; a run's end carries the status it leaves its instance in: stopped for the user's cancel, closed for a type that is not continuable or the oldest idle one past max_open, else idle; close(conversation, instance, reason=): an idle or stopped instance and its descendants, AGENT_INSTANCE closed; open_calls=: the manager's OpenCalls, whose stop recorded for an instance is taken when the instance is left closed (its end, close, max_open, or a turn that stops a one-shot run), so its calls are freed; max_open ranks by AgentRuns.end_order, the order ends were recorded in, never the clock): the brief read against the caller's own sub-agents, the run named (a turn's first run past the instances its conversation's store keeps: stored=, asked once per conversation per turn, again after a failed or stopped ask), its AGENT_RUN start and end observed and reported, the backend's hook (RunHook: AgentRun → RunAnswer) run in a task of its own with the run active and no tool call, the end by the answer (completed, partial for a cut or the step limit, refused, failed for an error or a raise, with one recoverable ERROR 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, FollowUpRequest, AgentRun (control, follow_up), RunAnswer, RunFailed, started_by, waiting_on_user (a sub-agent run waiting on the user: input_required, its slot lent, queued while its take-back waits for a slot, then running; nested waits once; request_user_input and the permission engine); records.py: RecordsWriter (each conversation's records written to its store as they change: changed, one write at a time per conversation taking the records as it starts, so changes made meanwhile go together in the next; flush, flush_all, discard (a delete's: what waits dropped, the write under way waited for); a failed write warned once per conversation, subagent_records_not_saved, never raised); slots.py: SlotPool (acquire(priority): a free slot, else a future in a heap by priority, RETURNING before NEW, then arrival; release; lent(slot, on_wait=): the slot lent while its run waits, nested lends once, taken back at RETURNING after (on_wait called when that has to wait), at most one take-back waiting for a slot and none once it is held (a wait that starts while one is queued takes it over, and one handed the slot withdraws any queued since), nothing taken back after a cancel, so a tool's caught timeout around a question leaves its run working without a slot, input_required until its next question is answered (running again, still without a slot) or its end; hand_back(slot, to): a child's slot to its parent waiting on it alone; free, waiting; a cancelled waiter leaves the heap, one handed a slot as it is cancelled hands it on; not asyncio.Semaphore), Slot (held, lent), RETURNING, NEW; control.py: RunControl (one run's: cancel(by=, error=) its task, the first cancel winning, own_cancel for the hook that takes it and returns, finish: the hook's work ended, no cancel after it (ADK's state read loses no answer), timing: the time limit while the hook runs; model_call/at_step_limit/final_call: the step limit, STEP_LIMIT_NOTE on the last allowed call; used: the token limit, against its own calls and side_tokens (its side calls and summaries, from the ledger), an answer past it that makes calls the run's last, cancelled by it, one that makes none its result (calls=); model_call once final stays final; a cancel leaves a task its turn is cancelling alone; steer/take_steering), STEP_LIMIT_NOTE; outcome.py: a sub-agent's refused or cut answer (outcome_of, the refusal notice as Deep Agents 0.7.34 words it, cut_off, cut_off_warning, OPENAI_REFUSAL_PREFIX: how ADK's OpenAI adapters word a refusal); policy.py: SubAgentPolicy (max_active, max_runs_per_turn, limits, max_open) and AgentLimits (max_model_calls, timeout, max_tokens; over: a type's limits over the policy's, field by field, None taking the base's), DEFAULT_LIMITS (100 model calls), frozen and checked as they are made (a ValueError naming the field), as_policy (the one reading of a subagents= argument: a TypeError for anything but a policy or None); brief.py: BRIEF_FIELDS, Brief, BriefError, read_brief (a task call's agent type and brief, against the types its caller may start: the error texts), task_message (a run's first message, a section per filled field; an inheriting type's ends with INHERITED_CONTEXT_NOTE), task_parameters and task_description (task's schema and description, the same for both backends; limit_sentences: the limits it states, "At most sub-agents work at once; more calls in one response wait for a free slot. At most runs per turn."); envelope.py: envelope (a delegation run's result: success only for completed, a one-line error, cancelled_by for a cancelled run), read_envelope (a dict or its JSON text, else None; never raises), 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_cause(run)` and `cancel(..., conversation=)`; a message steered to a run that its transcript does not hold when it ends (`RunControl.unstored`) is kept for the instance's next run; a run whose parent's run its control stopped ends `cancelled` by its parent (`its parent's run was stopped`); a run that did not complete fully names its open tasks in its envelope (`envelope(open_tasks=)`, `open_task_descriptions`) and a cancelled run keeps its plan and tasks; `SubAgentPolicy.follow_ups`; brief.py: `follow_up_description`/`follow_up_parameters` (the parent's tools' texts); follow_ups.py: `call_follow_up_tool` (a message_agent, stop_agent or check_agents call as the run in progress); roster.py: roster_text (the main agent's open sub-agents, newest first, one line each, ROSTER_OPEN/ROSTER_HEADER/ROSTER_CLOSE, at most ROSTER_MAX characters in whole lines, "" for none open), Rosters (a snapshot per conversation, as MemoryIndex: now, forget, clear; the root's own instances, parent root)
│ │ ├── adk/ # ADK orchestrator
│ │ │ ├── manager.py # GoogleADKWorkflowManager (the agents built from configs or, adk_config_path, by ADK from a native YAML (library-only: no BaseCLIApp starts one; loaded once per manager at the first _validate_agent_graph (_native_root: the settings' keys exported first; a retry, a model switch and a start after cleanup build on the same tree, whose toolsets the closed runner left reusable), its agents' models resolved leniently in _resolve_extra_models, the base's hook, its registered tools' services detected; configs passed with it ignored, adk_native_configs_ignored): the only difference; _do_initialize builds the app from the tree alone, _build_app → ADKBuild, through the hooks _plugin_chain (the whole chain, top to bottom, its head _init_plugins), _compaction_config (None for a root without a budget), _context_cache_config, _agent_model_refs; the event processor built from the build; a config-built agent's prompt as an instruction provider, sent as written: no `{name}` state injection; _compact_turn: ADK's compaction once, in the base's compact turn; supports_compact False once built for a root without a budget (_no_compact_support says why); the job resume hooks: _conversation_exists (the session read without its events, num_recent_events=0), _deliver_job_notice (the notice, for every app); _run_config: the agents' synchronous tools run in ADK's tool thread pool, 8 workers; _run_and_stream: a run that fails yields the turn's one ERROR, last, none after an ERROR already yielded, and keeps the record of its calls that returned for the next turn (OpenCalls.failed; _answer_left_open forgets it once its answers are stored); the agents: _create_agents builds each config's agent on its own (_agents, by name; no ADK sub_agents), a delegating one with a TaskTool (its own tool named task: AgentGraphError); a runner per sub-agent type (_agent_runners: NoAfterTurnCompactionRunner on App(name=child_app(app_name), root_agent=the type's agent, plugins=_agent_plugin_chain(agent), the app's context cache, no compaction) over the session service, closed with the main runner by _detach_backend, rebuilt by every initialization); _run_agent, the base's hook: the instance's child session (_child_session: a first run makes it from run.state and an inheriting instance's copied events, once; never one the store keeps, whose instance numbering goes past: ADK's create_session refuses it, and the run fails; a follow-up takes the stored session, answers the calls an earlier run left open there (left_open_by) and passes the caller's mark when it holds none; one the store lost is made as a first run's), _stored_instances (the base's hook: the highest instance number of each type the conversation's child sessions keep), the type's runner on the task message (a follow-up's own message) with an abort signal set before it is closed, a run-mode ADKEventProcessor, the raw log's records reported as they come (_report_raw_log); a model's failure raised as the provider's (_plugin_cause), an overflow RunFailed, a reply that is no answer RunAnswer(error=), the shared keys it changed read back)
│ │ │ ├── build.py # ADKBuild (root, reply_agents, plugins, compaction, cache, models); load_native_root (from_config at validation; what ADK cannot load, wrapped as AgentGraphError naming the file, ADK's error the cause; a root that is not an LlmAgent, a name used twice in the tree and a task-mode agent refused, AgentGraphError naming it; ensure_direct_anthropic); what the run reads of any tree: reply_agents (the root and the chat-mode agents it can transfer to), own_after_tool_agents (left out by the cap)
│ │ │ ├── task_tool.py # TaskTool: the framework's task on ADK (a BaseTool; its declaration task_parameters' JSON schema, parameters_json_schema; its description task_description; bound to the task declaration, an exact TaskTool only): a call → Delegations.delegate, the run's shared-key changes written to the caller's state, the envelope returned as JSON text (ADK's OpenAI Responses adapter sends only a dict's result); SHARED_KEYS (the outside-content mark alone); inherited_events (an inheriting run's history: the session's root-visible events, copied); FollowUpTool (with follow_ups: message_agent, stop_agent, check_agents, each an exact FollowUpTool bound to its declaration, the result as JSON text; an own tool of one of their names fails the build)
│ │ │ ├── compaction.py # AgentCliSummarizer (main agent only; summary_range, render_events; its usage normalized, timed and recorded in the conversation's ledger, ledgers, as soon as the call answers: an empty summary's too; on_written: a summary written drops the conversation's memory index snapshot), MainAgentPlugin (the running agent, first in every chain), NoAfterTurnCompactionRunner, compact_session
-│ │ │ ├── fit_guard_plugin.py # FitGuardPlugin: a request over its agent's budget has its oldest turns left out (drop_turns); what opens the conversation, the memory index then a summary (protected_head, never dropped), folded into the next user text (fold_summary); in a sub-agent type's chain (keep_task) a run's task message, its invocation's user content, never dropped either, the first kept turn joining it (a message steered after a tool result starts a turn); request_as_seen
-│ │ │ ├── overflow_plugin.py # OverflowPlugin (OVERFLOW_PLUGIN_FAILED: ADK's wrapper of its errors, which the manager unwraps): a provider's overflow summarized (the root; the retry: the summary and the turns it kept) or trimmed, retried once (the retry timed around its own request: call_clock.mark_latency), then CONTEXT_OVERFLOW: overflow_message for an agent that replies (reply_agents), subagent_overflow_message for a sub-agent's run (root None on its runner), which fails it; a sub-agent's trimmed retry keeps its task message (keep_task)
+│ │ │ ├── fit_guard_plugin.py # FitGuardPlugin: a request over its agent's budget has its oldest turns left out (drop_turns); what opens the conversation, the memory index, the roster, then a summary (protected_head, never dropped; is_roster), folded into the next user text (fold_summary); in a sub-agent type's chain (keep_task) a run's task message, its invocation's user content, and its instance's brief (brief_of: the event of its child session whose state delta set BRIEF_KEY) never dropped either, the first kept turn joining them (a message steered after a tool result starts a turn); request_as_seen
+│ │ │ ├── overflow_plugin.py # OverflowPlugin (OVERFLOW_PLUGIN_FAILED: ADK's wrapper of its errors, which the manager unwraps): a provider's overflow summarized (the root; the retry: the memory index and roster that open the request, the summary and the turns it kept) or trimmed (a sub-agent's keeping its task message and its instance's brief), retried once (the retry timed around its own request: call_clock.mark_latency), then CONTEXT_OVERFLOW: overflow_message for an agent that replies (reply_agents), subagent_overflow_message for a sub-agent's run (root None on its runner), which fails it; a sub-agent's trimmed retry keeps its task message (keep_task)
│ │ │ ├── memory_index_plugin.py # MemoryIndexPlugin: the conversation's memory index first in the root's requests (before the overflow handler and the fit guard, which keep and fold it)
-│ │ │ ├── sessions.py # A conversation's row in its session state (agentic_cli.title, agentic_cli.turns), saved with each user turn (run_async(state_delta=)); typed_prompts; ServiceSessions: the session hooks over a session service (the manager's and its reader's); make_session_service, session_db_url; open_sessions (a reader's store: empty without ADK's sessions table, looked at read-only); CHILD_APP_SUFFIX, child_app (--agents: the sub-agent runs' app, which no conversation list reads), child_session_id (/, the conversation id's % and / percent-encoded, so its first / always ends the conversation and no two conversations share an id; child_of reads one back; a ValueError past ADK's 128 characters; the instance's follow-up runs continue it), delete_children (a conversation's child sessions, events and all: those its records name and every one a listing finds), stored_instances (the highest instance number of each type a conversation's child sessions keep: by the instances its records name, else a listing); RECORDS_KEY (agentic_cli.agents): a conversation's sub-agent records, in the child app's session named as the conversation, encoded (records_session_id, a ValueError past ADK's 128 characters; load_records, save_records: the header under RECORDS_KEY and a key for each instance and run, made at the first write, then one event per write whose state delta holds only the keys that changed; delete_records); ServiceSessions.delete: the transcripts, then the records, then the conversation, whatever its look found
+│ │ │ ├── roster_plugin.py # RosterPlugin: the conversation's roster of the root's open sub-agents first in the root's requests, before MemoryIndexPlugin (which puts the index ahead of it), for a root with message_agent
+│ │ │ ├── sessions.py # A conversation's row in its session state (agentic_cli.title, agentic_cli.turns), saved with each user turn (run_async(state_delta=)); typed_prompts; ServiceSessions: the session hooks over a session service (the manager's and its reader's); make_session_service, session_db_url; open_sessions (a reader's store: empty without ADK's sessions table, looked at read-only); CHILD_APP_SUFFIX, child_app (--agents: the sub-agent runs' app, which no conversation list reads), child_session_id (/, the conversation id's % and / percent-encoded, so its first / always ends the conversation and no two conversations share an id; child_of reads one back; a ValueError past ADK's 128 characters; the instance's follow-up runs continue it), delete_children (a conversation's child sessions, events and all: those its records name and every one a listing finds), stored_instances (the highest instance number of each type a conversation's child sessions keep: by the instances its records name, else a listing); BRIEF_KEY (agentic_cli.brief): set by an instance's first run with its message, marking it as the instance's brief; RECORDS_KEY (agentic_cli.agents): a conversation's sub-agent records, in the child app's session named as the conversation, encoded (records_session_id, a ValueError past ADK's 128 characters; load_records, save_records: the header under RECORDS_KEY and a key for each instance and run, made at the first write, then one event per write whose state delta holds only the keys that changed; delete_records); ServiceSessions.delete: the transcripts, then the records, then the conversation, whatever its look found
│ │ │ ├── event_processor.py # ADKEventProcessor (each call's LLM_USAGE normalized by its model's provider kind, kinds (an agent without one: an unknown kind's), with its latency (call_clock's mark), and recorded in the conversation's ledger before on_event, a run's end with what it used; reply_agents: the agents whose text is the reply; another's, a sub-agent's, marked as activity; a reply that is no answer, NO_ANSWER_CODES, → the turn's ERROR; a failed result, an MCP isError one too, → a failed TOOL_RESULT naming its error, as on Deep Agents; TASK_PROGRESS after a tool call that changed the task list, its state delta's tasks, as on Deep Agents: start_turn forgets the list reported; every event names its run, the agent's own at depth 0, TOOL_CALL and TOOL_RESULT their tool_call_id; a task call's TOOL_RESULT shown as on Deep Agents, from its envelope: show_as_delegation; run=: a processor for one sub-agent run, on its child session, every event that run's, a sub-agent's text activity, no TASK_PROGRESS (a run's list is its own: only the root's is reported), its last answer with text, its outcome mark and its failure kept (answer, outcome, failure: an overflow, a reply that is no answer but an empty one) for _run_agent)
│ │ │ ├── model_factory.py # build_adk_model: ResolvedModel → ADK model, config, planner
│ │ │ ├── openai_compatible.py # OpenAICompatibleLlm (the configured providers: openrouter and openai_compatible kinds; reasoning text; OpenRouter's reasoning_details kept on the thought part (thought_signature, with the model that wrote them) and sent back on that turn's assistant message to that model only; a Chat Completions refusal, streamed or not, as the text ADK's Responses adapter makes of one, "OpenAI refusal: "; no field sent as null; OpenRouter's cache writes, which ADK's usage mapping drops, kept on the usage as cache_creation_input_tokens)
@@ -111,12 +112,12 @@ agentic-cli/
│ │ ├── deepagents/ # Deep Agents orchestrator (deepagents extra); imports neither adk/ nor langgraph/
│ │ │ ├── manager.py # DeepAgentsWorkflowManager (turns, sessions, the release hooks: the agents and MCP sessions, the checkpointer and index; MCP, skills, the job resume hooks (_conversation_exists, _deliver_job_notice), _compact_turn; _run_agent, the base's hook: the type's graph (_agent_graphs) astreamed in the run's task with var_child_runnable_config cleared, so its chunks reach its own loop alone, through a run-mode processor and a RunCallback of its own; the answer the last AIMessage with text, its outcome mark, the shared keys it changed by Deep Agents' _is_unchanged rule (copied), an overflow RunFailed)
│ │ │ ├── agent_builder.py # build_agent_tree: one create_agent per AgentConfig, each on its own (graphs=: kept by name for _run_agent; every agent compiled on the manager's checkpointer, a tree built without one compiling its sub-agents with none); a delegating agent's task from task_tool.build_task_tool (delegations=), its own tool named task an AgentGraphError; every sub-agent's RunControlMiddleware (delegations=), inside its SubAgentOutcomeMiddleware
-│ │ │ ├── middleware.py # InterruptedCallsMiddleware (each call recorded and answered as the active run's; a call id the agent's state holds renamed as the answer arrives, awrap_model_call outside the model side, fresh_call_id; a call answered by a result of its id between its answer and the next), PermissionMiddleware, ToolResultCapMiddleware, ToolCallErrorMiddleware, ActiveToolCallMiddleware (each call the active tool call around its tool), ForeignReasoningMiddleware, ContextOverflowMiddleware, MemoryIndexMiddleware (the root's memory index first in the first human message of each request), SubAgentOutcomeMiddleware (outermost on every sub-agent's model side: a refused or cut final answer rewritten, its reasoning kept, and marked, response_metadata["agentic_cli"]["outcome"], beside the other marks; a call that raises passes), RunControlMiddleware (inside it: a sub-agent run's control at its model calls, Delegations.control of the active run: the messages steered to it added to its state before each call, abefore_model; the call counted and the last allowed one given STEP_LIMIT_NOTE, with_note, its tools still bound; each answer's usage, langchain_tokens, to used; the run's last answer's tool calls dropped, without_calls); mark_latency/answer_latency: the run callback's mark of how long a call took, response_metadata["agentic_cli"]["latency_ms"]; only the gate has a synchronous tool or model wrapper (it denies the sync tool call), the rest wrap with the async ones (`InterruptedCallsMiddleware.before_agent` is a node hook, synchronous, run on async turns too): turns run through `astream`, and a synchronous run of a graph fails at the first without a sync wrapper, LangChain's NotImplementedError
+│ │ │ ├── middleware.py # InterruptedCallsMiddleware (each call recorded and answered as the active run's; a call id the agent's state holds renamed as the answer arrives, awrap_model_call outside the model side, fresh_call_id; a call answered by a result of its id between its answer and the next), PermissionMiddleware, ToolResultCapMiddleware, ToolCallErrorMiddleware, ActiveToolCallMiddleware (each call the active tool call around its tool), ForeignReasoningMiddleware, ContextOverflowMiddleware, MemoryIndexMiddleware (the root's memory index first in the first human message of each request), RosterMiddleware (outside it: the root's roster of its open sub-agents, after the index), SubAgentOutcomeMiddleware (outermost on every sub-agent's model side: a refused or cut final answer rewritten, its reasoning kept, and marked, response_metadata["agentic_cli"]["outcome"], beside the other marks; a call that raises passes), RunControlMiddleware (inside it: a sub-agent run's control at its model calls, Delegations.control of the active run: the messages steered to it added to its state before each call, abefore_model; the call counted and the last allowed one given STEP_LIMIT_NOTE, with_note, its tools still bound; each answer's usage, langchain_tokens, to used; the run's last answer's tool calls dropped, without_calls); mark_latency/answer_latency: the run callback's mark of how long a call took, response_metadata["agentic_cli"]["latency_ms"]; only the gate has a synchronous tool or model wrapper (it denies the sync tool call), the rest wrap with the async ones (`InterruptedCallsMiddleware.before_agent` is a node hook, synchronous, run on async turns too): turns run through `astream`, and a synchronous run of a graph fails at the first without a sync wrapper, LangChain's NotImplementedError
│ │ │ ├── tools.py # to_langchain_tools: a callable → StructuredTool whose .func/.coroutine is it
│ │ │ ├── task_tool.py # build_task_tool: the framework's task on Deep Agents (a StructuredTool over task_parameters' JSON schema, bound to the task declaration): a call → Delegations.delegate, whose shared-key change (the outside-content mark) and envelope (JSON, the ToolMessage) come back as one Command; SHARED_KEYS; inherited_messages (an inheriting run's history: the state's messages, the summary event applied, less the message that called task); build_follow_up_tools (with follow_ups: message_agent, stop_agent, check_agents, each a StructuredTool bound to its declaration, answering as task does)
│ │ │ ├── event_processor.py # DeepAgentsEventProcessor (stream → WorkflowEvent, each call's LLM_USAGE, with its latency (answer_latency), recorded in the conversation's usage ledger before on_event, a run's end with what it used; every event its processor's agent's and run's (run=: a processor for one sub-agent run, its text activity, no TASK_PROGRESS), from the root namespace's items only (a graph a tool runs streams in its own); the task call's TOOL_RESULT shown as on ADK, from its envelope: show_as_delegation); RunCallback (every model call timed, its answer marked with its latency before any middleware sees it; a summary's usage recorded in the conversation's ledger; what a node reports inside itself, through the turn's `LiveEvents`: required; `compact()` called outside a reporting context gets one nobody reads)
│ │ │ ├── sessions.py # thread_id(SessionRef), instance_thread_id and instance_run_config (a sub-agent instance's thread, [app, user, session, instance], its checkpoints' metadata carrying instance and thread_kind: instance), CheckpointSessions (instances: read from the instance threads' first input checkpoints (source input, step -1: no message in them, so the saver unpickles no transcript); stored_instances: those threads and the stored records' ids and counters; agent_records/save_agent_records/delete_agent_records: a conversation's sub-agent records, an item of the store beside the checkpointer under (agentic_cli, agents, , ), keyed by the session id; delete: those threads first, then the records, then the conversation; a first run onto a thread the store keeps fails (the manager's check); rows from an index in the store beside the checkpointer, written as a turn starts (its input counted: a killed process still lists it), then from the newest root checkpoint as it ends and after /compact; a database from before it scanned once per app and user), job notifications; open_sessions: a store's conversations for a reader, without the manager (empty without the checkpoints table, looked at read-only before any setup)
-│ │ │ ├── summarization.py # Each agent's thresholds from its budget (the manager's _budgets, given to build_agent_tree(budgets=); context_budget when none); NoArchiveBackend; history filters; compact()'s cut, summary and event (marked: the count reported before it is no trigger, _should_summarize); OverflowMapped: the summary model's overflows as ContextOverflowError, inside its retry; a request's count includes the memory index (index=), and a summary written drops its snapshot before the request goes on (on_written=)
+│ │ │ ├── summarization.py # Each agent's thresholds from its budget (the manager's _budgets, given to build_agent_tree(budgets=); context_budget when none); NoArchiveBackend; history filters; compact()'s cut, summary and event (marked: the count reported before it is no trigger, _should_summarize); OverflowMapped: the summary model's overflows as ContextOverflowError, inside its retry; a request's count includes the memory index (index=) and the roster (roster=), and a summary written drops their snapshots before the request goes on (on_written=); an instance's brief (brief_message: its first run's task message, marked; is_brief, brief_of: the last marked), restated first in each summary message of its thread that stands for it (_partition_messages, _build_new_messages_with_path, per call through _BRIEF)
│ │ │ ├── mcp_tools.py # MCPSessions: one owner task per (agent, server); the mcp identity map; a call fails once its session ends (_while_open: mcp's stdio client can leave one unanswered)
│ │ │ └── state.py # AgentCliState: plan, tasks (last write wins), outside_content (first write wins)
│ │ └── langgraph/ # LangGraph orchestrator (deprecated, removed in 0.8.0)
@@ -250,7 +251,7 @@ Workflow:
### Key Design Patterns
- **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): 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 when the request has one, 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 then a summary: `protected_head`) 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 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.
+- **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` lists a conversation's runs), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the caller's own sub-agents) and a brief (`workflow/agents/brief.py`: `title`, `objective`, `deliverable`, `constraints`, `known`, `done_when`), its schema and description the same on both backends (`task_parameters`, `task_description`: a line per type with its description, "The agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both: it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents `, 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` (the user's cancel), `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; 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 with sub-agents also gets `message_agent`, `stop_agent` and `check_agents` beside `task` (`workflow/agents/follow_ups.py::call_follow_up_tool` over `Delegations.message`/`stop`/`check`; ADK's `FollowUpTool`, Deep Agents' `build_follow_up_tools`; an own tool of one of their names fails the build, a Deep Agents MCP tool of one is skipped): `message_agent` continues an idle instance, steers a running one (before its next step; a run already stopping or finished is waited for, then the message follows the instance up or is refused; one being closed is refused as closed at once) or, with `interrupt` (refused, nothing cancelled, when no follow-up could start; an agent's keeps the turn's run it checked for), replaces its run (the user's interrupt is the user's stop); `stop_agent` cancels a running run by its parent (the instance idle; only the user's stop makes one `stopped`) and, with `close`, closes it and its descendants; a message steered to a run and not in its transcript when it ends goes to the instance's next run (`RunControl.stored`/`unstored`: ADK counts one stored as its child-session append returns, Deep Agents once the model call after it holds it); a run that did not complete fully names its open tasks in its envelope (`open_tasks`); a run whose parent's run was stopped by its control ends `cancelled` by its parent, not `interrupted`.
- **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.
diff --git a/README.md b/README.md
index b9e60b42..4995d17e 100644
--- a/README.md
+++ b/README.md
@@ -347,7 +347,9 @@ ADK integrations:
`context_summarize_at` of the input budget and `context_max_tokens`),
keeping the current turn and the newest 12% of that word for word; a
sub-agent's run, on its own child session, is never summarized. The fit guard leaves the
- oldest turns out of a request still over its agent's budget, and a
+ oldest turns out of a request still over its agent's budget (never the memory index, the
+ roster of sub-agents or a summary that open the main agent's, nor a sub-agent instance's
+ brief, the message its first run started from), and a
request the provider refuses as too long is summarized or trimmed and
retried once, then ends in one clear error (see
[Context management](#context-management)). A native ADK YAML app gets
@@ -406,7 +408,9 @@ What it supports:
the model's input budget (95% of its context window, less its
`max_tokens`) and `context_max_tokens` (200,000 tokens), keeping the newest
12% of that word for word. A model whose window is unknown counts as
- 128,000 tokens. A request the provider refuses as too long is summarized
+ 128,000 tokens. A sub-agent instance's summary opens with its brief (the
+ message its first run started from), so the brief survives every summary
+ of its thread. A request the provider refuses as too long is summarized
and retried once; a conversation that still does not fit ends the turn
with one error naming the model. A sub-agent's fails only its run, as on
ADK: the user is warned `: the request no longer fits 's
@@ -1418,7 +1422,12 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.",
user's to continue. A run that did not complete fully (partial, failed,
cancelled) names the tasks it left open in its envelope (`open_tasks`),
so its parent can continue it; a message sent to a run that ended before
- reading it reaches its instance's next run.
+ reading it reaches its instance's next run. The main agent's requests then
+ also list its open sub-agents, after the memory index: ``, one line
+ each, newest first (`- researcher-2 (researcher, idle): Find X. — X is 42.`),
+ ``, at most 2,000 characters. The list is taken once and kept, as
+ the memory index is, so the prompt stays cached: it is taken again when the
+ conversation is opened, after a summary and after `/compact`.
- **What the agent graph refuses.** `inherit_context` is for sub-agents only, and
only for the main agent's own sub-agents that have none of their own. A
coordinator cannot have a tool of its own named `task` (nor, with
diff --git a/src/agentic_cli/workflow/adk/fit_guard_plugin.py b/src/agentic_cli/workflow/adk/fit_guard_plugin.py
index 0c8e320f..a3c55399 100644
--- a/src/agentic_cli/workflow/adk/fit_guard_plugin.py
+++ b/src/agentic_cli/workflow/adk/fit_guard_plugin.py
@@ -13,13 +13,16 @@
- Over the agent's budget B, it drops the oldest whole turns from this
request (``drop_turns``) until it is under the agent's trigger: a turn
starts at a user's text, never at a tool result or right after a call, so
- a call keeps its result; the newest turn stays, and so do the memory index
- and a summary that open the conversation (``protected_head``). The first
+ a call keeps its result; the newest turn stays, and so do the memory index,
+ the roster of the main agent's sub-agents and a summary that open the
+ conversation (``protected_head``). The first
kept user content starts with a note, ``FIT_NOTE``, as a part of its own:
no new message, so no provider sees one more user message in a row. The
session is untouched: the next request starts from the whole history again.
- In a sub-agent run's request (``keep_task``: a sub-agent type's chain) the
- run's task message, its invocation's user content, is never left out
+ run's task message, its invocation's user content, and its instance's
+ brief (the event of its child session whose state delta set ``BRIEF_KEY``:
+ ``brief_of``; a follow-up's message is not the brief) are never left out
either: a message steered to the run after a tool result starts a turn,
and the turns between the task message and the first kept one go; that
turn's opening content joins the task message, after the note, as one
@@ -28,8 +31,8 @@
turn.
- When the newest turn alone is over the budget, nothing it could drop would
help: the request goes as it is, and the overflow handler answers.
-- As its last step, what opens the conversation (the memory index, a summary:
- each a user content of its own) is folded into the next content when that
+- As its last step, what opens the conversation (the memory index, the roster, a
+ summary: each a user content of its own) is folded into the next content when that
is a user's text, as parts before its own (``fold_summary``): a strict chat
template refuses two user messages in a row.
@@ -50,7 +53,7 @@
from __future__ import annotations
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from typing import TYPE_CHECKING, NamedTuple
from google.adk.plugins.base_plugin import BasePlugin
@@ -60,12 +63,15 @@
from agentic_cli.memory import INDEX_OPEN
from agentic_cli.workflow import live_events
from agentic_cli.workflow.context import ESTIMATE_MARGIN, chars_per_token
+from agentic_cli.workflow.adk.sessions import BRIEF_KEY
+from agentic_cli.workflow.agents.roster import ROSTER_OPEN
from agentic_cli.workflow.events import WorkflowEvent
from agentic_cli.workflow.summary_prompt import SUMMARY_PREFIX
if TYPE_CHECKING:
from google.adk.agents.callback_context import CallbackContext
from google.adk.agents.invocation_context import InvocationContext
+ from google.adk.events import Event
from google.adk.events.event_actions import EventActions
from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse
@@ -130,7 +136,8 @@ async def before_model_callback(
list(llm_request.contents), config.model_copy() if config is not None else None
))
task = callback_context.user_content if self._keep_task else None
- self._fit(llm_request, agent, budget, kind, task)
+ brief = brief_of(callback_context.session.events) if self._keep_task else None
+ self._fit(llm_request, agent, budget, kind, task, brief)
llm_request.contents = fold_summary(llm_request.contents)
return None
@@ -179,17 +186,20 @@ def _release(self, callback_context: "CallbackContext") -> None:
def _fit(
self, llm_request: "LlmRequest", agent: str, budget: "ContextBudget",
kind: "ProviderKind", task: types.Content | None = None,
+ brief: types.Content | None = None,
) -> None:
"""Leave the oldest turns out of ``llm_request`` when it is over the budget.
- ``task``, a sub-agent run's task message, is never left out.
+ ``task``, a sub-agent run's task message, and ``brief``, its
+ instance's, are never left out.
"""
estimate = estimate_request_tokens(llm_request, kind)
if estimate <= budget.budget:
return
overhead = overhead_tokens(llm_request, kind)
contents, dropped = drop_turns(
- llm_request.contents, target_tokens=budget.trigger - overhead, kind=kind, task=task
+ llm_request.contents, target_tokens=budget.trigger - overhead, kind=kind, task=task,
+ brief=brief,
)
if not dropped or overhead + _tokens(_contents_chars(contents), kind) > budget.budget:
# The newest turn alone is over: the overflow handler answers.
@@ -228,13 +238,13 @@ def overhead_tokens(llm_request: "LlmRequest", kind: "ProviderKind") -> int:
def fold_summary(contents: list[types.Content]) -> list[types.Content]:
- """``contents`` with what opens them (the index, a summary) folded into the next one.
+ """``contents`` with what opens them (the index, the roster, a summary) folded into the next one.
- The index and a summary are user contents of their own. Their parts go
+ The index, the roster and a summary are user contents of their own. Their parts go
before those of the user's text that follows, the index's first, so no
provider sees two user messages in a row. When no user text follows (a
- tool result, a model's turn), an index and a summary become one content.
- A lone index or summary before no user text is left as it is. ``contents``
+ tool result, a model's turn), they become one content.
+ A lone index, roster or summary before no user text is left as it is. ``contents``
are never changed in place.
"""
head = protected_head(contents)
@@ -252,7 +262,7 @@ def fold_summary(contents: list[types.Content]) -> list[types.Content]:
def drop_turns(
contents: list[types.Content], *, target_tokens: float, kind: "ProviderKind",
- task: types.Content | None = None,
+ task: types.Content | None = None, brief: types.Content | None = None,
) -> tuple[list[types.Content], int]:
"""``contents`` without their oldest whole turns, under ``target_tokens`` if it can be.
@@ -260,8 +270,8 @@ def drop_turns(
content that made no call: so a call and its result stay together. Turns
go oldest first, the oldest whatever the target (the caller knows the
request is too big), until the rest, with the note, is under the target;
- the newest turn always stays, and so do the index and a summary that open
- the conversation. The first kept user content gets ``FIT_NOTE`` as a part
+ the newest turn always stays, and so do the index, the roster and a
+ summary that open the conversation. The first kept user content gets ``FIT_NOTE`` as a part
before its own; ``contents`` themselves are left as they are.
``task`` is a sub-agent run's task message (its invocation's user
@@ -270,6 +280,13 @@ def drop_turns(
first kept one's opening content joins it, after the note, as one user
content. An inheriting run's history before it goes first.
+ ``brief`` is the run's instance's brief, which stays as the task message
+ does (a follow-up's task message is its own message, and the brief the
+ turn before it): what is kept opens with the first of them, the note,
+ the other when the cut went past it too, then the first kept turn's
+ opening content. One content when they are the same message (a first
+ run's).
+
Each content is measured once; what goes is subtracted from a running
sum.
@@ -282,7 +299,7 @@ def drop_turns(
starts = [i for i in range(len(body)) if _starts_turn(body, i)]
if not starts or starts[-1] == 0:
return contents, 0
- kept = _task_at(body, task)
+ kept = sorted({at for at in (_brief_at(body, brief), _task_at(body, task)) if at is not None})
sizes = [len(content.model_dump_json(exclude_none=True)) for content in contents]
remaining = sum(sizes) + _NOTE_CHARS
sizes = sizes[len(head):]
@@ -291,13 +308,14 @@ def drop_turns(
previous = 0
for dropped, cut in enumerate(cuts, start=1):
remaining -= sum(sizes[previous:cut])
- if kept is not None and previous <= kept < cut:
- remaining += sizes[kept] # the task message stays
+ # The brief and the task message stay.
+ remaining += sum(sizes[at] for at in kept if previous <= at < cut)
previous = cut
if _tokens(remaining, kind) < target_tokens:
break
- if kept is not None and kept < cut:
- return [*head, _joined(body[kept], body[cut]), *body[cut + 1:]], dropped
+ before = [body[at] for at in kept if at < cut]
+ if before:
+ return [*head, _joined(before, body[cut]), *body[cut + 1:]], dropped
return [*head, _noted(body[cut]), *body[cut + 1:]], dropped
@@ -306,7 +324,7 @@ def keep_newest_turns(
) -> tuple[list[types.Content], int]:
"""``contents`` from their ``turns``-th newest turn on, cut as ``drop_turns`` cuts.
- The index and a summary that open them stay, and the first kept user
+ The index, the roster and a summary that open them stay, and the first kept user
content gets ``FIT_NOTE``. For a retry after a summary: the turns the
summary kept, what every later call sends besides it.
@@ -329,25 +347,57 @@ def _noted(content: types.Content) -> types.Content:
*(content.parts or [])]})
-def _joined(task: types.Content, content: types.Content) -> types.Content:
- """``content`` after ``task`` and ``FIT_NOTE``, as one user content."""
- return content.model_copy(update={"parts": [*(task.parts or []),
- types.Part.from_text(text=FIT_NOTE),
- *(content.parts or [])]})
+def _joined(kept: Sequence[types.Content], content: types.Content) -> types.Content:
+ """``content`` after the first of ``kept``, ``FIT_NOTE`` and the rest of
+ ``kept``, as one user content."""
+ first, *rest = kept
+ return content.model_copy(update={"parts": [
+ *(first.parts or []),
+ types.Part.from_text(text=FIT_NOTE),
+ *(part for other in rest for part in other.parts or []),
+ *(content.parts or []),
+ ]})
+
+
+def _user_contents_like(contents: list[types.Content], like: types.Content | None) -> list[int]:
+ """Where the user contents with ``like``'s parts are in ``contents``."""
+ if like is None:
+ return []
+ return [
+ i for i, content in enumerate(contents)
+ if content.role == "user" and content.parts == like.parts
+ ]
def _task_at(contents: list[types.Content], task: types.Content | None) -> int | None:
"""Where ``task`` (a run's task message) is in ``contents``: the last user
content with its parts; None for none."""
- if task is None:
- return None
- found = [
- i for i, content in enumerate(contents)
- if content.role == "user" and content.parts == task.parts
- ]
+ found = _user_contents_like(contents, task)
return found[-1] if found else None
+def _brief_at(contents: list[types.Content], brief: types.Content | None) -> int | None:
+ """Where ``brief`` (an instance's first message) is in ``contents``: the
+ first user content with its parts; None for none."""
+ found = _user_contents_like(contents, brief)
+ return found[0] if found else None
+
+
+def brief_of(events: Sequence["Event"]) -> types.Content | None:
+ """The brief of the instance whose child session holds ``events``: the
+ content of the first event whose state delta set ``BRIEF_KEY`` (its first
+ run's message), or None.
+
+ A copied conversation (an inheriting instance's) carries no state delta,
+ so a parent's brief is never taken for the child's.
+ """
+ for event in events:
+ delta = event.actions.state_delta if event.actions is not None else None
+ if delta and BRIEF_KEY in delta:
+ return event.content
+ return None
+
+
def _starts_turn(contents: list[types.Content], i: int) -> bool:
if not _users_text(contents[i]):
return False
@@ -380,13 +430,18 @@ def is_memory_index(content: types.Content) -> bool:
return content.role == "user" and bool(first and first.text) and first.text.startswith(INDEX_OPEN)
+def is_roster(content: types.Content) -> bool:
+ """Whether ``content`` is the roster of sub-agents the main agent's requests carry."""
+ first = content.parts[0] if content.parts else None
+ return content.role == "user" and bool(first and first.text) and first.text.startswith(ROSTER_OPEN)
+
+
def protected_head(contents: list[types.Content]) -> list[types.Content]:
- """What opens ``contents`` and is never dropped: the index, then a summary."""
+ """What opens ``contents`` and is never dropped: the index, the roster, then a summary."""
count = 0
- if count < len(contents) and is_memory_index(contents[count]):
- count += 1
- if count < len(contents) and is_summary(contents[count]):
- count += 1
+ for opens in (is_memory_index, is_roster, is_summary):
+ if count < len(contents) and opens(contents[count]):
+ count += 1
return contents[:count]
diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py
index 0d9a6e62..8a3d883b 100644
--- a/src/agentic_cli/workflow/adk/manager.py
+++ b/src/agentic_cli/workflow/adk/manager.py
@@ -69,6 +69,7 @@
from agentic_cli.workflow.adk.permission_plugin import PermissionPlugin
from agentic_cli.workflow.adk.plugins import LLMLoggingPlugin, SentRequestLoggingPlugin
from agentic_cli.workflow.adk.sessions import (
+ BRIEF_KEY,
ServiceSessions,
child_app,
child_session_id,
@@ -677,8 +678,10 @@ def _plugin_chain(
- ``ToolResultCapPlugin``: every result over the limit is cut, but an
agent's with after-tool callbacks of its own, which a cut would
skip (``build.own_after_tool_agents``).
- - ``MemoryIndexPlugin``, when the main agent has a memory tool:
- before the overflow handler and the fit guard, which keep it.
+ - ``RosterPlugin``, when the main agent continues its sub-agents
+ (``_roster_wanted``), then ``MemoryIndexPlugin``, when it has a
+ memory tool, which puts the index ahead of the roster: both before
+ the overflow handler and the fit guard, which keep them.
- ``OverflowPlugin``: a call refused as too long is summarized (the
main agent) or trimmed, retried once from the request the fit guard
saw, then one clear answer; for an agent that replies, the turn's.
@@ -707,6 +710,7 @@ def _plugin_chain(
cache=cache,
skip_agents=own_after_tool_agents(root),
memory_index=self._memory_index_wanted(root.name),
+ roster=self._roster_wanted(root.name),
)
def _agent_plugin_chain(self, agent: LlmAgent) -> list:
@@ -726,7 +730,7 @@ def _agent_plugin_chain(self, agent: LlmAgent) -> list:
model refused or cut is said so, and marked, as its parent reads
it (an answer whose calls the step or token limit dropped among
them);
- - no memory index, and an overflow handler with no main agent: a
+ - no memory index and no roster, and an overflow handler with no main agent: a
sub-agent's overflow, trimmed and retried once, then answers its
call with an error response (``CONTEXT_OVERFLOW``) that ends the
run failed.
@@ -771,6 +775,7 @@ def _chain(
skip_agents: frozenset[str],
memory_index: bool,
stop_cause: Callable[[], str | None] | None = None,
+ roster: bool = False,
) -> list:
"""A plugin chain in the order ``_plugin_chain`` gives, from its ``head`` on.
@@ -794,6 +799,10 @@ def _chain(
)
plugins.append(InterruptedCallsPlugin(self._open_calls, cap, stop_cause=stop_cause))
plugins.append(cap)
+ if roster and root is not None:
+ from agentic_cli.workflow.adk.roster_plugin import RosterPlugin
+
+ plugins.append(RosterPlugin(root=root, roster_for=self._roster_now))
if memory_index and root is not None:
from agentic_cli.workflow.adk.memory_index_plugin import MemoryIndexPlugin
@@ -1648,7 +1657,9 @@ async def _child_session(
the conversation's store: instances are numbered past the ones it
keeps (``_stored_instances``). One it keeps all the same is never
replaced: ADK refuses to make it (``AlreadyExistsError``), and the
- run fails with that.
+ run fails with that. A first run's message carries a state delta that
+ marks it as the instance's brief (``BRIEF_KEY``), which the fit guard
+ keeps in every later run's request.
A follow-up takes the session its instance's earlier runs left: the
calls an earlier run left open there are answered first
@@ -1687,7 +1698,9 @@ async def _child_session(
)
for event in run.history or ():
await service.append_event(session, event)
- return dict(run.state), None
+ if run.follow_up:
+ return dict(run.state), None
+ return dict(run.state), {BRIEF_KEY: run.ref.run}
async def _stored_instances(self, conversation: SessionRef) -> dict[str, int]:
"""The highest instance number of each type ``conversation``'s child sessions keep.
diff --git a/src/agentic_cli/workflow/adk/overflow_plugin.py b/src/agentic_cli/workflow/adk/overflow_plugin.py
index c0be77c5..5864ffde 100644
--- a/src/agentic_cli/workflow/adk/overflow_plugin.py
+++ b/src/agentic_cli/workflow/adk/overflow_plugin.py
@@ -11,14 +11,16 @@
as every later call will be: the summary, then the turns it kept
(``WrittenSummary.kept_turns``, ``fit_guard_plugin.keep_newest_turns``). A
summary that fails is one warning a turn, as one before a model call is.
- The memory index that opens the request stays first in the retry, with
- the summary, and both are folded into its first user text.
+ The memory index and the roster of sub-agents that open the request stay
+ first in the retry, with the summary, and all are folded into its first
+ user text.
- **A sub-agent** (on its own runner, whose chain has this plugin without a
main agent) never summarizes; nor does the main agent when the summary
covers nothing the request holds. The request is then retried with its
oldest whole turns left out down to half the budget
(``fit_guard_plugin.drop_turns``); a sub-agent run's task message, its
- invocation's user content, is never among them (``keep_task``).
+ invocation's user content, is never among them, nor its instance's brief
+ (``keep_task``).
- The retry is built from the request as the fit guard saw it
(``FitGuardPlugin.request_as_seen``, this call's own copy, never a parallel
call's), without the model's context cache: a model's adapter may have
@@ -68,12 +70,13 @@
from agentic_cli.workflow import live_events
from agentic_cli.workflow.adk.call_clock import mark_latency
from agentic_cli.workflow.adk.fit_guard_plugin import (
+ brief_of,
drop_turns,
fold_summary,
- is_memory_index,
is_summary,
keep_newest_turns,
overhead_tokens,
+ protected_head,
report_trim,
)
from agentic_cli.workflow.context import (
@@ -126,7 +129,8 @@ class OverflowPlugin(BasePlugin):
fit_guard: The app's fit guard, whose copy of each request a retry
is built from; without one, the request the callback is given.
keep_task: Whether a trimmed retry keeps its task message (its
- invocation's user content) whatever it leaves out: a sub-agent
+ invocation's user content) and its instance's brief whatever it
+ leaves out: a sub-agent
type's chain, whose runs each start from one.
"""
@@ -177,13 +181,14 @@ async def on_model_error_callback(
target_tokens=budget.budget // 2 - overhead_tokens(request, kind),
kind=kind,
task=callback_context.user_content if self._keep_task else None,
+ brief=brief_of(callback_context.session.events) if self._keep_task else None,
)
if not dropped:
return self._does_not_fit(agent)
if summary is not None:
contents = _with_summary(contents, summary.text)
report_trim(len(request.contents), len(contents), agent, dropped)
- # The index and a summary that open the retry join the next user text.
+ # The index, the roster and a summary that open the retry join the next user text.
contents = fold_summary(contents)
retry = request.model_copy(update={"contents": contents})
model = callback_context.get_invocation_context().agent.canonical_model
@@ -259,13 +264,14 @@ def _does_not_fit(self, agent: str) -> LlmResponse:
def _with_summary(contents: list[types.Content], summary: str) -> list[types.Content]:
- """``contents`` with ``summary`` in place of the one they open with, after the index.
+ """``contents`` with ``summary`` in place of the one they open with, after the index and the roster.
- The memory index, when the contents open with it, stays first. The summary
+ The memory index and the roster, when the contents open with them, stay first. The summary
stands for the one they open with, and is folded as the fit guard folds
(``fold_summary``), so no provider sees one more user message in a row.
"""
- index = contents[:1] if contents and is_memory_index(contents[0]) else []
+ head = protected_head(contents)
+ index = head[:-1] if head and is_summary(head[-1]) else head
rest = list(contents[len(index):])
if rest and is_summary(rest[0]):
remainder = list(rest[0].parts or [])[1:]
diff --git a/src/agentic_cli/workflow/adk/roster_plugin.py b/src/agentic_cli/workflow/adk/roster_plugin.py
new file mode 100644
index 00000000..9f380a3c
--- /dev/null
+++ b/src/agentic_cli/workflow/adk/roster_plugin.py
@@ -0,0 +1,51 @@
+"""The main agent's roster of its open sub-agents, first in its requests.
+
+The roster is a snapshot per conversation (``BaseWorkflowManager._roster_now``,
+``workflow/agents/roster.py``), inserted when each request is built and never
+stored in the session. Registered before ``MemoryIndexPlugin``, which puts the
+memory index ahead of it, and before the overflow handler and the fit guard,
+which keep what opens a request (``protected_head``: the index, the roster,
+then a summary) and fold it into the first user text.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from typing import TYPE_CHECKING
+
+from google.adk.plugins.base_plugin import BasePlugin
+from google.genai import types
+
+if TYPE_CHECKING:
+ from google.adk.agents.callback_context import CallbackContext
+ from google.adk.models.llm_request import LlmRequest
+
+
+def roster_content(text: str) -> types.Content:
+ """The roster as a user content of its own."""
+ return types.Content(role="user", parts=[types.Part.from_text(text=text)])
+
+
+class RosterPlugin(BasePlugin):
+ """Puts the roster of open sub-agents first in the main agent's requests.
+
+ Args:
+ root: The main agent's name; sub-agents get no roster.
+ roster_for: The turn's conversation's roster (``""`` for none). It
+ reads the records in memory only.
+ """
+
+ def __init__(self, *, root: str, roster_for: Callable[[], str]) -> None:
+ super().__init__(name="roster")
+ self._root = root
+ self._roster_for = roster_for
+
+ async def before_model_callback(
+ self, *, callback_context: "CallbackContext", llm_request: "LlmRequest"
+ ) -> None:
+ if callback_context.agent_name != self._root:
+ return None
+ text = self._roster_for()
+ if text:
+ llm_request.contents = [roster_content(text), *llm_request.contents]
+ return None
diff --git a/src/agentic_cli/workflow/adk/sessions.py b/src/agentic_cli/workflow/adk/sessions.py
index 051ea580..d50b15fd 100644
--- a/src/agentic_cli/workflow/adk/sessions.py
+++ b/src/agentic_cli/workflow/adk/sessions.py
@@ -84,6 +84,10 @@
#: The state key of a conversation's sub-agent records, in its records session.
RECORDS_KEY = "agentic_cli.agents"
+#: The state key an instance's first run sets with its message (the run's id),
+#: in its child session: the event that sets it is the instance's brief, which
+#: the fit guard keeps on every later run (``fit_guard_plugin.brief_of``).
+BRIEF_KEY = "agentic_cli.brief"
#: The author of a records session's events (each a write of the records).
RECORDS_AUTHOR = "agentic_cli"
#: The state keys of an instance and a run of the records (then their number).
diff --git a/src/agentic_cli/workflow/agents/roster.py b/src/agentic_cli/workflow/agents/roster.py
new file mode 100644
index 00000000..5c320506
--- /dev/null
+++ b/src/agentic_cli/workflow/agents/roster.py
@@ -0,0 +1,126 @@
+"""The main agent's roster of its open sub-agents.
+
+A main agent that can continue its sub-agents (``message_agent``) is told which
+of its own are open: a list after the memory index, one line per instance that
+is idle, stopped or running, newest first, with its type, status and title and
+the first line of its last result. Closed instances are left out, and so is any
+line that would take the text past ``ROSTER_MAX`` characters (the oldest go;
+``check_agents`` lists them all).
+
+The roster is a snapshot per conversation (:class:`Rosters`), taken when the
+conversation's first request asks for it and dropped where the memory index's
+is, so the head of the request stays the same for prompt caching. Between
+snapshots it is stale: the tool results and notices in the conversation carry
+what changed. ADK puts it in a user content of its own (``RosterPlugin``) and
+Deep Agents in the first human message's text blocks (``RosterMiddleware``),
+the index ahead of it on both.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Mapping, Sequence
+
+from agentic_cli.workflow.agents.runs import (
+ INSTANCE_IDLE,
+ INSTANCE_RUNNING,
+ INSTANCE_STOPPED,
+ AgentRuns,
+ InstanceRecord,
+ RunRecord,
+)
+from agentic_cli.workflow.sessions import SessionRef, get_active_turn
+
+ROSTER_OPEN = ""
+ROSTER_CLOSE = ""
+ROSTER_HEADER = "Your sub-agents in this conversation (message_agent continues one):"
+#: The most characters the roster takes, tags and header included.
+ROSTER_MAX = 2_000
+
+#: The statuses of the instances it lists.
+_LISTED = frozenset({INSTANCE_RUNNING, INSTANCE_IDLE, INSTANCE_STOPPED})
+#: The main agent's instance id: the parent of its own sub-agents.
+_ROOT = "root"
+
+
+def _last_result(instance: InstanceRecord, records: Mapping[str, RunRecord]) -> str:
+ """The first non-blank line of the newest run's result that has one."""
+ for run in reversed(instance.runs):
+ record = records.get(run)
+ if record is None:
+ continue
+ for line in record.result.splitlines():
+ if line.strip():
+ return line.strip()
+ return ""
+
+
+def _line(instance: InstanceRecord, records: Mapping[str, RunRecord]) -> str:
+ line = f"- {instance.instance} ({instance.agent}, {instance.status}): {instance.title}"
+ result = _last_result(instance, records)
+ return f"{line} — {result}" if result else line
+
+
+def roster_text(instances: Sequence[InstanceRecord], records: Mapping[str, RunRecord]) -> str:
+ """The roster of ``instances`` (in the order they started), or ``""`` when none is open.
+
+ Args:
+ instances: The instances to list.
+ records: Their runs' records, by run id.
+ """
+ size = len(ROSTER_OPEN) + len(ROSTER_HEADER) + len(ROSTER_CLOSE) + 2
+ lines: list[str] = []
+ for instance in reversed(instances):
+ if instance.status not in _LISTED:
+ continue
+ line = _line(instance, records)
+ if size + len(line) + 1 > ROSTER_MAX:
+ break
+ lines.append(line)
+ size += len(line) + 1
+ if not lines:
+ return ""
+ return "\n".join([ROSTER_OPEN, ROSTER_HEADER, *lines, ROSTER_CLOSE])
+
+
+class Rosters:
+ """The roster of each conversation, taken once and kept.
+
+ Attributes:
+ snapshots: The roster each conversation took, by conversation. ``""``
+ is a snapshot too (no open instance): the conversation does not
+ ask again until the snapshot is dropped.
+ """
+
+ def __init__(self, runs: Callable[[], AgentRuns]) -> None:
+ """Hold no snapshot yet; ``runs`` gives the records a snapshot is taken from."""
+ self._runs = runs
+ self.snapshots: dict[SessionRef, str] = {}
+
+ def now(self) -> str:
+ """The roster the turn's conversation carries, taken the first time it is
+ asked for; ``""`` for none (and outside a turn).
+
+ It reads the records in memory only.
+ """
+ ref = get_active_turn()
+ if ref is None:
+ return ""
+ text = self.snapshots.get(ref)
+ if text is None:
+ runs = self._runs()
+ text = roster_text(
+ [i for i in runs.instances(ref) if i.parent == _ROOT],
+ {r.ref.run: r for r in runs.records(ref) if r.ref.run},
+ )
+ self.snapshots[ref] = text
+ return text
+
+ def forget(self, ref: SessionRef | None = None) -> None:
+ """Drop a conversation's snapshot (the turn's by default): its next request takes a new one."""
+ ref = ref or get_active_turn()
+ if ref is not None:
+ self.snapshots.pop(ref, None)
+
+ def clear(self) -> None:
+ """Drop every conversation's snapshot."""
+ self.snapshots.clear()
diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py
index 8cdd6ee1..aff43ceb 100644
--- a/src/agentic_cli/workflow/base_manager.py
+++ b/src/agentic_cli/workflow/base_manager.py
@@ -57,6 +57,7 @@
)
from agentic_cli.workflow.agents.policy import SubAgentPolicy, as_policy
from agentic_cli.workflow.agents.records import RecordsWriter
+from agentic_cli.workflow.agents.roster import Rosters
from agentic_cli.workflow.agents.runs import INSTANCE_CLOSED, RUN_END_STATUSES, AgentRuns
from agentic_cli.workflow.usage import (
PURPOSE_MEMORY_EXTRACTION,
@@ -306,7 +307,11 @@ class BaseWorkflowManager(ABC):
``_memory_index_cached`` (never reads) and ``_forget_memory_index``
(a summary written, ``/resume``, ``/compact``). Each is the manager's
own method, which forwards to the index, so a subclass may override
- one. The release clears the snapshots.
+ one. The release clears the snapshots. A root that continues its
+ sub-agents (``_roster_wanted``: it has ``message_agent``) also gets
+ their roster after the index, a snapshot per conversation too
+ (``agents/roster.py``): ``_roster_now`` takes it, and
+ ``_forget_memory_index`` drops it with the index's.
Example:
A minimal backend: it builds its engine in ``_do_initialize`` and
@@ -809,7 +814,8 @@ async def _deleting(self, conversation: SessionRef) -> AsyncGenerator[None, None
marks it again). After it,
unless it raised: its sub-agent records and their loading
(``agent_runs``), the calls it recorded (``OpenCalls``: a failed
- turn's too), its usage ledger and its numbering (``Delegations``), so
+ turn's too), its usage ledger, its main agent's roster and its
+ numbering (``Delegations``), so
a conversation of the same id starts as a new one.
"""
writer = self.__dict__.get("_records_writer")
@@ -829,6 +835,7 @@ async def _deleting(self, conversation: SessionRef) -> AsyncGenerator[None, None
if open_calls is not None:
open_calls.forget(conversation)
self._usage_ledgers.forget(conversation)
+ self._rosters.forget(conversation)
delegations = self.__dict__.get("_delegations_made")
if delegations is not None:
delegations.forget(conversation)
@@ -1425,8 +1432,39 @@ def _memory_index_cap(self) -> int:
return self._memory_index.cap()
def _forget_memory_index(self, ref: SessionRef | None = None) -> None:
- """Drop a conversation's snapshot (the turn's by default): its next request takes a new one."""
+ """Drop a conversation's memory index and roster snapshots (the turn's by default).
+
+ Both open the main agent's requests, so they change only where the
+ prompt prefix changes anyway: the next request takes new ones.
+ """
self._memory_index.forget(ref)
+ self._rosters.forget(ref)
+
+ @property
+ def _rosters(self) -> Rosters:
+ """The roster each conversation's main agent gets (``workflow/agents/roster.py``).
+
+ Made on first use, so a manager built without its constructor has it.
+ """
+ held = vars(self).get("_rosters_held")
+ if held is None:
+ held = self._rosters_held = Rosters(lambda: self.agent_runs)
+ return held
+
+ def _roster_wanted(self, root: str) -> bool:
+ """Whether ``root``'s requests carry the roster of its sub-agents.
+
+ Only a root that can continue them does (it has ``message_agent``:
+ sub-agents and the policy's ``follow_ups``); without the tool it could
+ do nothing with an open instance.
+ """
+ config = next((c for c in self._agent_configs if c.name == root), None)
+ return config is not None and bool(config.sub_agents) and self.subagent_policy.follow_ups
+
+ def _roster_now(self) -> str:
+ """The roster the turn's conversation carries, taken the first time it is
+ asked for; ``""`` for none. It reads only the records in memory."""
+ return self._rosters.now()
def _outside_content_mark(self, ref: SessionRef) -> str | None:
"""The tool that brought outside content into ``ref``'s conversation, or None."""
@@ -2522,6 +2560,7 @@ async def _release_resources(
self._initialized = False
self._budgets = {}
self._memory_index.clear()
+ self._rosters.clear()
catalog, self._catalog = self._catalog, None
not_synchronous: list[TypeError] = []
diff --git a/src/agentic_cli/workflow/deepagents/agent_builder.py b/src/agentic_cli/workflow/deepagents/agent_builder.py
index f2b1dd7e..1cd8937d 100644
--- a/src/agentic_cli/workflow/deepagents/agent_builder.py
+++ b/src/agentic_cli/workflow/deepagents/agent_builder.py
@@ -30,8 +30,10 @@
summarization counts
exactly what will be sent (``summarization.py``), every provider's context
overflow reaches it as one it summarizes on (``ContextOverflowMiddleware``),
- the memory index, for the main agent with a memory tool
- (``MemoryIndexMiddleware``), goes first in the request, and on Claude
+ the roster of its sub-agents, for the main agent that continues them
+ (``RosterMiddleware``), then the memory index, for the main agent with a
+ memory tool (``MemoryIndexMiddleware``), go first in the request (the
+ index ahead of the roster), and on Claude
with ``prompt_caching_enabled`` the cache marks land on the
final request (``AnthropicPromptCachingMiddleware``: the system prompt, the
last tool and the conversation, for 5 minutes, as on ADK).
@@ -67,6 +69,7 @@
InterruptedCallsMiddleware,
MemoryIndexMiddleware,
PermissionMiddleware,
+ RosterMiddleware,
RunControlMiddleware,
SubAgentOutcomeMiddleware,
ToolCallErrorMiddleware,
@@ -114,6 +117,7 @@ def build_agent_tree(
memory_index_forget: Callable[[], None] | None = None,
delegations: "Callable[[], Delegations] | None" = None,
graphs: "dict[str, CompiledStateGraph] | None" = None,
+ roster: Callable[[], str] | None = None,
) -> "CompiledStateGraph":
"""Build every agent, each on its own, and return the root.
@@ -158,15 +162,19 @@ def build_agent_tree(
other agent gets one.
memory_index_cached: The same index, which reads no file: the root's
summarization counts it in its requests' size.
- memory_index_forget: Drops the conversation's index snapshot: the
- root's summarization calls it when it writes a summary, before
- the request that carries the summary is sent.
+ memory_index_forget: Drops the conversation's index and roster
+ snapshots: the root's summarization calls it when it writes a
+ summary, before the request that carries the summary is sent.
delegations: The manager's delegations (``BaseWorkflowManager._delegations``):
given, an agent with sub-agents gets the ``task`` tool, which
hands each call to them, and every agent but the root
``RunControlMiddleware``, which keeps a run's limits. Without it
no agent delegates (a tree a unit test builds alone).
graphs: Filled, when given, with every agent's graph, by name.
+ roster: The root's roster of its open sub-agents for its conversation
+ (``""`` for none): given, the root's stack has ``RosterMiddleware``
+ and its summarization counts it (the manager passes it only for a
+ root that continues its sub-agents). No other agent gets one.
Raises:
AgentGraphError: A delegating agent's own tools include one named
@@ -185,6 +193,7 @@ def build(name: str) -> "CompiledStateGraph":
memory_index=memory_index if name == root else None,
memory_index_cached=memory_index_cached if name == root else None,
memory_index_forget=memory_index_forget if name == root else None,
+ roster=roster if name == root else None,
)
if name != root:
# Inside the outcome middleware, which reads the answer whose
@@ -290,6 +299,7 @@ def _model_side(
memory_index: Callable[[], str] | None = None,
memory_index_cached: Callable[[], str] | None = None,
memory_index_forget: Callable[[], None] | None = None,
+ roster: Callable[[], str] | None = None,
) -> list["AgentMiddleware"]:
"""What shapes each of the agent's model requests, outermost first."""
if resolved is None or settings is None:
@@ -298,11 +308,14 @@ def _model_side(
ForeignReasoningMiddleware(resolved.record.kind, agent=resolved.agent),
build_summarization(
model, resolved, settings, budget=budget,
- index=memory_index_cached, on_written=memory_index_forget,
+ index=memory_index_cached, roster=roster, on_written=memory_index_forget,
),
# Inside the summarization: it summarizes on the overflows it raises.
ContextOverflowMiddleware(),
]
+ if roster is not None:
+ # Outside the memory index's, which then goes ahead of it.
+ stack.append(RosterMiddleware(roster))
if memory_index is not None:
# Inside the summarization, which counts it, and before the caching.
stack.append(MemoryIndexMiddleware(memory_index))
diff --git a/src/agentic_cli/workflow/deepagents/manager.py b/src/agentic_cli/workflow/deepagents/manager.py
index 5e735763..74df1c0a 100644
--- a/src/agentic_cli/workflow/deepagents/manager.py
+++ b/src/agentic_cli/workflow/deepagents/manager.py
@@ -92,6 +92,7 @@
)
from agentic_cli.workflow.deepagents.summarization import (
ReportingSummarizationMiddleware,
+ brief_message,
compact_cutoff,
newest_answer,
summary_event,
@@ -280,6 +281,7 @@ async def _do_initialize(self) -> None:
summarizers: dict[str, ReportingSummarizationMiddleware] = {}
root = self._root_agent_name # from the graph the base validated
index_wanted = self._memory_index_wanted(root)
+ roster_wanted = self._roster_wanted(root)
graphs: dict[str, CompiledStateGraph] = {}
self._root = build_agent_tree(
self._agent_configs,
@@ -303,7 +305,10 @@ async def _do_initialize(self) -> None:
marks=self._outside_marks,
memory_index=self._memory_index_now if index_wanted else None,
memory_index_cached=self._memory_index_cached if index_wanted else None,
- memory_index_forget=self._forget_memory_index if index_wanted else None,
+ memory_index_forget=(
+ self._forget_memory_index if index_wanted or roster_wanted else None
+ ),
+ roster=self._roster_now if roster_wanted else None,
delegations=lambda: self._delegations,
graphs=graphs,
)
@@ -745,7 +750,9 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer:
The run is on its instance's own thread of the manager's checkpointer
(``instance_run_config``): a first run starts it with the task
message, a follow-up (``run.follow_up``) continues it, its input the
- message and the caller's mark when set. The calls an earlier run of
+ message and the caller's mark when set. A first run's task message is
+ marked as the instance's brief (``summarization.brief_message``), which
+ the instance's summaries keep. The calls an earlier run of
the instance left open are answered on that thread before its first
model call (``InterruptedCallsMiddleware``). The shared keys it
changed are compared with the thread's state as the run started it
@@ -776,7 +783,12 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer:
if conversation is None:
raise RuntimeError("A sub-agent run runs in a conversation's turn.")
graph = self._agent_graphs[run.ref.agent]
- task = HumanMessage(content=run.message, id=f"agentic-cli-task-{uuid.uuid4().hex}")
+ task_id = f"agentic-cli-task-{uuid.uuid4().hex}"
+ # A first run's message is its instance's brief, which its summaries keep.
+ task = (
+ HumanMessage(content=run.message, id=task_id) if run.follow_up
+ else brief_message(run.message, id=task_id)
+ )
if not run.follow_up and self._checkpointer is not None:
# A first run never continues a thread the store already keeps
# (as ADK refuses to make an existing session): whatever numbered
diff --git a/src/agentic_cli/workflow/deepagents/middleware.py b/src/agentic_cli/workflow/deepagents/middleware.py
index c1bbf0ae..2202955d 100644
--- a/src/agentic_cli/workflow/deepagents/middleware.py
+++ b/src/agentic_cli/workflow/deepagents/middleware.py
@@ -812,6 +812,28 @@ async def awrap_model_call(
raise
+def _opened_with(request: ModelRequest, text: str) -> ModelRequest:
+ """``request`` with ``text`` as the first text block of its first human message.
+
+ The state keeps its messages as they were; ``text`` empty, or no human
+ message, leaves the request as it is.
+ """
+ if not text:
+ return request
+ messages = list(request.messages)
+ for position, message in enumerate(messages):
+ if isinstance(message, HumanMessage):
+ content = message.content
+ blocks = (
+ [{"type": "text", "text": content}] if isinstance(content, str) else list(content)
+ )
+ messages[position] = message.model_copy(
+ update={"content": [{"type": "text", "text": text}, *blocks]}
+ )
+ return request.override(messages=messages)
+ return request
+
+
class MemoryIndexMiddleware(AgentMiddleware):
"""Puts the memory index first in the main agent's requests (spec §11.3).
@@ -832,20 +854,7 @@ def __init__(self, index_for: Callable[[], str]) -> None:
@staticmethod
def _with_index(request: ModelRequest, text: str) -> ModelRequest:
- if not text:
- return request
- messages = list(request.messages)
- for position, message in enumerate(messages):
- if isinstance(message, HumanMessage):
- content = message.content
- blocks = (
- [{"type": "text", "text": content}] if isinstance(content, str) else list(content)
- )
- messages[position] = message.model_copy(
- update={"content": [{"type": "text", "text": text}, *blocks]}
- )
- return request.override(messages=messages)
- return request
+ return _opened_with(request, text)
async def awrap_model_call(
self,
@@ -855,6 +864,33 @@ async def awrap_model_call(
return await handler(self._with_index(request, await asyncio.to_thread(self._index_for)))
+class RosterMiddleware(AgentMiddleware):
+ """Puts the roster of the main agent's open sub-agents first in its requests.
+
+ The roster (a snapshot per conversation, ``workflow/agents/roster.py``)
+ becomes the first text block of the first human message of the request
+ passed on; the state keeps its messages as they were. Outside
+ ``MemoryIndexMiddleware``, which then puts the index ahead of it, and
+ inside the summarization, which counts it and drops its snapshot when it
+ writes a summary.
+
+ Args:
+ roster_for: The turn's conversation's roster (``""`` for none); it
+ reads only the records in memory.
+ """
+
+ def __init__(self, roster_for: Callable[[], str]) -> None:
+ super().__init__()
+ self._roster_for = roster_for
+
+ async def awrap_model_call(
+ self,
+ request: ModelRequest,
+ handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
+ ) -> Any:
+ return await handler(_opened_with(request, self._roster_for()))
+
+
class ForeignReasoningMiddleware(AgentMiddleware):
"""No model is sent another provider's, or another agent's, reasoning.
diff --git a/src/agentic_cli/workflow/deepagents/summarization.py b/src/agentic_cli/workflow/deepagents/summarization.py
index 5c731205..41b4ba30 100644
--- a/src/agentic_cli/workflow/deepagents/summarization.py
+++ b/src/agentic_cli/workflow/deepagents/summarization.py
@@ -14,8 +14,9 @@
``context_max_tokens`` ceiling, and keep the newest 12% of that word for
word. A model whose window is unknown counts as 128,000 tokens, not Deep
Agents' fixed 170,000 tokens or 6 messages, which never fire on a small
-model. The memory index the main agent's requests carry counts toward their
-size (``ReportingSummarizationMiddleware._count_tokens``).
+model. The memory index and the roster of sub-agents the main agent's
+requests carry count toward their size
+(``ReportingSummarizationMiddleware._count_tokens``).
**No archive.** Deep Agents writes the summarized messages to its virtual
filesystem and gives the model the file's path; with its file tools off the
@@ -43,6 +44,20 @@
ends the turn; a sub-agent's answers its ``task`` call with the error
(``ToolCallErrorMiddleware``), and its coordinator goes on.
+**An instance's brief.** A sub-agent instance's first run marks its task
+message as the instance's brief (``brief_message``); a follow-up's message is
+not marked. A summary of the instance's thread stands for the messages before
+its cut, the brief among them, so it is restated: ``awrap_model_call`` puts the
+request's brief in a context variable for the call, ``_partition_messages``
+notes whether the brief is among the messages kept, and
+``_build_new_messages_with_path`` prepends the brief's text blocks to the
+summary message when it is not. Deep Agents stores that message as the event's
+and sends it first, so the event keeps its shape (one message before the cut),
+its cutoff arithmetic is untouched, and every reader of the event, an
+inheriting child of the instance included, sees the brief. The summary also
+summarizes the brief, which does no harm. The main agent's thread has no
+brief, and its summaries are Deep Agents' own.
+
**Reporting.** The summary call runs on the agent's own model, tagged
``lc_source="summarization"``; the run callback reports its start
(``CONTEXT_SUMMARIZING``) and its usage. Each summary applied is reported as
@@ -61,7 +76,7 @@
``_should_summarize`` then decides on its own estimate of the request
alone, as ADK's engine stops at a summary. They rest on private Deep Agents
methods (``_apply_event_to_messages``, ``_compute_state_cutoff``,
-``_build_new_messages_with_path``, ``_should_summarize``, ``_lc_helper``
+``_build_new_messages_with_path``, ``_partition_messages``, ``_should_summarize``, ``_lc_helper``
and its summary model, and, for a failed summary's range,
``_get_effective_messages`` and ``_determine_cutoff_index``); contract tests
pin them.
@@ -75,6 +90,8 @@
import logging
import warnings
from collections.abc import Awaitable, Callable, Sequence
+from contextvars import ContextVar
+from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
from deepagents.backends.protocol import (
@@ -100,6 +117,7 @@
from agentic_cli.logging import Loggers
from agentic_cli.workflow import live_events
from agentic_cli.workflow.context import (
+ MIN_SAVING,
ContextBudget,
FailedSummaries,
chars_per_token,
@@ -134,6 +152,8 @@
#: the mark's ``kind`` on a summary ``/compact`` wrote.
_MARK = "agentic_cli"
COMPACTED = "compact"
+#: The mark's ``kind`` on an instance's brief, its first run's task message.
+BRIEF = "brief"
#: Deep Agents' texts for a history it could not offload (an error log and a
#: warning), and the per-write warning before them. Matched at the start.
@@ -259,19 +279,24 @@ class ReportingSummarizationMiddleware(SummarizationMiddleware):
on the strength of a count reported before it, and one that wrote no text
is not tried again in its turn over the same range (``_should_summarize``).
- Its count of a request includes the memory index the agent's requests
- carry, which ``MemoryIndexMiddleware`` adds after this middleware. A
- summary written changes the prompt prefix, so ``on_written`` runs once
- it is, before the request goes on: the request that carries the new
- summary carries a new memory index too.
+ Its count of a request includes the memory index and the roster of
+ sub-agents the agent's requests carry, which ``MemoryIndexMiddleware``
+ and ``RosterMiddleware`` add after this middleware. A summary written
+ changes the prompt prefix, so ``on_written`` runs once it is, before the
+ request goes on: the request that carries the new summary carries a new
+ memory index and roster too.
Args:
agent: The agent whose stack this is.
index: The memory index the agent's requests carry (``""`` for none);
it must read no file (the manager's ``_memory_index_cached``).
+ roster: The roster of sub-agents the agent's requests carry (``""``
+ for none), counted as the index is: the manager's ``_roster_now``.
on_written: Called once a summary is written, before the model is
called with it (the manager drops the conversation's memory index
- snapshot).
+ and roster snapshots).
+ budget_tokens: The agent's input budget, which a summary skipped for
+ saving little never lets a request pass.
**kwargs: ``SummarizationMiddleware``'s arguments.
"""
@@ -280,12 +305,16 @@ def __init__(
*,
agent: str | None,
index: Callable[[], str] | None = None,
+ roster: Callable[[], str] | None = None,
on_written: Callable[[], None] | None = None,
+ budget_tokens: int | None = None,
**kwargs: Any,
) -> None:
super().__init__(**kwargs)
self.agent = agent
self._index = index
+ self._roster = roster
+ self._budget_tokens = budget_tokens
self._on_written = on_written
helper = self._lc_helper
# Inside the retry: a mapped overflow is never retried as it was sent.
@@ -300,12 +329,14 @@ def __init__(
def _count_tokens(
self, messages: list["AnyMessage"], system_message: Any, tools: Any
) -> int:
- """The base count, plus the memory index this agent's requests carry
- (added after this middleware, by ``MemoryIndexMiddleware``)."""
+ """The base count, plus the memory index and the roster this agent's
+ requests carry (added after this middleware, by ``MemoryIndexMiddleware``
+ and ``RosterMiddleware``)."""
total = super()._count_tokens(messages, system_message, tools)
- text = self._index() if self._index is not None else ""
- if text:
- total += self.token_counter([HumanMessage(content=text)])
+ for added in (self._index, self._roster):
+ text = added() if added is not None else ""
+ if text:
+ total += self.token_counter([HumanMessage(content=text)])
return total
def _should_summarize(self, messages: list["AnyMessage"], total_tokens: int) -> bool:
@@ -319,15 +350,33 @@ def _should_summarize(self, messages: list["AnyMessage"], total_tokens: int) ->
alone decides. Otherwise Deep Agents decides. Either way, a range
whose summary wrote no text earlier in the turn is skipped until it
has grown (``FailedSummaries``): it would come back empty again.
+
+ In an instance's thread (one with a brief), a summary at the trigger
+ that would stand for less than ``MIN_SAVING`` of it is not written,
+ as ADK's is not (``summary_range``): the brief restated in every
+ summary can keep a request near the trigger, and a summary per call
+ would save nothing. A request over the agent's input budget is
+ summarized whatever it saves, the window known to the profile or not;
+ without a budget nothing is skipped.
"""
if self._trigger_tokens is not None and _counted_before_the_summary(messages):
due = total_tokens >= self._trigger_tokens
else:
due = super()._should_summarize(messages, total_tokens)
- if due and self._failures.skips(live_events.current(), *self._range(messages)):
+ if not due:
+ return False
+ start, saving = self._range(messages)
+ small = self._trigger_tokens is not None and saving < MIN_SAVING * self._trigger_tokens
+ # Never past the input budget, whether or not the model's profile gives
+ # Deep Agents one to force a summary with.
+ within = self._budget_tokens is not None and total_tokens <= self._budget_tokens
+ if small and within and _BRIEF.get() is not None:
+ logger.debug("deepagents_summary_saves_little", agent=self.agent, saving=saving)
+ return False
+ if self._failures.skips(live_events.current(), start, saving):
logger.debug("deepagents_summary_not_retried", agent=self.agent)
return False
- return due
+ return True
def _range(self, messages: list["AnyMessage"]) -> tuple[str | None, int]:
"""Where a summary of ``messages`` would start, and its size in tokens.
@@ -345,6 +394,44 @@ async def awrap_model_call(
self,
request: "ModelRequest",
handler: Callable[["ModelRequest"], Awaitable["ModelResponse"]],
+ ) -> Any:
+ # The thread's brief, for a summary this call writes.
+ brief = brief_of(request.messages)
+ token = _BRIEF.set(_Brief(brief) if brief is not None else None)
+ try:
+ return await self._awrap_model_call(request, handler)
+ finally:
+ _BRIEF.reset(token)
+
+ def _partition_messages(
+ self, conversation_messages: list["AnyMessage"], cutoff_index: int
+ ) -> tuple[list["AnyMessage"], list["AnyMessage"]]:
+ """Deep Agents' partition, noting whether the call's brief is among the
+ messages kept: a summary restates it when it is not."""
+ summarized, kept = super()._partition_messages(conversation_messages, cutoff_index)
+ brief = _BRIEF.get()
+ if brief is not None:
+ brief.restate = not any(_same(message, brief.message) for message in kept)
+ return summarized, kept
+
+ def _build_new_messages_with_path(
+ self, summary: str, file_path: str | None
+ ) -> list["AnyMessage"]:
+ """Deep Agents' summary message, opening with the call's brief when the
+ summary stands for it (``_partition_messages``)."""
+ messages = super()._build_new_messages_with_path(summary, file_path)
+ brief = _BRIEF.get()
+ if brief is None or not brief.restate or len(messages) != 1:
+ return messages
+ (message,) = messages
+ return [message.model_copy(update={
+ "content": [*_text_blocks(brief.message.content), *_text_blocks(message.content)]
+ })]
+
+ async def _awrap_model_call(
+ self,
+ request: "ModelRequest",
+ handler: Callable[["ModelRequest"], Awaitable["ModelResponse"]],
) -> Any:
sent = False
@@ -463,6 +550,7 @@ def build_summarization(
*,
budget: ContextBudget | None = None,
index: Callable[[], str] | None = None,
+ roster: Callable[[], str] | None = None,
on_written: Callable[[], None] | None = None,
) -> SummarizationMiddleware:
"""An agent's summarization middleware, on its own model.
@@ -479,18 +567,25 @@ def build_summarization(
never reads a file. Before a conversation's first request it
counts nothing, and the provider-reported count, which the base
class also reads, covers it after.
+ roster: The roster of sub-agents the agent's requests carry, counted
+ as the index is: the manager's ``_roster_now``.
on_written: Called once a summary is written, before the request
- that carries it is sent: the manager's ``_forget_memory_index``.
+ that carries it is sent: the manager's ``_forget_memory_index``,
+ which drops the index's and the roster's snapshots.
Raises:
ContextBudgetError: The model's input budget is too small to work in.
"""
install_history_filters()
+ if budget is None:
+ budget = context_budget(resolved, settings)
trigger, keep = summarization_thresholds(resolved, settings, budget)
return ReportingSummarizationMiddleware(
agent=resolved.agent,
index=index,
+ roster=roster,
on_written=on_written,
+ budget_tokens=budget.budget,
model=model,
backend=NoArchiveBackend(),
trigger=trigger,
@@ -605,6 +700,53 @@ async def write_summary(
return summary.strip()
+def brief_message(text: str, *, id: str) -> HumanMessage:
+ """An instance's brief: its first run's task message, marked as the brief.
+
+ The mark is in ``response_metadata``, which no provider adapter sends, as
+ a job notification's is.
+ """
+ return HumanMessage(content=text, id=id, response_metadata={_MARK: {"kind": BRIEF}})
+
+
+def is_brief(message: "AnyMessage") -> bool:
+ """Whether ``message`` is an instance's brief (by its mark, never its text)."""
+ mark = message.response_metadata.get(_MARK)
+ return isinstance(mark, dict) and mark.get("kind") == BRIEF
+
+
+def brief_of(messages: Sequence["AnyMessage"]) -> "AnyMessage | None":
+ """The brief of the thread ``messages`` belong to: the last one marked.
+
+ The last, since an inheriting instance's copied conversation holds its
+ parent's brief before its own.
+ """
+ return next((m for m in reversed(messages) if is_brief(m)), None)
+
+
+@dataclass
+class _Brief:
+ """The brief of the thread a model call is for, and whether a summary it
+ writes restates it (``_partition_messages`` decides)."""
+
+ message: "AnyMessage"
+ restate: bool = False
+
+
+#: The brief of the model call in progress (``awrap_model_call``).
+_BRIEF: ContextVar[_Brief | None] = ContextVar("agentic_cli_summary_brief", default=None)
+
+
+def _same(a: "AnyMessage", b: "AnyMessage") -> bool:
+ """Whether ``a`` and ``b`` are one message: the same object, or the same id."""
+ return a is b or (a.id is not None and a.id == b.id)
+
+
+def _text_blocks(content: Any) -> list[Any]:
+ """``content`` as a list of content blocks."""
+ return [{"type": "text", "text": content}] if isinstance(content, str) else list(content)
+
+
def summary_event(
middleware: SummarizationMiddleware,
previous: SummarizationEvent | None,
diff --git a/tests/workflow/adk/test_child_sessions.py b/tests/workflow/adk/test_child_sessions.py
index 1b0f08f2..0c0b2b8a 100644
--- a/tests/workflow/adk/test_child_sessions.py
+++ b/tests/workflow/adk/test_child_sessions.py
@@ -23,6 +23,9 @@
- No child session lists, or is found, as a conversation.
- A message steered to a run is stored where the run read it: after the
tool result before it, before the answer it prompted, on every store.
+- An instance's first run marks its message as the instance's brief: the
+ event's state delta holds ``BRIEF_KEY`` (the run's id), which the fit
+ guard finds it by on every later run (``fit_guard_plugin.brief_of``).
Turns run the real manager on ``FakeAPI`` (Claude), on the memory store and
on sqlite.
@@ -48,7 +51,9 @@
from agentic_cli.tools.registry import register_tool # noqa: E402
from agentic_cli.workflow.adk import sessions as adk_sessions # noqa: E402
from agentic_cli.workflow.adk.manager import GoogleADKWorkflowManager # noqa: E402
-from agentic_cli.workflow.adk.sessions import RECORDS_KEY, child_app # noqa: E402
+from agentic_cli.workflow.adk.fit_guard_plugin import brief_of # noqa: E402
+from agentic_cli.workflow.adk.sessions import BRIEF_KEY, RECORDS_KEY, child_app # noqa: E402
+from agentic_cli.workflow.agents import SubAgentPolicy # noqa: E402
from agentic_cli.workflow.agents.runs import RECORDS_VERSION # noqa: E402
from agentic_cli.workflow.permissions import EXEMPT # noqa: E402
from agentic_cli.workflow.service_registry import WORKFLOW, get_service # noqa: E402
@@ -828,3 +833,40 @@ async def test_it_is_stored_between_the_result_and_the_answer_it_prompted(
"user: Also find Z.",
"researcher: X is 42; Z is 42.",
]
+
+
+class TestTheBrief:
+ @pytest.mark.parametrize("store", ["memory", "sqlite"])
+ async def test_a_first_runs_message_is_marked_and_a_follow_ups_is_not(
+ self, store, project, monkeypatch
+ ):
+ api = Team(
+ coordinator=[delegation("toolu_c1"), says("Asked."),
+ calls("message_agent", "toolu_c2", agent="researcher-1",
+ message="Now find Y."), says("Done.")],
+ researcher=[says("X is 42."), says("Y is 7.")],
+ )
+ route(monkeypatch, anthropic, "AsyncAnthropic", FakeAPI(api))
+ manager = GoogleADKWorkflowManager(
+ agent_configs=team(),
+ settings=BaseSettings(
+ session_store=store, default_model="claude-sonnet-4-6", default_user="u"
+ ),
+ subagents=SubAgentPolicy(follow_ups=True),
+ )
+ try:
+ await say(manager, "Go.")
+ await say(manager, "Again.")
+ session = await child(manager, "researcher-1")
+ finally:
+ await manager.cleanup()
+
+ marked = [event for event in session.events
+ if event.actions and BRIEF_KEY in (event.actions.state_delta or {})]
+ assert [(e.author, e.actions.state_delta[BRIEF_KEY]) for e in marked] == [
+ ("user", "researcher-1#1")
+ ]
+ assert brief_of(session.events) == marked[0].content
+ assert texts_of(session)[0] == marked[0].content.parts[0].text
+ assert marked[0].content.parts[0].text.startswith("# Task: Find X")
+ assert "Now find Y." in texts_of(session)
diff --git a/tests/workflow/adk/test_fit_guard.py b/tests/workflow/adk/test_fit_guard.py
index 716614d9..6791cfff 100644
--- a/tests/workflow/adk/test_fit_guard.py
+++ b/tests/workflow/adk/test_fit_guard.py
@@ -22,6 +22,7 @@
pytest.importorskip("google.adk")
+from google.adk.events import Event # noqa: E402
from google.adk.events.event_actions import EventActions # noqa: E402
from google.adk.models.llm_request import LlmRequest # noqa: E402
from google.adk.models.llm_response import LlmResponse # noqa: E402
@@ -32,9 +33,11 @@
from agentic_cli.workflow.adk.fit_guard_plugin import ( # noqa: E402
FIT_NOTE,
FitGuardPlugin,
+ brief_of,
drop_turns,
estimate_request_tokens,
)
+from agentic_cli.workflow.adk.sessions import BRIEF_KEY # noqa: E402
from agentic_cli.workflow.context import ContextBudget # noqa: E402
from agentic_cli.workflow.events import EventType, WorkflowEvent # noqa: E402
from agentic_cli.workflow.live_events import LiveEvents, reporting # noqa: E402
@@ -216,6 +219,101 @@ def test_without_it_the_oldest_turn_goes_whatever_it_is(self):
assert [part.text for part in kept[0].parts] == [FIT_NOTE, "Also find Z."]
+class TestAnInstancesBrief:
+ """An instance's brief (its first run's task message) is never left out of
+ a later run's request either (``brief=``): a follow-up's task message is
+ its own message, and the brief is the turn before it."""
+
+ BRIEF = "# Task: Find X.\n\n## Objective\nFind X."
+
+ def follow_up(self) -> list[types.Content]:
+ return [user(self.BRIEF), call("lookup", "c1"), result("lookup", "c1", page=LONG),
+ model("X is 42."), user("Now find Y."), call("lookup", "c2"),
+ result("lookup", "c2", page=LONG)]
+
+ def test_the_turns_after_it_go_and_the_rest_joins_it(self):
+ contents = self.follow_up()
+ task, brief = contents[4], contents[0]
+
+ kept, dropped = drop_turns(contents, target_tokens=0, kind=CLAUDE, task=task, brief=brief)
+ without, _ = drop_turns(contents, target_tokens=0, kind=CLAUDE, task=task)
+
+ assert dropped == 1
+ assert [part.text for part in kept[0].parts] == [self.BRIEF, FIT_NOTE, "Now find Y."]
+ assert kept[1:] == contents[5:]
+ assert [part.text for part in without[0].parts] == [FIT_NOTE, "Now find Y."]
+
+ def test_a_message_steered_after_the_follow_up_joins_both(self):
+ contents = [*self.follow_up(), user("Also find Z."), call("lookup", "c3"),
+ result("lookup", "c3", z=42)]
+ task, brief = contents[4], contents[0]
+
+ kept, dropped = drop_turns(contents, target_tokens=0, kind=CLAUDE, task=task, brief=brief)
+
+ assert dropped == 2
+ assert [part.text for part in kept[0].parts] == [
+ self.BRIEF, FIT_NOTE, "Now find Y.", "Also find Z."
+ ]
+ assert kept[1:] == contents[8:]
+
+ def test_an_inheriting_instances_history_goes_first(self):
+ contents = [user(LONG), model("A1."), *self.follow_up()]
+ task, brief = contents[6], contents[2]
+
+ kept, dropped = drop_turns(
+ contents, target_tokens=tokens(contents[2:]) + NOTE_ROOM, kind=CLAUDE,
+ task=task, brief=brief,
+ )
+
+ assert dropped == 1
+ assert [part.text for part in kept[0].parts] == [FIT_NOTE, self.BRIEF]
+ assert kept[1:] == contents[3:]
+
+ def test_its_first_run_s_brief_is_its_task(self):
+ brief = user(self.BRIEF)
+ contents = [brief, call("lookup", "c1"), result("lookup", "c1", page=LONG),
+ user("Also find Z.")]
+
+ kept, dropped = drop_turns(contents, target_tokens=0, kind=CLAUDE, task=brief, brief=brief)
+
+ assert dropped == 1
+ assert [part.text for part in kept[0].parts] == [self.BRIEF, FIT_NOTE, "Also find Z."]
+
+ def test_it_is_the_event_its_first_run_marked(self):
+ brief = user(self.BRIEF)
+ events = [
+ Event(author="user", content=user("Copied from the parent.")),
+ Event(author="user", content=brief,
+ actions=EventActions(state_delta={BRIEF_KEY: "researcher-1#1"})),
+ Event(author="researcher", content=model("X is 42.")),
+ Event(author="user", content=user("Now find Y."),
+ actions=EventActions(state_delta={"agentic_cli.outside_content": "web_fetch"})),
+ ]
+
+ assert brief_of(events) == brief
+ assert brief_of(events[:1]) is None and brief_of([]) is None
+
+ async def test_the_plugin_keeps_the_sessions_brief_in_a_sub_agent_types_chain(self):
+ contents = self.follow_up()
+ events = [Event(author="user", content=contents[0],
+ actions=EventActions(state_delta={BRIEF_KEY: "researcher-1#1"}))]
+ budget = ContextBudget(window=200_000, window_known=True, budget=tokens(contents) - 1,
+ trigger=tokens(contents[4:]) + NOTE_ROOM, keep=0)
+ plugin = FitGuardPlugin({"researcher": budget}, {"researcher": CLAUDE}, keep_task=True)
+ request = LlmRequest(contents=list(contents))
+ context = SimpleNamespace(
+ agent_name="researcher", invocation_id="i2", actions=EventActions(),
+ user_content=contents[4], session=SimpleNamespace(events=events),
+ )
+
+ with reporting(Recorded()):
+ await plugin.before_model_callback(callback_context=context, llm_request=request)
+
+ assert [part.text for part in request.contents[0].parts] == [
+ self.BRIEF, FIT_NOTE, "Now find Y."
+ ]
+
+
class TestFoldSummary:
"""A summarized conversation opens with the summary, a user content of its
own: folded into the next user's text, no provider sees two user messages
diff --git a/tests/workflow/adk/test_plugin_chain.py b/tests/workflow/adk/test_plugin_chain.py
index 8fdbb989..8870d12c 100644
--- a/tests/workflow/adk/test_plugin_chain.py
+++ b/tests/workflow/adk/test_plugin_chain.py
@@ -21,8 +21,9 @@
- ``interrupted_calls`` before ``tool_result_cap``: it records every
finished result, and the cap returns its cut, which ends ADK's after-tool
callbacks;
-- ``memory_index`` before ``context_overflow`` and ``fit_guard``, which keep
- it;
+- ``roster``, for a main agent that continues its sub-agents, before
+ ``memory_index``, which puts the index ahead of it; both before
+ ``context_overflow`` and ``fit_guard``, which keep them;
- ``fit_guard`` last but the raw log and the clock: it measures the request
every other plugin edited;
- ``llm_logging_sent``: it logs the request as sent;
@@ -30,7 +31,7 @@
A native ADK YAML app gets the same chain: only the building of its agents
differs (``workflow/adk/build.py``). Each sub-agent type's runner has a chain
-of its own in the same order (``_agent_plugin_chain``): no memory index, and
+of its own in the same order (``_agent_plugin_chain``): no memory index, no roster, and
after the raw log (which records an answer as the model gave it)
``run_control``, where the run's limits are kept at its model calls, then
``subagent_outcome``, where a sub-agent's refused or cut answer is said so;
@@ -46,6 +47,7 @@
from agentic_cli.config import BaseSettings # noqa: E402
from agentic_cli.tools.memory_tools import search_memory # noqa: E402
from agentic_cli.workflow.adk.manager import GoogleADKWorkflowManager # noqa: E402
+from agentic_cli.workflow.agents import SubAgentPolicy # noqa: E402
from agentic_cli.workflow.config import AgentConfig # noqa: E402
from tests.workflow.adk.fakes import dead_base_urls # noqa: E402
from tests.workflow.test_adk_context_cache import _native_yaml # noqa: E402
@@ -184,6 +186,44 @@ async def test_a_delegating_app(project):
assert logs == [shared]
+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
+ has none."""
+ manager = GoogleADKWorkflowManager(
+ agent_configs=[
+ AgentConfig(name="lead", prompt="Lead.", sub_agents=["helper"],
+ tools=[search_memory]),
+ AgentConfig(name="helper", prompt="Help.", description="Helps."),
+ ],
+ settings=_settings(extras=False),
+ subagents=SubAgentPolicy(follow_ups=True),
+ )
+
+ try:
+ await manager.initialize_services()
+ chain = [plugin.name for plugin in manager._runner.app.plugins]
+ helpers = [plugin.name for plugin in manager._agent_runners["helper"].app.plugins]
+ finally:
+ await manager.cleanup()
+
+ assert chain == [
+ "main_agent",
+ "call_latency",
+ "permission",
+ "tool_error",
+ "foreign_reasoning",
+ "interrupted_calls",
+ "tool_result_cap",
+ "roster",
+ "memory_index",
+ "context_overflow",
+ "fit_guard",
+ "call_sent",
+ ]
+ assert "roster" not in helpers
+
+
async def test_a_native_adk_yaml_app_gets_the_same_chain(project):
manager = GoogleADKWorkflowManager(
agent_configs=[], settings=_settings(extras=False),
diff --git a/tests/workflow/adk/test_roster_plugin.py b/tests/workflow/adk/test_roster_plugin.py
new file mode 100644
index 00000000..6e0f08e4
--- /dev/null
+++ b/tests/workflow/adk/test_roster_plugin.py
@@ -0,0 +1,120 @@
+"""ADK: the main agent's roster opens its requests after the memory index, is
+never dropped, and is folded into the first user text with it.
+
+``RosterPlugin`` puts the roster (``workflow/agents/roster.py``) first in the
+main agent's requests; it comes before ``MemoryIndexPlugin`` in the chain, so
+the index goes ahead of it. What opens a request is the index, the roster,
+then a summary (``protected_head``): the fit guard never drops them, folds them
+into the next user text in that order (``fold_summary``), and the overflow
+handler's retry keeps the index and the roster ahead of its new summary.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+pytest.importorskip("google.adk")
+
+from google.adk.models.llm_request import LlmRequest # noqa: E402
+
+from agentic_cli.workflow.adk.fit_guard_plugin import ( # noqa: E402
+ FIT_NOTE,
+ drop_turns,
+ fold_summary,
+ is_roster,
+ protected_head,
+)
+from agentic_cli.workflow.adk.memory_index_plugin import MemoryIndexPlugin, index_content # noqa: E402
+from agentic_cli.workflow.adk.overflow_plugin import _with_summary # noqa: E402
+from agentic_cli.workflow.adk.roster_plugin import RosterPlugin, roster_content # noqa: E402
+from agentic_cli.workflow.agents.roster import ROSTER_CLOSE, ROSTER_HEADER, ROSTER_OPEN # noqa: E402
+from agentic_cli.workflow.summary_prompt import SUMMARY_PREFIX # noqa: E402
+from tests.workflow.adk.test_fit_guard import ( # noqa: E402
+ CLAUDE,
+ LONG,
+ NOTE_ROOM,
+ call_context,
+ model,
+ tokens,
+ user,
+)
+from tests.workflow.adk.test_memory_index_plugin import INDEX, texts # noqa: E402
+
+ROSTER = "\n".join([ROSTER_OPEN, ROSTER_HEADER,
+ "- researcher-1 (researcher, idle): Find X. — X is 42.", ROSTER_CLOSE])
+SUMMARY = f"{SUMMARY_PREFIX}\n\nThe user is Ada."
+
+
+class TestThePlugin:
+ async def test_the_roster_goes_first_for_the_main_agent_only(self):
+ plugin = RosterPlugin(root="lead", roster_for=lambda: ROSTER)
+ mine, theirs = LlmRequest(contents=[user("Hi.")]), LlmRequest(contents=[user("Hi.")])
+
+ await plugin.before_model_callback(callback_context=call_context("lead"), llm_request=mine)
+ await plugin.before_model_callback(
+ callback_context=call_context("researcher"), llm_request=theirs
+ )
+
+ assert [texts(c) for c in mine.contents] == [[ROSTER], ["Hi."]]
+ assert [texts(c) for c in theirs.contents] == [["Hi."]]
+ assert is_roster(mine.contents[0]) and not is_roster(user("Hi."))
+
+ async def test_no_roster_no_change(self):
+ plugin = RosterPlugin(root="lead", roster_for=lambda: "")
+ request = LlmRequest(contents=[user("Hi.")])
+
+ await plugin.before_model_callback(callback_context=call_context("lead"), llm_request=request)
+
+ assert [texts(c) for c in request.contents] == [["Hi."]]
+
+ async def test_before_the_memory_index_in_the_chain_the_index_goes_ahead_of_it(self):
+ request = LlmRequest(contents=[user(SUMMARY), user("Hi.")])
+ chain = [RosterPlugin(root="lead", roster_for=lambda: ROSTER),
+ MemoryIndexPlugin(root="lead", index_for=lambda: INDEX)]
+
+ for plugin in chain:
+ await plugin.before_model_callback(
+ callback_context=call_context("lead"), llm_request=request
+ )
+
+ assert [texts(c) for c in request.contents] == [[INDEX], [ROSTER], [SUMMARY], ["Hi."]]
+
+
+class TestWhatOpensARequest:
+ def test_the_index_the_roster_then_a_summary(self):
+ opening = [index_content(INDEX), roster_content(ROSTER), user(SUMMARY)]
+
+ assert protected_head([*opening, user("Hi.")]) == opening
+ assert protected_head([roster_content(ROSTER), user("Hi.")]) == [roster_content(ROSTER)]
+ # Out of that order it opens nothing.
+ assert protected_head([roster_content(ROSTER), index_content(INDEX), user("Hi.")]) == [
+ roster_content(ROSTER)
+ ]
+
+ def test_folded_into_the_next_users_text_in_that_order(self):
+ folded = fold_summary([index_content(INDEX), roster_content(ROSTER), user(SUMMARY),
+ user("Two?"), model("A2.")])
+
+ assert [texts(c) for c in folded] == [[INDEX, ROSTER, SUMMARY, "Two?"], ["A2."]]
+ assert fold_summary(folded) == folded
+
+ def test_dropping_turns_keeps_them(self):
+ contents = [index_content(INDEX), roster_content(ROSTER), user(SUMMARY), user(LONG),
+ model("A1."), user(LONG), model("A2."), user("Three?")]
+ target = tokens([*contents[:3], *contents[5:]]) + NOTE_ROOM
+
+ kept, dropped = drop_turns(contents, target_tokens=target, kind=CLAUDE)
+
+ assert dropped == 1
+ assert kept[:3] == contents[:3]
+ assert texts(kept[3])[0] == FIT_NOTE
+
+ def test_the_overflow_retry_keeps_the_index_and_the_roster_first(self):
+ old = user(f"{SUMMARY_PREFIX}\n\nOld summary.")
+ new = f"{SUMMARY_PREFIX}\n\nNew summary."
+
+ retry = _with_summary([index_content(INDEX), roster_content(ROSTER), old, user("Two?")], new)
+ alone = _with_summary([roster_content(ROSTER), user("Two?")], new)
+
+ assert [texts(c) for c in retry] == [[INDEX, ROSTER, new, "Two?"]]
+ assert [texts(c) for c in alone] == [[ROSTER, new, "Two?"]]
diff --git a/tests/workflow/deepagents/test_brief.py b/tests/workflow/deepagents/test_brief.py
new file mode 100644
index 00000000..fa6ed1c6
--- /dev/null
+++ b/tests/workflow/deepagents/test_brief.py
@@ -0,0 +1,202 @@
+"""Deep Agents: an instance's brief is kept through every summary of its thread.
+
+An instance's first run marks its task message as its brief
+(``summarization.brief_message``); a follow-up's message is not marked. Its
+summarization (on its own model, against its own budget) keeps the brief
+ahead of the summary: the summary message Deep Agents stores opens with the
+brief's text, so every request after it, and every reader of the stored
+summary, holds the brief. A brief the summary leaves in the kept messages
+(an inheriting instance's history summarized alone) is not restated. The
+main agent's thread has no brief, and its summaries are Deep Agents' own.
+"""
+
+from __future__ import annotations
+
+from langchain.agents.middleware import ModelRequest
+from langchain_core.messages import AIMessage, HumanMessage
+
+from agentic_cli.workflow.agents import SubAgentPolicy
+from agentic_cli.workflow.context import context_budget
+from agentic_cli.workflow.config import AgentConfig
+from agentic_cli.workflow.deepagents.sessions import instance_thread_id
+from agentic_cli.workflow.deepagents.summarization import (
+ SUMMARIZATION_EVENT_KEY,
+ brief_message,
+ brief_of,
+ build_summarization,
+ is_brief,
+)
+from agentic_cli.workflow.summary_prompt import SUMMARY_PREFIX
+from tests.workflow.deepagents.fakes import ScriptedChat, ai, task
+from tests.workflow.deepagents.test_context import USER_TURN, context, resolved
+from tests.workflow.deepagents.test_manager import _manager, ctx, hermetic, scripted, turn # noqa: F401
+
+BRIEF = "# Task: Find X.\n\n## Objective\nFind X."
+
+
+def long_turns(first: int, last: int) -> list:
+ """Turns ``first`` to ``last``, each about 3,000 tokens and an answer."""
+ turns: list = []
+ for n in range(first, last + 1):
+ turns += [HumanMessage(f"Turn {n}: {USER_TURN}", id=f"h{n}"), AIMessage(f"A{n}.", id=f"a{n}")]
+ return turns
+
+
+async def summarized(chat: ScriptedChat, messages: list, event=None) -> tuple[list, dict]:
+ """One model call of a ``local:small`` agent (summarized at 16,150 tokens)
+ on ``messages``: what the model was sent, and the summary event stored."""
+ middleware = build_summarization(chat, resolved("local:small", agent="worker"), context())
+ state = {"messages": messages}
+ if event is not None:
+ state[SUMMARIZATION_EVENT_KEY] = event
+ seen: list = []
+
+ async def handler(request):
+ seen.append(list(request.messages))
+ return AIMessage("Done.")
+
+ response = await middleware.awrap_model_call(
+ ModelRequest(model=chat, messages=messages, state=state), handler
+ )
+ update = getattr(getattr(response, "command", None), "update", None) or {}
+ return seen[-1], update.get(SUMMARIZATION_EVENT_KEY)
+
+
+def blocks(message) -> list[str]:
+ content = message.content
+ return [content] if isinstance(content, str) else [block["text"] for block in content]
+
+
+class TestTheMark:
+ def test_a_brief_is_marked_and_found_the_last_one_wins(self):
+ parents = brief_message("# Task: The parent's.", id="t1")
+ own = brief_message(BRIEF, id="t2")
+ thread = [parents, AIMessage("Done."), own, AIMessage("X."), HumanMessage("Now Y.")]
+
+ assert is_brief(own) and not is_brief(HumanMessage(BRIEF))
+ assert own.response_metadata == {"agentic_cli": {"kind": "brief"}}
+ assert brief_of(thread) is own
+ assert brief_of([HumanMessage("Hi.")]) is None
+
+ async def test_an_instances_first_message_is_its_brief_and_a_follow_up_is_not(
+ self, ctx, monkeypatch
+ ):
+ scripted(
+ monkeypatch,
+ lead=[ai(calls=[task("helper", "Find X.", "c1")]), ai("Asked."),
+ ai(calls=[("message_agent", {"agent": "helper-1", "message": "Now Y."}, "c2")]),
+ ai("Done.")],
+ helper=[ai("X is 42."), ai("Y is 7.")],
+ )
+ manager = _manager(ctx.settings, [
+ AgentConfig(name="lead", prompt="p", sub_agents=["helper"]),
+ AgentConfig(name="helper", prompt="p", description="Helps."),
+ ], subagents=SubAgentPolicy(follow_ups=True))
+ try:
+ await turn(manager, "Go.")
+ await turn(manager, "Again.")
+ thread = instance_thread_id(manager.session_ref("s", "u"), "helper-1")
+ saved = await manager._checkpointer.aget_tuple({"configurable": {"thread_id": thread}})
+ finally:
+ await manager.cleanup()
+
+ messages = saved.checkpoint["channel_values"]["messages"]
+ humans = [m for m in messages if isinstance(m, HumanMessage)]
+ assert [is_brief(m) for m in humans] == [True, False]
+ assert humans[0].text.startswith("# Task: Find X.") and humans[1].text == "Now Y."
+ assert brief_of(messages) is humans[0]
+
+
+class TestTheSummaries:
+ async def test_a_summary_opens_with_the_brief(self):
+ chat = ScriptedChat(label="worker", script=[ai("A summary.")])
+ brief = brief_message(BRIEF, id="t1")
+ messages = [brief, AIMessage("Reading.", id="a0"), *long_turns(1, 6),
+ HumanMessage("Now find Y.", id="h7")]
+
+ sent, event = await summarized(chat, messages)
+
+ written = f"{SUMMARY_PREFIX}\n\nA summary."
+ assert blocks(sent[0]) == [BRIEF, written]
+ assert sent[0].additional_kwargs == {"lc_source": "summarization"}
+ assert blocks(event["summary_message"]) == [BRIEF, written]
+ assert [m.text for m in sent].count(BRIEF) == 0 # not as a message of its own too
+ assert sent[-1].text == "Now find Y."
+
+ async def test_every_summary_of_the_thread_keeps_it(self):
+ chat = ScriptedChat(label="worker", script=[ai("A summary."), ai("Another.")])
+ messages = [brief_message(BRIEF, id="t1"), AIMessage("Reading.", id="a0"),
+ *long_turns(1, 6), HumanMessage("Now find Y.", id="h7")]
+ _, first = await summarized(chat, messages)
+
+ grown = [*messages, AIMessage("Y.", id="a7"), *long_turns(8, 13),
+ HumanMessage("Now find Z.", id="h14")]
+ sent, second = await summarized(chat, grown, first)
+
+ assert blocks(second["summary_message"]) == [BRIEF, f"{SUMMARY_PREFIX}\n\nAnother."]
+ assert blocks(sent[0])[0] == BRIEF
+ assert second["cutoff_index"] > first["cutoff_index"]
+
+ async def test_a_brief_the_summary_keeps_is_not_restated(self):
+ """An inheriting instance's history before its brief, summarized alone."""
+ chat = ScriptedChat(label="worker", script=[ai("The history.")])
+ brief = brief_message(BRIEF, id="t1")
+ messages = [*long_turns(1, 6), brief, AIMessage("Short.", id="a7")]
+
+ sent, event = await summarized(chat, messages)
+
+ assert event is not None and brief in sent
+ assert blocks(sent[0]) == [f"{SUMMARY_PREFIX}\n\nThe history."]
+
+ async def test_a_thread_without_one_gets_deep_agents_own_summary(self):
+ chat = ScriptedChat(label="worker", script=[ai("A summary.")])
+ messages = [HumanMessage("Find X.", id="h0"), *long_turns(1, 6),
+ HumanMessage("Now find Y.", id="h7")]
+
+ sent, event = await summarized(chat, messages)
+
+ assert sent[0].content == f"{SUMMARY_PREFIX}\n\nA summary."
+ assert event["summary_message"].content == f"{SUMMARY_PREFIX}\n\nA summary."
+
+
+class TestALongBrief:
+ BIG = "Brief. " + "word " * 12_600 # about 14,000 tokens; local:small summarizes at 16,150
+
+ async def test_one_summary_not_one_per_call(self):
+ """A brief near the trigger stays in the request after its summary: a
+ later call whose summary would save little (under ``MIN_SAVING`` of
+ the trigger) does not write another."""
+ chat = ScriptedChat(label="worker", script=[ai(f"S{n}.") for n in range(1, 10)])
+ messages = [brief_message(self.BIG, id="t1"), AIMessage("Reading.", id="a0"),
+ HumanMessage("Turn 1: " + "word " * 2_400, id="h1"), AIMessage("A1.", id="a1")]
+ _, event = await summarized(chat, messages)
+ written = [event is not None]
+ for n in range(2, 10):
+ messages = [*messages, HumanMessage(f"Short {n}. " + "word " * 200, id=f"h{n}"),
+ AIMessage(f"A{n}.", id=f"a{n}")]
+ _, new = await summarized(chat, messages, event)
+ written.append(new is not None)
+ event = new or event
+
+ assert written == [True] + [False] * 8
+ assert blocks(event["summary_message"])[0] == self.BIG
+
+ async def test_never_a_request_past_the_budget(self):
+ """The skip is for requests under the input budget (here 19,000 tokens,
+ the window not being known to the model's profile): once the brief and
+ the steps pass it, a summary is written whatever it saves."""
+ chat = ScriptedChat(label="worker", script=[ai(f"S{n}.") for n in range(1, 10)])
+ middleware = build_summarization(chat, resolved("local:small", agent="worker"), context())
+ budget = context_budget(resolved("local:small", agent="worker"), context()).budget
+ messages = [brief_message(self.BIG, id="t1"), AIMessage("Reading.", id="a0"),
+ HumanMessage("Turn 1: " + "word " * 2_400, id="h1"), AIMessage("A1.", id="a1")]
+ sent, event = await summarized(chat, messages)
+ sizes = [middleware.token_counter(sent)]
+ for n in range(2, 10):
+ messages = [*messages, HumanMessage(f"Short {n}. " + "word " * 400, id=f"h{n}"),
+ AIMessage(f"A{n}.", id=f"a{n}")]
+ sent, new = await summarized(chat, messages, event)
+ sizes.append(middleware.token_counter(sent))
+ event = new or event
+
+ assert max(sizes) <= budget, sizes
diff --git a/tests/workflow/deepagents/test_compact.py b/tests/workflow/deepagents/test_compact.py
index 97bafec9..cba4afad 100644
--- a/tests/workflow/deepagents/test_compact.py
+++ b/tests/workflow/deepagents/test_compact.py
@@ -937,6 +937,22 @@ def test_a_cut_of_the_applied_messages_is_moved_to_the_states(self):
assert cutoff(event, 3, messages) == 6
assert cutoff({**event, "cutoff_message_id": "m5"}, 3, messages) == 7
+ def test_the_messages_summarized_and_kept_are_its_partition(self):
+ """An instance's summary restates its brief when the brief is not among
+ the messages kept (``_partition_messages``), in the message Deep Agents
+ builds (``_build_new_messages_with_path``), stores as the event's and
+ sends first (``tests/workflow/deepagents/test_brief.py``)."""
+ partition = SummarizationMiddleware._partition_messages
+ build = SummarizationMiddleware._build_new_messages_with_path
+ messages = [HumanMessage("One?", id="h1"), AIMessage("A1", id="a1"),
+ HumanMessage("Two?", id="h2")]
+
+ assert list(inspect.signature(partition).parameters) == [
+ "self", "conversation_messages", "cutoff_index"
+ ]
+ assert list(inspect.signature(build).parameters) == ["self", "summary", "file_path"]
+ assert partition(_middleware(), messages, 2) == (messages[:2], messages[2:])
+
def test_the_summary_message_without_an_archive(self):
middleware = _middleware()
(message,) = middleware._build_new_messages_with_path("A summary.", None)
diff --git a/tests/workflow/deepagents/test_context.py b/tests/workflow/deepagents/test_context.py
index dfd0ffab..aa4592d9 100644
--- a/tests/workflow/deepagents/test_context.py
+++ b/tests/workflow/deepagents/test_context.py
@@ -60,6 +60,7 @@
)
from agentic_cli.tools.registry import register_tool # noqa: E402
from agentic_cli.workflow.agents.brief import Brief, task_message # noqa: E402
+from agentic_cli.workflow.summary_prompt import SUMMARY_PREFIX # noqa: E402
from agentic_cli.workflow.config import AgentConfig # noqa: E402
from agentic_cli.workflow.context import ( # noqa: E402
OVERFLOW_ERROR_CODE,
@@ -78,6 +79,7 @@
ForeignReasoningMiddleware,
MemoryIndexMiddleware,
PermissionMiddleware,
+ RosterMiddleware,
SubAgentOutcomeMiddleware,
ToolCallErrorMiddleware,
ToolResultCapMiddleware,
@@ -433,6 +435,30 @@ def test_the_root_gets_the_memory_index_middleware(self, created, tmp_path, monk
]
assert MemoryIndexMiddleware not in [type(m) for m in created["helper"]["middleware"]]
+ def test_the_root_gets_the_roster_middleware_outside_the_memory_index(
+ self, created, tmp_path, monkeypatch
+ ):
+ monkeypatch.chdir(tmp_path)
+ build_agent_tree(
+ TEAM,
+ chat_models={config.name: ScriptedChat(label=config.name) for config in TEAM},
+ resolved={"lead": resolved(SONNET_THINKING, "lead"),
+ "helper": resolved("google:gemini-2.5-flash", "helper")},
+ tools={},
+ prompts={config.name: "p" for config in TEAM},
+ settings=context(tool_result_max_chars=30_000),
+ checkpointer=None,
+ memory_index=lambda: "",
+ memory_index_cached=lambda: "",
+ roster=lambda: "",
+ )
+ lead = [type(m) for m in created["lead"]["middleware"]]
+ assert lead[1:7] == [
+ ForeignReasoningMiddleware, ReportingSummarizationMiddleware, ContextOverflowMiddleware,
+ RosterMiddleware, MemoryIndexMiddleware, AnthropicPromptCachingMiddleware,
+ ]
+ assert RosterMiddleware not in [type(m) for m in created["helper"]["middleware"]]
+
def test_every_agent_summarizes_on_its_own_models_budget(self, created):
# The coordinator on a 1M-token Claude (the ceiling), the helper on a
# model whose window is unknown (the 128,000-token floor).
@@ -825,8 +851,12 @@ async def test_a_summary_stays_with_the_agent_that_wrote_it(self, small, monkeyp
assert first == [{"role": "system", "content": "Work."}, {"role": "user", "content": (
task_message(Brief(title="Brief", objective="Brief."))
)}]
- # and the worker's summary, of its brief and first report, stays its own.
- assert last[1]["content"].endswith("A summary of 3 messages.")
+ # and the worker's summary, of its brief and first report, stays its own,
+ # its brief ahead of it.
+ assert [part["text"] for part in last[1]["content"]] == [
+ task_message(Brief(title="Brief", objective="Brief.")),
+ f"{SUMMARY_PREFIX}\n\nA summary of 3 messages.",
+ ]
assert state["_summarization_event"]["cutoff_index"] == own["cutoff_index"]
assert state["_summarization_event"]["summary_message"].text == own["summary_message"].text
trimmed = [e for e in delegating if e.type is EventType.CONTEXT_TRIMMED]
diff --git a/tests/workflow/deepagents/test_roster_middleware.py b/tests/workflow/deepagents/test_roster_middleware.py
new file mode 100644
index 00000000..5c162432
--- /dev/null
+++ b/tests/workflow/deepagents/test_roster_middleware.py
@@ -0,0 +1,109 @@
+"""Deep Agents: the main agent's roster opens the first human message of its
+requests, after the memory index; the summarization counts it.
+
+``RosterMiddleware`` puts the roster (``workflow/agents/roster.py``) first in
+the first human message of each of the main agent's requests; it sits outside
+``MemoryIndexMiddleware``, which then puts the index ahead of it, and inside
+the summarization, which counts it (``roster=``) as it counts the index and
+drops its snapshot when it writes a summary (``on_written``).
+"""
+
+from __future__ import annotations
+
+from langchain.agents.middleware import ModelRequest
+from langchain_core.messages import AIMessage, HumanMessage
+
+from agentic_cli.workflow.agents import SubAgentPolicy
+from agentic_cli.workflow.agents.roster import ROSTER_CLOSE, ROSTER_HEADER, ROSTER_OPEN
+from agentic_cli.workflow.config import AgentConfig
+from agentic_cli.workflow.deepagents.middleware import MemoryIndexMiddleware, RosterMiddleware
+from agentic_cli.workflow.deepagents.summarization import build_summarization
+from tests.workflow.deepagents.fakes import ScriptedChat, ai
+from tests.workflow.deepagents.test_context import USER_TURN, context, resolved
+from tests.workflow.deepagents.test_manager import _manager, ctx, hermetic, scripted # noqa: F401
+from tests.workflow.deepagents.test_memory_index_middleware import INDEX
+
+ROSTER = "\n".join([ROSTER_OPEN, ROSTER_HEADER,
+ "- researcher-1 (researcher, idle): Find X. — X is 42.", ROSTER_CLOSE])
+
+
+def _request(messages):
+ return ModelRequest(model=ScriptedChat(), messages=messages, state={"messages": messages})
+
+
+async def sent(middleware, messages) -> list:
+ async def handler(request):
+ return request.messages
+
+ return await middleware.awrap_model_call(_request(messages), handler)
+
+
+async def test_the_roster_is_the_first_block_of_the_first_human_message():
+ history = [HumanMessage("Hello."), AIMessage("Hi."), HumanMessage("Again.")]
+
+ messages = await sent(RosterMiddleware(lambda: ROSTER), history)
+
+ assert messages[0].content == [{"type": "text", "text": ROSTER},
+ {"type": "text", "text": "Hello."}]
+ assert messages[1:] == history[1:]
+ assert history[0].content == "Hello." # the state keeps its message
+ assert await sent(RosterMiddleware(lambda: ""), history) == history
+
+
+async def test_outside_the_memory_index_middleware_the_index_goes_ahead_of_it():
+ inner = MemoryIndexMiddleware(lambda: INDEX)
+ outer = RosterMiddleware(lambda: ROSTER)
+
+ async def _messages(request):
+ return request.messages
+
+ async def handler(request):
+ return await inner.awrap_model_call(request, _messages)
+
+ messages = await outer.awrap_model_call(_request([HumanMessage("Hello.")]), handler)
+
+ assert [block["text"] for block in messages[0].content] == [INDEX, ROSTER, "Hello."]
+
+
+async def test_the_summarization_counts_the_roster():
+ chat = ScriptedChat(script=[ai("A summary.")])
+ model = resolved("local:small", agent="solo") # summarizes at 16,150 tokens
+ big = "\n".join([ROSTER_OPEN, ROSTER_HEADER, "- x" * 4_000, ROSTER_CLOSE])
+ plain = build_summarization(chat, model, context())
+ counted = build_summarization(chat, model, context(), roster=lambda: big)
+ both = build_summarization(chat, model, context(), index=lambda: INDEX, roster=lambda: big)
+ history = [HumanMessage(f"Turn {n}: {USER_TURN}") for n in range(1, 4)]
+
+ base = plain._count_tokens(history, None, None)
+ roster = plain.token_counter([HumanMessage(big)])
+ assert counted._count_tokens(history, None, None) == base + roster
+ assert both._count_tokens(history, None, None) == (
+ base + roster + plain.token_counter([HumanMessage(INDEX)])
+ )
+
+
+TEAM = [
+ AgentConfig(name="lead", prompt="p", sub_agents=["helper"]),
+ AgentConfig(name="helper", prompt="p", description="Helps."),
+]
+
+
+async def test_a_root_that_continues_its_sub_agents_counts_it_and_forgets_it(ctx, monkeypatch):
+ """With the policy's ``follow_ups`` (``message_agent``) the root's
+ summarization counts the roster, and its summary drops the roster's
+ snapshot, without a memory tool too; with the policy's defaults neither."""
+ scripted(monkeypatch, lead=[], helper=[])
+ following = _manager(ctx.settings, TEAM, subagents=SubAgentPolicy(follow_ups=True))
+ plain = _manager(ctx.settings, TEAM)
+ try:
+ await following.initialize_services()
+ await plain.initialize_services()
+ summarizer = following._root_summarization
+ plain_summarizer = plain._root_summarization
+ finally:
+ await following.cleanup()
+ await plain.cleanup()
+
+ assert summarizer._roster == following._roster_now
+ assert summarizer._on_written == following._forget_memory_index
+ assert plain_summarizer._roster is None and plain_summarizer._on_written is None
diff --git a/tests/workflow/test_adk_overflow.py b/tests/workflow/test_adk_overflow.py
index ac1286b1..e23f3eed 100644
--- a/tests/workflow/test_adk_overflow.py
+++ b/tests/workflow/test_adk_overflow.py
@@ -864,6 +864,43 @@ async def test_its_retry_keeps_its_task_message(self, project, monkeypatch):
assert texts(events)[-1] == "X is 42."
+class TestAFollowUpsOverflow:
+ async def test_its_retry_keeps_the_instances_brief(self, project, monkeypatch):
+ """A follow-up's task message is its own message: the retry of its
+ refused request leaves out the instance's earlier turns, never its
+ brief, which the follow-up joins."""
+ from agentic_cli.workflow.agents import SubAgentPolicy
+
+ _, status, body = SHAPES["claude-400"]
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+ follow = claude_says("")
+ follow["content"] = [{"type": "tool_use", "id": "toolu_c2", "name": "message_agent",
+ "input": {"agent": "researcher-1", "message": "Now find Y."}}]
+ follow["stop_reason"] = "tool_use"
+ api = Team(coordinator=[delegate(), claude_says("Asked."), follow, claude_says("Done.")],
+ researcher=[claude_says(f"X is 42. {LONG}"), httpx.Response(status, json=body),
+ claude_says("Y is 7.")])
+ route(monkeypatch, anthropic, "AsyncAnthropic", api)
+ manager = GoogleADKWorkflowManager(
+ agent_configs=team(inherit_context=False),
+ settings=BaseSettings(session_store="memory", default_model="claude-sonnet-4-6",
+ prompt_caching_enabled=False),
+ subagents=SubAgentPolicy(follow_ups=True),
+ )
+ try:
+ await turn(manager, "Find X, please.")
+ events = await turn(manager, "Now Y.")
+ finally:
+ await manager.cleanup()
+
+ refused, retry = (r.content.decode() for r in api.requests[4:6])
+ assert "X is 42." in refused and "X is 42." not in retry
+ assert "# Task: Find X." in retry
+ assert retry.index("# Task: Find X.") < retry.index(FIT_NOTE) < retry.index("Now find Y.")
+ assert errors(events) == []
+ assert texts(events)[-1] == "Done."
+
+
async def test_the_handler_comes_before_the_fit_guard(project, monkeypatch):
monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
manager = GoogleADKWorkflowManager(
diff --git a/tests/workflow/test_agent_roster.py b/tests/workflow/test_agent_roster.py
new file mode 100644
index 00000000..ce538913
--- /dev/null
+++ b/tests/workflow/test_agent_roster.py
@@ -0,0 +1,292 @@
+"""The main agent's roster of its open sub-agents (``workflow/agents/roster.py``).
+
+The roster opens the main agent's requests, after the memory index: one line
+per open instance (idle, stopped, running) of the main agent's own, newest
+first, at most ``ROSTER_MAX`` characters in all, whole lines only. It is a
+snapshot per conversation (``Rosters``), taken when the conversation's first
+request asks for it and kept until the manager forgets it, where it forgets
+the memory index's, so the head of the request stays the same for caching.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from datetime import datetime, timezone
+
+import pytest
+
+from agentic_cli.workflow.agents import (
+ INSTANCE_CLOSED,
+ INSTANCE_IDLE,
+ INSTANCE_RUNNING,
+ INSTANCE_STOPPED,
+ RUN_COMPLETED,
+ RUN_RUNNING,
+ AgentRuns,
+ InstanceRecord,
+ RunRecord,
+ SubAgentPolicy,
+)
+from agentic_cli.workflow.agents.roster import (
+ ROSTER_CLOSE,
+ ROSTER_HEADER,
+ ROSTER_MAX,
+ ROSTER_OPEN,
+ Rosters,
+ roster_text,
+)
+from agentic_cli.workflow.events import WorkflowEvent
+from agentic_cli.workflow.sessions import (
+ RunRef,
+ SessionRef,
+ reset_active_turn,
+ set_active_turn,
+)
+from tests.conftest import MockContext
+from tests.workflow.test_agent_records import TEAM, _Kept, turn
+
+FOLLOWING = SubAgentPolicy(follow_ups=True)
+REF = SessionRef(app_name="app", user_id="u", session_id="s")
+OTHER = SessionRef(app_name="app", user_id="u", session_id="t")
+AT = datetime(2026, 11, 19, tzinfo=timezone.utc)
+
+
+def instance(n: int, status: str = INSTANCE_IDLE, *, runs: int = 1, agent: str = "researcher",
+ parent: str = "root", title: str | None = None) -> InstanceRecord:
+ name = f"{agent}-{n}"
+ return InstanceRecord(
+ instance=name, agent=agent, parent=parent, depth=1, inherit_context=False,
+ title=title if title is not None else f"Find thing {n}.", status=status,
+ runs=[f"{name}#{k}" for k in range(1, runs + 1)],
+ )
+
+
+def record(run: str, result: str = "", status: str = RUN_COMPLETED) -> RunRecord:
+ name = run.rpartition("#")[0]
+ ref = RunRef(agent=name.rpartition("-")[0], instance=name, run=run, parent_run=None, depth=1)
+ return RunRecord(ref=ref, call_id=None, title="", status=status, started=AT, result=result)
+
+
+class TestTheText:
+ def test_the_specs_lines_newest_first(self):
+ instances = [instance(1), instance(2, INSTANCE_RUNNING), instance(3, INSTANCE_STOPPED)]
+ records = {
+ "researcher-1#1": record("researcher-1#1", "X is 42.\n\nMore on X."),
+ "researcher-2#1": record("researcher-2#1", "", RUN_RUNNING),
+ "researcher-3#1": record("researcher-3#1", "Y is 7."),
+ }
+
+ assert roster_text(instances, records) == "\n".join([
+ "",
+ "Your sub-agents in this conversation (message_agent continues one):",
+ "- researcher-3 (researcher, stopped): Find thing 3. — Y is 7.",
+ "- researcher-2 (researcher, running): Find thing 2.",
+ "- researcher-1 (researcher, idle): Find thing 1. — X is 42.",
+ "",
+ ])
+ assert (ROSTER_OPEN, ROSTER_CLOSE, ROSTER_MAX) == ("", "", 2_000)
+ assert ROSTER_HEADER == "Your sub-agents in this conversation (message_agent continues one):"
+
+ def test_a_closed_instance_is_left_out_and_none_open_is_no_roster(self):
+ instances = [instance(1, INSTANCE_CLOSED), instance(2)]
+
+ assert "researcher-1" not in roster_text(instances, {})
+ assert "- researcher-2 (researcher, idle): Find thing 2." in roster_text(instances, {})
+ assert roster_text([instance(1, INSTANCE_CLOSED)], {}) == ""
+ assert roster_text([], {}) == ""
+
+ def test_the_last_result_is_the_newest_runs_that_has_one(self):
+ # A follow-up at work has no result yet: its previous run's is the last.
+ working = instance(1, INSTANCE_RUNNING, runs=2)
+ records = {
+ "researcher-1#1": record("researcher-1#1", "\n X is 42. \nMore."),
+ "researcher-1#2": record("researcher-1#2", "", RUN_RUNNING),
+ }
+
+ assert "- researcher-1 (researcher, running): Find thing 1. — X is 42." in (
+ roster_text([working], records)
+ )
+
+ def test_at_most_its_cap_in_whole_lines_the_oldest_left_out(self):
+ long_title = "T" * 80
+ result = "R" * 200
+ instances = [instance(n, title=long_title) for n in range(1, 13)]
+ records = {f"researcher-{n}#1": record(f"researcher-{n}#1", result) for n in range(1, 13)}
+
+ text = roster_text(instances, records)
+
+ lines = text.splitlines()
+ assert lines[:2] == [ROSTER_OPEN, ROSTER_HEADER] and lines[-1] == ROSTER_CLOSE
+ listed = lines[2:-1]
+ line = "- researcher-{n} (researcher, idle): " + long_title + " — " + result
+ assert listed == [line.format(n=n) for n in range(12, 12 - len(listed), -1)]
+ assert len(text) <= ROSTER_MAX
+ # One line more would pass the cap.
+ assert len(text) + len(line.format(n=12 - len(listed))) + 1 > ROSTER_MAX
+ assert 0 < len(listed) < 12
+
+
+def started(ref: RunRef) -> WorkflowEvent:
+ return WorkflowEvent.agent_run(
+ ref, "started", call_id="c1", title=f"Find {ref.instance}.", inherit_context=False,
+ continuable=True,
+ )
+
+
+def ended(ref: RunRef, result: str) -> WorkflowEvent:
+ return WorkflowEvent.agent_run(
+ ref, RUN_COMPLETED, call_id="c1", result=result, instance_status=INSTANCE_IDLE,
+ )
+
+
+def run_of(instance_id: str, *, parent_run: str | None = None, depth: int = 1) -> RunRef:
+ return RunRef(agent=instance_id.rpartition("-")[0], instance=instance_id,
+ run=f"{instance_id}#1", parent_run=parent_run, depth=depth)
+
+
+def observed(runs: AgentRuns, conversation: SessionRef, *events: WorkflowEvent) -> None:
+ token = set_active_turn(conversation)
+ try:
+ for event in events:
+ runs.observe(event)
+ finally:
+ reset_active_turn(token)
+
+
+class TestTheSnapshots:
+ def test_taken_once_per_conversation_and_kept_until_forgotten(self):
+ runs = AgentRuns()
+ rosters = Rosters(lambda: runs)
+ first = run_of("researcher-1")
+ observed(runs, REF, started(first), ended(first, "X is 42."))
+ token = set_active_turn(REF)
+ try:
+ taken = rosters.now()
+ assert "- researcher-1 (researcher, idle): Find researcher-1. — X is 42." in taken
+ # A new instance changes nothing until the snapshot is forgotten.
+ second = run_of("researcher-2")
+ observed(runs, REF, started(second))
+ assert rosters.now() == taken and rosters.snapshots == {REF: taken}
+ rosters.forget()
+ assert "- researcher-2 (researcher, running): Find researcher-2." in rosters.now()
+ finally:
+ reset_active_turn(token)
+
+ def test_none_is_a_snapshot_too_and_outside_a_turn_there_is_none(self):
+ runs = AgentRuns()
+ rosters = Rosters(lambda: runs)
+ assert rosters.now() == "" and rosters.snapshots == {}
+ token = set_active_turn(REF)
+ try:
+ assert rosters.now() == ""
+ observed(runs, REF, started(run_of("researcher-1")))
+ assert rosters.now() == "" # taken: empty until forgotten
+ finally:
+ reset_active_turn(token)
+ assert rosters.snapshots == {REF: ""}
+
+ def test_only_the_main_agents_own_and_only_the_conversations(self):
+ runs = AgentRuns()
+ rosters = Rosters(lambda: runs)
+ mine = run_of("researcher-1")
+ nested = run_of("checker-1", parent_run="researcher-1#1", depth=2)
+ theirs = run_of("researcher-1")
+ observed(runs, REF, started(mine), started(nested))
+ observed(runs, OTHER, started(theirs), ended(theirs, "Elsewhere."))
+ token = set_active_turn(REF)
+ try:
+ text = rosters.now()
+ finally:
+ reset_active_turn(token)
+
+ assert "researcher-1 (researcher, running)" in text
+ assert "checker-1" not in text and "Elsewhere." not in text
+
+ def test_forget_by_conversation_and_clear(self):
+ rosters = Rosters(AgentRuns)
+ rosters.snapshots.update({REF: "a", OTHER: "b"})
+ rosters.forget(OTHER)
+ assert rosters.snapshots == {REF: "a"}
+ rosters.clear()
+ assert rosters.snapshots == {}
+
+
+# -- the manager: taken in a turn, forgotten where the memory index's is ------------------------
+
+
+@pytest.fixture
+def context():
+ with MockContext(google_api_key="test-key") as made:
+ yield made
+
+
+@pytest.fixture
+async def following(context):
+ """``following(subagents=FOLLOWING)``: a manager whose turn delegates once
+ (``test_agent_records._Kept``), with ``subagents``; cleaned up after the test."""
+ made: list[_Kept] = []
+
+ def make(subagents: SubAgentPolicy | None = FOLLOWING) -> _Kept:
+ manager = _Kept(TEAM, settings=context.settings, stored={}, subagents=subagents)
+ made.append(manager)
+ return manager
+
+ yield make
+ for manager in made:
+ await asyncio.wait_for(manager.cleanup(), 10)
+
+
+def roster_in(manager: _Kept, ref: SessionRef) -> str:
+ """What the manager's ``_roster_now`` gives in ``ref``'s turn."""
+ token = set_active_turn(ref)
+ try:
+ return manager._roster_now()
+ finally:
+ reset_active_turn(token)
+
+
+class TestTheManagersRoster:
+ def test_only_a_main_agent_that_continues_its_sub_agents_gets_one(self, following):
+ assert following()._roster_wanted("lead") is True
+ assert following()._roster_wanted("researcher") is False # no sub-agents
+ assert following(None)._roster_wanted("lead") is False # the policy's defaults
+
+ async def test_taken_in_a_turn_and_kept_until_the_memory_index_is_forgotten(self, following):
+ manager = following()
+ await turn(manager, "Find X.")
+ ref = manager.session_ref("s", "u")
+
+ taken = roster_in(manager, ref)
+ assert "- researcher-1 (researcher, idle): Find X. — Done." in taken
+ assert manager._rosters.snapshots == {ref: taken}
+ await turn(manager, "Find Y.")
+ assert roster_in(manager, ref) == taken
+ manager._forget_memory_index(ref)
+ assert "- researcher-2 (researcher, idle): Find Y. — Done." in roster_in(manager, ref)
+
+ async def test_opening_the_conversation_takes_a_new_one(self, following):
+ manager = following()
+ await turn(manager, "Find X.")
+ ref = manager.session_ref("s", "u")
+ assert roster_in(manager, ref)
+
+ await manager.load_session("s", user_id="u")
+
+ assert manager._rosters.snapshots == {}
+
+ async def test_the_release_clears_them_and_a_delete_forgets_its_own(self, following):
+ manager = following()
+ await turn(manager, "Find X.")
+ ref = manager.session_ref("s", "u")
+ other = manager.session_ref("t", "u")
+ roster_in(manager, ref)
+ manager._rosters.snapshots[other] = "kept"
+
+ await manager.delete_session("s", user_id="u")
+ assert manager._rosters.snapshots == {other: "kept"}
+ await manager._release_resources()
+ assert manager._rosters.snapshots == {}
+
+ def test_a_manager_built_without_its_constructor_has_them(self):
+ manager = _Kept.__new__(_Kept)
+ assert isinstance(manager._rosters, Rosters) and manager._rosters is manager._rosters
diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py
index 3658fb02..5e3cfe45 100644
--- a/tests/workflow/test_subagents_contract.py
+++ b/tests/workflow/test_subagents_contract.py
@@ -26,6 +26,11 @@
agent's prompt is ``You are .``, by which ADK's fake API tells the
agents apart.
+``make_crew(..., models={...})`` adds ``models`` entries to the settings: an
+agent on a model with a small window (``SMALL_MODEL``) has its long transcript
+summarized (Deep Agents) or trimmed (ADK). ``Crew.opening`` reads the first
+user message an agent's request held, where the main agent's roster goes.
+
Offline: no provider is reached and no catalog lists (``tests/conftest.py``).
"""
@@ -70,6 +75,7 @@
)
from agentic_cli.workflow.agents.control import STEP_LIMIT_NOTE, RunControl
from agentic_cli.workflow.agents.delegate import 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.envelope import (
INTERRUPTED_ERROR,
@@ -480,6 +486,7 @@ class Crew:
_call_results: Callable[[str, int], list[tuple[str, list[str]]]] | None = None
_instance_mark: Callable[[str], Awaitable[str]] | None = None
_models: Callable[[str], list[str]] | None = None
+ _opening: Callable[[str, int], list[str]] | None = None
async def turn(self, text: str = "Go.") -> list[WorkflowEvent]:
"""One turn of the conversation, run to its end; its events."""
@@ -519,6 +526,13 @@ def models(self, agent: str) -> list[str]:
assert self._models is not None
return self._models(agent)
+ def opening(self, agent: str, call: int = -1) -> list[str]:
+ """The text blocks of the first user message ``agent``'s model request
+ ``call`` held, in order: what opens its conversation (the main
+ agent's memory index and roster, folded into it)."""
+ assert self._opening is not None
+ return self._opening(agent, call)
+
def answer_with(self, answer: Callable[[UserInputRequest], Awaitable[str]]) -> None:
"""Answer every question and permission prompt with ``answer(request)``."""
self.manager.set_input_callback(answer)
@@ -636,13 +650,16 @@ def recorded(self, call_id: str, run: str | None = None) -> bool:
_ASYNC_ANTHROPIC = anthropic.AsyncAnthropic
-def _settings(store: str = "memory") -> BaseSettings:
- return BaseSettings(session_store=store, default_model="claude-sonnet-4-6")
+def _settings(store: str = "memory", models: dict[str, Any] | None = None) -> BaseSettings:
+ return BaseSettings(
+ session_store=store, default_model="claude-sonnet-4-6", models=dict(models or {})
+ )
def _adk_crew(
team: list[AgentConfig], scripts: dict[str, list[Step]], monkeypatch,
subagents: SubAgentPolicy | None = None, store: str = "memory",
+ models: dict[str, Any] | None = None,
) -> Crew:
from agentic_cli.workflow.adk.manager import GoogleADKWorkflowManager
from agentic_cli.workflow.adk.sessions import child_app
@@ -651,7 +668,7 @@ def _adk_crew(
monkeypatch.setattr(anthropic, "AsyncAnthropic", _ASYNC_ANTHROPIC)
route(monkeypatch, anthropic, "AsyncAnthropic", FakeAPI(claude))
manager = GoogleADKWorkflowManager(
- agent_configs=team, settings=_settings(store), subagents=subagents
+ agent_configs=team, settings=_settings(store, models), subagents=subagents
)
def results_read(name: str, call: int) -> dict[str, str]:
@@ -725,22 +742,33 @@ async def instance_mark(instance: str) -> str:
def models(name: str) -> list[str]:
return [body["model"] for sent, body in claude.sent if sent == name]
+ def opening(name: str, call: int) -> list[str]:
+ body = [body for sent, body in claude.sent if sent == name][call]
+ first = next(m for m in body["messages"] if m["role"] == "user")
+ content = first["content"]
+ if isinstance(content, str):
+ return [content]
+ return [block["text"] for block in content if block.get("type") == "text"]
+
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,
)
def _deepagents_crew(
team: list[AgentConfig], scripts: dict[str, list[Step]], monkeypatch,
subagents: SubAgentPolicy | None = None, store: str = "memory",
+ models: dict[str, Any] | None = None,
) -> Crew:
- from langchain_core.messages import ToolMessage
+ from langchain_core.messages import HumanMessage, ToolMessage
from agentic_cli.workflow.deepagents import manager as deepagents_manager
from tests.workflow.deepagents.fakes import ScriptedModels
+ entries = models
models = ScriptedModels(**{
name: [_scripted_answer(step) for step in steps] for name, steps in scripts.items()
})
@@ -755,7 +783,7 @@ def _deepagents_crew(
)
monkeypatch.setattr(deepagents_manager, "build_chat_model", models)
manager = deepagents_manager.DeepAgentsWorkflowManager(
- agent_configs=team, settings=_settings(store), subagents=subagents
+ agent_configs=team, settings=_settings(store, entries), subagents=subagents
)
def results_read(name: str, call: int) -> dict[str, str]:
@@ -833,10 +861,20 @@ async def instance_mark(instance: str) -> str:
def built_models(name: str) -> list[str]:
return [resolved.ref.model for resolved in models.built if resolved.agent == name]
+ def opening(name: str, call: int) -> list[str]:
+ first = next(
+ m for m in models.chats[name].conversation(call) if isinstance(m, HumanMessage)
+ )
+ if isinstance(first.content, str):
+ return [first.content]
+ return [block["text"] for block in first.content
+ if isinstance(block, dict) and block.get("type") == "text"]
+
return Crew(
"deepagents", manager, manager.session_ref(SESSION, USER), results_read, requests,
result_ids, answers, last_message, bodies, tool_names, message_count, state, marked,
_call_results=call_results, _instance_mark=instance_mark, _models=built_models,
+ _opening=opening,
)
@@ -1024,8 +1062,8 @@ def project(tmp_path, monkeypatch) -> Path:
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"``), each agent
- answering from its script (an agent without one has none); every manager
+ 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
made is cleaned up after the test."""
SEEN.clear()
BLOCKING["started"] = asyncio.Event()
@@ -1034,13 +1072,13 @@ async def make_crew(backend, project, monkeypatch):
def make(
team: list[AgentConfig], *, subagents: SubAgentPolicy | None = None,
- store: str = "memory", **scripts: list[Step],
+ 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}
complete[SIDE_CALLS] = list(scripts.get(SIDE_CALLS, ()))
complete[SUMMARIES] = list(scripts.get(SUMMARIES, ()))
build = _adk_crew if backend == "adk" else _deepagents_crew
- crew = build(team, complete, monkeypatch, subagents, store)
+ crew = build(team, complete, monkeypatch, subagents, store, models)
made.append(crew)
return crew
@@ -1868,7 +1906,7 @@ async def test_each_record_names_its_agent_and_its_run(self, make_crew, monkeypa
settings = BaseSettings(
session_store="memory", default_model="claude-sonnet-4-6", raw_llm_logging=True
)
- monkeypatch.setattr(sys.modules[__name__], "_settings", lambda store: settings)
+ monkeypatch.setattr(sys.modules[__name__], "_settings", lambda store, models=None: settings)
crew = make_crew(
team(),
coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")],
@@ -5327,3 +5365,160 @@ async def test_nothing_is_left_and_its_id_numbers_from_1(self, make_crew, store)
await crew.turn("Again.")
assert envelope_read(crew.results_read("coordinator")["c4"])["result"] == "Z is 3."
assert [r.ref.run for r in crew.records()] == ["researcher-1#1"]
+
+
+# -- a growing transcript keeps its brief; the main agent's roster ----------------------------
+
+#: A model with a small window: an input budget of 17,000 tokens, summarized at 14,450.
+SMALL_MODEL = "anthropic:claude-haiku-4-5"
+SMALL_ENTRY = {SMALL_MODEL: {"context_window": 20_000, "max_output": 2_000}}
+
+
+@register_tool(capabilities=EXEMPT, description="Read a long page (a contract-test tool).")
+def contract_read_page(n: int = 1) -> dict:
+ """Page ``n``: about 35,000 characters, its number first."""
+ return {"success": True, "page": f"Page {n}: " + "word " * 7_000}
+
+
+class TestALongTranscriptKeepsItsBrief:
+ """An instance's brief is never lost from its requests as its transcript
+ grows: Deep Agents summarizes the instance against its own budget and
+ keeps the brief ahead of the summary; ADK trims its request (its summaries
+ stay the main agent's) and keeps the brief whatever it leaves out. The
+ difference is the libraries': ADK keeps the run's own message too
+ (``keep_task``), where Deep Agents' summary stands for it once it is
+ older than what a summary keeps word for word."""
+
+ async def test_a_follow_up_after_its_summary_or_trim_still_holds_it(self, make_crew):
+ crew = make_crew(
+ [agent("coordinator", sub_agents=("researcher",)),
+ agent("researcher", tools=(contract_read_page,), model=SMALL_MODEL)],
+ subagents=FOLLOWING, models=SMALL_ENTRY,
+ coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Asked."),
+ calls(message("researcher-1", "Now find Y.", "c2")), says("Done.")],
+ researcher=[calls(use("contract_read_page", "r1", n=1)), says("X is 42."),
+ calls(use("contract_read_page", "r2", n=2)), says("Y is 7.")],
+ summaries=[says("The first page said X is 42.")],
+ )
+
+ await crew.turn()
+ with no_blocking_calls():
+ events = await crew.turn("Find Y too.")
+
+ # Its follow-up's second request was over the researcher's budget...
+ last = crew.bodies("researcher")[-1]
+ assert "Page 1:" not in last and "Page 2:" in last
+ assert [e.metadata["agent"] for e in events
+ if e.type is EventType.CONTEXT_TRIMMED] == ["researcher"]
+ # ...and still held the brief, once.
+ assert last.count("# Task: Find X.") == 1
+ assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Y is 7."
+
+
+def roster(*lines: str) -> str:
+ """The roster that lists ``lines``."""
+ return "\n".join([ROSTER_OPEN, ROSTER_HEADER, *lines, ROSTER_CLOSE])
+
+
+class TestTheRoster:
+ """The main agent's requests carry the roster of its open sub-agents when it
+ can continue them (``message_agent``), first in its conversation, after
+ the memory index: a snapshot taken when the conversation's first request
+ asks for it, taken again where the memory index's is (here: the
+ conversation opened again)."""
+
+ async def test_after_a_delegation_once_the_snapshot_is_retaken(self, make_crew):
+ crew = make_crew(
+ parent_team(), subagents=FOLLOWING,
+ coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Asked."),
+ says("Still."),
+ calls(delegate("researcher", "Find Y.", "c2")), says("Listed.")],
+ researcher=[says("X is 42.\nMore on X."), says("Y is 7.")],
+ )
+ await crew.turn()
+ await crew.turn("Again.")
+ # Taken before the delegation, at the conversation's first request: none yet.
+ assert not any(ROSTER_OPEN in body for body in crew.bodies("coordinator"))
+
+ await crew.manager.load_session(SESSION, user_id=USER)
+ with no_blocking_calls():
+ await crew.turn("And now?")
+
+ listed = roster("- researcher-1 (researcher, idle): Find X. — X is 42.")
+ # The same snapshot for the whole turn: researcher-2 waits for the next one.
+ assert crew.opening("coordinator", -2) == [listed, "Go."]
+ assert crew.opening("coordinator", -1) == [listed, "Go."]
+
+ async def test_a_summary_retakes_it(self, make_crew):
+ """A coordinator whose long conversation outgrows its small model is
+ summarized; the request that carries the summary carries a new
+ roster, which lists the instance the earlier requests' snapshot,
+ taken before it ran, did not."""
+ crew = make_crew(
+ [agent("coordinator", sub_agents=("researcher",), model=SMALL_MODEL),
+ agent("researcher")],
+ subagents=FOLLOWING, models=SMALL_ENTRY,
+ coordinator=[calls(delegate("researcher", "Find X.", "c1")),
+ says("Asked.", usage=(15_000, 10)), says("Done.")],
+ researcher=[says("X is 42.")],
+ summaries=[says("The first turn was read.")],
+ )
+ await crew.turn("Find X: " + "word " * 8_000)
+ with no_blocking_calls():
+ events = await crew.turn("And now? " + "word " * 4_000)
+
+ assert [e.metadata["agent"] for e in events
+ if e.type is EventType.CONTEXT_TRIMMED] == ["coordinator"]
+ listed = roster("- researcher-1 (researcher, idle): Find X. — X is 42.")
+ assert not any(ROSTER_OPEN in block for block in crew.opening("coordinator", -2))
+ assert crew.opening("coordinator", -1)[0] == listed
+
+ async def test_none_with_the_policys_defaults(self, make_crew):
+ crew = make_crew(
+ parent_team(),
+ coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Asked."),
+ says("Still.")],
+ researcher=[says("X is 42.")],
+ )
+ await crew.turn()
+ await crew.manager.load_session(SESSION, user_id=USER)
+ await crew.turn("And now?")
+
+ assert crew.opening("coordinator", -1) == ["Go."]
+ assert not any(ROSTER_OPEN in body for body in crew.bodies("coordinator"))
+
+ async def test_none_when_every_instance_is_closed(self, make_crew):
+ crew = make_crew(
+ parent_team(continuable=False), subagents=FOLLOWING,
+ coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Asked."),
+ says("Still.")],
+ researcher=[says("X is 42.")],
+ )
+ await crew.turn()
+ await crew.manager.load_session(SESSION, user_id=USER)
+ await crew.turn("And now?")
+
+ assert crew.instances() == [("researcher-1", INSTANCE_CLOSED)]
+ assert crew.opening("coordinator", -1) == ["Go."]
+
+ async def test_at_most_its_cap_newest_first_in_whole_lines(self, make_crew):
+ briefs = [f"Find item {n:02d}: " + "x" * 60 for n in range(1, 13)]
+ result = "R" * 150
+ crew = make_crew(
+ parent_team(), subagents=FOLLOWING,
+ coordinator=[calls(*(delegate("researcher", brief, f"c{n}")
+ for n, brief in enumerate(briefs, start=1))),
+ says("Asked."), says("Listed.")],
+ researcher=[says(result) for _ in briefs],
+ )
+ await crew.turn()
+ await crew.manager.load_session(SESSION, user_id=USER)
+ await crew.turn("And now?")
+
+ lines = [f"- researcher-{n} (researcher, idle): {briefs[n - 1]} — {result}"
+ for n in range(12, 0, -1)]
+ fits = [line for k, line in enumerate(lines, start=1)
+ if len(roster(*lines[:k])) <= ROSTER_MAX]
+ opened = crew.opening("coordinator", -1)
+ assert opened == [roster(*fits), "Go."]
+ assert 0 < len(fits) < 12 and len(opened[0]) <= ROSTER_MAX