From b57398ca40689ac14d580167a1d8b3b5e5dd8711 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:11:23 -0500 Subject: [PATCH 01/12] Sub-agents: a start with no call is a new instance each time AgentRuns.run_for names a run per (conversation, parent run, call id) so a repeated call is the same run while it is open. A start with no call (the user's) has no such key: it is a new instance each time, and nothing is remembered under an empty call id. --- src/agentic_cli/workflow/agents/runs.py | 17 ++++++++++++----- tests/workflow/test_agent_runs.py | 16 ++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/agentic_cli/workflow/agents/runs.py b/src/agentic_cli/workflow/agents/runs.py index 73aa6ccd..2a60e612 100644 --- a/src/agentic_cli/workflow/agents/runs.py +++ b/src/agentic_cli/workflow/agents/runs.py @@ -270,7 +270,8 @@ class AgentRuns: def __init__(self, *, on_change: Callable[[SessionRef | None], None] | None = None) -> None: self._on_change = on_change - # (conversation, parent run, call id) -> the run that call started. + # (conversation, parent run, call id) -> the run that call started (a + # start with no call, the user's, has no key). self._runs: dict[tuple[Any, str | None, str], RunRef] = {} # (conversation, agent) -> how many instances of it are numbered. self._numbered: dict[tuple[Any, str], int] = {} @@ -285,18 +286,23 @@ def __init__(self, *, on_change: Callable[[SessionRef | None], None] | None = No self._end_numbers: dict[Any, int] = {} def run_for( - self, conversation: SessionRef | None, parent: RunRef | None, call_id: str, agent: str + self, + conversation: SessionRef | None, + parent: RunRef | None, + call_id: str | None, + agent: str, ) -> RunRef: """The run the call ``call_id`` of ``parent``'s starts, of ``agent``. The same key names the same run while it is open; one that has ended is followed by a new instance of ``agent`` (numbered per agent, per conversation, from 1) and its run ``#1``. ``parent`` None, or the - root's own (``root_run``), is the root. + root's own (``root_run``), is the root. A start with no call + (``call_id`` None: the user's) has no key: each is a new instance. """ parent_run = None if parent is None or parent.is_root else parent.run key = (conversation, parent_run, call_id) - ref = self._runs.get(key) + ref = self._runs.get(key) if call_id is not None else None if ref is not None and not self._ended(conversation, ref): return ref count = self._numbered.get((conversation, agent), 0) + 1 @@ -309,7 +315,8 @@ def run_for( parent_run=parent_run, depth=(parent.depth if parent is not None else 0) + 1, ) - self._runs[key] = ref + if call_id is not None: + self._runs[key] = ref return ref def number_from(self, conversation: SessionRef | None, counts: Mapping[str, int]) -> None: diff --git a/tests/workflow/test_agent_runs.py b/tests/workflow/test_agent_runs.py index 69d24616..caf77b4e 100644 --- a/tests/workflow/test_agent_runs.py +++ b/tests/workflow/test_agent_runs.py @@ -148,6 +148,22 @@ def test_a_run_id_names_its_instance(self): assert [run_instance(ref.run) for ref in (middle, leaf)] == ["middle-1", "leaf-1"] + def test_without_a_call_each_is_a_new_instance_under_the_root(self): + """The user's start (``/agent new``) has no call: each is its own run, + an open one too, numbered with the rest.""" + runs = AgentRuns() + first = started(runs, ONE, "c1", "helper") + + named = [runs.run_for(ONE, None, None, "helper") for _ in range(2)] + + assert named == [ + RunRef(agent="helper", instance="helper-2", run="helper-2#1", parent_run=None, + depth=1), + RunRef(agent="helper", instance="helper-3", run="helper-3#1", parent_run=None, + depth=1), + ] + assert runs.run_for(ONE, None, "c1", "helper") is first # the call's own, still open + class TestNumberFrom: """A conversation's store may keep instances an earlier manager numbered From 46b7bf313e5da3d7e931075f40d861afc8ab47ab Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:11:56 -0500 Subject: [PATCH 02/12] Sub-agents: the user's start of a new instance Delegations.start_by_user starts a type for the user (/agent new): through start, with no caller and no call, so its parent is the root at depth 1, started_by user, counted toward no turn's runs, its brief the objective titled with its first line. Only a type whose spawnable_by and the policy's spawn_sources both name the user (startable_by_user); another is refused naming those the user may start, and a blank objective is refused (user_start_refused), with no run. --- src/agentic_cli/workflow/agents/delegate.py | 72 ++++++- tests/workflow/test_agent_delegate.py | 209 ++++++++++++++++++++ 2 files changed, 280 insertions(+), 1 deletion(-) diff --git a/src/agentic_cli/workflow/agents/delegate.py b/src/agentic_cli/workflow/agents/delegate.py index 84f233d4..03741499 100644 --- a/src/agentic_cli/workflow/agents/delegate.py +++ b/src/agentic_cli/workflow/agents/delegate.py @@ -180,6 +180,7 @@ from agentic_cli.workflow.agents.slots import NEW, Slot, SlotPool from agentic_cli.workflow.agents.spawn import ( AGENT_SOURCE, + USER_SOURCE, depth_sentence_applies, may_spawn, spawnable, @@ -219,8 +220,15 @@ ) -#: ``started_by`` of a run the user starts (a follow-up from a view). +#: ``started_by`` of a run the user starts (a follow-up from a view, or +#: ``/agent new``'s first run). USER = "user" +#: What the user's start of a type they may not start is told (``types``: those +#: they may, ", "-joined), and the start in an app that lets them start none. +USER_START_ERROR = "You cannot start '{agent_type}' here. Types you can start: {types}." +NO_USER_TYPES_ERROR = "This app lets you start no agent types." +#: The user's start with no objective (not text, or blank). +NO_OBJECTIVE_ERROR = "A new agent needs an objective." #: What a follow-up to an instance its sender may not continue is told. NOT_YOURS_ERROR = "'{instance}' is not one of your sub-agents. {yours}" YOURS = "Yours: {instances}." @@ -804,6 +812,68 @@ async def start(self, request: StartRequest) -> Delegated: tools=request.tools, model=request.model, ) + def startable_by_user(self) -> tuple[str, ...]: + """The types the user may start (``/agent new``), in config order. + + ``spawnable`` for ``"user"``: the policy's ``spawn_sources`` and the + type's ``spawnable_by`` both name the user. An inheriting one too: its + parent is the root, whose conversation it reads. + """ + return spawnable(list(self._types.values()), self.policy, USER_SOURCE) + + def user_start_refused(self, agent_type: str, objective: str) -> str | None: + """Why the user may not start ``agent_type`` on ``objective``, else None. + + A type they may not start (``startable_by_user``), named with those + they may (``NO_USER_TYPES_ERROR`` for none), then an objective that + is not text or is blank. + """ + startable = self.startable_by_user() + if agent_type not in startable: + if not startable: + return NO_USER_TYPES_ERROR + return USER_START_ERROR.format(agent_type=agent_type, types=", ".join(startable)) + if not isinstance(objective, str) or not objective.strip(): + return NO_OBJECTIVE_ERROR + return None + + async def start_by_user( + self, + conversation: SessionRef | None, + agent_type: str, + objective: str, + *, + state: Mapping[str, Any] | None = None, + history: Callable[[], Any] | None = None, + ) -> Delegated: + """The user's new instance of ``agent_type`` (``/agent new``), run to its end; its envelope. + + Through ``start``: no caller and no call, so its parent is the root + and its depth 1 (``max_spawn_depth`` never refuses it), + ``started_by`` the user, counted toward no turn's runs, a working + slot taken while it works. Its brief is the objective, titled with + its first line (``run_title``). One the user may not start + (``user_start_refused``) is the error result, and nothing else + happens. + + Args: + conversation: The conversation; None: the active turn's. + agent_type: The type to start. + objective: What the run is to do, as the user wrote it. + state: The conversation's shared state (its outside-content + mark), which the run starts from. + history: Called once, only when the type inherits: the + conversation, as the backend reads it. + """ + error = self.user_start_refused(agent_type, objective) + if error is not None: + return _refused(error) + return await self.start(StartRequest( + agent_type=agent_type, brief=Brief(title=run_title(objective), objective=objective), + started_by=USER, conversation=conversation, state=dict(state or {}), + history=history, counted=False, + )) + async def follow_up( self, request: FollowUpRequest, diff --git a/tests/workflow/test_agent_delegate.py b/tests/workflow/test_agent_delegate.py index b1a97d3b..bbee2cf4 100644 --- a/tests/workflow/test_agent_delegate.py +++ b/tests/workflow/test_agent_delegate.py @@ -4441,3 +4441,212 @@ async def test_a_narrowed_ones_follow_up_is_told_so(self, how): def test_the_cause_is_cut_to_200_characters(self): error = ToolsUnlistedError("choosy", ValueError("x" * 500)) assert len(error.reason) <= 203 and error.reason.startswith("ValueError: xxx") + + +# -- the user's start: /agent new -------------------------------------------------------- + +#: The user may start a type at run time (``/agent new``), agents none. +USERS = SubAgentPolicy(spawn_sources={"user"}) +READS = AgentConfig(name="reads", prompt="p", description="Reads it all.", inherit_context=True, + spawnable_by=frozenset({"user"})) +STARTABLE = {**SPAWNING, "reads": READS} + + +async def users_start( + made: Delegations, agent_type: str, objective: Any, **fields: Any +) -> tuple[dict[str, Any], list[WorkflowEvent]]: + """``made.start_by_user(CONVERSATION, ...)`` in a turn of ``CONVERSATION`` + (its span open), as the manager's ``start_instance`` runs it; its result, + the runs the turn counted, and what it reported.""" + live = LiveEvents() + out: dict[str, Any] = {} + + async def source(): + token = set_active_turn(CONVERSATION) + scope = open_turn_scope() + try: + with live_events.reporting(live): + out["result"] = await made.start_by_user( + CONVERSATION, agent_type, objective, **fields + ) + out["counted"] = runs_this_turn() + finally: + close_turn_scope(scope) + reset_active_turn(token) + if False: # pragma: no cover + yield + + events = [item async for item in merged(source(), live)] + return out, events + + +class TestTheUsersStart: + """``start_by_user``: a new instance the user starts (``/agent new``), + through ``start``: its parent the root, at depth 1, ``started_by`` the + user, counted toward no turn's runs, titled from its objective; only a + type the policy and the type let the user start.""" + + async def test_a_type_the_user_may_start_runs_under_the_root(self): + hook, asked = answering("Answered.") + runs = AgentRuns() + + out, events = await users_start( + delegations(hook, runs=runs, types=STARTABLE, policy=USERS), + "asked", "Answer Y.\nIn full.", + ) + + assert out["result"].result == { + "success": True, "agent": "asked-1", "run": "asked-1#1", + "status": RUN_COMPLETED, "partial": False, "result": "Answered.", "error": None, + } + (run,) = asked + assert (run.ref.depth, run.ref.parent_run, run.history, run.follow_up) == ( + 1, None, None, False + ) + assert run.message == task_message( + Brief(title="Answer Y.", objective="Answer Y.\nIn full.") + ) + assert events[0].metadata == { + "status": RUN_STARTED, "agent": "asked", "partial": False, "title": "Answer Y.", + "brief": {"title": "Answer Y.", "objective": "Answer Y.\nIn full."}, + "started_by": "user", "mode": "blocking", + "inherit_context": False, "continuable": True, + } + assert out["counted"] == 0 + (instance,) = runs.instances(CONVERSATION) + assert (instance.instance, instance.parent, instance.depth, instance.title) == ( + "asked-1", "root", 1, "Answer Y." + ) + (record,) = runs.records(CONVERSATION) + assert (record.started_by, record.call_id) == ("user", None) + + async def test_each_start_is_a_new_instance(self): + hook, _ = answering() + made = delegations(hook, types=STARTABLE, policy=USERS) + + first, _ = await users_start(made, "asked", "One.") + second, _ = await users_start(made, "asked", "Two.") + + assert [out["result"].result["agent"] for out in (first, second)] == [ + "asked-1", "asked-2", + ] + + async def test_it_runs_past_the_runs_a_turn_may_start(self): + """Its turn's runs are full: the user's start is no run of theirs.""" + hook, asked = answering() + made = delegations(hook, types=STARTABLE, + policy=SubAgentPolicy(spawn_sources={"user"}, max_runs_per_turn=1)) + live = LiveEvents() + results: list[Any] = [] + + async def source(): + token = set_active_turn(CONVERSATION) + scope = open_turn_scope() + try: + with live_events.reporting(live): + results.append(await made.start(start_request(call_id="c1"))) + results.append(await made.start_by_user(CONVERSATION, "asked", "Go.")) + results.append(runs_this_turn()) + finally: + close_turn_scope(scope) + reset_active_turn(token) + if False: # pragma: no cover + yield + + async for _ in merged(source(), live): + pass + + counted, users, total = results + assert (counted.result["status"], users.result["status"], total) == ( + RUN_COMPLETED, RUN_COMPLETED, 1 + ) + assert len(asked) == 2 + + async def test_an_inheriting_type_reads_the_conversation_given(self): + hook, asked = answering() + + await users_start( + delegations(hook, types=STARTABLE, policy=USERS), "reads", "Read it.", + history=lambda: ["the conversation"], + ) + + (run,) = asked + assert run.history == ["the conversation"] + assert run.message == task_message(Brief(title="Read it.", objective="Read it."), + inherit=True) + assert run.message.endswith(INHERITED_CONTEXT_NOTE) + + async def test_its_state_is_the_one_given(self): + hook, asked = answering() + + await users_start( + delegations(hook, types=STARTABLE, policy=USERS), "asked", "Go.", + state={"outside_content": "web_fetch"}, + ) + + assert asked[0].state == {"outside_content": "web_fetch"} + + def test_the_types_the_user_may_start(self): + hook, _ = answering() + assert delegations(hook, types=STARTABLE, policy=USERS).startable_by_user() == ( + "asked", "reads", + ) + assert delegations(hook, types=STARTABLE).startable_by_user() == () + # Agents may start helper; only the user may start asked and reads. + assert delegations(hook, types=STARTABLE, policy=AGENTS).startable_by_user() == ( + "asked", "reads", + ) + agents_only = SubAgentPolicy(spawn_sources={"agent"}) + assert delegations(hook, types=STARTABLE, policy=agents_only).startable_by_user() == () + + @pytest.mark.parametrize("agent_type", ["researcher", "helper", "nobody", "coordinator"]) + async def test_one_it_may_not_start_is_refused_naming_those_it_may(self, agent_type): + hook, asked = answering() + runs = AgentRuns() + + out, events = await users_start( + delegations(hook, runs=runs, types=STARTABLE, policy=USERS), agent_type, "Go." + ) + + assert out["result"].result == { + "success": False, + "error": f"You cannot start '{agent_type}' here. Types you can start: asked, reads.", + } + assert out["result"].run is None + assert (asked, events, runs.records(CONVERSATION), out["counted"]) == ([], [], [], 0) + + @pytest.mark.parametrize("policy", [SubAgentPolicy(), SubAgentPolicy(spawn_sources={"agent"})]) + async def test_with_none_the_user_may_start_it_says_so(self, policy): + hook, asked = answering() + + out, events = await users_start( + delegations(hook, types=STARTABLE, policy=policy), "asked", "Go." + ) + + assert out["result"].result == { + "success": False, "error": "This app lets you start no agent types.", + } + assert (asked, events) == ([], []) + + @pytest.mark.parametrize("objective", ["", " \n ", None, 42]) + async def test_a_start_needs_an_objective(self, objective): + hook, asked = answering() + + out, events = await users_start( + delegations(hook, types=STARTABLE, policy=USERS), "asked", objective + ) + + assert out["result"].result == { + "success": False, "error": "A new agent needs an objective.", + } + assert (asked, events) == ([], []) + + def test_its_refusals_say_why_before_any_run(self): + hook, _ = answering() + made = delegations(hook, types=STARTABLE, policy=USERS) + + assert made.user_start_refused("asked", "Go.") is None + assert made.user_start_refused("nobody", " ") == ( + "You cannot start 'nobody' here. Types you can start: asked, reads." + ) + assert made.user_start_refused("asked", " ") == "A new agent needs an objective." From 3d411b51d2d0329685bc4c63da412ea77c462b8f Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:15:35 -0500 Subject: [PATCH 03/12] Sub-agents: the manager's start of a new instance for the user start_instance(agent_type, objective) starts a sub-agent the user asked for as a turn of its own on the open conversation, as run_instance continues one: its first event is the run's start, which names the instance; a type the user may not start, or a blank objective, is one ERROR. Stopping the stream is the user's stop of the run, also before the run started (it is stopped as it starts), and interrupt_instance ends it as a process exit does. An inheriting type reads the conversation as the root's task would hand it, through a new backend hook (_inherited_history: ADK's session events, Deep Agents' root messages). run_instance and start_instance share one stream (_users_run). --- src/agentic_cli/workflow/adk/manager.py | 19 +- src/agentic_cli/workflow/base_manager.py | 252 ++++++++++--- .../workflow/deepagents/manager.py | 12 +- tests/workflow/test_subagents_contract.py | 346 ++++++++++++++++++ 4 files changed, 574 insertions(+), 55 deletions(-) diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index eeda09cc..06ca279f 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -81,7 +81,12 @@ stored_instances, turn_state, ) -from agentic_cli.workflow.adk.task_tool import SHARED_KEYS, TaskTool, follow_up_tools +from agentic_cli.workflow.adk.task_tool import ( + SHARED_KEYS, + TaskTool, + follow_up_tools, + inherited_events, +) from agentic_cli.workflow.adk.tool_result_cap_plugin import ToolResultCapPlugin from agentic_cli.workflow.agents.control import KEPT_TOOLS from agentic_cli.workflow.agents.delegate import ( @@ -2004,6 +2009,18 @@ async def _conversation_state(self, ref: SessionRef) -> dict[str, Any]: mark = self._outside_marks.get(ref) return {OUTSIDE_CONTENT_KEY: mark} if mark else {} + async def _inherited_history(self, ref: SessionRef) -> list[Any]: + """``ref``'s conversation as an inheriting run the user starts reads it. + + The conversation's session, read whole: copies of its root-visible + events (``inherited_events``), as the root's ``task`` hands them + from its session; none for a conversation with no session yet. + """ + session = await self._session_service.get_session( + app_name=ref.app_name, user_id=ref.user_id, session_id=ref.session_id, + ) + return inherited_events(session.events) if session is not None else [] + async def _deliver_job_notice( self, notice: str, record: Any, result: Any, ref: SessionRef ) -> AsyncGenerator[WorkflowEvent, None]: diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index 6830eee3..2cc0f3e5 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -33,6 +33,7 @@ from typing import Any, AsyncGenerator, Awaitable, Callable, Iterator, Mapping, TYPE_CHECKING from agentic_cli.workflow.events import ( + EventType, UserInputRequest, UserInputUnavailable, WorkflowEvent, @@ -69,6 +70,7 @@ INSTANCE_CLOSED, INSTANCE_RUNNING, RUN_END_STATUSES, + RUN_STARTED, AgentRuns, ) from agentic_cli.workflow.agents.spawn import can_have_children @@ -91,6 +93,7 @@ from agentic_cli.workflow.model_settings import ModelSettings, ThinkingSettings from agentic_cli.workflow.outside_content import OutsideContentMarks, outside_content_note from agentic_cli.workflow.sessions import ( + RunRef, SessionInfo, SessionRef, close_turn_scope, @@ -150,15 +153,51 @@ class _UserRun: - """A run the user started (``run_instance``), while its turn lasts: its - task once it starts, and whether it is interrupted (``interrupt_instance``), - which makes a stop of its stream a turn's cancel, not the user's stop.""" + """A run the user started (``run_instance``, ``start_instance``), while its + turn lasts: its task once it starts, and whether it is interrupted + (``interrupt_instance``), which makes a stop of its stream a turn's + cancel, not the user's stop.""" def __init__(self) -> None: self.work: asyncio.Task[Delegated] | None = None self.interrupted = False +class _UsersRunEvents(live_events.LiveEvents): + """The live events of a run the user starts (``_users_run``). + + The first run whose start they report is that run (the runs it starts + are reported later), noted as its start is reported, before anything + else of it, so a stop of the stream finds it even before the stream's + consumer read that start. ``Delegations`` reports a start on the loop. + """ + + def __init__(self) -> None: + super().__init__() + #: The run the user started, once its start is reported. + self.started: RunRef | None = None + self._started = asyncio.Event() + + def emit(self, event: WorkflowEvent) -> None: + if ( + self.started is None + and event.type is EventType.AGENT_RUN + and event.metadata.get("status") == RUN_STARTED + and event.run is not None + ): + self.started = event.run + self._started.set() + super().emit(event) + + async def until_started(self, work: "asyncio.Task[Any]") -> None: + """Wait until the run has started, or ``work`` (what starts it) has ended.""" + waiter = asyncio.ensure_future(self._started.wait()) + try: + await asyncio.wait({work, waiter}, return_when=asyncio.FIRST_COMPLETED) + finally: + waiter.cancel() + + def _module_of(klass: type) -> str: module = getattr(klass, "__module__", None) return module if isinstance(module, str) else "" @@ -940,57 +979,151 @@ async def run_instance( instance=instance, message=message, started_by=USER, conversation=ref, state=await self._conversation_state(ref), ) - live = live_events.LiveEvents() - key = (ref, instance) - held = self._user_runs[key] = _UserRun() + async with contextlib.aclosing(self._users_run( + ref, lambda: self._delegations.follow_up(request), + instance=instance, name=f"user run of {instance}", + )) as events: + async for event in events: + yield event - def stop_it() -> None: - # Its consumer stopped (Ctrl+C): the user's stop of the run - # alone, unless the run is interrupted (a turn's cancel). - if held.interrupted: - return - record = self.agent_runs.instance(ref, instance) - if record is not None and record.status == INSTANCE_RUNNING and record.runs: - self._delegations.cancel( - record.runs[-1], by=USER, error=STOPPED_BY_USER_ERROR, conversation=ref - ) + async def start_instance( + self, + agent_type: str, + objective: str, + *, + session_id: str | None = None, + user_id: str | None = None, + ) -> AsyncGenerator[WorkflowEvent, None]: + """Start a sub-agent of ``agent_type`` for the user, as a turn of its own (provisional). + + What ``/agent new `` runs: the instance's first + run, ``started_by`` the user, its parent the root (depth 1, so + ``max_spawn_depth`` never refuses it), its brief the objective, + titled with its first line. A turn of the conversation + (``_turn``: the root does not run), whose first event is the run's + ``AGENT_RUN`` start, which names the instance; then the run's events, + as ``run_instance``'s. It is counted toward no turn's runs + (``max_runs_per_turn``), takes a working slot while it works, and + starts from the conversation's outside-content mark; an inheriting + type reads the conversation as the root's ``task`` would hand it + (``_inherited_history``). A type the user may not start (the + policy's ``spawn_sources`` and the type's ``spawnable_by`` must both + name ``"user"``) or a blank objective is one ``ERROR`` event, and + nothing runs. The run's envelope is kept for ``instance_result``. + + Stopping the stream (Ctrl+C) is the user's stop of the run, as in + ``run_instance``: it ends ``cancelled`` by the user and the instance + is ``stopped``; a stop before the run started stops the run as it + starts. ``interrupt_instance`` ends it as a turn's cancel does. - async def source() -> AsyncGenerator[WorkflowEvent, None]: - if held.interrupted: # before its run started: none starts - raise asyncio.CancelledError - # The run's own task: a stop cancels the run, not its caller, - # so it ends cancelled by the user, not interrupted. - work = held.work = asyncio.create_task( - self._delegations.follow_up(request), name=f"user run of {instance}" - ) - try: - delegated = await asyncio.shield(work) - except asyncio.CancelledError: - if held.interrupted: - work.cancel() # the run's caller is cancelled: it ends interrupted - else: - stop_it() # a run that started after the consumer's stop looked - await asyncio.wait([work]) - if not work.cancelled() and work.exception() is None: - self._user_ran(ref, instance, work.result()) - raise - if delegated.run is None: - yield WorkflowEvent.error(str(delegated.result.get("error", ""))) - return - self._user_ran(ref, instance, delegated) + Yields: + The run's ``WorkflowEvent``s, its start first. + Raises: + Exception: The store's, when the conversation's sub-agent records, + or an inheriting type's conversation, cannot be read: nothing + runs. + """ + async with self._turn(session_id, user_id) as ref: + refused = self._delegations.user_start_refused(agent_type, objective) + if refused is not None: + yield WorkflowEvent.error(refused) + return + config = next((c for c in self._agent_configs if c.name == agent_type), None) + history = None + if config is not None and config.inherit_context: + copy = await self._inherited_history(ref) + history = lambda: copy # noqa: E731 - read once, before the run + state = await self._conversation_state(ref) + async with contextlib.aclosing(self._users_run( + ref, + lambda: self._delegations.start_by_user( + ref, agent_type, objective, state=state, history=history, + ), + name=f"user start of {agent_type}", + )) as events: + async for event in events: + yield event + + async def _users_run( + self, + ref: SessionRef, + work: Callable[[], Awaitable[Delegated]], + *, + instance: str | None = None, + name: str, + ) -> AsyncGenerator[WorkflowEvent, None]: + """A run the user starts in ``ref``'s turn, streamed (``run_instance``, ``start_instance``). + + ``work()`` starts it through ``Delegations`` and returns its + envelope; it runs in a task of its own, so a stop of the stream + cancels the run, not its caller: the run ends ``cancelled`` by the + user. A run that has not started when the stream stops is stopped + as it starts. An interrupted one (``interrupt_instance``, held under + ``instance``, or the new instance's id once its start is reported) + ends as a turn's cancel ends its runs. A refusal (no run) is one + ``ERROR``. The envelope of a run that ended is kept (``_user_ran``). + """ + live = _UsersRunEvents() + held = _UserRun() + key = (ref, instance) if instance is not None else None + if key is not None: + self._user_runs[key] = held + + def stop_it() -> None: + # Its consumer stopped (Ctrl+C): the user's stop of the run + # alone, unless the run is interrupted (a turn's cancel). + if held.interrupted or live.started is None or live.started.run is None: + return + self._delegations.cancel( + live.started.run, by=USER, error=STOPPED_BY_USER_ERROR, conversation=ref + ) + + async def source() -> AsyncGenerator[WorkflowEvent, None]: + if held.interrupted: # before its run started: none starts + raise asyncio.CancelledError + # The run's own task: a stop cancels the run, not its caller, + # so it ends cancelled by the user, not interrupted. + task = held.work = asyncio.create_task(work(), name=name) try: - with live_events.reporting(live): - async with contextlib.aclosing( - live_events.merged(source(), live, on_stop=stop_it) - ) as items: - async for item in items: - event = self._apply_event_hook(item) - if event is not None: - yield event - finally: - if self._user_runs.get(key) is held: - del self._user_runs[key] + delegated = await asyncio.shield(task) + except asyncio.CancelledError: + if held.interrupted: + task.cancel() # the run's caller is cancelled: it ends interrupted + else: + stop_it() + if live.started is None: + # Stopped before its run started (its instance being + # numbered): the run that starts is stopped as it starts. + await live.until_started(task) + stop_it() + await asyncio.wait([task]) + if not task.cancelled() and task.exception() is None: + ended = task.result() + if ended.run is not None: + self._user_ran(ref, ended.run.instance, ended) + raise + if delegated.run is None: + yield WorkflowEvent.error(str(delegated.result.get("error", ""))) + return + self._user_ran(ref, delegated.run.instance, delegated) + + try: + with live_events.reporting(live): + async with contextlib.aclosing( + live_events.merged(source(), live, on_stop=stop_it) + ) as items: + async for item in items: + if key is None and live.started is not None: + # The new instance is named: interrupt_instance finds it. + key = (ref, live.started.instance) + self._user_runs[key] = held + event = self._apply_event_hook(item) + if event is not None: + yield event + finally: + if key is not None and self._user_runs.get(key) is held: + del self._user_runs[key] def interrupt_instance( self, instance: str, *, session_id: str | None = None, user_id: str | None = None @@ -998,12 +1131,13 @@ def interrupt_instance( """Interrupt the run of ``instance`` the user started, as a turn's cancel (provisional). What a process exit does to a run: not the user's stop. The run of - that ``run_instance`` ends ``interrupted`` and its instance stays + that ``run_instance`` (or ``start_instance``, once its start named + the instance) ends ``interrupted`` and its instance stays ``idle``, so its parent may continue it; its stream then raises ``asyncio.CancelledError``, and its turn records the run and writes the records as it ends (a stop of that stream from now on is no - stop of the user's either). Only ``run_instance``'s run: a run of - the root's turn ends with that turn. + stop of the user's either). Only ``run_instance``'s and + ``start_instance``'s run: a run of the root's turn ends with that turn. Returns: Whether such a run was working (or about to start); False, @@ -1150,6 +1284,18 @@ async def _conversation_state(self, ref: SessionRef) -> dict[str, Any]: """ return {} + async def _inherited_history(self, ref: SessionRef) -> list[Any]: + """``ref``'s conversation as an inheriting run the user starts reads it (a backend hook). + + What the root's ``task`` would hand such a run (its ``history``), + read from the store between turns: ADK the conversation's + root-visible events (``adk/task_tool.py::inherited_events``), Deep + Agents the root's messages with its summary applied + (``deepagents/task_tool.py::inherited_messages``). Empty for a + conversation with none yet. The base has none. + """ + return [] + async def tell_root( self, text: str, *, session_id: str | None = None, user_id: str | None = None ) -> AsyncGenerator[WorkflowEvent, None]: diff --git a/src/agentic_cli/workflow/deepagents/manager.py b/src/agentic_cli/workflow/deepagents/manager.py index 3236fd72..a019164d 100644 --- a/src/agentic_cli/workflow/deepagents/manager.py +++ b/src/agentic_cli/workflow/deepagents/manager.py @@ -100,7 +100,7 @@ summary_event, write_summary, ) -from agentic_cli.workflow.deepagents.task_tool import SHARED_KEYS +from agentic_cli.workflow.deepagents.task_tool import SHARED_KEYS, inherited_messages from agentic_cli.workflow.deepagents.tools import to_langchain_tools from agentic_cli.workflow.events import WorkflowEvent from agentic_cli.workflow.langchain_models import build_chat_model @@ -567,6 +567,16 @@ async def _conversation_state(self, ref: "SessionRef") -> dict[str, Any]: mark = self._outside_marks.get(ref) return {"outside_content": mark} if mark else {} + async def _inherited_history(self, ref: "SessionRef") -> list[Any]: + """``ref``'s conversation as an inheriting run the user starts reads it. + + The root's messages in its newest checkpoint, its summary applied + (``inherited_messages``), as the root's ``task`` hands them from its + state; none for a conversation with no checkpoint yet. + """ + values = (await self._root.aget_state(run_config(ref))).values + return inherited_messages(values) + async def _deliver_job_notice( self, notice: str, record: Any, result: Any, ref: "SessionRef" ) -> AsyncGenerator[WorkflowEvent, None]: diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index b2e8960a..bae2dbb2 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -7321,3 +7321,349 @@ async def test_after_a_crash_its_open_call_is_answered_at_the_next_turn( assert [(call, len(held)) for call, held in second.call_results("coordinator", 0) if call == "c1"] == [("c1", 1)] assert INTERRUPTED in second.results_read("coordinator", 0)["c1"] + + +# -- the user's start: /agent new ----------------------------------------------------- + +#: The user may start a type at run time (``/agent new``); agents none. +STARTING = SubAgentPolicy(spawn_sources={"user"}) +HELPER_1 = RunRef(agent="helper", instance="helper-1", run="helper-1#1", parent_run=None, depth=1) + + +def user_team(**fields: Any) -> list[AgentConfig]: + """``team()`` and a helper only the user may start (by default), which looks + up, blocks or holds.""" + fields.setdefault("spawnable_by", frozenset({"user"})) + return [*team(), helper(tools=(contract_lookup, contract_block, contract_hold), **fields)] + + +async def user_start(crew: Crew, agent_type: str, objective: str) -> list[WorkflowEvent]: + """The user's new ``agent_type`` instance (``start_instance``), run to its end; its events.""" + return [event async for event in crew.manager.start_instance(agent_type, objective)] + + +class TestTheUsersStart: + """``start_instance``: a new instance the user starts, a turn of its own on + the open conversation: its parent the root, at depth 1, ``started_by: + user``, counted toward no turn's runs, a working slot taken; its first + event is its run's start; the root does not run.""" + + async def test_it_starts_a_new_instance_under_the_root_and_streams_as_a_turn( + self, make_crew + ): + from agentic_cli.workflow.agents.brief import Brief, task_message + + crew = make_crew( + user_team(), subagents=STARTING, + helper=[calls(use("contract_lookup", "h1", q="X")), says("Helped with X.")], + ) + + events = await user_start(crew, "helper", "Help with X.\nIn the docs.") + + started, ended = runs_of(events) + assert events[0] is started + assert started.run == HELPER_1 + assert (started.metadata["started_by"], started.metadata["title"], + started.metadata["brief"]) == ( + "user", "Help with X.", + {"title": "Help with X.", "objective": "Help with X.\nIn the docs."}, + ) + assert "call_id" not in started.metadata + assert (ended.metadata["status"], ended.metadata["result"], + ended.metadata["instance_status"]) == ( + RUN_COMPLETED, "Helped with X.", INSTANCE_IDLE + ) + assert [(e.content, e.run) for e in events if e.type is EventType.TEXT] == [ + ("Helped with X.", HELPER_1), + ] + assert crew.last_message("helper", 0) == task_message( + Brief(title="Help with X.", objective="Help with X.\nIn the docs.") + ) + assert crew.requests("coordinator") == 0 + (instance,) = crew.manager.agent_runs.instances(crew.conversation) + assert (instance.instance, instance.agent, instance.parent, instance.depth, + instance.status, instance.title) == ( + "helper-1", "helper", "root", 1, INSTANCE_IDLE, "Help with X." + ) + (record,) = crew.records() + assert (record.started_by, record.call_id, record.status) == ("user", None, RUN_COMPLETED) + assert crew.manager.instance_result("helper-1") == { + "success": True, "agent": "helper-1", "run": "helper-1#1", + "status": RUN_COMPLETED, "partial": False, "result": "Helped with X.", "error": None, + } + + async def test_each_start_is_a_new_instance(self, make_crew): + crew = make_crew(user_team(), subagents=STARTING, + helper=[says("One."), says("Two.")]) + + await user_start(crew, "helper", "One.") + await user_start(crew, "helper", "Two.") + + assert crew.instances() == [("helper-1", INSTANCE_IDLE), ("helper-2", INSTANCE_IDLE)] + + async def test_it_is_not_counted_toward_its_turns_runs(self, make_crew): + """With one run a turn, the new instance's own delegation runs: the + user's start took none of the turn's runs.""" + crew = make_crew( + [*team(), agent("planner", sub_agents=("checker",), description="Plans.", + spawnable_by=frozenset({"user"})), + agent("checker", tools=(contract_lookup,))], + subagents=SubAgentPolicy(spawn_sources={"user"}, max_runs_per_turn=1), + planner=[calls(delegate("checker", "Check X.", "p1")), says("Planned.")], + checker=[says("Checked.")], + ) + + events = await user_start(crew, "planner", "Plan X.") + + assert [(e.run.run, e.metadata["status"]) for e in runs_of(events)] == [ + ("planner-1#1", RUN_STARTED), ("checker-1#1", RUN_STARTED), + ("checker-1#1", RUN_COMPLETED), ("planner-1#1", RUN_COMPLETED), + ] + assert envelope_read(crew.results_read("planner")["p1"])["result"] == "Checked." + + async def test_it_takes_a_working_slot(self, make_crew): + crew = make_crew( + user_team(), subagents=SubAgentPolicy(spawn_sources={"user"}, max_active=1), + helper=[calls(use("contract_hold", "h1")), says("Held.")], + ) + + starting = asyncio.create_task(user_start(crew, "helper", "Hold.")) + crew.started.append(starting) + await asyncio.wait_for(HELD["started"].wait(), 10) + held = crew.slots().free + HELD["go"].set() + events = await asyncio.wait_for(starting, 10) + + assert (held, crew.slots().free) == (0, 1) + assert runs_of(events)[-1].metadata["status"] == RUN_COMPLETED + + async def test_one_the_user_may_not_start_is_one_error_and_nothing_runs(self, make_crew): + crew = make_crew(user_team(), subagents=STARTING, helper=[says("[never asked]")]) + + refused = [ + [(e.type, e.content) for e in await user_start(crew, agent_type, objective)] + for agent_type, objective in (("researcher", "Find X."), ("nobody", "Go."), + ("helper", " ")) + ] + + assert refused == [ + [(EventType.ERROR, "You cannot start 'researcher' here. Types you can start: helper.")], + [(EventType.ERROR, "You cannot start 'nobody' here. Types you can start: helper.")], + [(EventType.ERROR, "A new agent needs an objective.")], + ] + assert (crew.records(), crew.requests("helper")) == ([], 0) + + @pytest.mark.parametrize("policy", [None, SubAgentPolicy(spawn_sources={"agent"})]) + async def test_an_app_that_lets_the_user_start_none_says_so(self, make_crew, policy): + crew = make_crew(user_team(spawnable_by=frozenset({"agent", "user"})), subagents=policy, + helper=[says("[never asked]")]) + + events = await user_start(crew, "helper", "Help.") + + assert [(e.type, e.content) for e in events] == [ + (EventType.ERROR, "This app lets you start no agent types."), + ] + assert crew.records() == [] + + async def test_an_inheriting_type_reads_the_conversation(self, make_crew): + """Its parent is the root: it reads the root's conversation, as a + root's ``task`` would hand it.""" + from agentic_cli.workflow.agents.brief import INHERITED_CONTEXT_NOTE, Brief, task_message + + crew = make_crew( + [*team(), agent("reader", inherit_context=True, description="Reads.", + spawnable_by=frozenset({"user"}))], + subagents=STARTING, + coordinator=[says("Noted, Ada.")], reader=[says("The code is 7.")], + ) + await crew.turn("My name is Ada and the code is 7.") + + events = await user_start(crew, "reader", "Find the code.") + + (first,) = crew.bodies("reader") + assert "My name is Ada and the code is 7." in first and "Noted, Ada." in first + last = crew.last_message("reader", 0) + assert last == task_message( + Brief(title="Find the code.", objective="Find the code."), inherit=True + ) + assert last.endswith(INHERITED_CONTEXT_NOTE) + assert runs_of(events)[-1].metadata["result"] == "The code is 7." + assert crew.requests("coordinator") == 1 + + async def test_its_view_and_the_roots_message_agent_follow_it_up(self, make_crew): + crew = make_crew( + user_team(), subagents=SubAgentPolicy(spawn_sources={"user"}, follow_ups=True), + coordinator=[calls(message("helper-1", "And Z?", "c1")), says("Asked.")], + helper=[says("Helped with X."), says("Y is 7."), says("Z is 9.")], + ) + await user_start(crew, "helper", "Help with X.") + + await user_turn(crew, "helper-1", "And Y?") + await crew.turn() + + assert [(r.ref.run, r.status, r.started_by) for r in crew.records()] == [ + ("helper-1#1", RUN_COMPLETED, "user"), + ("helper-1#2", RUN_COMPLETED, "user"), + ("helper-1#3", RUN_COMPLETED, "agent:root"), + ] + assert envelope_read(crew.results_read("coordinator")["c1"])["result"] == "Z is 9." + # One transcript: the root's follow-up reads both of the user's runs. + assert "Helped with X." in crew.bodies("helper")[2] + assert "Y is 7." in crew.bodies("helper")[2] + + async def test_after_a_restart_it_is_numbered_past_the_stored(self, make_crew): + first = make_crew(user_team(), subagents=STARTING, store="sqlite", + helper=[says("One.")]) + await user_start(first, "helper", "One.") + await first.manager.cleanup() + second = make_crew(user_team(), subagents=STARTING, store="sqlite", + helper=[says("Two.")]) + + events = await user_start(second, "helper", "Two.") + + assert runs_of(events)[0].run.instance == "helper-2" + assert second.instances() == [("helper-1", INSTANCE_IDLE), ("helper-2", INSTANCE_IDLE)] + + +class TestTheUsersStopOfANewInstance: + """Stopping ``start_instance``'s stream (Ctrl+C in its view) is the user's + stop of its first run: ``cancelled`` by the user, the instance + ``stopped``; a run that starts after the stop is stopped as it starts. + ``interrupt_instance`` (a process exit) is no stop of the user's.""" + + async def test_ctrl_c_stops_its_first_run_by_the_user_and_the_instance_is_stopped( + self, make_crew + ): + crew = make_crew(user_team(), subagents=STARTING, + helper=[calls(use("contract_block", "h1")), says("Went on.")]) + seen: list[WorkflowEvent] = [] + + async def view() -> None: + async for event in crew.manager.start_instance("helper", "Wait here."): + seen.append(event) + + viewing = asyncio.create_task(view()) + await asyncio.wait_for(BLOCKING["started"].wait(), 10) + await Crew.stop(viewing) + + (record,) = crew.records() + assert (record.ref.run, record.status, record.cancelled_by, record.error) == ( + "helper-1#1", RUN_CANCELLED, "user", "stopped by the user", + ) + assert crew.instances() == [("helper-1", INSTANCE_STOPPED)] + assert seen[0].run == HELPER_1 + assert crew.manager.instance_result("helper-1")["cancelled_by"] == "user" + # Only the user continues it; its stopped call answered once. + events = await user_turn(crew, "helper-1", "Go on.") + assert runs_of(events)[-1].metadata["status"] == RUN_COMPLETED + assert [call for call, _ in crew.call_results("helper", -1)] == ["h1"] + assert crew.instances() == [("helper-1", INSTANCE_IDLE)] + + async def test_ctrl_c_as_the_stream_starts_stops_the_run_by_the_user(self, make_crew): + import inspect + + crew = make_crew(user_team(), subagents=STARTING, helper=[says("[never asked]")]) + + async def view() -> None: + async for _ in crew.manager.start_instance("helper", "Go."): + pass + + viewing = asyncio.create_task(view()) + landed = False + for _ in range(10_000): + await asyncio.sleep(0) + pumps = [t for t in asyncio.all_tasks() if t.get_name() == live_events.PUMP_TASK] + if pumps and inspect.getcoroutinestate(pumps[0].get_coro()) == inspect.CORO_CREATED: + viewing.cancel() + landed = True + break + if viewing.done(): + break + assert landed, "the cancel could not be landed in the window" + with contextlib.suppress(asyncio.CancelledError): + await asyncio.wait_for(viewing, 10) + + (record,) = crew.records() + assert (record.ref.run, record.status, record.cancelled_by) == ( + "helper-1#1", RUN_CANCELLED, "user", + ) + assert crew.instances() == [("helper-1", INSTANCE_STOPPED)] + assert crew.requests("helper") == 0 + + async def test_a_stop_while_its_instance_is_numbered_stops_the_run_as_it_starts( + self, make_crew + ): + """The stop lands while the start reads the store's instances + (before its run starts): the run that starts then is stopped.""" + crew = make_crew(user_team(), subagents=STARTING, helper=[says("[never asked]")]) + delegations = crew.manager._delegations + read, gate = asyncio.Event(), asyncio.Event() + stored = delegations._stored + + async def slow(conversation: SessionRef) -> Any: + read.set() + await gate.wait() + return await stored(conversation) + + delegations._stored = slow + + async def view() -> None: + async for _ in crew.manager.start_instance("helper", "Go."): + pass + + viewing = asyncio.create_task(view()) + await asyncio.wait_for(read.wait(), 10) + viewing.cancel() + await asyncio.sleep(0.05) + assert crew.records() == [] # not started yet + gate.set() + with contextlib.suppress(asyncio.CancelledError): + await asyncio.wait_for(viewing, 10) + + (record,) = crew.records() + assert (record.ref.run, record.status, record.cancelled_by) == ( + "helper-1#1", RUN_CANCELLED, "user", + ) + assert crew.instances() == [("helper-1", INSTANCE_STOPPED)] + assert crew.requests("helper") == 0 + + async def test_an_interrupt_ends_its_run_as_a_turns_cancel_and_the_instance_idle( + self, make_crew + ): + crew = make_crew(user_team(), subagents=STARTING, + helper=[calls(use("contract_block", "h1")), says("Went on.")]) + + async def view() -> None: + async for _ in crew.manager.start_instance("helper", "Wait here."): + pass + + viewing = asyncio.create_task(view()) + await asyncio.wait_for(BLOCKING["started"].wait(), 10) + assert crew.manager.interrupt_instance("helper-1") is True + done, _ = await asyncio.wait({viewing}, timeout=10) + if not done: + await Crew.stop(viewing) + assert done, "the interrupted run did not end" + assert viewing.cancelled() + + (record,) = crew.records() + assert (record.status, record.cancelled_by) == (RUN_INTERRUPTED, None) + assert crew.instances() == [("helper-1", INSTANCE_IDLE)] + assert crew.manager.interrupt_instance("helper-1") is False + + +class TestTheUsersStartOffTheLoop: + async def test_it_blocks_no_event_loop(self, make_crew): + """An inheriting type's: the conversation read from the sqlite store too.""" + crew = make_crew( + [*team(), agent("reader", inherit_context=True, description="Reads.", + spawnable_by=frozenset({"user"}))], + subagents=STARTING, store="sqlite", + coordinator=[says("Noted, Ada.")], reader=[says("The code is 7.")], + ) + await crew.turn("My name is Ada and the code is 7.") + + with no_blocking_calls(): + events = await user_start(crew, "reader", "Find the code.") + + assert runs_of(events)[-1].metadata["result"] == "The code is 7." From 891c546bc7bb529c1758b8f8705033381d4e730f Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:15:56 -0500 Subject: [PATCH 04/12] CLI: draw a new sub-agent's first run in its view MessageProcessor.process_start runs the workflow's start_instance as a turn: once the run's start names the new instance, opens is told it (its view opens there) before the start is drawn, and from then on the instance's text is the reply and its lines name nobody, as in a follow-up's view. A refusal is the turn's one error, and nothing opens. --- src/agentic_cli/cli/message_processor.py | 92 +++++++++++++++++++++++- tests/test_message_processor_render.py | 72 +++++++++++++++++++ 2 files changed, 162 insertions(+), 2 deletions(-) diff --git a/src/agentic_cli/cli/message_processor.py b/src/agentic_cli/cli/message_processor.py index 722d55c9..5475ea59 100644 --- a/src/agentic_cli/cli/message_processor.py +++ b/src/agentic_cli/cli/message_processor.py @@ -18,7 +18,12 @@ from agentic_cli.cli.dialogs import dialog_lock from agentic_cli.constants import truncate from agentic_cli.logging import Loggers, bind_context -from agentic_cli.workflow.agents.runs import RUN_INPUT_REQUIRED, RUN_QUEUED, RUN_RUNNING +from agentic_cli.workflow.agents.runs import ( + RUN_INPUT_REQUIRED, + RUN_QUEUED, + RUN_RUNNING, + RUN_STARTED, +) from agentic_cli.workflow.sessions import ConversationChangedError, instance_of if TYPE_CHECKING: @@ -649,6 +654,73 @@ def _source(workflow): _source, workflow_controller, ui, settings, usage_tracker, viewed=instance ) + async def process_start( + self, + agent_type: str, + objective: str, + workflow_controller: "WorkflowController", + ui: "ThinkingPromptSession", + settings: "BaseSettings", + usage_tracker: "UsageTracker | None" = None, + session_id: str | None = None, + *, + opens: "Callable[[str], Awaitable[None]] | None" = None, + ) -> TurnResult: + """Start a new sub-agent instance for the user and draw its first run, in its view. + + The source is ``workflow.start_instance`` (``/agent new``), whose + first event is the run's ``AGENT_RUN`` start. ``opens`` is called + with the instance that start names before it is drawn (the view + opens there), and from then on the run is drawn as + ``process_instance`` draws one: the instance's text is the reply and + its lines name nobody. A start that cannot run is the turn's one + ``ERROR``, and ``opens`` is not called. + + Args: + agent_type: The type to start. + objective: The user's objective for it. + workflow_controller: Controller managing workflow lifecycle. + ui: UI session for output. + settings: Application settings. + usage_tracker: Optional tracker for accumulating LLM token usage. + session_id: The conversation, the app's durable session. + opens: Called once with the new instance's id (``researcher-2``). + + Returns: + The turn's outcome; ``TurnResult.delivered`` is True only when the + event stream ran to completion. + + Raises: + asyncio.CancelledError: Ctrl+C stopped it (the user's stop of the + run): ``CANCELLED_LINE`` has been said, once. + """ + async with _says_so_when_stopped(ui, lambda: _job_manager(workflow_controller)): + if not await workflow_controller.ensure_initialized(ui): + ui.add_error( + "Cannot process message - workflow not initialized. " + "Please check your API keys (GOOGLE_API_KEY or ANTHROPIC_API_KEY)." + ) + return TurnResult( + TurnStatus.UNAVAILABLE, error="workflow not initialized" + ) + + bind_context(user_id=settings.default_user) + logger.info( + "handling_instance_start", agent_type=agent_type, objective_length=len(objective) + ) + + def _source(workflow): + return workflow.start_instance( + agent_type, + objective, + session_id=session_id, + user_id=settings.default_user, + ) + + return await self._run_turn( + _source, workflow_controller, ui, settings, usage_tracker, opens=opens + ) + async def process_notice( self, text: str, @@ -797,12 +869,16 @@ async def _run_turn( usage_tracker: "UsageTracker | None" = None, *, viewed: str | None = None, + opens: "Callable[[str], Awaitable[None]] | None" = None, ) -> TurnResult: """Drive one turn from an event-source factory through the UI. Shared by ``process`` (user message), ``process_resume`` (job result), ``process_instance`` (a sub-agent's run in its view, whose - instance is ``viewed``) and ``process_notice``. + instance is ``viewed``), ``process_start`` (a new instance's first + run, viewed once ``opens`` was told the instance its first + ``AGENT_RUN`` start names, before that start is drawn) and + ``process_notice``. ``source_factory(workflow)`` returns the WorkflowEvent async generator to consume; everything else (events box, HITL callback, Ctrl+C cancel, rate-limit retry, token accounting) is identical. @@ -848,6 +924,8 @@ async def _run_turn( The turn's outcome as a :class:`TurnResult`. ``partial`` reports whether the turn had already emitted output or run a tool. """ + from agentic_cli.workflow.events import EventType + state = _EventProcessingState( usage_tracker=usage_tracker, workflow_controller=workflow_controller, @@ -944,6 +1022,16 @@ async def _consume() -> None: try: async with aclosing(source_factory(workflow)) as events: async for event in events: + if ( + opens is not None + and state.viewed is None + and event.type is EventType.AGENT_RUN + and event.metadata.get("status") == RUN_STARTED + ): + # A start's run, named: its view opens here. + state.viewed = instance_of(event.run) + if state.viewed is not None: + await opens(state.viewed) handler = dispatch.get(event.type) if handler is not None: state.at_work = _at_work(event, state.viewed) diff --git a/tests/test_message_processor_render.py b/tests/test_message_processor_render.py index cfcd34b7..8fc25f8b 100644 --- a/tests/test_message_processor_render.py +++ b/tests/test_message_processor_render.py @@ -634,6 +634,11 @@ async def run_instance(self, instance, message, *, session_id=None, user_id=None async for event in self.process(message, user_id, session_id): yield event + async def start_instance(self, agent_type, objective, *, session_id=None, user_id=None): + self.asked.append(("start_instance", agent_type, objective, session_id, user_id)) + async for event in self.process(objective, user_id, session_id): + yield event + async def tell_root(self, text, *, session_id=None, user_id=None): self.asked.append(("tell_root", text, session_id, user_id)) async for event in self.process(text, user_id, session_id): @@ -734,3 +739,70 @@ async def test_the_root_reads_the_notice_and_its_answer_is_shown(self): ("tell_root", "The user worked with researcher-1 directly.", "s1", "tester"), ] assert ui.responses() == ["Noted: Y is 7."] + + +HELPER_1 = RunRef("helper", "helper-1", "helper-1#1", None, 1) +CHECKER_1 = RunRef("checker", "checker-1", "checker-1#1", "helper-1#1", 2) + + +class TestAStartInItsView: + """``process_start``: the user's new instance (``/agent new``, + ``start_instance``), drawn as a view's run once its start names it: + ``opens`` is told the instance before that start is drawn, and from then + on the instance's text is the reply and its lines name nobody.""" + + async def test_opens_is_told_the_instance_its_start_names_then_it_is_in_view(self): + events = [ + WorkflowEvent.agent_run(HELPER_1, "started", title="Help.", started_by="user"), + _by(HELPER_1, WorkflowEvent.tool_call("lookup", {"q": "x"})), + _by(CHECKER_1, WorkflowEvent.tool_call("check", {})), + _text_of(HELPER_1, "Helped."), + WorkflowEvent.agent_run(HELPER_1, "completed", result="Helped."), + ] + ui = _Watched() + workflow = _Viewing(events, ui) + opened: list[tuple[str, int]] = [] + + async def opens(instance: str) -> None: + opened.append((instance, len(workflow.lines))) + + result = await MessageProcessor().process_start( + "helper", "Help.", workflow_controller=ReplayController(workflow), ui=ui, + settings=_settings(), session_id="s1", opens=opens, + ) + + assert result.delivered + assert workflow.asked == [("start_instance", "helper", "Help.", "s1", "tester")] + assert opened == [("helper-1", 0)] # before its start was drawn + assert workflow.lines == [ + "Processing...", "Calling: lookup", "checker-1 › Calling: check", + "checker-1 › Calling: check", "checker-1 › Calling: check", + ] + assert ui.responses() == ["Helped."] + + async def test_a_refusal_is_the_turns_error_and_opens_nothing(self): + ui = _Watched() + workflow = _Viewing([WorkflowEvent.error("You cannot start 'x' here.")], ui) + opened: list[str] = [] + + async def opens(instance: str) -> None: + opened.append(instance) + + result = await MessageProcessor().process_start( + "x", "Go.", workflow_controller=ReplayController(workflow), ui=ui, + settings=_settings(), opens=opens, + ) + + assert not result.delivered + assert ui.errors() == ["You cannot start 'x' here."] + assert opened == [] + + async def test_the_main_agents_turn_opens_nothing(self): + """``opens`` is a start's: a turn's run starts are drawn as before.""" + ui, lines = await _watch([ + WorkflowEvent.agent_run(HELPER_1, "started", title="Help."), + _text_of(HELPER_1, "Helped."), + ]) + + assert lines == ["Processing...", "helper-1 › Helped."] + assert ui.responses() == [] From 643d383e376b376c13d593d67a57251baf3f9a9c Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:16:10 -0500 Subject: [PATCH 05/12] CLI: /agent new The /agent command takes new , the objective the rest of the line as typed, and hands them to the app's start_agent; without a type or an objective it says Usage: /agent new . /agent alone, the command's usage and its examples (/help agent) name it. --- src/agentic_cli/cli/agents_command.py | 41 ++++++++++---- tests/cli/test_agents_command.py | 78 +++++++++++++++++++++++++-- 2 files changed, 106 insertions(+), 13 deletions(-) diff --git a/src/agentic_cli/cli/agents_command.py b/src/agentic_cli/cli/agents_command.py index a796c882..c717199e 100644 --- a/src/agentic_cli/cli/agents_command.py +++ b/src/agentic_cli/cli/agents_command.py @@ -17,9 +17,11 @@ its error and its tokens by model. ``/agent `` opens one's view (``cli/agent_view.py``: the user works with -it directly, ``/back`` returns); ``/agent stop `` is the user's stop -of an instance (its run, if one works, cancelled by the user; only the user -may start its next run) and ``/agent close `` the user's close of it and +it directly, ``/back`` returns); ``/agent new `` starts a +new instance of a type the user may start (its objective the rest of the +line, as typed), whose view opens with its first run; ``/agent stop `` is +the user's stop of an instance (its run, if one works, cancelled by the user; +only the user may start its next run) and ``/agent close `` the user's close of it and its own sub-agents (no more runs; its work stays readable). Each says what it did, or why not. @@ -70,8 +72,12 @@ #: What ``/agents `` and ``/agent`` say for an id the conversation has no record of. NO_SUCH_AGENT = "No sub-agent {id} in this conversation. Type /agents for the list." #: What ``/agent`` alone says, and ``/agent stop`` or ``/agent close`` without an id. -AGENT_USAGE = "Usage: /agent | /agent stop | /agent close " +AGENT_USAGE = ( + "Usage: /agent | /agent new | /agent stop | /agent close " +) SUBCOMMAND_USAGE = "Usage: /agent {subcommand} " +#: What ``/agent new`` says without a type or an objective. +NEW_USAGE = "Usage: /agent new " #: What ``/agent stop`` says it did. STOPPED_TEXT = "Stopped {instance}: only you can start its next run." #: What ``/agent stop`` says when the instance ended up closed (a type that takes no more runs). @@ -121,23 +127,40 @@ async def execute(self, args: str, app: Any) -> None: class AgentCommand(Command): - """Open, stop or close one of the open conversation's sub-agents.""" + """Open, start, stop or close one of the open conversation's sub-agents.""" def __init__(self) -> None: super().__init__( name="agent", - description="Open one of this conversation's sub-agents, or stop or close one", - usage="/agent | stop | close ", - examples=["/agent researcher-2", "/agent stop researcher-2", "/agent close researcher-2"], + description=( + "Open one of this conversation's sub-agents, start a new one, or stop or close one" + ), + usage="/agent | new | stop | close ", + examples=[ + "/agent researcher-2", + "/agent new researcher Find what changed in the 2.0 release.", + "/agent stop researcher-2", + "/agent close researcher-2", + ], category=CommandCategory.WORKFLOW, ) async def execute(self, args: str, app: Any) -> None: - """``/agent `` opens its view; ``stop `` and ``close `` stop and close it.""" + """``/agent `` opens its view; ``new `` starts one + and opens its view; ``stop `` and ``close `` stop and close it.""" workflow = _workflow(app) if workflow is None: return conversation = workflow.session_ref(getattr(app, "session_id", None)) + words = args.split(None, 1) + if words and words[0] == "new": + # The objective is the rest of the line, as typed. + rest = words[1].split(None, 1) if len(words) > 1 else [] + if len(rest) < 2 or not rest[1].strip(): + app.session.add_warning(NEW_USAGE) + return + await app.start_agent(rest[0], rest[1].strip()) + return parts = self.parse_args(args).positional.split() if not parts: app.session.add_warning(AGENT_USAGE) diff --git a/tests/cli/test_agents_command.py b/tests/cli/test_agents_command.py index f3d18f84..2f22af8e 100644 --- a/tests/cli/test_agents_command.py +++ b/tests/cli/test_agents_command.py @@ -25,7 +25,14 @@ from rich.console import Console from agentic_cli.cli import agents_command -from agentic_cli.cli.agents_command import AGENT_USAGE, NO_RUNS, AgentCommand, AgentsCommand +from agentic_cli.cli.agents_command import ( + AGENT_USAGE, + NEW_USAGE, + NO_RUNS, + AgentCommand, + AgentsCommand, +) +from agentic_cli.cli.builtin_commands import HelpCommand from agentic_cli.cli.commands import CommandCategory, CommandRegistry from agentic_cli.config import BaseSettings from agentic_cli.workflow.adk.manager import GoogleADKWorkflowManager @@ -585,6 +592,10 @@ async def test_each_says_why_it_did_nothing(self, manager): assert not any(s.add_success.called for s in said) async def test_without_an_id_it_says_how(self, manager): + assert AGENT_USAGE == ( + "Usage: /agent | /agent new | /agent stop " + "| /agent close " + ) said = [await agent(manager, args) for args in ("", "stop", "close")] assert [s.add_warning.call_args.args for s in said] == [ @@ -609,6 +620,55 @@ async def unreadable(conversation: SessionRef) -> None: ) +class TestNew: + """``/agent new ``: the type, then the rest of the line + as typed, handed to the app's ``start_agent`` (``tests/cli/test_agent_view.py`` + runs it).""" + + @staticmethod + async def new(manager, args: str): + """``/agent `` in an app that records what it was asked to start.""" + started: list[tuple[str, str]] = [] + + async def start_agent(agent_type: str, objective: str) -> bool: + started.append((agent_type, objective)) + return True + + app = SimpleNamespace(workflow=manager, session_id="s1", session=autospec_session(), + start_agent=start_agent) + await AgentCommand().execute(args, app) + return app.session, started + + async def test_the_objective_is_the_rest_of_the_line_as_typed(self, manager): + _, started = await self.new(manager, 'new researcher Find --all of "X",\tnow. ') + + assert started == [("researcher", 'Find --all of "X",\tnow.')] + + @pytest.mark.parametrize("args", ["new", "new researcher", "new researcher "]) + async def test_without_a_type_or_an_objective_it_says_how(self, manager, args): + session, started = await self.new(manager, args) + + assert NEW_USAGE == "Usage: /agent new " + session.add_warning.assert_called_once_with(NEW_USAGE) + assert started == [] + + async def test_help_shows_it_with_an_example(self): + registry = CommandRegistry() + registry.register(HelpCommand()) + registry.register(AgentCommand()) + session = autospec_session() + + await HelpCommand().execute("agent", SimpleNamespace(command_registry=registry, + session=session)) + + console = Console(file=io.StringIO(), record=True, width=120) + console.print(*session.add_rich.call_args.args) + text = console.export_text() + assert "/agent | new | stop | close " in text + assert "/agent new researcher Find what changed in the 2.0 release." in text + assert "start a new one" in text + + class _Down: """An app whose workflow is not running.""" @@ -641,10 +701,11 @@ async def test_when_it_failed_to_start(self): "Sub-agent runs not available (failed to start)." ) - async def test_agent_says_the_same(self): + @pytest.mark.parametrize("args", ["stop researcher-1", "new researcher Find X."]) + async def test_agent_says_the_same(self, args): app = _Down(None) - await AgentCommand().execute("stop researcher-1", app) + await AgentCommand().execute(args, app) app.session.add_warning.assert_called_once_with( "Sub-agent runs not available (initializing...)." @@ -664,4 +725,13 @@ def test_it_is_a_built_in_workflow_command(): one = registry.get("agent") assert isinstance(one, AgentCommand) assert one.category is CommandCategory.WORKFLOW - assert one.usage == "/agent | stop | close " + assert one.usage == "/agent | new | stop | close " + assert one.description == ( + "Open one of this conversation's sub-agents, start a new one, or stop or close one" + ) + assert one.examples == [ + "/agent researcher-2", + "/agent new researcher Find what changed in the 2.0 release.", + "/agent stop researcher-2", + "/agent close researcher-2", + ] From 86eae4fe7ffdf59686bdb23dded1af2af8c985ca Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:17:58 -0500 Subject: [PATCH 06/12] CLI: /agent new opens the new sub-agent's view on its first run start_view (BaseCLIApp.start_agent) leaves a view that is open, then starts the instance (ConversationCore.start_instance) in a task of its own; once the run's start names the instance its view opens, holding that task and the processor drawing it (AgentView.adopt, AgentView(processor=)), so the first run streams there, a line steers it, Ctrl+C is the user's stop and /back tells the main agent, as for a follow-up. A refusal opens nothing; Ctrl+C before the view opened stops the run and opens none. --- src/agentic_cli/cli/agent_view.py | 98 +++++++++++++-- src/agentic_cli/cli/app.py | 16 ++- src/agentic_cli/cli/conversation.py | 45 +++++++ tests/cli/test_agent_view.py | 183 ++++++++++++++++++++++++++++ 4 files changed, 334 insertions(+), 8 deletions(-) diff --git a/src/agentic_cli/cli/agent_view.py b/src/agentic_cli/cli/agent_view.py index 44747da3..a7e024dc 100644 --- a/src/agentic_cli/cli/agent_view.py +++ b/src/agentic_cli/cli/agent_view.py @@ -23,6 +23,13 @@ the user's, so the instance stays ``idle``. A closed instance's view is read-only: no prompt, and a line typed there is refused. +``/agent new `` starts an instance for the user (the +manager's ``start_instance``: its parent the main agent, ``started_by: +user``) and opens its view once the run's start names it: the run streams +there, in a task the view holds as it holds a follow-up's, so a line typed +steers it, Ctrl+C stops it and ``/back`` tells the main agent of it. In +another view it leaves that one first, as ``/back`` does. + ``/back`` leaves: it waits for a run still working, prints ``── back to main ──``, and, when a run the user started there ended since the main agent was last told, tells the main agent once, in a notice turn (``tell_root`` with @@ -97,10 +104,18 @@ class AgentView: told: The run of the user's whose envelope the main agent knows of (``instance_result``'s, as the view opened): ``/back`` tells it only of a later one. + processor: The view's message processor; None: a new one + (``/agent new``'s is the one drawing the instance's first run). """ def __init__( - self, app: Any, instance: str, conversation: "SessionRef", told: str | None + self, + app: Any, + instance: str, + conversation: "SessionRef", + told: str | None, + *, + processor: MessageProcessor | None = None, ) -> None: self.app = app self.instance = instance @@ -108,7 +123,7 @@ def __init__( self.told = told #: The view's own message processor: its runs' task list is the #: instance's, never the main agent's task box. - self.processor = MessageProcessor() + self.processor = processor if processor is not None else MessageProcessor() #: The prompt the app had: put back by ``/back``. self.prompt_before: Any = None self._runs: set[asyncio.Task[None]] = set() @@ -241,9 +256,14 @@ async def take(self, line: str) -> None: ): app.session.add_message("system", STEERED.format(instance=self.instance)) return - run = asyncio.create_task( + self.adopt(asyncio.create_task( self._run(line, self._last), name=f"view run of {self.instance}" - ) + )) + + def adopt(self, run: "asyncio.Task[None]") -> None: + """Hold ``run``, a task that works for the instance in view: its last, + which a line typed next waits for, stopped by Ctrl+C (``stop``) and + waited for by ``settled``.""" self._last = run self._runs.add(run) run.add_done_callback(self._ended) @@ -346,14 +366,78 @@ async def open_view(app: Any, instance: str) -> bool: latest = workflow.instance_result( instance, session_id=conversation.session_id, user_id=conversation.user_id ) - view = AgentView(app, instance, conversation, told=(latest or {}).get("run")) + _enter(app, AgentView(app, instance, conversation, told=(latest or {}).get("run")), record) + return True + + +def _enter(app: Any, view: AgentView, record: "InstanceRecord") -> None: + """Make ``view`` the app's: its rule and recap, its prompt and status bar.""" view.show(record) view.prompt_before = app.session.message app._agent_view = view app._workflow_controller.view_segment = view.status_segment view.refresh() - logger.info("agent_view_opened", instance=instance) - return True + logger.info("agent_view_opened", instance=view.instance) + + +async def start_view(app: Any, agent_type: str, objective: str) -> bool: + """``/agent new `` (``BaseCLIApp.start_agent``): a new + instance for the user, and its view. + + A view open first is left, as ``/back`` leaves it (its run waited for, + the main agent told). The start runs in a task of its own, a write to + the conversation under its turn lock (``ConversationCore.start_instance``) + drawn by a processor of its own; once the run's start names the + instance, its view opens on it, holding that task and that processor, + so the rest of the run streams there as a follow-up's does. This + returns then, or when the start ended without a run (a refusal, said; + a conversation another process has open). Ctrl+C before the view + opened (the command's cancel) stops the run as the view's Ctrl+C does, + and opens none. + + Returns: + Whether the new instance's view opened. + """ + if app.agent_view is not None: + await leave_view(app) + processor = MessageProcessor() + opened: asyncio.Future[bool] = asyncio.get_running_loop().create_future() + start: asyncio.Task[None] | None = None + + async def opens(instance: str) -> None: + # Called inside the start, once its run's start names the instance. + workflow = app.workflow + conversation = workflow.session_ref(getattr(app, "session_id", None)) + record = workflow.agent_runs.instance(conversation, instance) + if record is None or opened.done(): + return + view = AgentView(app, instance, conversation, told=None, processor=processor) + assert start is not None + view.adopt(start) + _enter(app, view, record) + opened.set_result(True) + + async def run() -> None: + parts = dataclasses.replace(app._turn_parts(), processor=processor) + try: + await app._conversation.start_instance(agent_type, objective, parts, opens=opens) + finally: + if not opened.done(): + opened.set_result(False) + view = app.agent_view + if view is not None and view.processor is processor: + view.refresh() + + start = asyncio.create_task(run(), name=f"new {agent_type}") + try: + if await asyncio.shield(opened): + return True + except asyncio.CancelledError: + start.cancel() + await asyncio.wait({start}) + raise + await start # ended without a run: its failure, if any, is the command's + return False async def leave_view(app: Any) -> bool: diff --git a/src/agentic_cli/cli/app.py b/src/agentic_cli/cli/app.py index 08045c34..43b3a98e 100644 --- a/src/agentic_cli/cli/app.py +++ b/src/agentic_cli/cli/app.py @@ -31,7 +31,7 @@ from thinking_prompt import AppInfo, ThinkingPromptSession, ThinkingPromptStyles -from agentic_cli.cli.agent_view import AgentView, bind_ctrl_c, leave_view, open_view +from agentic_cli.cli.agent_view import AgentView, bind_ctrl_c, leave_view, open_view, start_view from agentic_cli.cli.commands import Command, CommandRegistry from agentic_cli.cli.dialogs import serialize_dialogs from agentic_cli.cli.message_processor import MessageProcessor, _says_so_when_stopped @@ -653,6 +653,20 @@ async def open_agent_view(self, instance: str) -> bool: """ return await open_view(self, instance) + async def start_agent(self, agent_type: str, objective: str) -> bool: + """Start a new sub-agent of ``agent_type`` on ``objective`` and open its view (provisional). + + What ``/agent new `` calls (``cli/agent_view.py``): + the workflow's ``start_instance``, whose run streams in the new + instance's view. In a view it leaves that one first. + + Returns: + Whether the view opened. False, said: a type the user may not + start, a blank objective, or a conversation another process has + open. + """ + return await start_view(self, agent_type, objective) + async def leave_agent_view(self) -> bool: """Leave the open sub-agent's view, back to the main conversation (provisional): what ``/back`` calls. diff --git a/src/agentic_cli/cli/conversation.py b/src/agentic_cli/cli/conversation.py index efa4a14e..fc8b0b10 100644 --- a/src/agentic_cli/cli/conversation.py +++ b/src/agentic_cli/cli/conversation.py @@ -640,6 +640,51 @@ async def run_instance(self, instance: str, message: str, parts: TurnParts) -> b turns=False, ) + async def start_instance( + self, + agent_type: str, + objective: str, + parts: TurnParts, + *, + opens: Callable[[str], Awaitable[None]] | None = None, + ) -> bool: + """Start a new sub-agent instance for the user (``/agent new``), its first run in its view. + + A write to the conversation under the turn lock, as ``run_instance`` + is: held to write, the conversations ``/new`` left dropped around + it, ``written`` once it reached a ready workflow, not ``turned``. + ``opens`` is called with the new instance's id once its run's start + names it (``MessageProcessor.process_start``). + + Args: + agent_type: The type to start. + objective: The user's objective for it. + parts: The app's parts it runs on (the new view's processor). + opens: Called once with the new instance's id. + + Returns: + Whether it ran: False when another process has the conversation + open (said), and nothing ran. + + Raises: + asyncio.CancelledError: Ctrl+C stopped it, as the processor says, + or while it waited for the turn lock. + """ + return await self._write( + parts, + lambda: parts.processor.process_start( + agent_type, + objective, + workflow_controller=parts.controller, + ui=parts.ui, + settings=parts.settings, + usage_tracker=parts.tracker, + session_id=self.session_id, + opens=opens, + ), + turns=False, + ) + async def tell_root(self, text: str, parts: TurnParts) -> bool: """Tell the main agent what the user did in a sub-agent's view, as a turn. diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index 71dc2a88..56db61ca 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -19,6 +19,7 @@ from __future__ import annotations import asyncio +import contextlib import json from types import MethodType, SimpleNamespace @@ -61,6 +62,7 @@ SESSION, SMALL_ENTRY, SMALL_MODEL, + STARTING, USER, Crew, agent, @@ -79,6 +81,7 @@ says, until, use, + user_team, ) RULE = "── researcher-1 · researcher · idle ──" @@ -1011,3 +1014,183 @@ async def test_finished_jobs_wait_in_a_view_and_the_bar_counts_them(self, make_c assert await app.resume_finished_jobs() == 0 assert crew.requests("coordinator") == 2 assert [r.job_id for r in jobs.awaiting_resume()] == [record.job_id] + + +# -- /agent new: a new instance's view, its first run streamed there --------------------- + +NEW_RULE = "── helper-1 · helper · running ──" + + +async def new_view(make_crew, *, team=None, **crew_args) -> tuple[Crew, BaseCLIApp]: + """A crew with a helper only the user may start (``user_team``), and an app + in its main conversation.""" + crew = make_crew(team or user_team(), subagents=STARTING, **crew_args) + return crew, await app_on(crew) + + +class TestANewInstancesView: + """``/agent new `` starts an instance for the user + (``start_instance``) and opens its view once its run's start names it: + the run streams there, a line typed steers it, Ctrl+C is the user's stop + and ``/back`` tells the main agent once, as for a follow-up run.""" + + async def test_its_view_opens_and_its_first_run_streams_there(self, make_crew): + crew, app = await new_view(make_crew, helper=[says("Helped with X.", usage=(900, 30))]) + + await typed(app, "/agent new helper Help with X.") + + assert said(app.session, "add_message")[-2:] == ["/agent new helper Help with X.", NEW_RULE] + (recap,) = app.session.add_rich.call_args.args + assert rows_of(recap) == [ + ("Title", "Help with X."), ("Objective", "Help with X."), + ("Last run", "#1 · running"), ("Tokens", "0 in / 0 out"), + ] + assert said(app.session, "add_response") == ["Helped with X."] + assert app.agent_view.instance == "helper-1" + assert app.session.message == "helper-1> " + assert status(app).startswith("helper-1 · idle") + assert [(r.ref.run, r.status, r.started_by) for r in crew.records()] == [ + ("helper-1#1", RUN_COMPLETED, "user"), + ] + assert crew.requests("coordinator") == 0 + + async def test_a_line_typed_while_its_first_run_works_is_given_to_that_run(self, make_crew): + crew, app = await new_view( + make_crew, helper=[calls(use("contract_hold", "h1")), says("X is 42; Z is 9.")], + ) + + await app.process_input("/agent new helper Hold on.") + await asyncio.wait_for(HELD["started"].wait(), 10) + await app.process_input("Also find Z.") + HELD["go"].set() + await settled_or_fail(app) + + assert said(app.session, "add_message")[-2:] == [ + "Also find Z.", STEERED.format(instance="helper-1"), + ] + assert crew.last_message("helper", -1) == "Also find Z." + assert [r.ref.run for r in crew.records()] == ["helper-1#1"] + assert said(app.session, "add_response")[-1] == "X is 42; Z is 9." + + async def test_ctrl_c_stops_its_first_run_the_users_stop(self, make_crew): + crew, app = await new_view( + make_crew, helper=[calls(use("contract_block", "h1")), says("Went on.")], + ) + + await app.process_input("/agent new helper Wait here.") + await asyncio.wait_for(BLOCKING["started"].wait(), 10) + assert app.agent_view.stop() is True + await settled_or_fail(app) + + (record,) = crew.records() + assert (record.status, record.cancelled_by) == (RUN_CANCELLED, "user") + assert crew.instances() == [("helper-1", INSTANCE_STOPPED)] + assert said(app.session, "add_message").count(CANCELLED_LINE) == 1 + assert app.session.message == "helper-1> " + assert status(app).startswith("helper-1 · stopped") + await typed(app, "Go on.") + assert crew.instances() == [("helper-1", INSTANCE_IDLE)] + assert said(app.session, "add_response")[-1] == "Went on." + + async def test_back_tells_the_main_agent_once(self, make_crew): + crew, app = await new_view( + make_crew, coordinator=[says("Noted: helped.")], helper=[says("Helped with X.")], + ) + + await typed(app, "/agent new helper Help with X.", "/back") + + latest = crew.manager.instance_result("helper-1", session_id=SESSION) + assert latest["result"] == "Helped with X." + assert said(app.session, "add_message")[-3:] == [ + "/back", BACK_RULE, TELLING.format(instance="helper-1"), + ] + assert crew.last_message("coordinator") == view_notice("helper-1", latest) + assert said(app.session, "add_response")[-1] == "Noted: helped." + assert app.session.message == ">>> " + # Back in its view and out again: nothing new to tell. + await typed(app, "/agent helper-1", "/back") + assert crew.requests("coordinator") == 1 + + async def test_a_type_you_cannot_start_opens_no_view(self, make_crew): + crew, app = await new_view(make_crew) + + await typed(app, "/agent new researcher Find X.") + + assert said(app.session, "add_error")[-1] == ( + "You cannot start 'researcher' here. Types you can start: helper." + ) + assert app.agent_view is None + assert app.session.message == ">>> " + assert crew.records() == [] + + async def test_in_a_view_it_leaves_that_view_first(self, make_crew): + crew, app = await in_a_view( + make_crew, team=[*follow_team(), *user_team()[2:]], subagents=STARTING, + coordinator=[says("Noted.")], researcher=[says("Y is 7.")], helper=[says("Helped.")], + ) + + await typed(app, "Now find Y.", "/agent new helper Help.") + + assert said(app.session, "add_message")[-4:] == [ + "/agent new helper Help.", BACK_RULE, TELLING.format(instance="researcher-1"), + NEW_RULE, + ] + assert said(app.session, "add_response")[-2:] == ["Noted.", "Helped."] + assert app.agent_view.instance == "helper-1" + + async def test_ctrl_c_before_its_view_opens_stops_the_run_and_opens_none(self, make_crew): + """thinking-prompt's Ctrl+C cancels the command while the start waits + for the store (before its run started): the run that starts is + stopped by the user, said once, and no view opens.""" + crew, app = await new_view(make_crew, helper=[says("[never asked]")]) + delegations = crew.manager._delegations + read, gate = asyncio.Event(), asyncio.Event() + stored = delegations._stored + + async def slow(conversation): + read.set() + await gate.wait() + return await stored(conversation) + + delegations._stored = slow + + command = asyncio.create_task(app.process_input("/agent new helper Go.")) + await asyncio.wait_for(read.wait(), 10) + command.cancel() + await asyncio.sleep(0.05) + gate.set() + with contextlib.suppress(asyncio.CancelledError): + await asyncio.wait_for(command, 10) + + (record,) = crew.records() + assert (record.status, record.cancelled_by) == (RUN_CANCELLED, "user") + assert crew.instances() == [("helper-1", INSTANCE_STOPPED)] + assert said(app.session, "add_message").count(CANCELLED_LINE) == 1 + assert app.agent_view is None + assert crew.requests("helper") == 0 + + async def test_an_interrupt_leaves_it_idle(self, make_crew): + """What the app's exit does to the run in view (``AgentView.interrupt``): + no stop of the user's.""" + crew, app = await new_view( + make_crew, helper=[calls(use("contract_block", "h1")), says("Went on.")], + ) + + await app.process_input("/agent new helper Wait here.") + await asyncio.wait_for(BLOCKING["started"].wait(), 10) + assert app.agent_view.interrupt() is True + await settled_or_fail(app) + + (record,) = crew.records() + assert (record.status, record.cancelled_by) == (RUN_INTERRUPTED, None) + assert crew.instances() == [("helper-1", INSTANCE_IDLE)] + + async def test_it_blocks_no_event_loop(self, make_crew): + crew = make_crew(user_team(), subagents=STARTING, store="sqlite", + coordinator=[says("Noted.")], helper=[says("Helped.")]) + app = await app_on(crew) + + with no_blocking_calls(): + await typed(app, "/agent new helper Help.", "/back") + + assert said(app.session, "add_response") == ["Helped.", "Noted."] From 85902bca77ee392ec54467a45a4c17bbc1d34653 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:19:41 -0500 Subject: [PATCH 07/12] Tests: /agent new on a real console The console app's scripted workflow starts a researcher for /agent new; over a pty the new sub-agent's view opens on its first run, a line typed steers it, and /back tells the main agent once. --- tests/cli/console_app.py | 29 +++++++++++++++++++++++++++-- tests/cli/test_console_turns.py | 27 ++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/tests/cli/console_app.py b/tests/cli/console_app.py index 8136724f..3c6b79c8 100644 --- a/tests/cli/console_app.py +++ b/tests/cli/console_app.py @@ -36,8 +36,10 @@ says ``Holding.`` and waits for a line given to it (``steer_instance``), then says ``Steered: ``; ``slow`` says ``Working on it.`` and waits until Ctrl+C stops it (the user's stop: the instance is stopped); anything else -says ``Researched: ``. The main agent's notice after the view -(``tell_root``) is answered ``Told: ``. +says ``Researched: ``. ``/agent new researcher `` +(``start_instance``) starts a new researcher whose first run does the same +with its objective; another type is refused. The main agent's notice after +the view (``tell_root``) is answered ``Told: ``. ``/compact`` reports that a summary is being written, waits until a file named ``summarized`` appears, then reports its usage and what it did: 2 @@ -233,6 +235,29 @@ async def run_instance(self, instance, message, *, session_id=None, user_id=None started_by="user", mode="blocking") self._observe(conversation, started) yield started + async for event in self._work(conversation, ref, message): + yield event + + async def start_instance(self, agent_type, objective, *, session_id=None, user_id=None): + if agent_type != "researcher": + yield WorkflowEvent.error( + f"You cannot start '{agent_type}' here. Types you can start: researcher." + ) + return + conversation = self.session_ref(session_id) # one user here + ref = self.agent_runs.run_for(conversation, None, None, agent_type) + started = WorkflowEvent.agent_run( + ref, "started", title=objective, brief={"title": objective, "objective": objective}, + started_by="user", mode="blocking", + ) + self._observe(conversation, started) + yield started + async for event in self._work(conversation, ref, objective): + yield event + + async def _work(self, conversation, ref, message: str): + """A run the user started, on ``message``: its text, then its end.""" + instance = ref.instance ended = WorkflowEvent.agent_run(ref, "cancelled", error="stopped by the user", cancelled_by="user", instance_status="stopped") try: diff --git a/tests/cli/test_console_turns.py b/tests/cli/test_console_turns.py index 44dac3b7..db49c337 100644 --- a/tests/cli/test_console_turns.py +++ b/tests/cli/test_console_turns.py @@ -1,7 +1,8 @@ """Turns on a real console, over a pty: Ctrl+C, a question, typing ahead, ``/new``, ``/resume``, ``/compact``, the status bar's ``ctx`` and a sub-agent's view (``/agent ``: a follow-up, a line that steers the run -that works, Ctrl+C on it, ``/back``). +that works, Ctrl+C on it, ``/back``; ``/agent new``: a new +sub-agent's first run in its view). thinking-prompt 0.4's Ctrl+C cancels the turn's task, its dialogs are ``Dialog`` objects, drawn in a box or inline, and it refuses Enter while a @@ -597,3 +598,27 @@ def test_in_a_view_a_line_steers_the_run_that_works_and_ctrl_c_stops_it(console) transcript = console.transcript assert transcript.count("Operation cancelled...") == 1 assert "Busy" not in transcript + + +def test_agent_new_opens_the_view_its_run_streams_there_and_back_tells_the_main_agent(console): + """``/agent new `` opens the new sub-agent's view on its + first run: its reply streams there, a line typed while it works steers + it (the prompt takes it: no "Busy"), and ``/back`` tells the main agent once.""" + console.type_line("/agent new researcher hold") + console.expect("── researcher-1 · researcher · running ──") + console.expect("Holding.") + console.type_line("Also find Z.") + console.expect("Given to researcher-1's run before its next step.") + console.expect("Steered: Also find Z.") + console.type_line("/back") + console.expect("── back to main ──") + console.expect("Told: The user worked with researcher-1 directly") + console.type_line("which") + console.expect("Session: ") + console.exit() + + transcript = console.transcript + steered = transcript.index("Steered: Also find Z.") + assert steered < transcript.index("── back to main ──") + assert transcript.count("Told: The user worked with researcher-1 directly") == 1 + assert "Busy" not in transcript From 3bc4415e464ebfd0f57dae4d284cf59373d68cfa Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:20:14 -0500 Subject: [PATCH 08/12] Docs: /agent new The CHANGELOG, the README's user's control and commands table, and CLAUDE.md's lines for the agents command, the view, the message processor, the conversation core, the manager and the delegations say how the user starts a sub-agent and where its first run streams. --- CHANGELOG.md | 28 ++++++++++++++++++++++++++++ CLAUDE.md | 16 ++++++++-------- README.md | 8 +++++++- 3 files changed, 43 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7611ccc3..8a347e28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -575,6 +575,34 @@ the start of the entry's title. ### Added +- **`/agent new `: you start a sub-agent, and its view + opens on its first run.** A type whose `spawnable_by` names `"user"`, in + an app whose policy's `spawn_sources` names it too + (`SubAgentPolicy(spawn_sources={"user"})`), may be started by the user: + `/agent new researcher Find what changed in the 2.0 release.` starts + `researcher-`, its parent the main agent (depth 1, so `max_spawn_depth` + never refuses it), `started_by: user`, its brief the objective (the rest of + the line, as typed), titled with the objective's first line. It is counted + toward no turn's runs, takes a working slot while it works, and an + inheriting type reads the main conversation as the main agent's `task` + would hand it. Its view opens as its run starts and the run streams there, + as a follow-up's does: a line typed steers it, Ctrl+C is your stop (the run + `cancelled`, the sub-agent `stopped`; one pressed before the run started + stops it as it starts, and no view opens), `/back` tells the main agent + once, and, being the main agent's sub-agent, the main agent's + `message_agent` may continue it. In another sub-agent's view it leaves that + one first. A type you cannot start opens nothing ("You cannot start + 'writer' here. Types you can start: researcher."; "This app lets you start + no agent types." when there is none), and a missing type or objective says + `Usage: /agent new `. The manager's entry point + (provisional): `start_instance(agent_type, objective)`, a turn of its own + whose first event is the run's start, which names the instance; a refusal + is one `ERROR` ("A new agent needs an objective." for a blank one), + stopping the stream is the user's stop, and `interrupt_instance` ends it as + a process exit does. The app's `start_agent(agent_type, objective)` is what + the command calls; the manager's delegations' `start_by_user`, + `startable_by_user` and `user_start_refused` (provisional) start and refuse + it. On both backends, contract-tested. - **A skill that starts an agent: the frontmatter key `agent`, on both backends.** A skill's `SKILL.md` may name one of the app's agent types at the top of its frontmatter (`agent: researcher`). Where the app diff --git a/CLAUDE.md b/CLAUDE.md index d7394f05..21c4647f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,25 +33,25 @@ agentic-cli/ │ │ ├── app.py # BaseCLIApp (subagents=: the SubAgentPolicy every manager the app builds gets, through its WorkflowController; main(): the command line, add_arguments/from_args, exit_status; session_start: how run() begins, the run's own conversation loaded before the prompt, also when the workflow did not start (_adopt_its_own: an id the app was given held from the start, one the run made from its first write); its resume once the prompt is up (_open_on_startup, holding the turn lock from before the prompt takes a line: a turn typed ahead waits and runs there; Ctrl+C there ends the app; --continue passes over conversations another process holds, _newest_free, the one chosen held beside the run's own until the switch); --continue and --resume find the conversation's backend from every installed backend's reader before the workflow is built (_start_on_its_backend: the run builds that backend once); the --resume hint at exit (the run's store named after a session_store change; the backend only when no reader reads it, LangGraph: --resume opens a conversation on its own); the session it builds; get_theme(name); /settings: _build_ui_items, apply_settings and save_settings delegate to cli/settings_ui.py (SettingsUI: an app's override applies); run() installs the ADK log filters first (workflow/adk/log_filters.py: an app built but never run installs none), then the SIGHUP/SIGTERM handlers that kill live execute_python runs before chaining to the previous handler (_stop_runs_on_signals); the LangGraph deprecation notice; start_new_session(backend=None): /new [backend] (the settings' orchestrator by default; another backend: the memories proposed, WorkflowController.switch_backend, then the switch to the new id at its place; a Ctrl+C once it runs opens its conversation first); a line typed runs in ConversationCore.run_turn (on _turn_parts: the app's parts as they are), then the jobs at the turn's end through the app's own resume_finished_jobs(); compact() (ConversationCore.compact), start_new_session() and resume_session(): /compact, /new and /resume, under the conversation's turn lock (_turn_lock: ConversationCore.turn_lock; pick_session(), the picker, is not: it waits on a dialog); session_store=memory keeps one conversation at a time (Place.kept; session_store: the run's store): /new drops the one left once the switch is made, after its memories are proposed (_drop: its delete_session, shielded; on another backend the manager released takes it along; one it cannot confirm gone, the workflow down or its lookup or delete raising, is remembered and dropped once a workflow is ready: before the next turn, or right after the turn whose own start revives the workflow, and always before that turn's delivery of finished jobs, /compact and the next /new, never while it is the open one: ConversationCore.drop_left), and resume_session, pick_session, --resume (status 1) and --continue (a new conversation) are refused with NOT_KEPT, before any look-up; every installed backend's conversations (list_conversations, delete_conversation, session_backend; cli/stored_conversations.py): the picker names each row's backend and returns a PickedConversation, and /resume opens a conversation on the backend that keeps it (_open_elsewhere: held there, memories proposed, switch_backend with the run's services, then the switch at its place; an id two backends keep opens on the running one, the other named); every change of conversation through ConversationCore.switch (_conversation; _session_id and _turned forward to it); the session_id setter deprecated (its synchronous part, switch_now, and a DeprecationWarning); a conversation's memories proposed once per conversation used (_turned); the memory proposals waiting, said at startup and after /new and /resume (_name_waiting_proposals); resume_finished_jobs(): ConversationCore.deliver_finished_jobs, the jobs waiting named at startup by ConversationCore.waiting_jobs (_name_its_waiting_jobs), none in a sub-agent's view; a sub-agent's view (cli/agent_view.py, provisional: agent_view, open_agent_view(id), leave_agent_view()): process_input gives a line typed there to AgentView.take, and draws its prompt and status bar again after a command; start_new_session and resume_session leave it first (_leave_view_first); run() binds Ctrl+C to the run in view (bind_ctrl_c) and interrupts one still working at exit, as a process exit does, waited for before the workflow closes (AgentView.interrupt: not the user's stop, the run interrupted and its sub-agent idle)) │ │ ├── commands.py # Command, CommandRegistry │ │ ├── job_monitor.py # JobMonitor: the status bar's jobs segment (running, queued, a finished job's note, ↻N: waiting_jobs' rule, can_resume answers kept 30 s (the other backends' look too: kept_elsewhere), forgotten after /sessions --delete or when the workflow is replaced), one tick every 2 s, its JobManager.list() on a worker thread -│ │ ├── conversation.py # ConversationCore: the conversation the turns run in (its id, turned, its lock at its Place: the backend and store, the store the run's for its whole life (Place.kept: not the memory store, where the CLI keeps one conversation at a time and NOT_KEPT says why nothing else opens), the backend recorded as the app starts, for a new conversation on another backend, and on a /settings change of the orchestrator while the workflow is down, its next start builds afresh and nothing of the conversation is stored (SettingsUI._move_here, WorkflowController.next_start_builds), never read from the settings in between; deferred: an id this run made (the start's, /new's, an orchestrator change's) is in no store, so it is held from its first write, hold_to_write under the turn lock before a turn, a job's notice or /compact (_held_to_write; a run in which no turn runs makes no lock file: a line typed while the workflow is down takes the hold before its retried start; a lock that cannot be taken, an OSError, leaves it unheld, said once, and the write goes on); fresh: nothing of it stored, opened_empty (an id this run made, or one a load found empty) and not written (no turn of it ran on a ready workflow), the one condition for another backend); switch: the one protocol (/new on any backend, /resume, startup, the same id in another place while the workflow is down): the target's lock taken (another process's refused), memories proposed, the workflow loads it (a stored one gone: not made, or, made already in another place, opened empty: gone), then made at once (lock, id, task list, usage counters) or let go, a workflow that took it given the old one back; made before the load when there is no other conversation to stay in (the same id, or another place: a new or stored conversation on another backend); a Ctrl+C at any await leaves one conversation held; switch_now: the deprecated session_id setter's part; turn_lock: what writes to the conversation and every switch take it; run_turn, compact and run_job_resume: a turn (echoed, held to write, turned, written once it reached a ready workflow; run_turn says whether it ran, whatever the processor returns), /compact and a finished job's notice under it, on TurnParts (the app's parts as they are); run_instance and tell_root (_write): a line typed in a sub-agent's view as its next run (process_instance; written, not turned) and the main agent's notice after a view (process_notice; turned), under it too; deliver_finished_jobs: each job that waits here (cli/waiting_jobs.py's rule, which waiting_jobs names them by, the other backends' look through TurnParts.kept_elsewhere), every JobManager call on a worker thread, a delivery claimed only once it can reach the agent (process_resume(claim=), after the readiness check and can_resume; _claim_delivery: a claim a Ctrl+C stopped is handed back, JobManager.release_resume), a failure before the claim said once per job and conversation when the CLI tells jobs on its own (telling_on_its_own); to_drop/drop_left: the conversations /new left on the memory store that the store may still hold (the workflow down, a lookup or delete that raised), dropped through TurnParts.drop under the turn lock once a workflow is ready, before a turn, /compact or a delivery uses it (after a turn or /compact that started it), one try per point, done once the store has it no more (a workflow without supports_sessions has none), the open one skipped; a delivery with none to drop takes no turn lock +│ │ ├── conversation.py # ConversationCore: the conversation the turns run in (its id, turned, its lock at its Place: the backend and store, the store the run's for its whole life (Place.kept: not the memory store, where the CLI keeps one conversation at a time and NOT_KEPT says why nothing else opens), the backend recorded as the app starts, for a new conversation on another backend, and on a /settings change of the orchestrator while the workflow is down, its next start builds afresh and nothing of the conversation is stored (SettingsUI._move_here, WorkflowController.next_start_builds), never read from the settings in between; deferred: an id this run made (the start's, /new's, an orchestrator change's) is in no store, so it is held from its first write, hold_to_write under the turn lock before a turn, a job's notice or /compact (_held_to_write; a run in which no turn runs makes no lock file: a line typed while the workflow is down takes the hold before its retried start; a lock that cannot be taken, an OSError, leaves it unheld, said once, and the write goes on); fresh: nothing of it stored, opened_empty (an id this run made, or one a load found empty) and not written (no turn of it ran on a ready workflow), the one condition for another backend); switch: the one protocol (/new on any backend, /resume, startup, the same id in another place while the workflow is down): the target's lock taken (another process's refused), memories proposed, the workflow loads it (a stored one gone: not made, or, made already in another place, opened empty: gone), then made at once (lock, id, task list, usage counters) or let go, a workflow that took it given the old one back; made before the load when there is no other conversation to stay in (the same id, or another place: a new or stored conversation on another backend); a Ctrl+C at any await leaves one conversation held; switch_now: the deprecated session_id setter's part; turn_lock: what writes to the conversation and every switch take it; run_turn, compact and run_job_resume: a turn (echoed, held to write, turned, written once it reached a ready workflow; run_turn says whether it ran, whatever the processor returns), /compact and a finished job's notice under it, on TurnParts (the app's parts as they are); run_instance, start_instance and tell_root (_write): a line typed in a sub-agent's view as its next run (process_instance; written, not turned), /agent new's first run (process_start; written, not turned) and the main agent's notice after a view (process_notice; turned), under it too; deliver_finished_jobs: each job that waits here (cli/waiting_jobs.py's rule, which waiting_jobs names them by, the other backends' look through TurnParts.kept_elsewhere), every JobManager call on a worker thread, a delivery claimed only once it can reach the agent (process_resume(claim=), after the readiness check and can_resume; _claim_delivery: a claim a Ctrl+C stopped is handed back, JobManager.release_resume), a failure before the claim said once per job and conversation when the CLI tells jobs on its own (telling_on_its_own); to_drop/drop_left: the conversations /new left on the memory store that the store may still hold (the workflow down, a lookup or delete that raised), dropped through TurnParts.drop under the turn lock once a workflow is ready, before a turn, /compact or a delivery uses it (after a turn or /compact that started it), one try per point, done once the store has it no more (a workflow without supports_sessions has none), the open one skipped; a delivery with none to drop takes no turn lock │ │ ├── conversation_lock.py # ConversationLock: one process per stored conversation (flock under /locks/; ConversationCore holds it and refuses one held elsewhere; /sessions --delete too, through conversation_held) │ │ ├── builtin_commands.py # /help (by category; /help : its usage and examples), /status (the main agent's context rows: context_budget, in a sub-agent's view the instance's, AgentView.context_rows; why the workflow did not start: app.workflow_error; tokens by agent: the main agent, each sub-agent with its runs, the side calls by purpose, from the manager's usage ledger), /models (ModelsCommand: the list, each model's facts and sources, Status for an entry left out, the providers in use; /models searches the full listings; refresh), /sessions (every installed backend's, a Backend column; --delete= on the backend that keeps it, --backend= for an id two keep; on the memory store NOT_KEPT, no table, --delete refused), /resume [] (sessions; refused on the memory store), /jobs (resume: finished jobs; in a sub-agent's view JOBS_WAIT: they wait for /back), /compact [focus] (refused in a sub-agent's view: COMPACT_IN_VIEW), /new [backend] (an unknown backend or a missing extra refused: check_backend), ... -│ │ ├── agents_command.py # /agents: the open conversation's sub-agent instances (agent_runs.instances under workflow.session_ref(app.session_id)) in a picker (a Dialog with one ChoiceField, as /resume's: `picker`), each followed by the ones it started (id · type · status · title), Enter opening the view of the one picked (app.open_agent_view); /agent opens its view (open_agent_view: cli/agent_view.py), /agent stop and /agent close are the user's stop and close (stop_instance, close_instance, the app's conversation named), each saying what it did or why not (NO_SUCH_AGENT, ALREADY_TEXT), nothing tried on records not read; /agents (its panel: tokens in/out from the usage ledger, usage_of, live for a running run; time): one instance (every run of it) or run (type, parent, title, the instance's Model and Tools when its delegation gave them, NO_OWN_TOOLS for none; each run's status and time, its brief's other fields (a follow-up's message in their place), its result's first lines, its own last plan and tasks, its error, its tokens by model); the records are the conversation's, kept beside it in its store and loaded with it (`workflow.load_agents`, asked by /agents too: a conversation resumed after a restart lists its runs before its first turn; a store that cannot be read is said, and the runs held shown), a run from before a restart showing its record's tokens by model (its usage, no call count); a module of its own, as /memory's +│ │ ├── agents_command.py # /agents: the open conversation's sub-agent instances (agent_runs.instances under workflow.session_ref(app.session_id)) in a picker (a Dialog with one ChoiceField, as /resume's: `picker`), each followed by the ones it started (id · type · status · title), Enter opening the view of the one picked (app.open_agent_view); /agent opens its view (open_agent_view: cli/agent_view.py), /agent new starts one and opens its view (app.start_agent; the objective the rest of the line as typed; NEW_USAGE without one; AGENT_USAGE names it), /agent stop and /agent close are the user's stop and close (stop_instance, close_instance, the app's conversation named), each saying what it did or why not (NO_SUCH_AGENT, ALREADY_TEXT), nothing tried on records not read; /agents (its panel: tokens in/out from the usage ledger, usage_of, live for a running run; time): one instance (every run of it) or run (type, parent, title, the instance's Model and Tools when its delegation gave them, NO_OWN_TOOLS for none; each run's status and time, its brief's other fields (a follow-up's message in their place), its result's first lines, its own last plan and tasks, its error, its tokens by model); the records are the conversation's, kept beside it in its store and loaded with it (`workflow.load_agents`, asked by /agents too: a conversation resumed after a restart lists its runs before its first turn; a store that cannot be read is said, and the runs held shown), a run from before a restart showing its record's tokens by model (its usage, no call count); a module of its own, as /memory's │ │ ├── dialogs.py # One dialog at a time on a session: serialize_dialogs (BaseCLIApp.session's setter wraps a real session's six dialog methods, whoever calls them: the framework's commands, an app's own, a question's dialog) and dialog_lock(ui) (the message processor holds it around a question's dialog; a task may take it again) make a sub-agent view's run (outside the input handler) asking while a command's dialog is open, or the reverse, wait instead of raising (thinking-prompt raises on a second dialog: a permission prompt would be a denial the user never saw); a stand-in whose methods are mocks is left as it is -│ │ ├── agent_view.py # A sub-agent's view (provisional; open_view/leave_view behind BaseCLIApp.open_agent_view/leave_agent_view, /back: BackCommand): entering prints VIEW_RULE ("── researcher-2 · researcher · idle ──") and a recap (title, its first brief's objective, its last run's status, its result's first lines, its tokens: instance_tokens, each run's from the usage ledger or its record), the prompt "> " (none for a closed one: read-only, READ_ONLY) and WorkflowController.view_segment (its status, its ctx: its last own step's prompt against its own trigger, its model choice's for an instance on one, its tokens); AgentView.take: a line steers the run that works (steer_instance, STEERED) or starts the instance's next run in a task of its own (ConversationCore.run_instance on the view's own MessageProcessor), outside the input handler, so the prompt takes the lines that steer it (thinking-prompt takes none while a handler runs); bind_ctrl_c: Ctrl+C stops that run (AgentView.stop: the user's stop) through a prompt_toolkit binding on the session's application, active only while it works; AgentView.interrupt (at exit): the manager's interrupt_instance, then the view's tasks cancelled; a line typed before the run ends waits for it inside the view (a stop says the cancel once), and one typed while the workflow is down is the next run all the same (its start retries); leave_view (/back): waits for the run, retries a workflow that is down, BACK_RULE, the prompt and bar back, then one notice turn (ConversationCore.tell_root, view_notice, TELLING) when a run the user started there ended since the main agent last heard, then the finished jobs that waited (job_auto_resume); in a view /compact is refused (COMPACT_IN_VIEW), /jobs resume waits (JOBS_WAIT), /status shows its context_rows, /new and /resume leave it first +│ │ ├── agent_view.py # A sub-agent's view (provisional; open_view/leave_view behind BaseCLIApp.open_agent_view/leave_agent_view, /back: BackCommand): entering prints VIEW_RULE ("── researcher-2 · researcher · idle ──") and a recap (title, its first brief's objective, its last run's status, its result's first lines, its tokens: instance_tokens, each run's from the usage ledger or its record), the prompt "> " (none for a closed one: read-only, READ_ONLY) and WorkflowController.view_segment (its status, its ctx: its last own step's prompt against its own trigger, its model choice's for an instance on one, its tokens); AgentView.take: a line steers the run that works (steer_instance, STEERED) or starts the instance's next run in a task of its own (ConversationCore.run_instance on the view's own MessageProcessor), outside the input handler, so the prompt takes the lines that steer it (thinking-prompt takes none while a handler runs); bind_ctrl_c: Ctrl+C stops that run (AgentView.stop: the user's stop) through a prompt_toolkit binding on the session's application, active only while it works; AgentView.interrupt (at exit): the manager's interrupt_instance, then the view's tasks cancelled; a line typed before the run ends waits for it inside the view (a stop says the cancel once), and one typed while the workflow is down is the next run all the same (its start retries); leave_view (/back): waits for the run, retries a workflow that is down, BACK_RULE, the prompt and bar back, then one notice turn (ConversationCore.tell_root, view_notice, TELLING) when a run the user started there ended since the main agent last heard, then the finished jobs that waited (job_auto_resume); start_view (/agent new, BaseCLIApp.start_agent): a view open first left (leave_view), the start (ConversationCore.start_instance → MessageProcessor.process_start) in a task of its own on a MessageProcessor of its own, the view opened on the instance its run's start names (opens) holding that task (AgentView.adopt) and processor, so its first run streams, steers and stops there; Ctrl+C before it opened stops the run, no view; in a view /compact is refused (COMPACT_IN_VIEW), /jobs resume waits (JOBS_WAIT), /status shows its context_rows, /new and /resume leave it first │ │ ├── memory_command.py # /memory: the list (a picker like /resume's), one memory (Delete, History), /memory , history (Restore), inbox (Accept/Discard/Skip), stale; proposals_line; Enter's button is Close or Skip, and Delete acts only on the memory as shown │ │ ├── workflow_controller.py # WorkflowController (lazy/background init; subagents=: the SubAgentPolicy every manager it builds gets, a switch_backend's too; the session store of every manager of the run, store, fixed at its first start; the backend it runs, backend: the settings' orchestrator at its first start, then switch_backend's (a conversation on another backend, new or opened: the new manager started first on the run's services lent, given over by the old one and published at once, the old one released in the controller's task, a cancel stops only the wait; a failed start or give leaves the old one with its services; while down, a manager a failed reinitialization kept lends its services to the next build, _lender, and is released once they are given); reinitialize, a model switch, always in place; the status bar names the main agent's model, or in a sub-agent's view what view_segment says of the instance, the jobs segment kept) │ │ ├── session_resume.py # What /resume shows: the picker (picker: each row's backend once one is another's; PickedConversation, the id a str naming its backend), the "Resumed:" line ("Resumed on :" on another backend), the replay of the last 10 messages │ │ ├── stored_conversations.py # StoredConversations: one look at every installed backend's stored conversations (the running workflow's own, each other backend's SessionReader, opened and closed with the look): rows merged newest first, each naming its backend; where(id), delete; a backend not read (its extra missing, its store failing) left out and named in notes; a failing store warned of in the log at each look the user asks for, once a run for the app's own (warned: the job monitor's, a finished job's) │ │ ├── session_args.py # --continue / --resume → SessionStart (BaseCLIApp.main() adds them; start: new, continue, resume; SessionArgumentParser: --resume without its id names --continue and /resume) -│ │ ├── message_processor.py # WorkflowEvent → ThinkingPromptSession rendering (a sub-agent run's events box lines and transcript tool results under its name, "researcher-2 › …": the event's run, _at_work; the main agent's unchanged; a run's AGENT_RUN queued, input_required and running each write its line: "Queued: waiting for a free slot", "Waiting for your answer", "Working..."); Ctrl+C stops the request being processed (its boxes end with it; "Operation cancelled..." once, then the background jobs it submitted that still run, named; CancelledError re-raised); tool questions as dialogs, one at a time (a sub-agent run's titled with its instance, "researcher-2 · Permission" or "researcher-2 asks", a question's text opening with its run_label; one whose asking task alone is cancelled, a run stopped by its limit, its parent or the user, withdrawn and the events box back, the turn going on); process_compact: /compact run as a turn (compact() as its event source, live events merged in); process_instance: a line in a sub-agent's view as a turn (run_instance as its source; viewed: the instance's text is the reply, its lines name nobody, each of its run events redraws the status bar); process_notice: the main agent's notice after a view (tell_root as its source); a success line for each memory write (save_memory, update_memory, delete_memory); a failed turn said once, from its ERROR as from a raise ("Rate limited: …" for rate_limited, "Send your message again" for a ConversationChangedError) +│ │ ├── message_processor.py # WorkflowEvent → ThinkingPromptSession rendering (a sub-agent run's events box lines and transcript tool results under its name, "researcher-2 › …": the event's run, _at_work; the main agent's unchanged; a run's AGENT_RUN queued, input_required and running each write its line: "Queued: waiting for a free slot", "Waiting for your answer", "Working..."); Ctrl+C stops the request being processed (its boxes end with it; "Operation cancelled..." once, then the background jobs it submitted that still run, named; CancelledError re-raised); tool questions as dialogs, one at a time (a sub-agent run's titled with its instance, "researcher-2 · Permission" or "researcher-2 asks", a question's text opening with its run_label; one whose asking task alone is cancelled, a run stopped by its limit, its parent or the user, withdrawn and the events box back, the turn going on); process_compact: /compact run as a turn (compact() as its event source, live events merged in); process_instance: a line in a sub-agent's view as a turn (run_instance as its source; viewed: the instance's text is the reply, its lines name nobody, each of its run events redraws the status bar); process_start: /agent new's first run (start_instance as its source; opens told the instance its first AGENT_RUN start names, before that start is drawn, viewed from then on); process_notice: the main agent's notice after a view (tell_root as its source); a success line for each memory write (save_memory, update_memory, delete_memory); a failed turn said once, from its ERROR as from a raise ("Rate limited: …" for rate_limited, "Send your message again" for a ConversationChangedError) │ │ ├── settings_command.py # /settings: a Dialog with Save and Cancel; the fields that changed → apply_settings, then save_settings(keys=changed) (an override that cannot take `keys` fails there: "Settings applied but not saved: …") │ │ ├── settings_introspection.py # Pydantic field → thinking-prompt form field (built complete: they are frozen) │ │ ├── settings_ui.py # SettingsUI(app), what BaseCLIApp's _build_ui_items/apply_settings/save_settings delegate to (it calls the app's hooks: get_ui_setting_keys, get_theme, start_new_session; keeps nothing): the fields (the model pickers: the list, catalog.offered with model_services.role_models, as /models has it; a role's model the list leaves out offered first as " (current)", "Not offered ()" starting the description, so a Save changes no model untouched); a Save all or nothing, each key as settings_persistence declares (an orchestrator change, check_backend first, starts a new conversation on the new backend through the app's start_new_session() when the open one is fresh, ConversationCore.fresh read under the turn lock, else "(applies to the next /new)"; while the workflow is down a fresh one moves there, _move_here, decided again under the turn lock); Ctrl+C wherever a Save waits says "Operation cancelled..." once (_says_so_when_stopped; a new conversation's own, as /new says it) and undoes it; the save on a worker thread │ │ ├── waiting_jobs.py # Which finished jobs wait to be told in the open conversation: one rule (JobRecord.awaiting_resume, then its own, no conversation's, or a gone conversation's: can_resume, then the other installed backends' readers, opens_anywhere: one another backend keeps is not gone, its job waits for it) for the deliveries, ↻N and the startup line │ │ └── usage_tracker.py # Token usage / status bar: ctx = the main agent's last prompt over its context_trigger (a call with a purpose, a sub-agent's, a summary's or a side call's, never moves it); the token segment the open conversation's total, every call of its turns; format_usage: /status's rows by agent and /agents 's tokens by model │ ├── workflow/ -│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none), and _agent_tool_names, what a task call's tools may name (the agent's own tools by the names its model sees, KEPT_TOOLS left out; the base's: its configured tools; ADK and Deep Agents add MCP and skill tools; ADK raises delegate.ToolsUnlistedError for a toolset it could not list, which Delegations answers TOOLS_UNLISTED_ERROR); _run_models: a run's maps of each agent's model and numbers, its type's its model choice's when it runs on one; the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', each config's model_choices as its model would be, with its model_settings, into _choice_models by (agent, choice), choice_models, then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built, and _compute_choice_budgets (each model choice's, context_budget(agent, model=choice)): each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) +│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none), and _agent_tool_names, what a task call's tools may name (the agent's own tools by the names its model sees, KEPT_TOOLS left out; the base's: its configured tools; ADK and Deep Agents add MCP and skill tools; ADK raises delegate.ToolsUnlistedError for a toolset it could not list, which Delegations answers TOOLS_UNLISTED_ERROR); _run_models: a run's maps of each agent's model and numbers, its type's its model choice's when it runs on one; the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), start_instance (a turn: Delegations.start_by_user, the user's new instance, parent root, depth 1, started_by user, counted toward no turn's runs; a type the user may not start or a blank objective one ERROR; an inheriting type's copy of the conversation from _inherited_history, the backend's hook: ADK's session's root-visible events, Deep Agents' root messages, summary applied; its first event the run's start), both streamed by _users_run (the run in a task of its own; _UsersRunEvents notes the run as its start is reported, so a stop before the consumer read it, or before the run started, stops it by the user as it starts), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', each config's model_choices as its model would be, with its model_settings, into _choice_models by (agent, choice), choice_models, then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built, and _compute_choice_budgets (each model choice's, context_budget(agent, model=choice)): each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) │ │ ├── factory.py # create_workflow_manager_from_settings (_BACKENDS: orchestrator → "module:Class" + extra, imported when chosen; orchestrator=: another backend than the settings'; session_store=: the store a manager is built for, BaseWorkflowManager.session_store, the settings' by default; subagents=: the SubAgentPolicy the manager gets, checked before a backend is imported); orchestrator_of; check_backend (an unknown name, a missing extra) │ │ ├── session_readers.py # SessionReader: a backend's stored conversations read without its manager (list/info/exists/delete/aclose, rows naming the backend; delete deletes what the manager's does, ADK's sub-agent transcripts and records with the conversation), opened from the settings and a store (open_session_reader: the backend's own session code, adk/sessions.py::open_sessions and deepagents/sessions.py::open_sessions, imported on a worker thread; no agents, models or services; a sqlite store not made yet reads empty and is not made, Deep Agents not even imported for it; a database without its backend's tables, looked at read-only, reads empty, nothing written to it: no table, no journal mode); none for the memory store or LangGraph; ImportError (the install hint) for a missing extra; reader_backends │ │ ├── service_registry.py # get_service/require_service + ContextVar registry; the registry keys and KNOWN_SERVICE_KEYS, read from services.py's table @@ -84,7 +84,7 @@ agentic-cli/ │ │ │ ├── capabilities.py # Capability, EXEMPT │ │ │ ├── matchers.py # PathMatcher, URLMatcher, ShellMatcher, StringGlobMatcher │ │ │ └── rules.py, store.py, prompt.py (build_request(run=): a sub-agent's prompt opens with its run; is_permission_request: by its perm- id) -│ │ ├── agents/ # Sub-agents: runs.py: the RUN_* statuses (a working run's: RUN_QUEUED, RUN_RUNNING, RUN_INPUT_REQUIRED, RUN_WORKING_STATUSES; a record says running from its start), INSTANCE_RUNNING/IDLE/STOPPED/CLOSED and INSTANCE_STATUSES, InstanceRecord (an instance: parent, depth, title, status, runs, continuable, and the tools and model its first run's start gave it, read as None from records without them), RunRecord (input: a follow-up's message as written, "" for a first run), AgentRuns (a manager's runs and instances by conversation: run_for names - and its first run #1 per (conversation, parent run, call id), a new one once it ended; next_run: an instance's next run; instances/instance, kept from the events: a start makes or reopens the instance running, an end sets its status from instance_status, AGENT_INSTANCE a change without a run; number_from: past the instances a conversation's store keeps, a count never lowered; observe records AGENT_RUN under the turn it is reported in; interrupt_open; a record's usage: what the run used, by model, from its end event or the ledger; its plan and tasks: the run's own last, from its end event; RECORDS_VERSION, export (a conversation's records as JSON-safe data: v, saved, numbered, instances, runs) and restore (replaces them; a run found working ends interrupted, INTERRUPTED_ERROR, at the later of its start and saved, its instance idle, closed for a type that is not continuable; each run's end order stored (end), any time or field that does not read ValueError; counters never below an instance kept; ValueError for another version or records that do not read, nothing changed), stored_instance_ids (the instances stored records name; None for none), AgentRuns(on_change=): told each change, never by restore), run_title, result_head, run_instance and run_number (the one reader of a run id: researcher-2#1's instance and number), run_label (how a dialog names a run: researcher-2 (researcher, run 1)), SUBAGENT_ERROR_PREFIX (ADK's old words for a failed delegation, kept for callers), show_as_delegation(result, envelope) (a delegation's TOOL_RESULT shown alike on both backends: the result's first line, or Failed: ; metadata["result"] the envelope); a record's brief, started_by, mode and cancelled_by; delegate.py: Delegations (delegate(DelegationRequest) → Delegated and follow_up(FollowUpRequest) → Delegated: the one place a run starts and ends, on both backends (a follow-up is the instance's next run through the same hook, AgentRun.follow_up: refused as an error result, no run, for an unknown or not-yours instance (NOT_YOURS_ERROR, YOURS, NO_SUB_AGENTS), a closed one (CLOSED_ERROR), one the user stopped when an agent sends it (STOPPED_ERROR), a running one (RUNNING_ERROR), one whose type the app no longer has (TYPE_GONE_ERROR) and a blank message (NO_MESSAGE_ERROR); an agent's counts toward max_runs_per_turn, the user's (started_by USER) does not; a run's end carries the status it leaves its instance in: stopped for the user's cancel, closed for a type that is not continuable or the oldest idle one past max_open, else idle; close(conversation, instance, reason=): an idle or stopped instance and its descendants, AGENT_INSTANCE closed; open_calls=: the manager's OpenCalls, whose stop recorded for an instance is taken when the instance is left closed (its end, close, max_open, or a turn that stops a one-shot run), so its calls are freed; max_open ranks by AgentRuns.end_order, the order ends were recorded in, never the clock): the brief read against what the calling run may start (offered(agent, depth): its own sub-agents, then, while may_spawn, the types agents may start at run time, an inheriting one for the root alone; task_offer: task's TaskOffer for that run, None for nothing; types: every agent type by name, read-only, what a skill's start checks against), its tools and model against the type's own (read_choices, tool_names= asked only for a call naming tools), then start(StartRequest, its tools= and model= carried to AgentRun.tools/.model and RunControl.tools, and said by its start: every run of the instance keeps them, a follow-up one whose type lost them refused, CHOICE_GONE_ERROR), the one entry for a first run (counted unless the user's, started_by as given; who may start the type is the asker's to check), the run named (a turn's first run past the instances its conversation's store keeps: stored=, asked once per conversation per turn, again after a failed or stopped ask), its AGENT_RUN start and end observed and reported, the backend's hook (RunHook: AgentRun → RunAnswer) run in a task of its own with the run active and no tool call, the end by the answer (completed, partial for a cut or the step limit, refused, failed for an error or a raise, with one recoverable ERROR failed: , or RunFailed's own words, its result the text the run wrote before it failed (RunFailed(text=); a failed model call the hook's RunAnswer.error, failure_reason, with error_code its type, the warning's code), cancelled by its control with what the hook had), interrupted on its turn's cancel, which wins; the envelope as the result; each run under its RunControl, the type's limits over the policy's, kept while it works: control(run), cancel(run_id, by=, error=), the run alone; a call past max_runs_per_turn the error result RUNS_PER_TURN_ERROR, no run; the stored instances asked under a lock per conversation; forget(conversation): a deleted one's slots, unread messages, waiting closes and asks; each run in a working slot of its conversation's SlotPool, slots(conversation): policy.max_active slots, made on first use and kept, the root taking none: taken right before its hook and its time limit, queued then running while it waits for one, given back at its end, straight back to a caller that waits on it alone; a caller that delegates lends its slot while it waits for its children), DelegationRequest, StartRequest, FollowUpRequest, AgentRun (control, follow_up), RunAnswer, RunFailed, started_by, waiting_on_user (a sub-agent run waiting on the user: input_required, its slot lent, queued while its take-back waits for a slot, then running; nested waits once; request_user_input and the permission engine); records.py: RecordsWriter (each conversation's records written to its store as they change: changed, one write at a time per conversation taking the records as it starts, so changes made meanwhile go together in the next; flush, flush_all, discard (a delete's: what waits dropped, the write under way waited for); a failed write warned once per conversation, subagent_records_not_saved, never raised); slots.py: SlotPool (acquire(priority): a free slot, else a future in a heap by priority, RETURNING before NEW, then arrival; release; lent(slot, on_wait=): the slot lent while its run waits, nested lends once, taken back at RETURNING after (on_wait called when that has to wait), at most one take-back waiting for a slot and none once it is held (a wait that starts while one is queued takes it over, and one handed the slot withdraws any queued since), nothing taken back after a cancel, so a tool's caught timeout around a question leaves its run working without a slot, input_required until its next question is answered (running again, still without a slot) or its end; hand_back(slot, to): a child's slot to its parent waiting on it alone; free, waiting; a cancelled waiter leaves the heap, one handed a slot as it is cancelled hands it on; not asyncio.Semaphore), Slot (held, lent), RETURNING, NEW; control.py: RunControl (one run's: tools, the type's own tools it may use, and keeps(name): one of them or of KEPT_TOOLS, the state and delegation tools, what both backends filter by; cancel(by=, error=) its task, the first cancel winning, own_cancel for the hook that takes it and returns, finish: the hook's work ended, no cancel after it (ADK's state read loses no answer), timing: the time limit while the hook runs; model_call/at_step_limit/final_call: the step limit, STEP_LIMIT_NOTE on the last allowed call; used: the token limit, against its own calls and side_tokens (its side calls and summaries, from the ledger), an answer past it that makes calls the run's last, cancelled by it, one that makes none its result (calls=); model_call once final stays final; a cancel leaves a task its turn is cancelling alone; steer/take_steering), STEP_LIMIT_NOTE; outcome.py: a sub-agent's refused or cut answer (outcome_of, the refusal notice as Deep Agents 0.7.34 words it, cut_off, cut_off_warning, OPENAI_REFUSAL_PREFIX: how ADK's OpenAI adapters word a refusal); policy.py: SubAgentPolicy (max_active, max_runs_per_turn, limits, max_open, follow_ups, spawn_sources: of SPAWN_SOURCES, kept as a frozenset, max_spawn_depth) and AgentLimits (max_model_calls, timeout, max_tokens; over: a type's limits over the policy's, field by field, None taking the base's), DEFAULT_LIMITS (100 model calls), frozen and checked as they are made (a ValueError naming the field), as_policy (the one reading of a subagents= argument: a TypeError for anything but a policy or None); brief.py: BRIEF_FIELDS, Brief, BriefError, read_brief (a task call's agent type and brief, against the types its caller may start: the error texts), read_choices (its tools, some of the type's own, and its model, one of its model_choices: TOOLS_ERROR, NO_TOOLS_ERROR, MODEL_ERROR, NO_MODEL_CHOICES_ERROR), task_message (a run's first message, a section per filled field; an inheriting type's ends with INHERITED_CONTEXT_NOTE), task_parameters and task_description (task's schema and description, the same for both backends: tools always, TOOLS_DESCRIPTION, model when a type offered has choices, MODEL_DESCRIPTION, and a type's line its "model choices: , "; limit_sentences: the limits it states, "At most sub-agents work at once; more calls in one response wait for a free slot. At most runs per turn.", then DEPTH_SENTENCE, "Sub-agents cannot start sub-agents.", when no run the call starts may start one; warn=False for a description made per run), TaskOffer and task_offer (both, for the types one run may start); envelope.py: envelope (a delegation run's result: success only for completed, a one-line error, cancelled_by for a cancelled run), read_envelope (a dict or its JSON text, else None; never raises), view_notice (`VIEW_NOTICE`: what the root is told once the user worked with an instance), the limit and interrupted error texts; `Delegations.message` (an idle instance's follow-up; a running one's run steered, or with `interrupt` cancelled by its parent and followed up; one run per instance, so of two messages to one idle instance in one answer the first runs and the second is steered into it), `stop` (a running instance's run cancelled by its parent, the instance idle; `close` closes it and its descendants, a running one's at its run's end), `check`, `steer(conversation, run, message)`, `stop_by_user`/`close_by_user` (`STOPPED_BY_USER_ERROR`, `CLOSED_BY_USER`: a running run cancelled by the user and waited for), `stop_cause(run)` and `cancel(..., conversation=)`; a message steered to a run that its transcript does not hold when it ends (`RunControl.unstored`) is kept for the instance's next run; a run whose parent's run its control stopped ends `cancelled` by its parent (`its parent's run was stopped`); a run that did not complete fully names its open tasks in its envelope (`envelope(open_tasks=)`, `open_task_descriptions`) and a cancelled run keeps its plan and tasks; `SubAgentPolicy.follow_ups`; brief.py: `follow_up_description`/`follow_up_parameters` (the parent's tools' texts); follow_ups.py: `call_follow_up_tool` (a message_agent, stop_agent or check_agents call as the run in progress); spawn.py: spawnable (the types a source may start at run time: the policy's spawn_sources and the type's spawnable_by), may_spawn (depth below max_spawn_depth), can_have_children (who is built with task, and with follow_ups the parent's tools and the roster: sub-agents, or a type agents may start while the root or runs below it may), depth_sentence_applies, AGENT_SOURCE/SKILL_SOURCE/USER_SOURCE; no backend imports; roster.py: roster_text (the main agent's open sub-agents, newest first, one line each, ROSTER_OPEN/ROSTER_HEADER/ROSTER_CLOSE, at most ROSTER_MAX characters in whole lines, "" for none open), Rosters (a snapshot per conversation, as MemoryIndex: now, forget, clear; the root's own instances, parent root) +│ │ ├── agents/ # Sub-agents: runs.py: the RUN_* statuses (a working run's: RUN_QUEUED, RUN_RUNNING, RUN_INPUT_REQUIRED, RUN_WORKING_STATUSES; a record says running from its start), INSTANCE_RUNNING/IDLE/STOPPED/CLOSED and INSTANCE_STATUSES, InstanceRecord (an instance: parent, depth, title, status, runs, continuable, and the tools and model its first run's start gave it, read as None from records without them), RunRecord (input: a follow-up's message as written, "" for a first run), AgentRuns (a manager's runs and instances by conversation: run_for names - and its first run #1 per (conversation, parent run, call id), a new one once it ended, and a start with no call (the user's) a new one each time; next_run: an instance's next run; instances/instance, kept from the events: a start makes or reopens the instance running, an end sets its status from instance_status, AGENT_INSTANCE a change without a run; number_from: past the instances a conversation's store keeps, a count never lowered; observe records AGENT_RUN under the turn it is reported in; interrupt_open; a record's usage: what the run used, by model, from its end event or the ledger; its plan and tasks: the run's own last, from its end event; RECORDS_VERSION, export (a conversation's records as JSON-safe data: v, saved, numbered, instances, runs) and restore (replaces them; a run found working ends interrupted, INTERRUPTED_ERROR, at the later of its start and saved, its instance idle, closed for a type that is not continuable; each run's end order stored (end), any time or field that does not read ValueError; counters never below an instance kept; ValueError for another version or records that do not read, nothing changed), stored_instance_ids (the instances stored records name; None for none), AgentRuns(on_change=): told each change, never by restore), run_title, result_head, run_instance and run_number (the one reader of a run id: researcher-2#1's instance and number), run_label (how a dialog names a run: researcher-2 (researcher, run 1)), SUBAGENT_ERROR_PREFIX (ADK's old words for a failed delegation, kept for callers), show_as_delegation(result, envelope) (a delegation's TOOL_RESULT shown alike on both backends: the result's first line, or Failed: ; metadata["result"] the envelope); a record's brief, started_by, mode and cancelled_by; delegate.py: Delegations (delegate(DelegationRequest) → Delegated and follow_up(FollowUpRequest) → Delegated: the one place a run starts and ends, on both backends (a follow-up is the instance's next run through the same hook, AgentRun.follow_up: refused as an error result, no run, for an unknown or not-yours instance (NOT_YOURS_ERROR, YOURS, NO_SUB_AGENTS), a closed one (CLOSED_ERROR), one the user stopped when an agent sends it (STOPPED_ERROR), a running one (RUNNING_ERROR), one whose type the app no longer has (TYPE_GONE_ERROR) and a blank message (NO_MESSAGE_ERROR); an agent's counts toward max_runs_per_turn, the user's (started_by USER) does not; a run's end carries the status it leaves its instance in: stopped for the user's cancel, closed for a type that is not continuable or the oldest idle one past max_open, else idle; close(conversation, instance, reason=): an idle or stopped instance and its descendants, AGENT_INSTANCE closed; open_calls=: the manager's OpenCalls, whose stop recorded for an instance is taken when the instance is left closed (its end, close, max_open, or a turn that stops a one-shot run), so its calls are freed; max_open ranks by AgentRuns.end_order, the order ends were recorded in, never the clock): the brief read against what the calling run may start (offered(agent, depth): its own sub-agents, then, while may_spawn, the types agents may start at run time, an inheriting one for the root alone; task_offer: task's TaskOffer for that run, None for nothing; types: every agent type by name, read-only, what a skill's start checks against), its tools and model against the type's own (read_choices, tool_names= asked only for a call naming tools), then start(StartRequest, its tools= and model= carried to AgentRun.tools/.model and RunControl.tools, and said by its start: every run of the instance keeps them, a follow-up one whose type lost them refused, CHOICE_GONE_ERROR) (also start_by_user's, /agent new's: a type startable_by_user, spawnable for "user", else user_start_refused's USER_START_ERROR, NO_USER_TYPES_ERROR or NO_OBJECTIVE_ERROR as the error result; no caller or call, started_by USER, counted False, titled run_title(objective)), the one entry for a first run (counted unless the user's, started_by as given; who may start the type is the asker's to check), the run named (a turn's first run past the instances its conversation's store keeps: stored=, asked once per conversation per turn, again after a failed or stopped ask), its AGENT_RUN start and end observed and reported, the backend's hook (RunHook: AgentRun → RunAnswer) run in a task of its own with the run active and no tool call, the end by the answer (completed, partial for a cut or the step limit, refused, failed for an error or a raise, with one recoverable ERROR failed: , or RunFailed's own words, its result the text the run wrote before it failed (RunFailed(text=); a failed model call the hook's RunAnswer.error, failure_reason, with error_code its type, the warning's code), cancelled by its control with what the hook had), interrupted on its turn's cancel, which wins; the envelope as the result; each run under its RunControl, the type's limits over the policy's, kept while it works: control(run), cancel(run_id, by=, error=), the run alone; a call past max_runs_per_turn the error result RUNS_PER_TURN_ERROR, no run; the stored instances asked under a lock per conversation; forget(conversation): a deleted one's slots, unread messages, waiting closes and asks; each run in a working slot of its conversation's SlotPool, slots(conversation): policy.max_active slots, made on first use and kept, the root taking none: taken right before its hook and its time limit, queued then running while it waits for one, given back at its end, straight back to a caller that waits on it alone; a caller that delegates lends its slot while it waits for its children), DelegationRequest, StartRequest, FollowUpRequest, AgentRun (control, follow_up), RunAnswer, RunFailed, started_by, waiting_on_user (a sub-agent run waiting on the user: input_required, its slot lent, queued while its take-back waits for a slot, then running; nested waits once; request_user_input and the permission engine); records.py: RecordsWriter (each conversation's records written to its store as they change: changed, one write at a time per conversation taking the records as it starts, so changes made meanwhile go together in the next; flush, flush_all, discard (a delete's: what waits dropped, the write under way waited for); a failed write warned once per conversation, subagent_records_not_saved, never raised); slots.py: SlotPool (acquire(priority): a free slot, else a future in a heap by priority, RETURNING before NEW, then arrival; release; lent(slot, on_wait=): the slot lent while its run waits, nested lends once, taken back at RETURNING after (on_wait called when that has to wait), at most one take-back waiting for a slot and none once it is held (a wait that starts while one is queued takes it over, and one handed the slot withdraws any queued since), nothing taken back after a cancel, so a tool's caught timeout around a question leaves its run working without a slot, input_required until its next question is answered (running again, still without a slot) or its end; hand_back(slot, to): a child's slot to its parent waiting on it alone; free, waiting; a cancelled waiter leaves the heap, one handed a slot as it is cancelled hands it on; not asyncio.Semaphore), Slot (held, lent), RETURNING, NEW; control.py: RunControl (one run's: tools, the type's own tools it may use, and keeps(name): one of them or of KEPT_TOOLS, the state and delegation tools, what both backends filter by; cancel(by=, error=) its task, the first cancel winning, own_cancel for the hook that takes it and returns, finish: the hook's work ended, no cancel after it (ADK's state read loses no answer), timing: the time limit while the hook runs; model_call/at_step_limit/final_call: the step limit, STEP_LIMIT_NOTE on the last allowed call; used: the token limit, against its own calls and side_tokens (its side calls and summaries, from the ledger), an answer past it that makes calls the run's last, cancelled by it, one that makes none its result (calls=); model_call once final stays final; a cancel leaves a task its turn is cancelling alone; steer/take_steering), STEP_LIMIT_NOTE; outcome.py: a sub-agent's refused or cut answer (outcome_of, the refusal notice as Deep Agents 0.7.34 words it, cut_off, cut_off_warning, OPENAI_REFUSAL_PREFIX: how ADK's OpenAI adapters word a refusal); policy.py: SubAgentPolicy (max_active, max_runs_per_turn, limits, max_open, follow_ups, spawn_sources: of SPAWN_SOURCES, kept as a frozenset, max_spawn_depth) and AgentLimits (max_model_calls, timeout, max_tokens; over: a type's limits over the policy's, field by field, None taking the base's), DEFAULT_LIMITS (100 model calls), frozen and checked as they are made (a ValueError naming the field), as_policy (the one reading of a subagents= argument: a TypeError for anything but a policy or None); brief.py: BRIEF_FIELDS, Brief, BriefError, read_brief (a task call's agent type and brief, against the types its caller may start: the error texts), read_choices (its tools, some of the type's own, and its model, one of its model_choices: TOOLS_ERROR, NO_TOOLS_ERROR, MODEL_ERROR, NO_MODEL_CHOICES_ERROR), task_message (a run's first message, a section per filled field; an inheriting type's ends with INHERITED_CONTEXT_NOTE), task_parameters and task_description (task's schema and description, the same for both backends: tools always, TOOLS_DESCRIPTION, model when a type offered has choices, MODEL_DESCRIPTION, and a type's line its "model choices: , "; limit_sentences: the limits it states, "At most sub-agents work at once; more calls in one response wait for a free slot. At most runs per turn.", then DEPTH_SENTENCE, "Sub-agents cannot start sub-agents.", when no run the call starts may start one; warn=False for a description made per run), TaskOffer and task_offer (both, for the types one run may start); envelope.py: envelope (a delegation run's result: success only for completed, a one-line error, cancelled_by for a cancelled run), read_envelope (a dict or its JSON text, else None; never raises), view_notice (`VIEW_NOTICE`: what the root is told once the user worked with an instance), the limit and interrupted error texts; `Delegations.message` (an idle instance's follow-up; a running one's run steered, or with `interrupt` cancelled by its parent and followed up; one run per instance, so of two messages to one idle instance in one answer the first runs and the second is steered into it), `stop` (a running instance's run cancelled by its parent, the instance idle; `close` closes it and its descendants, a running one's at its run's end), `check`, `steer(conversation, run, message)`, `stop_by_user`/`close_by_user` (`STOPPED_BY_USER_ERROR`, `CLOSED_BY_USER`: a running run cancelled by the user and waited for), `stop_cause(run)` and `cancel(..., conversation=)`; a message steered to a run that its transcript does not hold when it ends (`RunControl.unstored`) is kept for the instance's next run; a run whose parent's run its control stopped ends `cancelled` by its parent (`its parent's run was stopped`); a run that did not complete fully names its open tasks in its envelope (`envelope(open_tasks=)`, `open_task_descriptions`) and a cancelled run keeps its plan and tasks; `SubAgentPolicy.follow_ups`; brief.py: `follow_up_description`/`follow_up_parameters` (the parent's tools' texts); follow_ups.py: `call_follow_up_tool` (a message_agent, stop_agent or check_agents call as the run in progress); spawn.py: spawnable (the types a source may start at run time: the policy's spawn_sources and the type's spawnable_by), may_spawn (depth below max_spawn_depth), can_have_children (who is built with task, and with follow_ups the parent's tools and the roster: sub-agents, or a type agents may start while the root or runs below it may), depth_sentence_applies, AGENT_SOURCE/SKILL_SOURCE/USER_SOURCE; no backend imports; roster.py: roster_text (the main agent's open sub-agents, newest first, one line each, ROSTER_OPEN/ROSTER_HEADER/ROSTER_CLOSE, at most ROSTER_MAX characters in whole lines, "" for none open), Rosters (a snapshot per conversation, as MemoryIndex: now, forget, clear; the root's own instances, parent root) │ │ ├── adk/ # ADK orchestrator │ │ │ ├── manager.py # GoogleADKWorkflowManager (the agents built from configs or, adk_config_path, by ADK from a native YAML (library-only: no BaseCLIApp starts one; loaded once per manager at the first _validate_agent_graph (_native_root: the settings' keys exported first; a retry, a model switch and a start after cleanup build on the same tree, whose toolsets the closed runner left reusable), its agents' models resolved leniently in _resolve_extra_models, the base's hook, its registered tools' services detected; configs passed with it ignored, adk_native_configs_ignored): the only difference; _do_initialize builds the app from the tree alone, _build_app → ADKBuild, through the hooks _plugin_chain (the whole chain, top to bottom, its head _init_plugins), _compaction_config (None for a root without a budget), _context_cache_config, _agent_model_refs; the event processor built from the build; a config-built agent's prompt as an instruction provider, sent as written: no `{name}` state injection; _compact_turn: ADK's compaction once, in the base's compact turn; supports_compact False once built for a root without a budget (_no_compact_support says why); the job resume hooks: _conversation_exists (the session read without its events, num_recent_events=0), _deliver_job_notice (the notice, for every app); _run_config: the agents' synchronous tools run in ADK's tool thread pool, 8 workers; _run_and_stream: a run that fails yields the turn's one ERROR, last, none after an ERROR already yielded, and keeps the record of its calls that returned for the next turn (OpenCalls.failed; _answer_left_open forgets it once its answers are stored); the agents: _create_agents builds each config's agent on its own (_agents, by name; no ADK sub_agents), a delegating one with a TaskTool (its own tool named task: AgentGraphError); a runner per sub-agent type (_agent_runners: NoAfterTurnCompactionRunner on App(name=child_app(app_name), root_agent=the type's agent, plugins=_agent_plugin_chain(agent), the app's context cache, no compaction) over the session service, closed with the main runner by _detach_backend, rebuilt by every initialization); a runner per (type, model choice) too (_variant_runners over _variant_agents: the type's agent built on the choice, _build_agent(model=), its chain _agent_plugin_chain(agent, model=, budget=), every plugin reading the choice's model, kind and numbers under the type's name), closed and rebuilt alike; _agent_tool_names: the built agent's tools by name, an MCP toolset's listed when first asked and kept for the build; _run_agent, the base's hook: the runner of run.model's choice or the type's, its processor on _run_models' maps, the raw log told the choice (_chosen_model); the instance's child session (_child_session: a first run makes it from run.state and an inheriting instance's copied events, once; never one the store keeps, whose instance numbering goes past: ADK's create_session refuses it, and the run fails; a follow-up takes the stored session, answers the calls an earlier run left open there (left_open_by) and passes the caller's mark when it holds none; one the store lost is made as a first run's), _stored_instances (the base's hook: the highest instance number of each type the conversation's child sessions keep), the type's runner on the task message (a follow-up's own message) with an abort signal set before it is closed, a run-mode ADKEventProcessor, the raw log's records reported as they come (_report_raw_log); a model's failure raised as the provider's (_plugin_cause), an overflow RunFailed, a reply that is no answer RunAnswer(error=), the shared keys it changed read back) │ │ │ ├── build.py # ADKBuild (root, reply_agents, plugins, compaction, cache, models); load_native_root (from_config at validation; what ADK cannot load, wrapped as AgentGraphError naming the file, ADK's error the cause; a root that is not an LlmAgent, a name used twice in the tree and a task-mode agent refused, AgentGraphError naming it; ensure_direct_anthropic); what the run reads of any tree: reply_agents (the root and the chat-mode agents it can transfer to), own_after_tool_agents (left out by the cap) @@ -256,7 +256,7 @@ Workflow: - **Tool error handling**: All tools return `{"success": bool, ...}` dicts. Never raise `ToolError`. An exception that still escapes a tool is a bug, but it costs one call rather than the turn: on ADK, `workflow/adk/tool_error_plugin.py::ToolErrorPlugin` turns it into an error dict; on Deep Agents, `workflow/deepagents/middleware.py::ToolCallErrorMiddleware`, inside the permission gate, gives the same result, `{"success": false, "error": " failed: : "}` cut to 500 characters (both use `workflow/tool_errors.py`). A call to a tool name the agent does not have gets ADK's own text, its first two lines (`unknown_tool_result`: "nope failed: ValueError: Tool 'nope' not found." and the agent's tools by name), logged `tool_not_found` at info (the model's mistake): on ADK the permission gate lets ADK's stand-in through (`is_unknown_tool`: a bare `BaseTool` described "Tool not found", which runs nothing; contract-tested) and `ToolErrorPlugin` answers its lookup error; on Deep Agents the gate answers it. It catches `Exception`, never `BaseException`, so cancelling still cancels (google-adk 2.15 hands a cancelled call's `CancelledError` to `ToolErrorPlugin` for cleanup, ignoring the answer: it answers nothing and logs `tool_cancelled` at debug, no warning). `task` raises nothing into it: a sub-agent's model or run failing (its summary or overflow included: its own tools' errors are results already) fails the run, whose envelope its parent reads (`error`: the provider's reason; on ADK out of ADK's plugin wrapper), reported at once through the turn's live events as one recoverable `ERROR`, ` failed: `, the run's: the coordinator carries on. A sub-agent's overflow (still too long after its summary or trim) fails its run, on both backends, in the words of ADK's overflow handler, `: the request no longer fits 's context window.` with `error_code` `CONTEXT_OVERFLOW` (`context.py::subagent_overflow_message`): ADK's `OverflowPlugin` answers the run's model call with it, Deep Agents' manager raises it (`RunFailed`). A refusal is no exception here (the framework adds no `ModelRefusalMiddleware`): a sub-agent whose final answer a model refused ends its run `refused`, and its parent reads, as its envelope's result, Deep Agents 0.7.34's notice ("The subagent stopped because a model refused the request. … Retrying the same request is unlikely to succeed; rephrase it or continue without it."), on both backends and whichever deepagents the pin installs (0.7.28 has no notice of its own; 0.7.34+ finds no refusal block left to word again); an answer cut at the output limit keeps its text, followed by `[cut off at the output limit]`, and its run ends `completed` and `partial`, with one recoverable warning ("'s answer was cut off at the output limit"); the answer's thoughts or reasoning are kept. ADK's `SubAgentOutcomePlugin` and Deep Agents' `SubAgentOutcomeMiddleware` rewrite and mark the answer, by `workflow/agents/outcome.py`. On ADK the plugin reads the answer's `finish_reason` (Claude's `refusal` and a Chat Completions `content_filter` arrive as `SAFETY`, `max_tokens` and `length` as `MAX_TOKENS`, Gemini's as themselves), the `error_code` ADK sets on an answer with no content (a Gemini prompt's `block_reason`), the `reason` an `OTHER` stop names in its JSON error message (ADK's OpenAI Responses adapter's `incomplete_details`, `content_filter` among them) and a text part `OpenAI refusal: ` (that adapter's refusal, and `OpenAICompatibleLlm`'s of a Chat Completions `refusal`, which ADK's class drops). On Deep Agents the middleware reads `response_metadata`'s `stop_reason` (ChatAnthropic), `finish_reason` (ChatOpenAI, ChatGoogleGenerativeAI), `incomplete_details.reason` (the Responses API) and `prompt_feedback.block_reason` (a Gemini prompt block), and a refusal the answer holds (a refusal block, standard or `non_standard`, or `additional_kwargs["refusal"]`). The root's own answers reach the user as their model gave them: on ADK a root's refusal with no answer (Claude's, Gemini's) is still the turn's one `ERROR` (" returned no answer"), and a root on OpenRouter or an OpenAI-compatible server replies "OpenAI refusal: ". On both backends the root's own failure leaves the run: the turn's one `ERROR`. A gate or error result goes back as the call's `ToolMessage` with `status="error"`. LangGraph's `ToolNode` runs with `handle_tool_errors=True`. - **Tool result cap**: every tool result passes `workflow/tool_output.py::cap_tool_result` (registered, MCP and skill tools, `job_result`, a delegation's envelope on either backend, and the envelope a view's notice carries: `BaseWorkflowManager._user_ran` keeps `instance_result` capped): one over `tool_result_max_chars` is cut to its shape and as much of its head and tail as fits (the kept length is bisected, since JSON escapes vary), with a note (under `truncated`, or appended to a string) pointing at its full output in `./.{app_name}/tool-output/`, written for `read_file` to page by lines (lines over 2,000 characters split). A string that holds a JSON object (`json_object`: a delegation's envelope, which both task tools write unescaped, `ensure_ascii=False`; a framework tool's dict in a Deep Agents `ToolMessage`) is cut as that dict and given back as its JSON text, so the parent reads JSON still, on both backends. On ADK, `workflow/adk/tool_result_cap_plugin.py::ToolResultCapPlugin` is registered after `InterruptedCallsPlugin`, since ADK stops at the first `after_tool_callback` that returns a value, and it leaves out an agent with `after_tool_callback`s of its own (a native YAML app's, `build.own_after_tool_agents`), which ADK would skip once the cap answered. ADK's Claude and OpenAI Responses adapters send only a result's `content`, else its `result`, so the plugin also puts the note there (`_note_where_sent`). On Deep Agents, `ToolResultCapMiddleware` sits between the permission gate and `ToolCallErrorMiddleware`, so an error result is capped too, and reads a `ToolMessage` (its text cut by the cap's string rule, text blocks joined into the first) and each `ToolMessage` of a `Command`. A call of the framework's `read_file` (by identity, as each gate resolves tools) on a saved output is cut without a second save. Saving never fails the call (`tool_output_not_saved` warns once per folder, then debug), and a cap that raises leaves the result uncut (`tool_result_cap_failed` at warning, its traceback at debug). - **Summarizing on ADK (main agent only)**: every app's App (a native ADK YAML app's too, when its root's model has a context budget) has ADK's `EventsCompactionConfig` with `workflow/adk/compaction.py::AgentCliSummarizer` at the root's trigger (`context_budget`, as on Deep Agents); ADK checks before every agent's model call, and `MainAgentPlugin` (the first plugin) records the running agent in a ContextVar, so the summarizer writes only for the root (a sub-agent's run, on its type's runner, has no compaction config at all: a sub-agent compacting the shared session lost its brief and looped, 100 requests in one turn, offline). The summarizer picks its own range before paying for anything (`summary_range`: the newest `keep` tokens and the current turn kept, a cut only where a user turn starts, never parting a call from its result, long-running calls excepted since ADK re-injects them, nor leaving a kept event stamped inside the range; none for a saving under 20% of the trigger, the seed left out of it), writes on the root's own model (`_simple_model(SUMMARY_MAX_TOKENS, agent=root)`, thinking off) with `workflow/summary_prompt.py`, the rendering sized to that model's window (the middle cut, `MIDDLE_OMITTED`, the seed kept whole), and returns **user-role** text starting `SUMMARY_PREFIX` (a model-role first message is one Claude refuses), which the fit guard folds, after the memory index and the roster when the request has them, into the next user text (`fold_summary`), so no request holds two user messages in a row. `last_kept_turns` and `last_error` are for its callers: a manual summarizer warns of nothing itself. It reports through the turn's live events (`_run_and_stream` iterates the runner through `live_events.merged` under `reporting(live)`); any failure is one recoverable `ERROR` a turn, never raised to ADK. `NoAfterTurnCompactionRunner` overrides ADK's private `Runner._run_post_invocation_compaction` (contract-tested), so the prompt never waits for a summary after the answer. `FitGuardPlugin` is the last plugin (but `SentRequestLoggingPlugin`, which logs a request as sent, and `CallSentPlugin`, which starts the call's clock) and `OverflowPlugin` the one before it (`MemoryIndexPlugin`, when the root has a memory tool and `memory_index_enabled` is on, the one before that: it puts the conversation's memory index snapshot first in the root's requests, never in the session): the guard leaves a request's oldest turns out when it is over its agent's budget (keeping the newest turn and what opens the conversation, the memory index, the roster of the root's open sub-agents (`RosterPlugin`, before `MemoryIndexPlugin`, for a root with `message_agent`), then a summary: `protected_head`; in a sub-agent type's chain also the run's task message and its instance's brief, `brief_of`) and keeps each request as it came in (`request_as_seen`: one copy per model call, under the call's `EventActions`, which ADK passes to all three of its callbacks: each sub-agent run is an invocation of its own on a child session, but two runs of one type share that type's runner and its plugins, and a run drops only what its own cancelled calls left, as it ends), and the overflow handler, on a provider's overflow, summarizes now (the root, through `compact_session`, ADK's private `_run_compaction_for_token_threshold_config`; `_summarize_now` returns `WrittenSummary(text, kept_turns)`, and the retry is the index, the roster, the summary and those turns) or trims to half the budget (a sub-agent, or nothing to summarize), builds the retry from the guard's copy without the context cache, retries once on the agent's `canonical_model`, then answers the root with `LlmResponse(error_code="CONTEXT_OVERFLOW")`, never model text (ADK would store it as the reply), which `ADKEventProcessor` maps to the turn's `ERROR`; a retry that fails otherwise propagates, and `_run_and_stream` unwraps ADK's plugin-manager `RuntimeError` to the provider's error; a sub-agent's call that still does not fit is answered with an error response too, `CONTEXT_OVERFLOW` and `subagent_overflow_message`, which its run's processor keeps as the run's failure: the run ends `failed` with those words (`RunFailed`), its parent reads them in the envelope, and the user is warned once, by the framework's delegation (`agents/delegate.py`), as on Deep Agents. A native ADK YAML app gets all of it: only the building of its agents differs (`workflow/adk/build.py`). Its chat-mode sub-agents keep transferring, and an agent the root transfers to replies to the user (`build.reply_agents`: its text is the reply, recent_messages reads it, its overflow is the turn's clear error, its calls write the outside-content mark); the summary and the memory index stay the root's, so such an agent is trimmed by the fit guard, not summarized. An agent's own callbacks (a native app's) run after every plugin, and only when none answered: its before-model callbacks see the request after the fit guard, and the cap leaves out an agent with after-tool callbacks. A main agent whose model does not resolve through the catalog has no budget and no summary. -- **Sub-agents delegate and return**: on both backends a sub-agent run is a call of its parent's `task` tool (the framework's: `tools/_core/delegation.py` declares it, `workflow/agents/delegate.py` runs it) that returns in the same turn; only the root replies to the user (a sub-agent's `TEXT` carries `metadata["subagent"]`, and the CLI shows it as the events box's status line, under its run's name: `researcher-2 › …`; `/agents` picks among a conversation's instances), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the types the calling run may start, `Delegations.offered`: its own sub-agents, then, with `SubAgentPolicy.spawn_sources` holding `"agent"` and the run's depth below `max_spawn_depth`, the types whose `AgentConfig.spawnable_by` names `"agent"`, `workflow/agents/spawn.py`; a free type, in no `sub_agents` list, is never the root; `task` is offered for each run, ADK declaring it per request and Deep Agents rewriting a sub-agent's per model call, and a run offered nothing has none) and a brief (`workflow/agents/brief.py`: `title`, `objective`, `deliverable`, `constraints`, `known`, `done_when`), then `tools` (some of the type's own tools, `_agent_tool_names`: the run is offered only those and the tools every run keeps, `RunControl.keeps`, ADK's `RunControlPlugin` and Deep Agents' `RunControlMiddleware` filtering its requests and answering a call of another `unknown_tool_result`) and `model` (one of `AgentConfig.model_choices`, offered only when a type has some: the run is on the type's agent built on that choice at initialization, ADK a runner and Deep Agents a graph per (type, choice), resolved and budgeted with the rest, `_run_models`), its schema and description the same on both backends (`task_parameters`, `task_description`: a line per type with its description, "The agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both, through `Delegations.start` (a `StartRequest`, the one entry for a first run): it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents `, never written to the conversation. It ends as the `RunAnswer` says: its last text (a reply that also called a tool included; none at all, an empty result shown `No answer`), `refused` or `partial` by the outcome mark, `failed` for an error or a raise (one recoverable `ERROR`, ` failed: `, or the hook's own words, `RunFailed`: an overflow's; its result the text it wrote before it failed: a failed model call is the hook's `RunAnswer.error`, `failure_reason`, its warning's code `RunAnswer.error_code`, the error's type, and `RunFailed` carries `text=`); and the call's result is the run's envelope as JSON (`workflow/agents/envelope.py`), shown by `show_as_delegation`. A cancel of the caller's task stops the run's task first and ends the run `interrupted`. Each run works under its `RunControl` (`workflow/agents/control.py`, `AgentRun.control`), with its type's `AgentConfig.limits` over the policy's (`SubAgentPolicy.limits`, `DEFAULT_LIMITS`: 100 model calls): `Delegations.cancel(run_id, by=, error=)` cancels the run alone (its parent, the user or a limit), and the hook, seeing its own cancel (`own_cancel`), stops the run as a stopped turn's (ADK: its abort signal, its open calls sealed in its child session; Deep Agents: its stream closed) and returns what it has: the run ends `cancelled` with `cancelled_by` and that text, `partial`, while its siblings and the turn go on; the turn's own cancel still wins (`interrupted`). Past its `timeout` (counted from when its hook starts, `timing`) the run is cancelled by its limit (`time limit reached`); each model call is counted before it is made (`RunControlPlugin` in each sub-agent chain, `RunControlMiddleware` on each sub-agent's model side) and the last allowed one gets `STEP_LIMIT_NOTE` after its last message, its tools still declared (Claude refuses tool calls in a request that defines no tools); its answer's calls are dropped, never run, so the run completes `partial`, `step limit reached`; each call's tokens are counted after it, with what the run's other calls used (`RunControl(side_tokens=)`: its tools' side calls and its summaries, the ledger's rows of the run that are no agent step, `UsageLedger.by_purpose(run=)`), so the limit is the run's total as its usage record counts it, and past `max_tokens` an answer that makes tool calls is the run's last, its calls dropped, `cancelled` by its limit (`token limit reached`), while one that makes none ends the run as it would, `completed`, its result whole (a model that reports no usage counts none of its own). A turn starts at most `max_runs_per_turn` runs, at any depth (`sessions.runs_this_turn`): a call past it is the error result, no run started; `task`'s description says so (`limit_sentences`). At most `max_active` runs of a conversation work at once, at any depth (`workflow/agents/slots.py::SlotPool`, one per conversation, `Delegations.slots`; the root takes no slot): a run takes a slot right before its hook and its time limit start and gives it back at its end, however it ends; one that finds none waits `queued` (an `AGENT_RUN` and its record say so, then `running`), not counted against its `timeout`. A run lends its slot while it waits on its children (one lend for all it waits on at once; the child that ends last hands its slot straight back, so the tree in progress goes on ahead of the runs that have not started) or on the user (`waiting_on_user`: `input_required`, `queued` once answered while it waits for its slot back, then `running`, in `request_user_input` and in the permission engine from before its one-prompt lock until after it: a run waiting for a slot while holding the lock would hold every other run's prompt; a prompt no one can be shown, no input callback or its turn ended, lends nothing: `can_request_user_input`), so nested fan-out never deadlocks; a cancel, queued or lending, leaves no waiter in the heap and no slot taken. A message steered to a working run (`RunControl.steer`, through `Delegations.control(run)`) is added after its last message, as the user's, before its next model call, and stays in its transcript (ADK: appended to its child session, the run's later events stamped after it so a durable store reads them back in order; Deep Agents: added to its state); a sub-agent run's task message is never trimmed, on ADK neither by the fit guard nor by the overflow handler's retry, whatever was steered after it. A dialog whose run is stopped is withdrawn, the turn going on (`MessageProcessor`). `AgentConfig.inherit_context` sets what a run sees: False (the default) its task alone, True its parent's conversation too, read once as the run starts (the conversation after any summary; Deep Agents' less the message that called `task`, which ADK's copy keeps), before the task message, which then ends with `INHERITED_CONTEXT_NOTE` (whose conversation it reads, which message is its task); `validate_agent_graph` refuses a value that is not True or False, `inherit_context=True` on the root, on an agent with sub-agents and below another sub-agent. On ADK (`workflow/adk/task_tool.py::TaskTool`) every config-built agent is built on its own, with no ADK `sub_agents`, so ADK offers none `transfer_to_agent`, and gets ADK's identity line ("You are an agent. Your internal name is …"); a delegating agent has one `TaskTool`. A sub-agent is an instance that outlives its run: `idle` when the run ends, its next run a follow-up (`Delegations.follow_up`, through the same hook with `AgentRun.follow_up`, the message as written and no history), one run per instance at a time; a run's end leaves its instance `stopped` (once the user stopped it: its run cancelled by the user, or an idle one; only the user continues it), `closed` (`AgentConfig.continuable` False, or past `SubAgentPolicy.max_open`: the oldest idle one) or `idle`, `Delegations.close` closes an idle or stopped one and its descendants, and `AGENT_INSTANCE` carries a change without a run; the user controls any instance of the open conversation through the manager (`run_instance`: a follow-up as a turn of its own, its Ctrl+C the user's stop; `stop_instance`, `close_instance`, `steer_instance`; `tell_root`: a notice turn of the root, marked as a job's) and the CLI's `/agents` picker, `/agent stop|close ` and `/agent `'s view (`cli/agent_view.py`: a line typed there is the instance's next run or a steer of the run that works, Ctrl+C the user's stop, `/back` the root's notice); on ADK a follow-up continues the instance's child session, the calls an earlier run left open answered first (`left_open_by`, from the instance's record), on Deep Agents the instance's own checkpointer thread (`instance_run_config`: its input the message and the caller's mark, the shared keys it changed compared with the thread's state as the run started). Each sub-agent type runs on its own runner (`App(name=child_app(app_name))`, the type's agent its root, `_agent_plugin_chain`: the main chain configured for a sub-agent, no memory index, no summary, `RunControlPlugin` and `SubAgentOutcomePlugin`; every plugin's per-call state keyed by invocation) over the manager's session service, on a child session per instance (`child_session_id`: `/`, the conversation id's `%` and `/` percent-encoded; an inheriting instance's gets the conversation's events copied once, at its first run, `task_tool.inherited_events`), under an app no conversation list reads. On Deep Agents (`workflow/deepagents/task_tool.py::build_task_tool`) each type's graph is built on its own, and a run `astream`s it in its task with `var_child_runnable_config` cleared, so its chunks reach its own loop alone, never its parent's stream; an inheriting run's history is the parent's messages with Deep Agents' summary event applied (`SummarizationMiddleware._apply_event_to_messages`, private: `tests/workflow/deepagents/test_compact.py` pins it), and `ForeignReasoningMiddleware(kind, agent=...)` leaves out the reasoning of AI messages another agent wrote. A native ADK YAML app keeps transferring (chat-mode sub-agents); a task-mode agent in one is refused at validation, since ADK runs its delegation outside the tool pipeline and keeps the call open across turns. With `SubAgentPolicy(follow_ups=True)` every agent that can have sub-agents (`can_have_children`: its own, or types it may start at run time) also gets `message_agent`, `stop_agent` and `check_agents` beside `task` (`workflow/agents/follow_ups.py::call_follow_up_tool` over `Delegations.message`/`stop`/`check`; ADK's `FollowUpTool`, Deep Agents' `build_follow_up_tools`; an own tool of one of their names fails the build, a Deep Agents MCP tool of one is skipped): `message_agent` continues an idle instance, steers a running one (before its next step; a run already stopping or finished is waited for, then the message follows the instance up or is refused; one being closed is refused as closed at once) or, with `interrupt` (refused, nothing cancelled, when no follow-up could start; an agent's keeps the turn's run it checked for), replaces its run (the user's interrupt is the user's stop); `stop_agent` cancels a running run by its parent (the instance idle; only the user's stop makes one `stopped`) and, with `close`, closes it and its descendants; a message steered to a run and not in its transcript when it ends goes to the instance's next run (`RunControl.stored`/`unstored`: ADK counts one stored as its child-session append returns, Deep Agents once the model call after it holds it); a run that did not complete fully names its open tasks in its envelope (`open_tasks`); a run whose parent's run was stopped by its control ends `cancelled` by its parent, not `interrupted`. A skill whose frontmatter names a type (`agent: `, `tools/skills/agents.py`) starts a run of it when an agent loads it where the app lets a skill start an agent (`"skill"` in `spawn_sources`; otherwise the key is ignored, the skill loads as instructions and the build warns, `skill_agent_ignored`), on both backends (ADK: `adk/skill_tool.py::SkillLoadTool` in `load_skill`'s place; Deep Agents: `_SkillAnswers.load_skill`), when the type's `spawnable_by` holds `"skill"`, the skill has instructions and the loading run may start one (`may_spawn`): through `Delegations.start` (`started_by: skill:`, the loading run its parent, its task message the skill's body under its name, counted toward `max_runs_per_turn`), the call's result the envelope with `"skill"`, shown as a delegation; otherwise `{"success": false, "error": "The skill '' starts the agent '', which ."}`, no run, and a skill its agent's first run could not start is warned of as the agent is built (`skill_agent_not_startable`). +- **Sub-agents delegate and return**: on both backends a sub-agent run is a call of its parent's `task` tool (the framework's: `tools/_core/delegation.py` declares it, `workflow/agents/delegate.py` runs it) that returns in the same turn; only the root replies to the user (a sub-agent's `TEXT` carries `metadata["subagent"]`, and the CLI shows it as the events box's status line, under its run's name: `researcher-2 › …`; `/agents` picks among a conversation's instances), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the types the calling run may start, `Delegations.offered`: its own sub-agents, then, with `SubAgentPolicy.spawn_sources` holding `"agent"` and the run's depth below `max_spawn_depth`, the types whose `AgentConfig.spawnable_by` names `"agent"`, `workflow/agents/spawn.py`; a free type, in no `sub_agents` list, is never the root; `task` is offered for each run, ADK declaring it per request and Deep Agents rewriting a sub-agent's per model call, and a run offered nothing has none) and a brief (`workflow/agents/brief.py`: `title`, `objective`, `deliverable`, `constraints`, `known`, `done_when`), then `tools` (some of the type's own tools, `_agent_tool_names`: the run is offered only those and the tools every run keeps, `RunControl.keeps`, ADK's `RunControlPlugin` and Deep Agents' `RunControlMiddleware` filtering its requests and answering a call of another `unknown_tool_result`) and `model` (one of `AgentConfig.model_choices`, offered only when a type has some: the run is on the type's agent built on that choice at initialization, ADK a runner and Deep Agents a graph per (type, choice), resolved and budgeted with the rest, `_run_models`), its schema and description the same on both backends (`task_parameters`, `task_description`: a line per type with its description, "The agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both, through `Delegations.start` (a `StartRequest`, the one entry for a first run): it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents `, never written to the conversation. It ends as the `RunAnswer` says: its last text (a reply that also called a tool included; none at all, an empty result shown `No answer`), `refused` or `partial` by the outcome mark, `failed` for an error or a raise (one recoverable `ERROR`, ` failed: `, or the hook's own words, `RunFailed`: an overflow's; its result the text it wrote before it failed: a failed model call is the hook's `RunAnswer.error`, `failure_reason`, its warning's code `RunAnswer.error_code`, the error's type, and `RunFailed` carries `text=`); and the call's result is the run's envelope as JSON (`workflow/agents/envelope.py`), shown by `show_as_delegation`. A cancel of the caller's task stops the run's task first and ends the run `interrupted`. Each run works under its `RunControl` (`workflow/agents/control.py`, `AgentRun.control`), with its type's `AgentConfig.limits` over the policy's (`SubAgentPolicy.limits`, `DEFAULT_LIMITS`: 100 model calls): `Delegations.cancel(run_id, by=, error=)` cancels the run alone (its parent, the user or a limit), and the hook, seeing its own cancel (`own_cancel`), stops the run as a stopped turn's (ADK: its abort signal, its open calls sealed in its child session; Deep Agents: its stream closed) and returns what it has: the run ends `cancelled` with `cancelled_by` and that text, `partial`, while its siblings and the turn go on; the turn's own cancel still wins (`interrupted`). Past its `timeout` (counted from when its hook starts, `timing`) the run is cancelled by its limit (`time limit reached`); each model call is counted before it is made (`RunControlPlugin` in each sub-agent chain, `RunControlMiddleware` on each sub-agent's model side) and the last allowed one gets `STEP_LIMIT_NOTE` after its last message, its tools still declared (Claude refuses tool calls in a request that defines no tools); its answer's calls are dropped, never run, so the run completes `partial`, `step limit reached`; each call's tokens are counted after it, with what the run's other calls used (`RunControl(side_tokens=)`: its tools' side calls and its summaries, the ledger's rows of the run that are no agent step, `UsageLedger.by_purpose(run=)`), so the limit is the run's total as its usage record counts it, and past `max_tokens` an answer that makes tool calls is the run's last, its calls dropped, `cancelled` by its limit (`token limit reached`), while one that makes none ends the run as it would, `completed`, its result whole (a model that reports no usage counts none of its own). A turn starts at most `max_runs_per_turn` runs, at any depth (`sessions.runs_this_turn`): a call past it is the error result, no run started; `task`'s description says so (`limit_sentences`). At most `max_active` runs of a conversation work at once, at any depth (`workflow/agents/slots.py::SlotPool`, one per conversation, `Delegations.slots`; the root takes no slot): a run takes a slot right before its hook and its time limit start and gives it back at its end, however it ends; one that finds none waits `queued` (an `AGENT_RUN` and its record say so, then `running`), not counted against its `timeout`. A run lends its slot while it waits on its children (one lend for all it waits on at once; the child that ends last hands its slot straight back, so the tree in progress goes on ahead of the runs that have not started) or on the user (`waiting_on_user`: `input_required`, `queued` once answered while it waits for its slot back, then `running`, in `request_user_input` and in the permission engine from before its one-prompt lock until after it: a run waiting for a slot while holding the lock would hold every other run's prompt; a prompt no one can be shown, no input callback or its turn ended, lends nothing: `can_request_user_input`), so nested fan-out never deadlocks; a cancel, queued or lending, leaves no waiter in the heap and no slot taken. A message steered to a working run (`RunControl.steer`, through `Delegations.control(run)`) is added after its last message, as the user's, before its next model call, and stays in its transcript (ADK: appended to its child session, the run's later events stamped after it so a durable store reads them back in order; Deep Agents: added to its state); a sub-agent run's task message is never trimmed, on ADK neither by the fit guard nor by the overflow handler's retry, whatever was steered after it. A dialog whose run is stopped is withdrawn, the turn going on (`MessageProcessor`). `AgentConfig.inherit_context` sets what a run sees: False (the default) its task alone, True its parent's conversation too, read once as the run starts (the conversation after any summary; Deep Agents' less the message that called `task`, which ADK's copy keeps), before the task message, which then ends with `INHERITED_CONTEXT_NOTE` (whose conversation it reads, which message is its task); `validate_agent_graph` refuses a value that is not True or False, `inherit_context=True` on the root, on an agent with sub-agents and below another sub-agent. On ADK (`workflow/adk/task_tool.py::TaskTool`) every config-built agent is built on its own, with no ADK `sub_agents`, so ADK offers none `transfer_to_agent`, and gets ADK's identity line ("You are an agent. Your internal name is …"); a delegating agent has one `TaskTool`. A sub-agent is an instance that outlives its run: `idle` when the run ends, its next run a follow-up (`Delegations.follow_up`, through the same hook with `AgentRun.follow_up`, the message as written and no history), one run per instance at a time; a run's end leaves its instance `stopped` (once the user stopped it: its run cancelled by the user, or an idle one; only the user continues it), `closed` (`AgentConfig.continuable` False, or past `SubAgentPolicy.max_open`: the oldest idle one) or `idle`, `Delegations.close` closes an idle or stopped one and its descendants, and `AGENT_INSTANCE` carries a change without a run; the user controls any instance of the open conversation through the manager (`run_instance`: a follow-up as a turn of its own, its Ctrl+C the user's stop; `start_instance`: the user's new instance, `/agent new`, the same; `stop_instance`, `close_instance`, `steer_instance`; `tell_root`: a notice turn of the root, marked as a job's) and the CLI's `/agents` picker, `/agent stop|close ` and `/agent `'s view (`cli/agent_view.py`: a line typed there is the instance's next run or a steer of the run that works, Ctrl+C the user's stop, `/back` the root's notice); on ADK a follow-up continues the instance's child session, the calls an earlier run left open answered first (`left_open_by`, from the instance's record), on Deep Agents the instance's own checkpointer thread (`instance_run_config`: its input the message and the caller's mark, the shared keys it changed compared with the thread's state as the run started). Each sub-agent type runs on its own runner (`App(name=child_app(app_name))`, the type's agent its root, `_agent_plugin_chain`: the main chain configured for a sub-agent, no memory index, no summary, `RunControlPlugin` and `SubAgentOutcomePlugin`; every plugin's per-call state keyed by invocation) over the manager's session service, on a child session per instance (`child_session_id`: `/`, the conversation id's `%` and `/` percent-encoded; an inheriting instance's gets the conversation's events copied once, at its first run, `task_tool.inherited_events`), under an app no conversation list reads. On Deep Agents (`workflow/deepagents/task_tool.py::build_task_tool`) each type's graph is built on its own, and a run `astream`s it in its task with `var_child_runnable_config` cleared, so its chunks reach its own loop alone, never its parent's stream; an inheriting run's history is the parent's messages with Deep Agents' summary event applied (`SummarizationMiddleware._apply_event_to_messages`, private: `tests/workflow/deepagents/test_compact.py` pins it), and `ForeignReasoningMiddleware(kind, agent=...)` leaves out the reasoning of AI messages another agent wrote. A native ADK YAML app keeps transferring (chat-mode sub-agents); a task-mode agent in one is refused at validation, since ADK runs its delegation outside the tool pipeline and keeps the call open across turns. With `SubAgentPolicy(follow_ups=True)` every agent that can have sub-agents (`can_have_children`: its own, or types it may start at run time) also gets `message_agent`, `stop_agent` and `check_agents` beside `task` (`workflow/agents/follow_ups.py::call_follow_up_tool` over `Delegations.message`/`stop`/`check`; ADK's `FollowUpTool`, Deep Agents' `build_follow_up_tools`; an own tool of one of their names fails the build, a Deep Agents MCP tool of one is skipped): `message_agent` continues an idle instance, steers a running one (before its next step; a run already stopping or finished is waited for, then the message follows the instance up or is refused; one being closed is refused as closed at once) or, with `interrupt` (refused, nothing cancelled, when no follow-up could start; an agent's keeps the turn's run it checked for), replaces its run (the user's interrupt is the user's stop); `stop_agent` cancels a running run by its parent (the instance idle; only the user's stop makes one `stopped`) and, with `close`, closes it and its descendants; a message steered to a run and not in its transcript when it ends goes to the instance's next run (`RunControl.stored`/`unstored`: ADK counts one stored as its child-session append returns, Deep Agents once the model call after it holds it); a run that did not complete fully names its open tasks in its envelope (`open_tasks`); a run whose parent's run was stopped by its control ends `cancelled` by its parent, not `interrupted`. A skill whose frontmatter names a type (`agent: `, `tools/skills/agents.py`) starts a run of it when an agent loads it where the app lets a skill start an agent (`"skill"` in `spawn_sources`; otherwise the key is ignored, the skill loads as instructions and the build warns, `skill_agent_ignored`), on both backends (ADK: `adk/skill_tool.py::SkillLoadTool` in `load_skill`'s place; Deep Agents: `_SkillAnswers.load_skill`), when the type's `spawnable_by` holds `"skill"`, the skill has instructions and the loading run may start one (`may_spawn`): through `Delegations.start` (`started_by: skill:`, the loading run its parent, its task message the skill's body under its name, counted toward `max_runs_per_turn`), the call's result the envelope with `"skill"`, shown as a delegation; otherwise `{"success": false, "error": "The skill '' starts the agent '', which ."}`, no run, and a skill its agent's first run could not start is warned of as the agent is built (`skill_agent_not_startable`). - **Token usage**: every model call the framework makes is one `LLM_USAGE`, on both backends, side calls included (`generate_simple`: `summarize`'s, `purpose` `tool`; `on_session_end`'s, `memory_extraction`, outside any turn; an app's own, `side_call`, or what its caller names with `workflow/usage.py::side_call`), its counts normalized where it is made (`normalized_tokens`: `prompt_tokens` every input token, cache reads and writes included; `completion_tokens` every output token, thinking included; ADK's read by its model's provider kind, `adk_usage_event`/`adk_tokens`, since Gemini and ADK's Claude adapter keep the thinking apart from the candidates and OpenAI's count it inside, an agent of no known kind read as apart; Deep Agents' by LangChain's one convention, `langchain_tokens`; the raw log's usage records alike), and timed (`latency_ms`: on ADK from the request to the answer, `workflow/adk/call_clock.py`'s plugins marking the answer's `custom_metadata`; on Deep Agents by the turn's `RunCallback`, which marks the answer's `response_metadata["agentic_cli"]`, beside the outcome mark; a side call, a summary and the overflow retry around their own request; no adapter sends either mark). Each is recorded in its conversation's ledger (`UsageLedger`; `BaseWorkflowManager.usage`/`usage_of`, in memory for the manager's life: a backend switch's new manager starts afresh, as with `agent_runs`) where it is made, before `on_event` (the event processors, ADK's summarizer, as soon as its call answers, Deep Agents' `RunCallback`, `_report_side_call`), under the run it is made in and its conversation's turn while one runs (as the manager counts them, `/compact` and job notices included: not `SessionInfo.turns`; none in another conversation's turn or from a task its turn outlived, which `_report_side_call` reports to no one); a sub-agent run's `AGENT_RUN` end carries what it used, by model (`metadata["usage"]`, `RunRecord.usage`). The CLI's status bar sums the events it sees (the open conversation's total, on any backend); `/status` shows the ledger by agent. LangGraph (deprecated) records no ledger. - **Tool registration**: Use `@register_tool(category=..., capabilities=..., description=...)` decorator. `capabilities=` is required — pass `EXEMPT` for tools that need no permission check or a list of `Capability(name, target_arg=...)` tuples the engine matches against rules. Tools are auto-discovered via the global `ToolRegistry`. A tool in `AgentConfig.tools` that the registry did not issue is denied at every call; building the agents names it once (`tool_not_registered`, per agent and tool: `BaseWorkflowManager._name_unregistered`): a plain callable, a `FunctionTool`/`StructuredTool` judged by the function it runs (as the gates unwrap it), an app's own tool class; ADK's own tool objects excepted (a built-in runs inside the model). `outside_content=True` (or a function of the call's arguments) declares that a call brings content from outside the user and the project into the conversation (a page, a document, a program's output): once the gate allows one, a memory write in that conversation is approved per call (see Permissions); an application's tools are unmarked unless they declare it, and a variant must declare the same flag as its tool. - **Async tools never block the event loop**: a synchronous tool runs on a worker thread on both backends; an async tool runs on the event loop itself, where a blocking call (DNS, a connect, a file lock's wait, a sleep, a subprocess wait, PDF parsing, page conversion, embedding) freezes the whole app, Ctrl+C included. An async tool runs its slow work with `asyncio.to_thread`. `tests/tools/test_async_tools_never_block.py` lists every async tool (the registry's, the factories' service-bound variants, Deep Agents' skill tools), so a new one fails until it is listed, and calls each through the loop guard (`tests/loop_guard.py`). @@ -266,7 +266,7 @@ Workflow: - **Manager detection**: tools declare their own service needs — `@register_tool(..., requires="knowledge_base")` (or a tuple for several) — and the key is validated against `service_registry.KNOWN_SERVICE_KEYS` at registration (only *constructible* services are declarable). `BaseWorkflowManager._detect_required_managers()` reads that metadata off the registry for each agent's tools (by registry identity, so `register(func, name=...)`'s original callable still declares its services); `_build_services()` then lazily constructs only the services actually needed, into a local dict that is released in full if a later constructor raises (nothing is published, so nothing else could close it). Each framework service is one row of `workflow/services.py::SERVICES` (`ServiceSpec`: how it is built, how it is closed, the tools it gives, whether a tool may declare it, how its references to its owner move), and `KNOWN_SERVICE_KEYS` and the closers are read from that table. A downstream tool may request any framework-provided service without editing the framework; there is no mechanism for registering new service *types* (a backend that builds one of its own overrides `_build_services_into`, `_get_service_tool_map` and `_SYNC_SERVICE_CLOSERS`). - **Canonical tool names + permission identity**: `ToolDefinition.name` is the single identity. `register_tool(name="public_name")` wraps the callable so `func.__name__` is the registered name (backends derive the model-visible name from the callable). Permission gating **and tool assembly** resolve through a **registry-owned identity binding**: each `ToolRegistry` owns a `id(obj) → (weakref, definition)` map (`registry.bind_identity()`/`identify()`; the module-level `tools.registry.bind_tool_identity()`/`identify_tool()` answer for `get_registry()`). Every hit is confirmed with `is` against the weak reference, so neither a name, a class name, nor a forged `__eq__`/`__hash__` can stand in for it, and a recycled address inherits nothing. Identity is **per registry** — a tool registered into an application's own `ToolRegistry` is not one of the framework's, so it stays untouched during assembly and is denied at permission time — which is also what lets a short-lived registry, its definitions and their closures be garbage collected. Everything the framework issues is bound at its construction site: registered callables, factory service-bound variants, renamed wrappers, and the native ADK tool objects the framework builds (skill tools, in `tools/skills/toolset.py`; the delegation tool, `workflow/adk/task_tool.py::TaskTool`, bound to the exempt `task` declaration (`tools/_core/delegation.py`) as it is made, an exact `TaskTool` only). An application's `AgentTool`, a `TaskTool` subclass or a same-named look-alike stays unbound and is denied; `tests/workflow/test_adk_delegation.py` pins each, and contract tests pin what of ADK's `BaseTool` it relies on. `workflow/adk/permission_plugin.py` unwraps `.func` only for the exact ADK types whose contract is to call it (`FunctionTool`, `LongRunningFunctionTool`, and ADK's own `TransferToAgentTool`), and gates genuine `McpTool` instances (`isinstance`, since ADK creates them on connect) under a synthetic `mcp` capability. `TransferToAgentTool` is a `FunctionTool` **subclass** ADK auto-injects into an agent that can transfer (a native ADK YAML app's: config-built agents delegate instead); matching only exact `FunctionTool` denied the built-in routing tool as unregistered, so delegation could not work at all. It is trusted on exactly the same terms as the others — ADK constructs it as `super().__init__(func=transfer_to_agent)` and overrides only `_get_declaration()` (to add the agent-name enum), never `run_async`, so what it invokes is still exactly `self.func`. Listing the **exact class** keeps every other subclass, forged object and same-named tool denied; no name authority is restored. Deep Agents' `PermissionMiddleware` follows the same rules: bound objects first, then `.coroutine`/`.func` of an **exact** `StructuredTool` only (`workflow/deepagents/tools.py::to_langchain_tools` builds one whose `.func`/`.coroutine` *is* the registered callable, and hides a `tool_context` parameter, passing `None`, so an ADK-style tool loads unchanged). The objects it builds or receives are bound where they are made: the `task` tool `build_task_tool` makes (`workflow/deepagents/task_tool.py`), to the `task` declaration (`tools/_core/delegation.py`), as it is made; the LangChain skill tools (`tools/skills/langchain_tools.py`), to the definitions `tools/skills/permissions.py` registers for ADK's, so ADK and Deep Agents gate them alike; and each MCP tool, in the manager's own map (`mcp_tools.MCPSessions.identify`, consulted before the registry, never the registry itself), to a synthetic definition under the `mcp` capability with the tool's (prefixed) name as the target. Anything unbound is denied — and, in assembly (service detection, service-tool substitution, canonicalization, long-running wrapping), left exactly as the application supplied it: a plain callable named `kb_search` is not the framework's tool and must not be given its services, its service-bound variant, or its long-running contract. Substitution additionally requires the service variant to *be* that same definition (`identify_tool(variant) is definition`); factories bind each closure to the exact module-level tool it re-binds, so a tool an application has taken over keeps its own implementation. - **One name, one tool**: `ToolRegistry.register()` raises on any name that is already registered — matching capabilities are *not* grounds for sharing one, since they say nothing about the docstring or the model-visible schema. Sharing is declared, never inferred: `declare_tool(name, ...)` (exported from `agentic_cli.tools`) declares a tool that has **no backend-neutral implementation** (`ToolDefinition.func is None`), and each backend registers its own with `register_tool(..., variant_of=name)` — same identity and permission contract, its own signature and docstring. Re-declaring the same contract is idempotent; changing its description or capabilities raises. `definition.variants` is ordered by defining module, so it never depends on import order, and assembly substitutes a variant's canonical callable via `registry.canonical_for()` (never `None`). A `replace=True` retires the previous definition's callables, and retired backend variants are excluded from `include_state_tools` injection, so the model never sees two tools with one name. That is how the ADK and LangGraph `save_plan`/`get_plan`/`save_tasks`/`get_tasks` coexist (declared in `tools/_core/state_tools.py`); previously they contested the name and import order decided the winner. The framework's delegation tool `task` is declared the same way (`tools/_core/delegation.py`, at `agentic_cli.tools` import, before any application tool registers), so an application's `register_tool(name="task")` raises on every backend, and a coordinator whose own tools include one named `task` (on both backends), or a Deep Agents agent with skills whose own tools use a skill tool's name, fails to build with `AgentGraphError`. A bare-name reference to a declared-only tool raises "ambiguous" rather than guessing a backend. `replace=True` takes a name over deliberately and **retires the old definition's identities**, so its callables resolve to nothing (denied, and left alone by assembly) rather than inheriting the replacement's capabilities. The parent's tools `message_agent`, `stop_agent` and `check_agents` are declared the same way (`declare_follow_up_tools`, `FOLLOW_UP_TOOLS`), so an application tool of one of their names raises. -- **Turn/lifecycle concurrency**: a manager runs one turn at a time — `process()`/`resume_with_job_result()`, `compact()` (`/compact`), `run_instance()` (the user's follow-up of a sub-agent) and `tell_root()`, enter through `_turn()` (the base's: the conversation named in the log context, then `_turn_admission()`, which holds `_turn_lock`, then `_workflow_context()`; job resume, `can_resume` and `compact` are the base's templates over the backend's hooks), and `reinitialize`/`cleanup` (the base's, for ADK and Deep Agents: a backend implements only the release's hooks) hold `_lifecycle_lock` **and** `_turn_lock` (`initialize_services` only `_lifecycle_lock`). Lock order is lifecycle → turn; a turn initializes *before* taking the turn lock, which is what keeps the two from deadlocking — and because of that a cleanup can land in between, so admission re-checks `_backend_ready()` while holding the turn lock and reinitializes once (or fails cleanly) rather than running against released resources. Initialization is transactional: services are built on a worker thread into a *local* dict and published only while the attempt still owns init (a cancelled attempt releases what the thread went on to build), and a failed attempt rolls back. A failed in-place reinitialization leaves the manager uninitialized; the controller reports `FAILED` and refuses to hand it out, but **keeps** it so a retry can revive it with its preserved (possibly in-memory) sessions intact. `WorkflowController` serializes init/reinitialize/swap/close on its own lifecycle lock, and a background init that finishes after `close()` releases its manager instead of publishing it. +- **Turn/lifecycle concurrency**: a manager runs one turn at a time — `process()`/`resume_with_job_result()`, `compact()` (`/compact`), `run_instance()` (the user's follow-up of a sub-agent), `start_instance()` (the user's new one) and `tell_root()`, enter through `_turn()` (the base's: the conversation named in the log context, then `_turn_admission()`, which holds `_turn_lock`, then `_workflow_context()`; job resume, `can_resume` and `compact` are the base's templates over the backend's hooks), and `reinitialize`/`cleanup` (the base's, for ADK and Deep Agents: a backend implements only the release's hooks) hold `_lifecycle_lock` **and** `_turn_lock` (`initialize_services` only `_lifecycle_lock`). Lock order is lifecycle → turn; a turn initializes *before* taking the turn lock, which is what keeps the two from deadlocking — and because of that a cleanup can land in between, so admission re-checks `_backend_ready()` while holding the turn lock and reinitializes once (or fails cleanly) rather than running against released resources. Initialization is transactional: services are built on a worker thread into a *local* dict and published only while the attempt still owns init (a cancelled attempt releases what the thread went on to build), and a failed attempt rolls back. A failed in-place reinitialization leaves the manager uninitialized; the controller reports `FAILED` and refuses to hand it out, but **keeps** it so a retry can revive it with its preserved (possibly in-memory) sessions intact. `WorkflowController` serializes init/reinitialize/swap/close on its own lifecycle lock, and a background init that finishes after `close()` releases its manager instead of publishing it. - **HITL callback is context-local**: `set_input_callback()` stores into a per-manager `ContextVar`, so a second consumer installing its callback cannot capture a running turn's prompt, and one consumer's `clear_input_callback()` cannot unregister another's. `MessageProcessor` cancels and awaits its consumer task **before** clearing the callback, so no tool is left asking a question nobody owns. And the callback answers only inside its turn: a task a turn started (`asyncio.create_task` copies the context, the callback with it) that asks after the turn ended gets `UserInputUnavailable` (`request_user_input`; the turn's span, `workflow/sessions.py::open_turn_scope`/`close_turn_scope`, opened and closed by `_workflow_context`, which the copy carries), as with no approver: a question goes unanswered and a permission ASK is denied by the engine's no-approver rule. - **Code that may run on the host is approved per call**: CPython has no in-process sandbox, so `execute_python` runs inside the OS sandbox or not at all by default (`os_sandbox_strict` true: no backend, a failed wrap, or a sandbox tool that fails as it starts (the runner's first stderr line, `_STARTED_MARKER`, never came) is a refusal that keeps its cause and ends with `executor.how_to_run`: sandbox-exec, bwrap and Ubuntu 24.04's user namespaces, none on Windows, and the opt-out where it lives, `exec_policy.sandbox_opt_out`: `~/.{app_name}/settings.json` or the env variable, since the project file and `/settings` cannot set it), and the module set is chosen from the path a call takes (`executor.py::_choose_run`, then `validate_code(allowed_modules=)`). The engine never imports `tools/`: `BaseWorkflowManager` passes `PermissionEngine(uncontained=tools.exec_policy.uncontained_exec_capabilities)`, called with the settings at each check (a settings change applies at once). For a capability it names, `engine.unstorable_reason` is `UNCONTAINED` (the one decision, shared with the prompt: only "Allow once" and "Deny", with its note), and `_evaluate` skips allow rules from grants (`SESSION`, and `PROJECT`, the user's `project_grants.json`), so a grant from when the code ran contained approves nothing; a `USER` rule still applies. A prompt for `*.exec` shows all of the code (the dialog body scrolls). - **No harness-level turn replay**: ADK persists a turn's input during invocation setup, and Deep Agents' checkpointer at the turn's first step, so the CLI never re-invokes an event source. Retries belong to the provider client (`HttpRetryOptions`). `MessageProcessor` returns a typed `TurnResult`. A turn that fails yields one `ERROR` and returns, on both backends (the base `process()`'s contract; `WorkflowEvent.turn_failed`: the error's text, `rate_limited`, `error_type`); an `ERROR` the turn already yielded that is not recoverable is its one; a cancel still raises, and a turn that cannot start (initialization, admission, or its conversation cannot be read) raises before any event. The CLI says a rate limit from the event as it does from a manager that raises. diff --git a/README.md b/README.md index b253f70f..a7cd2aa1 100644 --- a/README.md +++ b/README.md @@ -1535,12 +1535,18 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", conversation is opened, after a summary and after `/compact`. - **The user's control.** `/agents` picks a sub-agent and opens its view, as `/agent ` does (next bullet); + `/agent new ` starts a new one of a type the app lets you + start (its `spawnable_by` and the policy's `spawn_sources` both name + `"user"`): its parent is the main agent, its brief the objective (the rest + of the line), and its view opens on its first run, which streams there; `/agent stop ` (its run cancelled by you, `cancelled_by: user`; it is then `stopped`: its parent's messages are refused, only you can start its next run) and `/agent close ` (it and its own sub-agents). The manager's entry points (provisional, on the open conversation, any of its sub-agents): `run_instance(id, message)` (a turn of its own, counted toward no turn's runs; stopping the stream is your stop of the run), + `start_instance(type, objective)` (your new sub-agent's first run, a turn of + its own as `run_instance`'s, its run's start first), `interrupt_instance(id)` (that run ends `interrupted`, as at a process exit, not your stop), `stop_instance(id)`, `close_instance(id)`, `steer_instance(id, message)`, @@ -2406,7 +2412,7 @@ Built-in slash commands available in all apps: | `/sandbox` | `/sb` | List / reset stateful sandbox sessions | | `/jobs` | | List and manage long-running background jobs (`/jobs all`, `/jobs `, `/jobs cancel `, `/jobs clean`; `/jobs resume` tells the agent this conversation's finished jobs) | | `/agents` | | Pick one of this conversation's sub-agents, each under the one that started it: id, type, status (`running`, `idle`, `stopped`, `closed`), title; Enter opens its view (`/agents ` shows one instance or run, each run's status and time, the first lines of its result, its error and its tokens by model) | -| `/agent` | | One sub-agent: `/agent ` opens its view (a line typed there is its next run, or steers the run that works; `/back` returns), `/agent stop ` stops it (its run, if one works; only you can start its next run), `/agent close ` closes it and its own sub-agents (no more runs; its work stays readable) | +| `/agent` | | One sub-agent: `/agent ` opens its view (a line typed there is its next run, or steers the run that works; `/back` returns), `/agent new ` starts a new one of a type the app lets you start and opens its view on its first run, `/agent stop ` stops it (its run, if one works; only you can start its next run), `/agent close ` closes it and its own sub-agents (no more runs; its work stays readable) | | `/papers` | `/docs` | List knowledge-base documents (filter by source, query, --global) | | `/sessions` | `/sess` | List the saved sessions of every installed backend: backend, title, turns, last update (delete one with `--delete=`; `--backend=` picks one of an id two backends keep); on the memory store it says none are kept | | `/back` | | Leave a sub-agent's view, back to the main conversation; the main agent is told what you did there | From b2b17ae5a3eabe70b81534ba184f3a2ec2cd9675 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:07:30 -0500 Subject: [PATCH 09/12] Sub-agents: a stop before a start never enters the run; a start stores its conversation until_started awaits one future, resolved by the report of the run's start or the end of its work, so a stop before the start cancels the run before its hook is entered. start_instance stores a conversation that is not yet (ADK: the session with one state-only event, Deep Agents: an index row, titled from the objective, no turns), so /resume, --continue and --resume reach a conversation whose only work is a start. The processors' shared body is one helper (_user_turn). The docs say the main agent continues the user's instance only with the follow-up tools. --- CHANGELOG.md | 7 +- CLAUDE.md | 4 +- src/agentic_cli/cli/message_processor.py | 116 +++++++++--------- src/agentic_cli/workflow/adk/manager.py | 5 + src/agentic_cli/workflow/adk/sessions.py | 28 +++++ src/agentic_cli/workflow/base_manager.py | 51 ++++++-- .../workflow/deepagents/manager.py | 5 + .../workflow/deepagents/sessions.py | 28 ++++- tests/cli/console_app.py | 1 + tests/cli/test_agent_view.py | 13 ++ tests/cli/test_console_turns.py | 10 ++ tests/test_message_processor_render.py | 10 +- tests/workflow/test_subagents_contract.py | 69 +++++++++++ 13 files changed, 270 insertions(+), 77 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a347e28..a5a38372 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -590,8 +590,11 @@ the start of the entry's title. `cancelled`, the sub-agent `stopped`; one pressed before the run started stops it as it starts, and no view opens), `/back` tells the main agent once, and, being the main agent's sub-agent, the main agent's - `message_agent` may continue it. In another sub-agent's view it leaves that - one first. A type you cannot start opens nothing ("You cannot start + `message_agent` may continue it (when the main agent has the follow-up + tools: `follow_ups`, and a sub-agent it may start or a type agents may + start). A conversation whose only work is a start is stored, titled with + the objective, so `/resume`, `--continue` and `--resume` reach it. In + another sub-agent's view it leaves that one first. A type you cannot start opens nothing ("You cannot start 'writer' here. Types you can start: researcher."; "This app lets you start no agent types." when there is none), and a missing type or objective says `Usage: /agent new `. The manager's entry point diff --git a/CLAUDE.md b/CLAUDE.md index 21c4647f..5623a846 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,7 +51,7 @@ agentic-cli/ │ │ ├── waiting_jobs.py # Which finished jobs wait to be told in the open conversation: one rule (JobRecord.awaiting_resume, then its own, no conversation's, or a gone conversation's: can_resume, then the other installed backends' readers, opens_anywhere: one another backend keeps is not gone, its job waits for it) for the deliveries, ↻N and the startup line │ │ └── usage_tracker.py # Token usage / status bar: ctx = the main agent's last prompt over its context_trigger (a call with a purpose, a sub-agent's, a summary's or a side call's, never moves it); the token segment the open conversation's total, every call of its turns; format_usage: /status's rows by agent and /agents 's tokens by model │ ├── workflow/ -│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none), and _agent_tool_names, what a task call's tools may name (the agent's own tools by the names its model sees, KEPT_TOOLS left out; the base's: its configured tools; ADK and Deep Agents add MCP and skill tools; ADK raises delegate.ToolsUnlistedError for a toolset it could not list, which Delegations answers TOOLS_UNLISTED_ERROR); _run_models: a run's maps of each agent's model and numbers, its type's its model choice's when it runs on one; the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), start_instance (a turn: Delegations.start_by_user, the user's new instance, parent root, depth 1, started_by user, counted toward no turn's runs; a type the user may not start or a blank objective one ERROR; an inheriting type's copy of the conversation from _inherited_history, the backend's hook: ADK's session's root-visible events, Deep Agents' root messages, summary applied; its first event the run's start), both streamed by _users_run (the run in a task of its own; _UsersRunEvents notes the run as its start is reported, so a stop before the consumer read it, or before the run started, stops it by the user as it starts), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', each config's model_choices as its model would be, with its model_settings, into _choice_models by (agent, choice), choice_models, then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built, and _compute_choice_budgets (each model choice's, context_budget(agent, model=choice)): each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) +│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none), and _agent_tool_names, what a task call's tools may name (the agent's own tools by the names its model sees, KEPT_TOOLS left out; the base's: its configured tools; ADK and Deep Agents add MCP and skill tools; ADK raises delegate.ToolsUnlistedError for a toolset it could not list, which Delegations answers TOOLS_UNLISTED_ERROR); _run_models: a run's maps of each agent's model and numbers, its type's its model choice's when it runs on one; the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), start_instance (a turn: Delegations.start_by_user, the user's new instance, parent root, depth 1, started_by user, counted toward no turn's runs; a type the user may not start or a blank objective one ERROR; a conversation not yet stored stored first, _keep_conversation: ADK's session with one state-only event, Deep Agents' index row, titled from the objective with no turns; an inheriting type's copy of the conversation from _inherited_history, the backend's hook: ADK's session's root-visible events, Deep Agents' root messages, summary applied; its first event the run's start), both streamed by _users_run (the run in a task of its own; _UsersRunEvents notes the run as its start is reported and until_started awaits that one future, so a stop before the consumer read it, or before the run started, stops it by the user as it starts, before its hook is entered), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', each config's model_choices as its model would be, with its model_settings, into _choice_models by (agent, choice), choice_models, then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built, and _compute_choice_budgets (each model choice's, context_budget(agent, model=choice)): each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) │ │ ├── factory.py # create_workflow_manager_from_settings (_BACKENDS: orchestrator → "module:Class" + extra, imported when chosen; orchestrator=: another backend than the settings'; session_store=: the store a manager is built for, BaseWorkflowManager.session_store, the settings' by default; subagents=: the SubAgentPolicy the manager gets, checked before a backend is imported); orchestrator_of; check_backend (an unknown name, a missing extra) │ │ ├── session_readers.py # SessionReader: a backend's stored conversations read without its manager (list/info/exists/delete/aclose, rows naming the backend; delete deletes what the manager's does, ADK's sub-agent transcripts and records with the conversation), opened from the settings and a store (open_session_reader: the backend's own session code, adk/sessions.py::open_sessions and deepagents/sessions.py::open_sessions, imported on a worker thread; no agents, models or services; a sqlite store not made yet reads empty and is not made, Deep Agents not even imported for it; a database without its backend's tables, looked at read-only, reads empty, nothing written to it: no table, no journal mode); none for the memory store or LangGraph; ImportError (the install hint) for a missing extra; reader_backends │ │ ├── service_registry.py # get_service/require_service + ContextVar registry; the registry keys and KNOWN_SERVICE_KEYS, read from services.py's table @@ -256,7 +256,7 @@ Workflow: - **Tool error handling**: All tools return `{"success": bool, ...}` dicts. Never raise `ToolError`. An exception that still escapes a tool is a bug, but it costs one call rather than the turn: on ADK, `workflow/adk/tool_error_plugin.py::ToolErrorPlugin` turns it into an error dict; on Deep Agents, `workflow/deepagents/middleware.py::ToolCallErrorMiddleware`, inside the permission gate, gives the same result, `{"success": false, "error": " failed: : "}` cut to 500 characters (both use `workflow/tool_errors.py`). A call to a tool name the agent does not have gets ADK's own text, its first two lines (`unknown_tool_result`: "nope failed: ValueError: Tool 'nope' not found." and the agent's tools by name), logged `tool_not_found` at info (the model's mistake): on ADK the permission gate lets ADK's stand-in through (`is_unknown_tool`: a bare `BaseTool` described "Tool not found", which runs nothing; contract-tested) and `ToolErrorPlugin` answers its lookup error; on Deep Agents the gate answers it. It catches `Exception`, never `BaseException`, so cancelling still cancels (google-adk 2.15 hands a cancelled call's `CancelledError` to `ToolErrorPlugin` for cleanup, ignoring the answer: it answers nothing and logs `tool_cancelled` at debug, no warning). `task` raises nothing into it: a sub-agent's model or run failing (its summary or overflow included: its own tools' errors are results already) fails the run, whose envelope its parent reads (`error`: the provider's reason; on ADK out of ADK's plugin wrapper), reported at once through the turn's live events as one recoverable `ERROR`, ` failed: `, the run's: the coordinator carries on. A sub-agent's overflow (still too long after its summary or trim) fails its run, on both backends, in the words of ADK's overflow handler, `: the request no longer fits 's context window.` with `error_code` `CONTEXT_OVERFLOW` (`context.py::subagent_overflow_message`): ADK's `OverflowPlugin` answers the run's model call with it, Deep Agents' manager raises it (`RunFailed`). A refusal is no exception here (the framework adds no `ModelRefusalMiddleware`): a sub-agent whose final answer a model refused ends its run `refused`, and its parent reads, as its envelope's result, Deep Agents 0.7.34's notice ("The subagent stopped because a model refused the request. … Retrying the same request is unlikely to succeed; rephrase it or continue without it."), on both backends and whichever deepagents the pin installs (0.7.28 has no notice of its own; 0.7.34+ finds no refusal block left to word again); an answer cut at the output limit keeps its text, followed by `[cut off at the output limit]`, and its run ends `completed` and `partial`, with one recoverable warning ("'s answer was cut off at the output limit"); the answer's thoughts or reasoning are kept. ADK's `SubAgentOutcomePlugin` and Deep Agents' `SubAgentOutcomeMiddleware` rewrite and mark the answer, by `workflow/agents/outcome.py`. On ADK the plugin reads the answer's `finish_reason` (Claude's `refusal` and a Chat Completions `content_filter` arrive as `SAFETY`, `max_tokens` and `length` as `MAX_TOKENS`, Gemini's as themselves), the `error_code` ADK sets on an answer with no content (a Gemini prompt's `block_reason`), the `reason` an `OTHER` stop names in its JSON error message (ADK's OpenAI Responses adapter's `incomplete_details`, `content_filter` among them) and a text part `OpenAI refusal: ` (that adapter's refusal, and `OpenAICompatibleLlm`'s of a Chat Completions `refusal`, which ADK's class drops). On Deep Agents the middleware reads `response_metadata`'s `stop_reason` (ChatAnthropic), `finish_reason` (ChatOpenAI, ChatGoogleGenerativeAI), `incomplete_details.reason` (the Responses API) and `prompt_feedback.block_reason` (a Gemini prompt block), and a refusal the answer holds (a refusal block, standard or `non_standard`, or `additional_kwargs["refusal"]`). The root's own answers reach the user as their model gave them: on ADK a root's refusal with no answer (Claude's, Gemini's) is still the turn's one `ERROR` (" returned no answer"), and a root on OpenRouter or an OpenAI-compatible server replies "OpenAI refusal: ". On both backends the root's own failure leaves the run: the turn's one `ERROR`. A gate or error result goes back as the call's `ToolMessage` with `status="error"`. LangGraph's `ToolNode` runs with `handle_tool_errors=True`. - **Tool result cap**: every tool result passes `workflow/tool_output.py::cap_tool_result` (registered, MCP and skill tools, `job_result`, a delegation's envelope on either backend, and the envelope a view's notice carries: `BaseWorkflowManager._user_ran` keeps `instance_result` capped): one over `tool_result_max_chars` is cut to its shape and as much of its head and tail as fits (the kept length is bisected, since JSON escapes vary), with a note (under `truncated`, or appended to a string) pointing at its full output in `./.{app_name}/tool-output/`, written for `read_file` to page by lines (lines over 2,000 characters split). A string that holds a JSON object (`json_object`: a delegation's envelope, which both task tools write unescaped, `ensure_ascii=False`; a framework tool's dict in a Deep Agents `ToolMessage`) is cut as that dict and given back as its JSON text, so the parent reads JSON still, on both backends. On ADK, `workflow/adk/tool_result_cap_plugin.py::ToolResultCapPlugin` is registered after `InterruptedCallsPlugin`, since ADK stops at the first `after_tool_callback` that returns a value, and it leaves out an agent with `after_tool_callback`s of its own (a native YAML app's, `build.own_after_tool_agents`), which ADK would skip once the cap answered. ADK's Claude and OpenAI Responses adapters send only a result's `content`, else its `result`, so the plugin also puts the note there (`_note_where_sent`). On Deep Agents, `ToolResultCapMiddleware` sits between the permission gate and `ToolCallErrorMiddleware`, so an error result is capped too, and reads a `ToolMessage` (its text cut by the cap's string rule, text blocks joined into the first) and each `ToolMessage` of a `Command`. A call of the framework's `read_file` (by identity, as each gate resolves tools) on a saved output is cut without a second save. Saving never fails the call (`tool_output_not_saved` warns once per folder, then debug), and a cap that raises leaves the result uncut (`tool_result_cap_failed` at warning, its traceback at debug). - **Summarizing on ADK (main agent only)**: every app's App (a native ADK YAML app's too, when its root's model has a context budget) has ADK's `EventsCompactionConfig` with `workflow/adk/compaction.py::AgentCliSummarizer` at the root's trigger (`context_budget`, as on Deep Agents); ADK checks before every agent's model call, and `MainAgentPlugin` (the first plugin) records the running agent in a ContextVar, so the summarizer writes only for the root (a sub-agent's run, on its type's runner, has no compaction config at all: a sub-agent compacting the shared session lost its brief and looped, 100 requests in one turn, offline). The summarizer picks its own range before paying for anything (`summary_range`: the newest `keep` tokens and the current turn kept, a cut only where a user turn starts, never parting a call from its result, long-running calls excepted since ADK re-injects them, nor leaving a kept event stamped inside the range; none for a saving under 20% of the trigger, the seed left out of it), writes on the root's own model (`_simple_model(SUMMARY_MAX_TOKENS, agent=root)`, thinking off) with `workflow/summary_prompt.py`, the rendering sized to that model's window (the middle cut, `MIDDLE_OMITTED`, the seed kept whole), and returns **user-role** text starting `SUMMARY_PREFIX` (a model-role first message is one Claude refuses), which the fit guard folds, after the memory index and the roster when the request has them, into the next user text (`fold_summary`), so no request holds two user messages in a row. `last_kept_turns` and `last_error` are for its callers: a manual summarizer warns of nothing itself. It reports through the turn's live events (`_run_and_stream` iterates the runner through `live_events.merged` under `reporting(live)`); any failure is one recoverable `ERROR` a turn, never raised to ADK. `NoAfterTurnCompactionRunner` overrides ADK's private `Runner._run_post_invocation_compaction` (contract-tested), so the prompt never waits for a summary after the answer. `FitGuardPlugin` is the last plugin (but `SentRequestLoggingPlugin`, which logs a request as sent, and `CallSentPlugin`, which starts the call's clock) and `OverflowPlugin` the one before it (`MemoryIndexPlugin`, when the root has a memory tool and `memory_index_enabled` is on, the one before that: it puts the conversation's memory index snapshot first in the root's requests, never in the session): the guard leaves a request's oldest turns out when it is over its agent's budget (keeping the newest turn and what opens the conversation, the memory index, the roster of the root's open sub-agents (`RosterPlugin`, before `MemoryIndexPlugin`, for a root with `message_agent`), then a summary: `protected_head`; in a sub-agent type's chain also the run's task message and its instance's brief, `brief_of`) and keeps each request as it came in (`request_as_seen`: one copy per model call, under the call's `EventActions`, which ADK passes to all three of its callbacks: each sub-agent run is an invocation of its own on a child session, but two runs of one type share that type's runner and its plugins, and a run drops only what its own cancelled calls left, as it ends), and the overflow handler, on a provider's overflow, summarizes now (the root, through `compact_session`, ADK's private `_run_compaction_for_token_threshold_config`; `_summarize_now` returns `WrittenSummary(text, kept_turns)`, and the retry is the index, the roster, the summary and those turns) or trims to half the budget (a sub-agent, or nothing to summarize), builds the retry from the guard's copy without the context cache, retries once on the agent's `canonical_model`, then answers the root with `LlmResponse(error_code="CONTEXT_OVERFLOW")`, never model text (ADK would store it as the reply), which `ADKEventProcessor` maps to the turn's `ERROR`; a retry that fails otherwise propagates, and `_run_and_stream` unwraps ADK's plugin-manager `RuntimeError` to the provider's error; a sub-agent's call that still does not fit is answered with an error response too, `CONTEXT_OVERFLOW` and `subagent_overflow_message`, which its run's processor keeps as the run's failure: the run ends `failed` with those words (`RunFailed`), its parent reads them in the envelope, and the user is warned once, by the framework's delegation (`agents/delegate.py`), as on Deep Agents. A native ADK YAML app gets all of it: only the building of its agents differs (`workflow/adk/build.py`). Its chat-mode sub-agents keep transferring, and an agent the root transfers to replies to the user (`build.reply_agents`: its text is the reply, recent_messages reads it, its overflow is the turn's clear error, its calls write the outside-content mark); the summary and the memory index stay the root's, so such an agent is trimmed by the fit guard, not summarized. An agent's own callbacks (a native app's) run after every plugin, and only when none answered: its before-model callbacks see the request after the fit guard, and the cap leaves out an agent with after-tool callbacks. A main agent whose model does not resolve through the catalog has no budget and no summary. -- **Sub-agents delegate and return**: on both backends a sub-agent run is a call of its parent's `task` tool (the framework's: `tools/_core/delegation.py` declares it, `workflow/agents/delegate.py` runs it) that returns in the same turn; only the root replies to the user (a sub-agent's `TEXT` carries `metadata["subagent"]`, and the CLI shows it as the events box's status line, under its run's name: `researcher-2 › …`; `/agents` picks among a conversation's instances), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the types the calling run may start, `Delegations.offered`: its own sub-agents, then, with `SubAgentPolicy.spawn_sources` holding `"agent"` and the run's depth below `max_spawn_depth`, the types whose `AgentConfig.spawnable_by` names `"agent"`, `workflow/agents/spawn.py`; a free type, in no `sub_agents` list, is never the root; `task` is offered for each run, ADK declaring it per request and Deep Agents rewriting a sub-agent's per model call, and a run offered nothing has none) and a brief (`workflow/agents/brief.py`: `title`, `objective`, `deliverable`, `constraints`, `known`, `done_when`), then `tools` (some of the type's own tools, `_agent_tool_names`: the run is offered only those and the tools every run keeps, `RunControl.keeps`, ADK's `RunControlPlugin` and Deep Agents' `RunControlMiddleware` filtering its requests and answering a call of another `unknown_tool_result`) and `model` (one of `AgentConfig.model_choices`, offered only when a type has some: the run is on the type's agent built on that choice at initialization, ADK a runner and Deep Agents a graph per (type, choice), resolved and budgeted with the rest, `_run_models`), its schema and description the same on both backends (`task_parameters`, `task_description`: a line per type with its description, "The agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both, through `Delegations.start` (a `StartRequest`, the one entry for a first run): it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents `, never written to the conversation. It ends as the `RunAnswer` says: its last text (a reply that also called a tool included; none at all, an empty result shown `No answer`), `refused` or `partial` by the outcome mark, `failed` for an error or a raise (one recoverable `ERROR`, ` failed: `, or the hook's own words, `RunFailed`: an overflow's; its result the text it wrote before it failed: a failed model call is the hook's `RunAnswer.error`, `failure_reason`, its warning's code `RunAnswer.error_code`, the error's type, and `RunFailed` carries `text=`); and the call's result is the run's envelope as JSON (`workflow/agents/envelope.py`), shown by `show_as_delegation`. A cancel of the caller's task stops the run's task first and ends the run `interrupted`. Each run works under its `RunControl` (`workflow/agents/control.py`, `AgentRun.control`), with its type's `AgentConfig.limits` over the policy's (`SubAgentPolicy.limits`, `DEFAULT_LIMITS`: 100 model calls): `Delegations.cancel(run_id, by=, error=)` cancels the run alone (its parent, the user or a limit), and the hook, seeing its own cancel (`own_cancel`), stops the run as a stopped turn's (ADK: its abort signal, its open calls sealed in its child session; Deep Agents: its stream closed) and returns what it has: the run ends `cancelled` with `cancelled_by` and that text, `partial`, while its siblings and the turn go on; the turn's own cancel still wins (`interrupted`). Past its `timeout` (counted from when its hook starts, `timing`) the run is cancelled by its limit (`time limit reached`); each model call is counted before it is made (`RunControlPlugin` in each sub-agent chain, `RunControlMiddleware` on each sub-agent's model side) and the last allowed one gets `STEP_LIMIT_NOTE` after its last message, its tools still declared (Claude refuses tool calls in a request that defines no tools); its answer's calls are dropped, never run, so the run completes `partial`, `step limit reached`; each call's tokens are counted after it, with what the run's other calls used (`RunControl(side_tokens=)`: its tools' side calls and its summaries, the ledger's rows of the run that are no agent step, `UsageLedger.by_purpose(run=)`), so the limit is the run's total as its usage record counts it, and past `max_tokens` an answer that makes tool calls is the run's last, its calls dropped, `cancelled` by its limit (`token limit reached`), while one that makes none ends the run as it would, `completed`, its result whole (a model that reports no usage counts none of its own). A turn starts at most `max_runs_per_turn` runs, at any depth (`sessions.runs_this_turn`): a call past it is the error result, no run started; `task`'s description says so (`limit_sentences`). At most `max_active` runs of a conversation work at once, at any depth (`workflow/agents/slots.py::SlotPool`, one per conversation, `Delegations.slots`; the root takes no slot): a run takes a slot right before its hook and its time limit start and gives it back at its end, however it ends; one that finds none waits `queued` (an `AGENT_RUN` and its record say so, then `running`), not counted against its `timeout`. A run lends its slot while it waits on its children (one lend for all it waits on at once; the child that ends last hands its slot straight back, so the tree in progress goes on ahead of the runs that have not started) or on the user (`waiting_on_user`: `input_required`, `queued` once answered while it waits for its slot back, then `running`, in `request_user_input` and in the permission engine from before its one-prompt lock until after it: a run waiting for a slot while holding the lock would hold every other run's prompt; a prompt no one can be shown, no input callback or its turn ended, lends nothing: `can_request_user_input`), so nested fan-out never deadlocks; a cancel, queued or lending, leaves no waiter in the heap and no slot taken. A message steered to a working run (`RunControl.steer`, through `Delegations.control(run)`) is added after its last message, as the user's, before its next model call, and stays in its transcript (ADK: appended to its child session, the run's later events stamped after it so a durable store reads them back in order; Deep Agents: added to its state); a sub-agent run's task message is never trimmed, on ADK neither by the fit guard nor by the overflow handler's retry, whatever was steered after it. A dialog whose run is stopped is withdrawn, the turn going on (`MessageProcessor`). `AgentConfig.inherit_context` sets what a run sees: False (the default) its task alone, True its parent's conversation too, read once as the run starts (the conversation after any summary; Deep Agents' less the message that called `task`, which ADK's copy keeps), before the task message, which then ends with `INHERITED_CONTEXT_NOTE` (whose conversation it reads, which message is its task); `validate_agent_graph` refuses a value that is not True or False, `inherit_context=True` on the root, on an agent with sub-agents and below another sub-agent. On ADK (`workflow/adk/task_tool.py::TaskTool`) every config-built agent is built on its own, with no ADK `sub_agents`, so ADK offers none `transfer_to_agent`, and gets ADK's identity line ("You are an agent. Your internal name is …"); a delegating agent has one `TaskTool`. A sub-agent is an instance that outlives its run: `idle` when the run ends, its next run a follow-up (`Delegations.follow_up`, through the same hook with `AgentRun.follow_up`, the message as written and no history), one run per instance at a time; a run's end leaves its instance `stopped` (once the user stopped it: its run cancelled by the user, or an idle one; only the user continues it), `closed` (`AgentConfig.continuable` False, or past `SubAgentPolicy.max_open`: the oldest idle one) or `idle`, `Delegations.close` closes an idle or stopped one and its descendants, and `AGENT_INSTANCE` carries a change without a run; the user controls any instance of the open conversation through the manager (`run_instance`: a follow-up as a turn of its own, its Ctrl+C the user's stop; `start_instance`: the user's new instance, `/agent new`, the same; `stop_instance`, `close_instance`, `steer_instance`; `tell_root`: a notice turn of the root, marked as a job's) and the CLI's `/agents` picker, `/agent stop|close ` and `/agent `'s view (`cli/agent_view.py`: a line typed there is the instance's next run or a steer of the run that works, Ctrl+C the user's stop, `/back` the root's notice); on ADK a follow-up continues the instance's child session, the calls an earlier run left open answered first (`left_open_by`, from the instance's record), on Deep Agents the instance's own checkpointer thread (`instance_run_config`: its input the message and the caller's mark, the shared keys it changed compared with the thread's state as the run started). Each sub-agent type runs on its own runner (`App(name=child_app(app_name))`, the type's agent its root, `_agent_plugin_chain`: the main chain configured for a sub-agent, no memory index, no summary, `RunControlPlugin` and `SubAgentOutcomePlugin`; every plugin's per-call state keyed by invocation) over the manager's session service, on a child session per instance (`child_session_id`: `/`, the conversation id's `%` and `/` percent-encoded; an inheriting instance's gets the conversation's events copied once, at its first run, `task_tool.inherited_events`), under an app no conversation list reads. On Deep Agents (`workflow/deepagents/task_tool.py::build_task_tool`) each type's graph is built on its own, and a run `astream`s it in its task with `var_child_runnable_config` cleared, so its chunks reach its own loop alone, never its parent's stream; an inheriting run's history is the parent's messages with Deep Agents' summary event applied (`SummarizationMiddleware._apply_event_to_messages`, private: `tests/workflow/deepagents/test_compact.py` pins it), and `ForeignReasoningMiddleware(kind, agent=...)` leaves out the reasoning of AI messages another agent wrote. A native ADK YAML app keeps transferring (chat-mode sub-agents); a task-mode agent in one is refused at validation, since ADK runs its delegation outside the tool pipeline and keeps the call open across turns. With `SubAgentPolicy(follow_ups=True)` every agent that can have sub-agents (`can_have_children`: its own, or types it may start at run time) also gets `message_agent`, `stop_agent` and `check_agents` beside `task` (`workflow/agents/follow_ups.py::call_follow_up_tool` over `Delegations.message`/`stop`/`check`; ADK's `FollowUpTool`, Deep Agents' `build_follow_up_tools`; an own tool of one of their names fails the build, a Deep Agents MCP tool of one is skipped): `message_agent` continues an idle instance, steers a running one (before its next step; a run already stopping or finished is waited for, then the message follows the instance up or is refused; one being closed is refused as closed at once) or, with `interrupt` (refused, nothing cancelled, when no follow-up could start; an agent's keeps the turn's run it checked for), replaces its run (the user's interrupt is the user's stop); `stop_agent` cancels a running run by its parent (the instance idle; only the user's stop makes one `stopped`) and, with `close`, closes it and its descendants; a message steered to a run and not in its transcript when it ends goes to the instance's next run (`RunControl.stored`/`unstored`: ADK counts one stored as its child-session append returns, Deep Agents once the model call after it holds it); a run that did not complete fully names its open tasks in its envelope (`open_tasks`); a run whose parent's run was stopped by its control ends `cancelled` by its parent, not `interrupted`. A skill whose frontmatter names a type (`agent: `, `tools/skills/agents.py`) starts a run of it when an agent loads it where the app lets a skill start an agent (`"skill"` in `spawn_sources`; otherwise the key is ignored, the skill loads as instructions and the build warns, `skill_agent_ignored`), on both backends (ADK: `adk/skill_tool.py::SkillLoadTool` in `load_skill`'s place; Deep Agents: `_SkillAnswers.load_skill`), when the type's `spawnable_by` holds `"skill"`, the skill has instructions and the loading run may start one (`may_spawn`): through `Delegations.start` (`started_by: skill:`, the loading run its parent, its task message the skill's body under its name, counted toward `max_runs_per_turn`), the call's result the envelope with `"skill"`, shown as a delegation; otherwise `{"success": false, "error": "The skill '' starts the agent '', which ."}`, no run, and a skill its agent's first run could not start is warned of as the agent is built (`skill_agent_not_startable`). +- **Sub-agents delegate and return**: on both backends a sub-agent run is a call of its parent's `task` tool (the framework's: `tools/_core/delegation.py` declares it, `workflow/agents/delegate.py` runs it) that returns in the same turn; only the root replies to the user (a sub-agent's `TEXT` carries `metadata["subagent"]`, and the CLI shows it as the events box's status line, under its run's name: `researcher-2 › …`; `/agents` picks among a conversation's instances), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the types the calling run may start, `Delegations.offered`: its own sub-agents, then, with `SubAgentPolicy.spawn_sources` holding `"agent"` and the run's depth below `max_spawn_depth`, the types whose `AgentConfig.spawnable_by` names `"agent"`, `workflow/agents/spawn.py`; a free type, in no `sub_agents` list, is never the root; `task` is offered for each run, ADK declaring it per request and Deep Agents rewriting a sub-agent's per model call, and a run offered nothing has none) and a brief (`workflow/agents/brief.py`: `title`, `objective`, `deliverable`, `constraints`, `known`, `done_when`), then `tools` (some of the type's own tools, `_agent_tool_names`: the run is offered only those and the tools every run keeps, `RunControl.keeps`, ADK's `RunControlPlugin` and Deep Agents' `RunControlMiddleware` filtering its requests and answering a call of another `unknown_tool_result`) and `model` (one of `AgentConfig.model_choices`, offered only when a type has some: the run is on the type's agent built on that choice at initialization, ADK a runner and Deep Agents a graph per (type, choice), resolved and budgeted with the rest, `_run_models`), its schema and description the same on both backends (`task_parameters`, `task_description`: a line per type with its description, "The agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both, through `Delegations.start` (a `StartRequest`, the one entry for a first run): it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents `, never written to the conversation. It ends as the `RunAnswer` says: its last text (a reply that also called a tool included; none at all, an empty result shown `No answer`), `refused` or `partial` by the outcome mark, `failed` for an error or a raise (one recoverable `ERROR`, ` failed: `, or the hook's own words, `RunFailed`: an overflow's; its result the text it wrote before it failed: a failed model call is the hook's `RunAnswer.error`, `failure_reason`, its warning's code `RunAnswer.error_code`, the error's type, and `RunFailed` carries `text=`); and the call's result is the run's envelope as JSON (`workflow/agents/envelope.py`), shown by `show_as_delegation`. A cancel of the caller's task stops the run's task first and ends the run `interrupted`. Each run works under its `RunControl` (`workflow/agents/control.py`, `AgentRun.control`), with its type's `AgentConfig.limits` over the policy's (`SubAgentPolicy.limits`, `DEFAULT_LIMITS`: 100 model calls): `Delegations.cancel(run_id, by=, error=)` cancels the run alone (its parent, the user or a limit), and the hook, seeing its own cancel (`own_cancel`), stops the run as a stopped turn's (ADK: its abort signal, its open calls sealed in its child session; Deep Agents: its stream closed) and returns what it has: the run ends `cancelled` with `cancelled_by` and that text, `partial`, while its siblings and the turn go on; the turn's own cancel still wins (`interrupted`). Past its `timeout` (counted from when its hook starts, `timing`) the run is cancelled by its limit (`time limit reached`); each model call is counted before it is made (`RunControlPlugin` in each sub-agent chain, `RunControlMiddleware` on each sub-agent's model side) and the last allowed one gets `STEP_LIMIT_NOTE` after its last message, its tools still declared (Claude refuses tool calls in a request that defines no tools); its answer's calls are dropped, never run, so the run completes `partial`, `step limit reached`; each call's tokens are counted after it, with what the run's other calls used (`RunControl(side_tokens=)`: its tools' side calls and its summaries, the ledger's rows of the run that are no agent step, `UsageLedger.by_purpose(run=)`), so the limit is the run's total as its usage record counts it, and past `max_tokens` an answer that makes tool calls is the run's last, its calls dropped, `cancelled` by its limit (`token limit reached`), while one that makes none ends the run as it would, `completed`, its result whole (a model that reports no usage counts none of its own). A turn starts at most `max_runs_per_turn` runs, at any depth (`sessions.runs_this_turn`): a call past it is the error result, no run started; `task`'s description says so (`limit_sentences`). At most `max_active` runs of a conversation work at once, at any depth (`workflow/agents/slots.py::SlotPool`, one per conversation, `Delegations.slots`; the root takes no slot): a run takes a slot right before its hook and its time limit start and gives it back at its end, however it ends; one that finds none waits `queued` (an `AGENT_RUN` and its record say so, then `running`), not counted against its `timeout`. A run lends its slot while it waits on its children (one lend for all it waits on at once; the child that ends last hands its slot straight back, so the tree in progress goes on ahead of the runs that have not started) or on the user (`waiting_on_user`: `input_required`, `queued` once answered while it waits for its slot back, then `running`, in `request_user_input` and in the permission engine from before its one-prompt lock until after it: a run waiting for a slot while holding the lock would hold every other run's prompt; a prompt no one can be shown, no input callback or its turn ended, lends nothing: `can_request_user_input`), so nested fan-out never deadlocks; a cancel, queued or lending, leaves no waiter in the heap and no slot taken. A message steered to a working run (`RunControl.steer`, through `Delegations.control(run)`) is added after its last message, as the user's, before its next model call, and stays in its transcript (ADK: appended to its child session, the run's later events stamped after it so a durable store reads them back in order; Deep Agents: added to its state); a sub-agent run's task message is never trimmed, on ADK neither by the fit guard nor by the overflow handler's retry, whatever was steered after it. A dialog whose run is stopped is withdrawn, the turn going on (`MessageProcessor`). `AgentConfig.inherit_context` sets what a run sees: False (the default) its task alone, True its parent's conversation too, read once as the run starts (the conversation after any summary; Deep Agents' less the message that called `task`, which ADK's copy keeps), before the task message, which then ends with `INHERITED_CONTEXT_NOTE` (whose conversation it reads, which message is its task); `validate_agent_graph` refuses a value that is not True or False, `inherit_context=True` on the root, on an agent with sub-agents and below another sub-agent. On ADK (`workflow/adk/task_tool.py::TaskTool`) every config-built agent is built on its own, with no ADK `sub_agents`, so ADK offers none `transfer_to_agent`, and gets ADK's identity line ("You are an agent. Your internal name is …"); a delegating agent has one `TaskTool`. A sub-agent is an instance that outlives its run: `idle` when the run ends, its next run a follow-up (`Delegations.follow_up`, through the same hook with `AgentRun.follow_up`, the message as written and no history), one run per instance at a time; a run's end leaves its instance `stopped` (once the user stopped it: its run cancelled by the user, or an idle one; only the user continues it), `closed` (`AgentConfig.continuable` False, or past `SubAgentPolicy.max_open`: the oldest idle one) or `idle`, `Delegations.close` closes an idle or stopped one and its descendants, and `AGENT_INSTANCE` carries a change without a run; the user controls any instance of the open conversation through the manager (`run_instance`: a follow-up as a turn of its own, its Ctrl+C the user's stop; `start_instance`: the user's new instance, `/agent new`, the same; `stop_instance`, `close_instance`, `steer_instance`; `tell_root`: a notice turn of the root, marked as a job's) and the CLI's `/agents` picker, `/agent stop|close `, `/agent new ` and `/agent `'s view (`cli/agent_view.py`: a line typed there is the instance's next run or a steer of the run that works, Ctrl+C the user's stop, `/back` the root's notice); on ADK a follow-up continues the instance's child session, the calls an earlier run left open answered first (`left_open_by`, from the instance's record), on Deep Agents the instance's own checkpointer thread (`instance_run_config`: its input the message and the caller's mark, the shared keys it changed compared with the thread's state as the run started). Each sub-agent type runs on its own runner (`App(name=child_app(app_name))`, the type's agent its root, `_agent_plugin_chain`: the main chain configured for a sub-agent, no memory index, no summary, `RunControlPlugin` and `SubAgentOutcomePlugin`; every plugin's per-call state keyed by invocation) over the manager's session service, on a child session per instance (`child_session_id`: `/`, the conversation id's `%` and `/` percent-encoded; an inheriting instance's gets the conversation's events copied once, at its first run, `task_tool.inherited_events`), under an app no conversation list reads. On Deep Agents (`workflow/deepagents/task_tool.py::build_task_tool`) each type's graph is built on its own, and a run `astream`s it in its task with `var_child_runnable_config` cleared, so its chunks reach its own loop alone, never its parent's stream; an inheriting run's history is the parent's messages with Deep Agents' summary event applied (`SummarizationMiddleware._apply_event_to_messages`, private: `tests/workflow/deepagents/test_compact.py` pins it), and `ForeignReasoningMiddleware(kind, agent=...)` leaves out the reasoning of AI messages another agent wrote. A native ADK YAML app keeps transferring (chat-mode sub-agents); a task-mode agent in one is refused at validation, since ADK runs its delegation outside the tool pipeline and keeps the call open across turns. With `SubAgentPolicy(follow_ups=True)` every agent that can have sub-agents (`can_have_children`: its own, or types it may start at run time) also gets `message_agent`, `stop_agent` and `check_agents` beside `task` (`workflow/agents/follow_ups.py::call_follow_up_tool` over `Delegations.message`/`stop`/`check`; ADK's `FollowUpTool`, Deep Agents' `build_follow_up_tools`; an own tool of one of their names fails the build, a Deep Agents MCP tool of one is skipped): `message_agent` continues an idle instance, steers a running one (before its next step; a run already stopping or finished is waited for, then the message follows the instance up or is refused; one being closed is refused as closed at once) or, with `interrupt` (refused, nothing cancelled, when no follow-up could start; an agent's keeps the turn's run it checked for), replaces its run (the user's interrupt is the user's stop); `stop_agent` cancels a running run by its parent (the instance idle; only the user's stop makes one `stopped`) and, with `close`, closes it and its descendants; a message steered to a run and not in its transcript when it ends goes to the instance's next run (`RunControl.stored`/`unstored`: ADK counts one stored as its child-session append returns, Deep Agents once the model call after it holds it); a run that did not complete fully names its open tasks in its envelope (`open_tasks`); a run whose parent's run was stopped by its control ends `cancelled` by its parent, not `interrupted`. A skill whose frontmatter names a type (`agent: `, `tools/skills/agents.py`) starts a run of it when an agent loads it where the app lets a skill start an agent (`"skill"` in `spawn_sources`; otherwise the key is ignored, the skill loads as instructions and the build warns, `skill_agent_ignored`), on both backends (ADK: `adk/skill_tool.py::SkillLoadTool` in `load_skill`'s place; Deep Agents: `_SkillAnswers.load_skill`), when the type's `spawnable_by` holds `"skill"`, the skill has instructions and the loading run may start one (`may_spawn`): through `Delegations.start` (`started_by: skill:`, the loading run its parent, its task message the skill's body under its name, counted toward `max_runs_per_turn`), the call's result the envelope with `"skill"`, shown as a delegation; otherwise `{"success": false, "error": "The skill '' starts the agent '', which ."}`, no run, and a skill its agent's first run could not start is warned of as the agent is built (`skill_agent_not_startable`). - **Token usage**: every model call the framework makes is one `LLM_USAGE`, on both backends, side calls included (`generate_simple`: `summarize`'s, `purpose` `tool`; `on_session_end`'s, `memory_extraction`, outside any turn; an app's own, `side_call`, or what its caller names with `workflow/usage.py::side_call`), its counts normalized where it is made (`normalized_tokens`: `prompt_tokens` every input token, cache reads and writes included; `completion_tokens` every output token, thinking included; ADK's read by its model's provider kind, `adk_usage_event`/`adk_tokens`, since Gemini and ADK's Claude adapter keep the thinking apart from the candidates and OpenAI's count it inside, an agent of no known kind read as apart; Deep Agents' by LangChain's one convention, `langchain_tokens`; the raw log's usage records alike), and timed (`latency_ms`: on ADK from the request to the answer, `workflow/adk/call_clock.py`'s plugins marking the answer's `custom_metadata`; on Deep Agents by the turn's `RunCallback`, which marks the answer's `response_metadata["agentic_cli"]`, beside the outcome mark; a side call, a summary and the overflow retry around their own request; no adapter sends either mark). Each is recorded in its conversation's ledger (`UsageLedger`; `BaseWorkflowManager.usage`/`usage_of`, in memory for the manager's life: a backend switch's new manager starts afresh, as with `agent_runs`) where it is made, before `on_event` (the event processors, ADK's summarizer, as soon as its call answers, Deep Agents' `RunCallback`, `_report_side_call`), under the run it is made in and its conversation's turn while one runs (as the manager counts them, `/compact` and job notices included: not `SessionInfo.turns`; none in another conversation's turn or from a task its turn outlived, which `_report_side_call` reports to no one); a sub-agent run's `AGENT_RUN` end carries what it used, by model (`metadata["usage"]`, `RunRecord.usage`). The CLI's status bar sums the events it sees (the open conversation's total, on any backend); `/status` shows the ledger by agent. LangGraph (deprecated) records no ledger. - **Tool registration**: Use `@register_tool(category=..., capabilities=..., description=...)` decorator. `capabilities=` is required — pass `EXEMPT` for tools that need no permission check or a list of `Capability(name, target_arg=...)` tuples the engine matches against rules. Tools are auto-discovered via the global `ToolRegistry`. A tool in `AgentConfig.tools` that the registry did not issue is denied at every call; building the agents names it once (`tool_not_registered`, per agent and tool: `BaseWorkflowManager._name_unregistered`): a plain callable, a `FunctionTool`/`StructuredTool` judged by the function it runs (as the gates unwrap it), an app's own tool class; ADK's own tool objects excepted (a built-in runs inside the model). `outside_content=True` (or a function of the call's arguments) declares that a call brings content from outside the user and the project into the conversation (a page, a document, a program's output): once the gate allows one, a memory write in that conversation is approved per call (see Permissions); an application's tools are unmarked unless they declare it, and a variant must declare the same flag as its tool. - **Async tools never block the event loop**: a synchronous tool runs on a worker thread on both backends; an async tool runs on the event loop itself, where a blocking call (DNS, a connect, a file lock's wait, a sleep, a subprocess wait, PDF parsing, page conversion, embedding) freezes the whole app, Ctrl+C included. An async tool runs its slow work with `asyncio.to_thread`. `tests/tools/test_async_tools_never_block.py` lists every async tool (the registry's, the factories' service-bound variants, Deep Agents' skill tools), so a new one fails until it is listed, and calls each through the loop guard (`tests/loop_guard.py`). diff --git a/src/agentic_cli/cli/message_processor.py b/src/agentic_cli/cli/message_processor.py index 5475ea59..25eab5cf 100644 --- a/src/agentic_cli/cli/message_processor.py +++ b/src/agentic_cli/cli/message_processor.py @@ -469,6 +469,39 @@ async def process( request: thinking-prompt cancels the input handler running it. ``CANCELLED_LINE`` has been said, once. """ + def _source(workflow): + return workflow.process( + message=message, + user_id=settings.default_user, + session_id=session_id, + ) + + return await self._user_turn( + _source, workflow_controller, ui, settings, usage_tracker, + log="handling_message", fields={"message_length": len(message)}, + ) + + async def _user_turn( + self, + source_factory, + workflow_controller: "WorkflowController", + ui: "ThinkingPromptSession", + settings: "BaseSettings", + usage_tracker: "UsageTracker | None", + *, + log: str, + fields: dict[str, Any], + viewed: str | None = None, + opens: "Callable[[str], Awaitable[None]] | None" = None, + ) -> TurnResult: + """What a turn of the user's own does around ``_run_turn``: ``process``, + ``process_instance`` and ``process_start``. + + Ctrl+C says ``CANCELLED_LINE`` once (``_says_so_when_stopped``). A + workflow that did not initialize is said and is an ``UNAVAILABLE`` + result; otherwise the user is bound to the log, ``log`` is logged with + ``fields``, and the turn runs. + """ async with _says_so_when_stopped(ui, lambda: _job_manager(workflow_controller)): # Wait for initialization if needed if not await workflow_controller.ensure_initialized(ui): @@ -481,17 +514,10 @@ async def process( ) bind_context(user_id=settings.default_user) - logger.info("handling_message", message_length=len(message)) - - def _source(workflow): - return workflow.process( - message=message, - user_id=settings.default_user, - session_id=session_id, - ) - + logger.info(log, **fields) return await self._run_turn( - _source, workflow_controller, ui, settings, usage_tracker + source_factory, workflow_controller, ui, settings, usage_tracker, + viewed=viewed, opens=opens, ) async def process_resume( @@ -627,32 +653,19 @@ async def process_instance( asyncio.CancelledError: Ctrl+C stopped it (the user's stop of the run): ``CANCELLED_LINE`` has been said, once. """ - async with _says_so_when_stopped(ui, lambda: _job_manager(workflow_controller)): - if not await workflow_controller.ensure_initialized(ui): - ui.add_error( - "Cannot process message - workflow not initialized. " - "Please check your API keys (GOOGLE_API_KEY or ANTHROPIC_API_KEY)." - ) - return TurnResult( - TurnStatus.UNAVAILABLE, error="workflow not initialized" - ) - - bind_context(user_id=settings.default_user) - logger.info( - "handling_instance_message", instance=instance, message_length=len(message) + def _source(workflow): + return workflow.run_instance( + instance, + message, + session_id=session_id, + user_id=settings.default_user, ) - def _source(workflow): - return workflow.run_instance( - instance, - message, - session_id=session_id, - user_id=settings.default_user, - ) - - return await self._run_turn( - _source, workflow_controller, ui, settings, usage_tracker, viewed=instance - ) + return await self._user_turn( + _source, workflow_controller, ui, settings, usage_tracker, viewed=instance, + log="handling_instance_message", + fields={"instance": instance, "message_length": len(message)}, + ) async def process_start( self, @@ -694,32 +707,19 @@ async def process_start( asyncio.CancelledError: Ctrl+C stopped it (the user's stop of the run): ``CANCELLED_LINE`` has been said, once. """ - async with _says_so_when_stopped(ui, lambda: _job_manager(workflow_controller)): - if not await workflow_controller.ensure_initialized(ui): - ui.add_error( - "Cannot process message - workflow not initialized. " - "Please check your API keys (GOOGLE_API_KEY or ANTHROPIC_API_KEY)." - ) - return TurnResult( - TurnStatus.UNAVAILABLE, error="workflow not initialized" - ) - - bind_context(user_id=settings.default_user) - logger.info( - "handling_instance_start", agent_type=agent_type, objective_length=len(objective) + def _source(workflow): + return workflow.start_instance( + agent_type, + objective, + session_id=session_id, + user_id=settings.default_user, ) - def _source(workflow): - return workflow.start_instance( - agent_type, - objective, - session_id=session_id, - user_id=settings.default_user, - ) - - return await self._run_turn( - _source, workflow_controller, ui, settings, usage_tracker, opens=opens - ) + return await self._user_turn( + _source, workflow_controller, ui, settings, usage_tracker, opens=opens, + log="handling_instance_start", + fields={"agent_type": agent_type, "objective_length": len(objective)}, + ) async def process_notice( self, diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index 06ca279f..e5c3cd3a 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -75,6 +75,7 @@ child_app, child_session_id, is_notice, + keep_conversation, load_records, make_session_service, save_records, @@ -2009,6 +2010,10 @@ async def _conversation_state(self, ref: SessionRef) -> dict[str, Any]: mark = self._outside_marks.get(ref) return {OUTSIDE_CONTENT_KEY: mark} if mark else {} + async def _keep_conversation(self, ref: SessionRef, objective: str) -> None: + """Store the conversation when it is not yet (``keep_conversation``).""" + await keep_conversation(self._session_service, ref, objective) + async def _inherited_history(self, ref: SessionRef) -> list[Any]: """``ref``'s conversation as an inheriting run the user starts reads it. diff --git a/src/agentic_cli/workflow/adk/sessions.py b/src/agentic_cli/workflow/adk/sessions.py index cf6f6c3e..bebcdff6 100644 --- a/src/agentic_cli/workflow/adk/sessions.py +++ b/src/agentic_cli/workflow/adk/sessions.py @@ -409,6 +409,34 @@ def turn_state(session: "Session", message: str) -> dict[str, Any]: return delta +async def keep_conversation(service: "BaseSessionService", ref: SessionRef, objective: str) -> None: + """Store ``ref``'s conversation when it holds no event yet, titled from ``objective``. + + ADK lists a session only once it holds an event, and keeps its state only + through events: the session is made when there is none, and one state-only + event (``RECORDS_AUTHOR``, no content: no request carries it) sets its + title and no turns of the user's, the row ``turn_state`` would leave. A + session with events, or with a row of its own, is left as it is. + """ + from google.adk.events import Event, EventActions + from google.adk.sessions.base_session_service import GetSessionConfig + + session = await service.get_session( + app_name=ref.app_name, user_id=ref.user_id, session_id=ref.session_id, + config=GetSessionConfig(num_recent_events=1), + ) + if session is not None and session.events: + return + if session is None: + session = await service.create_session( + app_name=ref.app_name, user_id=ref.user_id, session_id=ref.session_id, + ) + delta: dict[str, Any] = {TURNS_KEY: 0, TITLE_KEY: session_title(objective)} + await service.append_event(session, Event( + author=RECORDS_AUTHOR, actions=EventActions(state_delta=delta), + )) + + def row_from_state(session: "Session") -> SessionInfo | None: """The row the session's state holds, or None when it holds none.""" state = session.state or {} diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index 2cc0f3e5..237dcb7f 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -176,7 +176,7 @@ def __init__(self) -> None: super().__init__() #: The run the user started, once its start is reported. self.started: RunRef | None = None - self._started = asyncio.Event() + self._waiting: asyncio.Future[None] | None = None def emit(self, event: WorkflowEvent) -> None: if ( @@ -186,16 +186,27 @@ def emit(self, event: WorkflowEvent) -> None: and event.run is not None ): self.started = event.run - self._started.set() + self._wake() super().emit(event) + def _wake(self) -> None: + waiting = self._waiting + if waiting is not None and not waiting.done(): + waiting.set_result(None) + async def until_started(self, work: "asyncio.Task[Any]") -> None: - """Wait until the run has started, or ``work`` (what starts it) has ended.""" - waiter = asyncio.ensure_future(self._started.wait()) - try: - await asyncio.wait({work, waiter}, return_when=asyncio.FIRST_COMPLETED) - finally: - waiter.cancel() + """Wait until the run has started, or ``work`` (what starts it) has ended. + + One future, resolved by the report of the start or by the end of + ``work`` and awaited directly: the caller then runs in the step after + the report, ahead of the run's own first step, so a stop it makes + cancels the run before its hook is entered. + """ + if self.started is not None or work.done(): + return + self._waiting = asyncio.get_running_loop().create_future() + work.add_done_callback(lambda _: self._wake()) + await self._waiting def _module_of(klass: type) -> str: @@ -1019,16 +1030,22 @@ async def start_instance( Yields: The run's ``WorkflowEvent``s, its start first. + A conversation that is not stored yet is stored first, titled from + the objective with no turns of the user's with the main agent + (``_keep_conversation``), so what the user did here is found by + ``/resume``, ``--continue`` and ``--resume``. + Raises: Exception: The store's, when the conversation's sub-agent records, - or an inheriting type's conversation, cannot be read: nothing - runs. + or an inheriting type's conversation, cannot be read or the + conversation cannot be stored: nothing runs. """ async with self._turn(session_id, user_id) as ref: refused = self._delegations.user_start_refused(agent_type, objective) if refused is not None: yield WorkflowEvent.error(refused) return + await self._keep_conversation(ref, objective) config = next((c for c in self._agent_configs if c.name == agent_type), None) history = None if config is not None and config.inherit_context: @@ -1284,6 +1301,17 @@ async def _conversation_state(self, ref: SessionRef) -> dict[str, Any]: """ return {} + async def _keep_conversation(self, ref: SessionRef, objective: str) -> None: + """Store ``ref``'s conversation when it is not yet, as a turn's start does (a backend hook). + + What a conversation whose only work is a run the user started + (``start_instance``) needs to be one the session hooks find + (``session_exists``, ``list_sessions``): its title is the objective's + (``session_title``) and its turns none, since the user typed none to + the main agent. A stored conversation keeps its title and turns. The + base stores nothing. + """ + async def _inherited_history(self, ref: SessionRef) -> list[Any]: """``ref``'s conversation as an inheriting run the user starts reads it (a backend hook). @@ -3024,7 +3052,8 @@ async def _turn( """Run the block as one turn of a conversation, and yield the conversation. How every turn-shaped entry point starts (``process``, - ``resume_with_job_result``, ``compact``, ``run_instance``, ``tell_root``): the conversation is + ``resume_with_job_result``, ``compact``, ``run_instance``, + ``start_instance``, ``tell_root``): the conversation is resolved as ``session_ref`` resolves it (the manager's current session and the default user for what is omitted) and named in the log context; then turn admission (:meth:`_turn_admission`: the diff --git a/src/agentic_cli/workflow/deepagents/manager.py b/src/agentic_cli/workflow/deepagents/manager.py index a019164d..6721e771 100644 --- a/src/agentic_cli/workflow/deepagents/manager.py +++ b/src/agentic_cli/workflow/deepagents/manager.py @@ -567,6 +567,11 @@ async def _conversation_state(self, ref: "SessionRef") -> dict[str, Any]: mark = self._outside_marks.get(ref) return {"outside_content": mark} if mark else {} + async def _keep_conversation(self, ref: "SessionRef", objective: str) -> None: + """Write the conversation's row when it has none (``CheckpointSessions.keep``).""" + if self._sessions is not None: + await self._sessions.keep(ref, objective) + async def _inherited_history(self, ref: "SessionRef") -> list[Any]: """``ref``'s conversation as an inheriting run the user starts reads it. diff --git a/src/agentic_cli/workflow/deepagents/sessions.py b/src/agentic_cli/workflow/deepagents/sessions.py index 879864b1..0d82fa1e 100644 --- a/src/agentic_cli/workflow/deepagents/sessions.py +++ b/src/agentic_cli/workflow/deepagents/sessions.py @@ -254,11 +254,33 @@ def __init__( self._backfill = backfill async def exists(self, ref: SessionRef) -> bool: - """Whether ``ref``'s root thread holds at least one message.""" - return bool(_messages(await self._root(ref))) + """Whether ``ref``'s root thread holds at least one message, or the index holds its row. + + A row without a message is a conversation whose only work is a run the + user started (``keep``). + """ + if _messages(await self._root(ref)): + return True + item = await self._store.aget(_rows_of(ref.app_name, ref.user_id), ref.session_id) + return item is not None and _from_value(ref.session_id, item.value) is not None + + async def keep(self, ref: SessionRef, objective: str) -> None: + """Write ``ref``'s row, titled from ``objective`` with no turns, when it has none. + + What a conversation whose only work is a run the user started + (``start_instance``) needs to be listed and found. A conversation that + holds a message or a row keeps its title and turns. A failed write is + raised: the start's conversation could not be stored. + """ + if await self.exists(ref): + return + row = SessionInfo(ref.session_id, session_title(objective), 0, datetime.now(timezone.utc)) + await self._store.aput( + _rows_of(ref.app_name, ref.user_id), ref.session_id, _value(row), index=False + ) async def info(self, ref: SessionRef) -> SessionInfo | None: - """``ref``'s row, or None when its root thread holds no message. + """``ref``'s row, or None when its root thread holds no message and the index no row. The index's row; a conversation it does not hold (written before it, or whose row could not be written) is read from its checkpoint. diff --git a/tests/cli/console_app.py b/tests/cli/console_app.py index 3c6b79c8..d0f2ae01 100644 --- a/tests/cli/console_app.py +++ b/tests/cli/console_app.py @@ -244,6 +244,7 @@ async def start_instance(self, agent_type, objective, *, session_id=None, user_i f"You cannot start '{agent_type}' here. Types you can start: researcher." ) return + self._sessions.add(session_id) # stored, as the real manager's start stores it conversation = self.session_ref(session_id) # one user here ref = self.agent_runs.run_for(conversation, None, None, agent_type) started = WorkflowEvent.agent_run( diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index 56db61ca..ebff358b 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -1185,6 +1185,19 @@ async def test_an_interrupt_leaves_it_idle(self, make_crew): assert (record.status, record.cancelled_by) == (RUN_INTERRUPTED, None) assert crew.instances() == [("helper-1", INSTANCE_IDLE)] + async def test_a_conversation_of_only_this_is_a_used_one_the_exit_names(self, make_crew): + """Stored (the exit's ``--resume`` hint names a stored conversation) and + no longer fresh: ``/new`` and a switch of backend treat it as used.""" + crew, app = await new_view(make_crew, store="sqlite", helper=[says("Helped.")]) + app._conversation.opened_empty = True # as a new conversation is opened + + await typed(app, "/agent new helper Help with X.") + + assert await app._is_stored(app.workflow, app.session_id) + assert app._conversation.written and not app._conversation.fresh + assert not app._conversation.turned + assert app.session_id in app._resume_hint() + async def test_it_blocks_no_event_loop(self, make_crew): crew = make_crew(user_team(), subagents=STARTING, store="sqlite", coordinator=[says("Noted.")], helper=[says("Helped.")]) diff --git a/tests/cli/test_console_turns.py b/tests/cli/test_console_turns.py index db49c337..f01d2c7d 100644 --- a/tests/cli/test_console_turns.py +++ b/tests/cli/test_console_turns.py @@ -622,3 +622,13 @@ def test_agent_new_opens_the_view_its_run_streams_there_and_back_tells_the_main_ assert steered < transcript.index("── back to main ──") assert transcript.count("Told: The user worked with researcher-1 directly") == 1 assert "Busy" not in transcript + + +def test_a_conversation_whose_only_work_is_agent_new_is_named_at_exit(console): + """Nothing was said to the main agent: the exit still names how to come + back to the conversation the new sub-agent worked in.""" + console.type_line("/agent new researcher look") + console.expect("Researched: look") + console.exit() + + assert "Resume this conversation" in console.transcript diff --git a/tests/test_message_processor_render.py b/tests/test_message_processor_render.py index 8fc25f8b..13900f9f 100644 --- a/tests/test_message_processor_render.py +++ b/tests/test_message_processor_render.py @@ -762,18 +762,26 @@ async def test_opens_is_told_the_instance_its_start_names_then_it_is_in_view(sel ui = _Watched() workflow = _Viewing(events, ui) opened: list[tuple[str, int]] = [] + order: list[str] = [] + controller = ReplayController(workflow) + controller.update_status_bar = lambda ui: order.append("drawn") # a view's events draw it async def opens(instance: str) -> None: + order.append("opens") opened.append((instance, len(workflow.lines))) result = await MessageProcessor().process_start( - "helper", "Help.", workflow_controller=ReplayController(workflow), ui=ui, + "helper", "Help.", workflow_controller=controller, ui=ui, settings=_settings(), session_id="s1", opens=opens, ) assert result.delivered assert workflow.asked == [("start_instance", "helper", "Help.", "s1", "tester")] assert opened == [("helper-1", 0)] # before its start was drawn + # The start is drawn (the status bar) only once the view opened; so is each + # later event of the run, never before. + assert order[:2] == ["opens", "drawn"] + assert order.count("opens") == 1 assert workflow.lines == [ "Processing...", "Calling: lookup", "checker-1 › Calling: check", "checker-1 › Calling: check", "checker-1 › Calling: check", diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index bae2dbb2..9dd9e56a 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -6043,6 +6043,20 @@ async def test_it_blocks_no_event_loop(self, make_crew): assert [e.content for e in events if e.type is EventType.TEXT] == ["Noted."] +def watch_hook(crew: Crew) -> list[str]: + """The runs whose hook is entered (a backend's model call comes after it).""" + entered: list[str] = [] + delegations = crew.manager._delegations + hook = delegations._hook + + async def recording(run: Any) -> Any: + entered.append(run.ref.run) + return await hook(run) + + delegations._hook = recording + return entered + + class TestTheUsersStopInTheWindowBeforeTheRunStarts: """A Ctrl+C that lands as ``run_instance`` starts merging: its pump is made but has not run, so the instance is not ``running`` yet. The run @@ -6057,6 +6071,7 @@ async def test_ctrl_c_as_the_stream_starts_stops_the_run_by_the_user(self, make_ researcher=[says("X is 42."), says("Went on.")], ) await crew.turn() + entered = watch_hook(crew) async def view() -> None: async for _ in crew.manager.run_instance("researcher-1", "Go on."): @@ -6082,6 +6097,7 @@ async def view() -> None: "researcher-1#2", RUN_CANCELLED, "user", ) assert crew.instances() == [("researcher-1", INSTANCE_STOPPED)] + assert entered == [] # stopped before its first step: no hook, no model call class TestTheUsersControlAfterARestart: @@ -7525,6 +7541,55 @@ async def test_after_a_restart_it_is_numbered_past_the_stored(self, make_crew): assert second.instances() == [("helper-1", INSTANCE_IDLE), ("helper-2", INSTANCE_IDLE)] +class TestTheUsersStartStoresItsConversation: + """A conversation whose only work is a start is stored as a turn's start + stores one: titled from the objective, no turns of the user's with the + main agent; ``/resume``, ``--continue`` and ``--resume`` reach it.""" + + async def test_a_start_alone_stores_the_conversation(self, make_crew): + crew = make_crew(user_team(), subagents=STARTING, store="sqlite", + helper=[says("Helped.")]) + assert not await crew.manager.session_exists(SESSION, user_id=USER) + + await user_start(crew, "helper", "Help with X.\nIn the docs.") + + assert await crew.manager.session_exists(SESSION, user_id=USER) + (row,) = await crew.manager.list_sessions(user_id=USER) + assert (row.session_id, row.title, row.turns) == (SESSION, "Help with X. In the docs.", 0) + info = await crew.manager.session_info(SESSION, user_id=USER) + assert (info.title, info.turns) == ("Help with X. In the docs.", 0) + + async def test_a_conversation_with_turns_keeps_its_title_and_turns(self, make_crew): + crew = make_crew(user_team(), subagents=STARTING, store="sqlite", + coordinator=[says("Noted.")], helper=[says("Helped.")]) + await crew.turn("My first prompt.") + + await user_start(crew, "helper", "Help with X.") + + (row,) = await crew.manager.list_sessions(user_id=USER) + assert (row.title, row.turns) == ("My first prompt.", 1) + + async def test_the_main_agents_first_turn_after_it_counts_one(self, make_crew): + crew = make_crew(user_team(), subagents=STARTING, store="sqlite", + coordinator=[says("Noted.")], helper=[says("Helped."), says("Again.")]) + await user_start(crew, "helper", "Help with X.") + + await crew.turn("Now you.") + + (row,) = await crew.manager.list_sessions(user_id=USER) + assert row.turns == 1 + events = await user_start(crew, "helper", "Again.") + assert runs_of(events)[-1].metadata["status"] == RUN_COMPLETED + + async def test_a_refusal_stores_nothing(self, make_crew): + crew = make_crew(user_team(), subagents=STARTING, store="sqlite") + + await user_start(crew, "researcher", "Find X.") + + assert not await crew.manager.session_exists(SESSION, user_id=USER) + assert await crew.manager.list_sessions(user_id=USER) == [] + + class TestTheUsersStopOfANewInstance: """Stopping ``start_instance``'s stream (Ctrl+C in its view) is the user's stop of its first run: ``cancelled`` by the user, the instance @@ -7563,6 +7628,7 @@ async def test_ctrl_c_as_the_stream_starts_stops_the_run_by_the_user(self, make_ import inspect crew = make_crew(user_team(), subagents=STARTING, helper=[says("[never asked]")]) + entered = watch_hook(crew) async def view() -> None: async for _ in crew.manager.start_instance("helper", "Go."): @@ -7589,6 +7655,7 @@ async def view() -> None: ) assert crew.instances() == [("helper-1", INSTANCE_STOPPED)] assert crew.requests("helper") == 0 + assert entered == [] async def test_a_stop_while_its_instance_is_numbered_stops_the_run_as_it_starts( self, make_crew @@ -7596,6 +7663,7 @@ async def test_a_stop_while_its_instance_is_numbered_stops_the_run_as_it_starts( """The stop lands while the start reads the store's instances (before its run starts): the run that starts then is stopped.""" crew = make_crew(user_team(), subagents=STARTING, helper=[says("[never asked]")]) + entered = watch_hook(crew) delegations = crew.manager._delegations read, gate = asyncio.Event(), asyncio.Event() stored = delegations._stored @@ -7626,6 +7694,7 @@ async def view() -> None: ) assert crew.instances() == [("helper-1", INSTANCE_STOPPED)] assert crew.requests("helper") == 0 + assert entered == [] async def test_an_interrupt_ends_its_run_as_a_turns_cancel_and_the_instance_idle( self, make_crew From 492804869b24e48f9f9455be8393074c9e6bc99c Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:31:02 -0500 Subject: [PATCH 10/12] Sub-agents: a kept conversation keeps its title on both backends Deep Agents' record keeps the title of a row keep wrote (the objective's) when a notice or the first typed prompt rewrites it, and a turn that stored no message leaves that row instead of deleting it, as ADK does. The state-only event keep_conversation writes on ADK is authored by the root agent, so the router logs no unknown-agent warning at the next turn. A CHANGELOG line and a docstring paragraph are moved. --- CHANGELOG.md | 7 +-- src/agentic_cli/workflow/adk/manager.py | 4 +- src/agentic_cli/workflow/adk/sessions.py | 14 +++--- src/agentic_cli/workflow/base_manager.py | 6 +-- .../workflow/deepagents/sessions.py | 32 ++++++++++--- tests/workflow/deepagents/test_sessions.py | 26 +++++++++++ tests/workflow/test_subagents_contract.py | 45 ++++++++++++++++++- 7 files changed, 116 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a5a38372..76b44eb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -594,9 +594,10 @@ the start of the entry's title. tools: `follow_ups`, and a sub-agent it may start or a type agents may start). A conversation whose only work is a start is stored, titled with the objective, so `/resume`, `--continue` and `--resume` reach it. In - another sub-agent's view it leaves that one first. A type you cannot start opens nothing ("You cannot start - 'writer' here. Types you can start: researcher."; "This app lets you start - no agent types." when there is none), and a missing type or objective says + another sub-agent's view it leaves that one first. A type you cannot start + opens nothing ("You cannot start 'writer' here. Types you can start: + researcher."; "This app lets you start no agent types." when there is + none), and a missing type or objective says `Usage: /agent new `. The manager's entry point (provisional): `start_instance(agent_type, objective)`, a turn of its own whose first event is the run's start, which names the instance; a refusal diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index e5c3cd3a..f02a6827 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -2012,7 +2012,9 @@ async def _conversation_state(self, ref: SessionRef) -> dict[str, Any]: async def _keep_conversation(self, ref: SessionRef, objective: str) -> None: """Store the conversation when it is not yet (``keep_conversation``).""" - await keep_conversation(self._session_service, ref, objective) + await keep_conversation( + self._session_service, ref, objective, author=self._root_agent_name + ) async def _inherited_history(self, ref: SessionRef) -> list[Any]: """``ref``'s conversation as an inheriting run the user starts reads it. diff --git a/src/agentic_cli/workflow/adk/sessions.py b/src/agentic_cli/workflow/adk/sessions.py index bebcdff6..22a433c4 100644 --- a/src/agentic_cli/workflow/adk/sessions.py +++ b/src/agentic_cli/workflow/adk/sessions.py @@ -409,14 +409,18 @@ def turn_state(session: "Session", message: str) -> dict[str, Any]: return delta -async def keep_conversation(service: "BaseSessionService", ref: SessionRef, objective: str) -> None: +async def keep_conversation( + service: "BaseSessionService", ref: SessionRef, objective: str, *, author: str +) -> None: """Store ``ref``'s conversation when it holds no event yet, titled from ``objective``. ADK lists a session only once it holds an event, and keeps its state only through events: the session is made when there is none, and one state-only - event (``RECORDS_AUTHOR``, no content: no request carries it) sets its - title and no turns of the user's, the row ``turn_state`` would leave. A - session with events, or with a row of its own, is left as it is. + event (no content: no request carries it) sets its title and no turns of + the user's, the row ``turn_state`` would leave. Its ``author`` is the root + agent's name: it is only ever the first event of a new conversation, and + ADK's router, which warns of an event from an agent the app lacks, picks + the root for it as it would anyway. A session with events is left as it is. """ from google.adk.events import Event, EventActions from google.adk.sessions.base_session_service import GetSessionConfig @@ -433,7 +437,7 @@ async def keep_conversation(service: "BaseSessionService", ref: SessionRef, obje ) delta: dict[str, Any] = {TURNS_KEY: 0, TITLE_KEY: session_title(objective)} await service.append_event(session, Event( - author=RECORDS_AUTHOR, actions=EventActions(state_delta=delta), + author=author, actions=EventActions(state_delta=delta), )) diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index 237dcb7f..f87fb9d2 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -1027,14 +1027,14 @@ async def start_instance( is ``stopped``; a stop before the run started stops the run as it starts. ``interrupt_instance`` ends it as a turn's cancel does. - Yields: - The run's ``WorkflowEvent``s, its start first. - A conversation that is not stored yet is stored first, titled from the objective with no turns of the user's with the main agent (``_keep_conversation``), so what the user did here is found by ``/resume``, ``--continue`` and ``--resume``. + Yields: + The run's ``WorkflowEvent``s, its start first. + Raises: Exception: The store's, when the conversation's sub-agent records, or an inheriting type's conversation, cannot be read or the diff --git a/src/agentic_cli/workflow/deepagents/sessions.py b/src/agentic_cli/workflow/deepagents/sessions.py index 0d82fa1e..aa6da4f7 100644 --- a/src/agentic_cli/workflow/deepagents/sessions.py +++ b/src/agentic_cli/workflow/deepagents/sessions.py @@ -276,7 +276,8 @@ async def keep(self, ref: SessionRef, objective: str) -> None: return row = SessionInfo(ref.session_id, session_title(objective), 0, datetime.now(timezone.utc)) await self._store.aput( - _rows_of(ref.app_name, ref.user_id), ref.session_id, _value(row), index=False + _rows_of(ref.app_name, ref.user_id), ref.session_id, _value(row, kept=True), + index=False, ) async def info(self, ref: SessionRef) -> SessionInfo | None: @@ -305,21 +306,34 @@ async def record(self, ref: SessionRef, adding: Sequence[BaseMessage] = ()) -> N ends, however it ends, and after ``/compact``, without ``adding``, which corrects that row. A conversation without a message has none: a first turn stopped before its input was stored takes its row back. + A row ``keep`` wrote (a conversation started by a run the user began) + is the exception: it keeps its title, the objective's, whatever is + typed later, and a turn that stored no message leaves it. A failed write is logged at debug and costs nothing else: the conversation's next turn writes its row again. """ namespace = _rows_of(ref.app_name, ref.user_id) try: item = await self._root(ref) + held = await self._store.aget(namespace, ref.session_id) + kept = held.value if held is not None and _is_kept(held.value) else None if adding: messages = [*_messages(item), *adding] row = _row_of(ref.session_id, messages, datetime.now(timezone.utc)) elif _messages(item): row = _row(ref.session_id, item) + elif kept is not None: + return else: await self._store.adelete(namespace, ref.session_id) return - await self._store.aput(namespace, ref.session_id, _value(row), index=False) + if kept is not None: + title = _from_value(ref.session_id, kept) + if title is not None: + row = SessionInfo(row.session_id, title.title, row.turns, row.updated) + await self._store.aput( + namespace, ref.session_id, _value(row, kept=kept is not None), index=False + ) except Exception: # noqa: BLE001 - the turn is not the index's to fail logger.debug( "session_row_not_written", session_id=ref.session_id, exc_info=True @@ -680,14 +694,22 @@ def _marks_of(app_name: str, user_id: str) -> tuple[str, ...]: return (*_BACKFILLS, _label(app_name), _label(user_id)) -def _value(row: SessionInfo) -> dict[str, Any]: - """A row as the index stores it.""" - return { +def _value(row: SessionInfo, *, kept: bool = False) -> dict[str, Any]: + """A row as the index stores it (``kept``: ``keep`` wrote it, and its title stays).""" + value: dict[str, Any] = { "title": row.title, "turns": row.turns, "updated": row.updated.isoformat(), "v": _ROW_VERSION, } + if kept: + value["kept"] = True + return value + + +def _is_kept(value: Any) -> bool: + """Whether a stored row is one ``keep`` wrote.""" + return isinstance(value, dict) and value.get("kept") is True def _from_value(session_id: str, value: Any) -> SessionInfo | None: diff --git a/tests/workflow/deepagents/test_sessions.py b/tests/workflow/deepagents/test_sessions.py index bbde30e2..47963e1a 100644 --- a/tests/workflow/deepagents/test_sessions.py +++ b/tests/workflow/deepagents/test_sessions.py @@ -885,3 +885,29 @@ async def test_a_restart_numbers_past_them(self, hermetic, monkeypatch): # The first manager's run is in its records, loaded with the conversation. assert runs == ["worker-1#1", "worker-2#1"] assert kept == ["worker-1", "worker-2"] + + +class TestAKeptRow: + """A conversation whose only work is a run the user started has a row + ``keep`` wrote: a turn that stores no message leaves it, and a title it + holds is its title.""" + + async def test_a_turn_that_stored_no_message_leaves_the_kept_row(self, saver, store): + sessions = CheckpointSessions(saver, store) + await sessions.keep(ref(), "Objective title.") + + await sessions.record(ref(), [HumanMessage("Typed.")]) # the turn's start + await sessions.record(ref()) # its end: the input was never stored + + assert await sessions.exists(ref()) + (row,) = await sessions.list("app", "alice") + assert row.title == "Objective title." + + async def test_a_conversation_never_kept_is_titled_and_dropped_as_before(self, saver, store): + sessions = CheckpointSessions(saver, store) + + await sessions.record(ref(), [HumanMessage("Typed.")]) + assert [(r.title, r.turns) for r in await sessions.list("app", "alice")] == [("Typed.", 1)] + await sessions.record(ref()) # no message stored: its row goes + + assert await sessions.list("app", "alice") == [] diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 9dd9e56a..03953e73 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -7577,10 +7577,53 @@ async def test_the_main_agents_first_turn_after_it_counts_one(self, make_crew): await crew.turn("Now you.") (row,) = await crew.manager.list_sessions(user_id=USER) - assert row.turns == 1 + assert (row.title, row.turns) == ("Help with X.", 1) events = await user_start(crew, "helper", "Again.") assert runs_of(events)[-1].metadata["status"] == RUN_COMPLETED + async def test_the_main_agents_notice_keeps_the_objectives_title_and_no_turns( + self, make_crew + ): + """``/back``'s notice is no typed prompt: the row stays as the start left it.""" + crew = make_crew(user_team(), subagents=STARTING, store="sqlite", + coordinator=[says("Noted.")], helper=[says("Helped.")]) + await user_start(crew, "helper", "Objective title.") + + _ = [event async for event in crew.manager.tell_root( + "The user worked with helper-1 directly.", session_id=SESSION, user_id=USER + )] + + (row,) = await crew.manager.list_sessions(user_id=USER) + assert (row.title, row.turns) == ("Objective title.", 0) + + async def test_the_first_typed_prompt_after_it_counts_one_and_keeps_the_title( + self, make_crew + ): + crew = make_crew(user_team(), subagents=STARTING, store="sqlite", + coordinator=[says("Noted.")], helper=[says("Helped.")]) + await user_start(crew, "helper", "Objective title.") + + await crew.turn("First typed prompt.") + + (row,) = await crew.manager.list_sessions(user_id=USER) + assert (row.title, row.turns) == ("Objective title.", 1) + + async def test_the_first_root_turn_after_it_logs_no_unknown_agent_warning( + self, make_crew, caplog + ): + """ADK's router warns of an event whose author is none of the app's agents.""" + import logging + + crew = make_crew(user_team(), subagents=STARTING, store="sqlite", + coordinator=[says("Noted.")], helper=[says("Helped.")]) + await user_start(crew, "helper", "Objective title.") + + with caplog.at_level(logging.DEBUG): + await crew.turn("First typed prompt.") + + assert [r.getMessage() for r in caplog.records + if "unknown agent" in r.getMessage()] == [] + async def test_a_refusal_stores_nothing(self, make_crew): crew = make_crew(user_team(), subagents=STARTING, store="sqlite") From baba18bede930f50d53a4af88b2cc671dcb34863 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:46:27 -0500 Subject: [PATCH 11/12] Sub-agents: a kept conversation is unmarked and the backfill leaves its row The state-only event keep_conversation writes on ADK carries an unmarked outside-content record, so the conversation is not read as one from before 0.7.0 and marked, nor its new instance. The Deep Agents backfill leaves a row keep wrote as it is. --- src/agentic_cli/workflow/adk/sessions.py | 10 +++++-- .../workflow/deepagents/sessions.py | 10 ++++++- .../workflow/deepagents/test_session_index.py | 27 +++++++++++++++++++ tests/workflow/test_subagents_contract.py | 20 ++++++++++++++ 4 files changed, 64 insertions(+), 3 deletions(-) diff --git a/src/agentic_cli/workflow/adk/sessions.py b/src/agentic_cli/workflow/adk/sessions.py index 22a433c4..cf61b73a 100644 --- a/src/agentic_cli/workflow/adk/sessions.py +++ b/src/agentic_cli/workflow/adk/sessions.py @@ -70,6 +70,7 @@ from agentic_cli.logging import Loggers from agentic_cli.tools.jobs.resume import JOB_NOTICE_HEADER from agentic_cli.workflow.agents.runs import stored_instance_ids +from agentic_cli.workflow.outside_content import OUTSIDE_CONTENT_KEY from agentic_cli.workflow.sessions import SessionInfo, SessionRef, session_title if TYPE_CHECKING: @@ -417,7 +418,9 @@ async def keep_conversation( ADK lists a session only once it holds an event, and keeps its state only through events: the session is made when there is none, and one state-only event (no content: no request carries it) sets its title and no turns of - the user's, the row ``turn_state`` would leave. Its ``author`` is the root + the user's, the row ``turn_state`` would leave, and an unmarked + outside-content record (a session with events and none is read as one + from before 0.7.0 and marked). Its ``author`` is the root agent's name: it is only ever the first event of a new conversation, and ADK's router, which warns of an event from an agent the app lacks, picks the root for it as it would anyway. A session with events is left as it is. @@ -435,7 +438,10 @@ async def keep_conversation( session = await service.create_session( app_name=ref.app_name, user_id=ref.user_id, session_id=ref.session_id, ) - delta: dict[str, Any] = {TURNS_KEY: 0, TITLE_KEY: session_title(objective)} + # The conversation is new: it holds no outside content (what a first turn records). + delta: dict[str, Any] = { + TURNS_KEY: 0, TITLE_KEY: session_title(objective), OUTSIDE_CONTENT_KEY: "", + } await service.append_event(session, Event( author=author, actions=EventActions(state_delta=delta), )) diff --git a/src/agentic_cli/workflow/deepagents/sessions.py b/src/agentic_cli/workflow/deepagents/sessions.py index aa6da4f7..b231f440 100644 --- a/src/agentic_cli/workflow/deepagents/sessions.py +++ b/src/agentic_cli/workflow/deepagents/sessions.py @@ -522,13 +522,19 @@ async def _filled(self, app_name: str, user_id: str) -> bool: version = mark.value.get("v") if mark is not None else None return isinstance(version, int) and version >= _BACKFILL_VERSION + async def _is_kept_row(self, namespace: tuple[str, ...], session_id: str) -> bool: + """Whether the index's row of ``session_id`` is one ``keep`` wrote.""" + item = await self._store.aget(namespace, session_id) + return item is not None and _is_kept(item.value) + async def _fill(self, app_name: str, user_id: str) -> dict[str, SessionInfo]: """Index the app and user's conversations from their checkpoints, once. Scans the saver (``_scan``), writes the row of each conversation the index lacks or holds an older row of, and marks the app and user done, in one batch. The rows are read after the scan, so a newer one - that another process's turn wrote meanwhile is kept. A failed write + that another process's turn wrote meanwhile is kept, and so is a row + ``keep`` wrote. A failed write is logged at debug, and the next listing scans again. Returns: @@ -540,6 +546,8 @@ async def _fill(self, app_name: str, user_id: str) -> dict[str, SessionInfo]: writes: list[PutOp] = [] for session_id, row in scanned.items(): held = rows.get(session_id) + if held is not None and await self._is_kept_row(namespace, session_id): + continue # ``keep``'s row is left as it is if held is None or held.updated < row.updated: rows[session_id] = row writes.append(PutOp(namespace, session_id, _value(row), index=False)) diff --git a/tests/workflow/deepagents/test_session_index.py b/tests/workflow/deepagents/test_session_index.py index 834c0f14..7b140bae 100644 --- a/tests/workflow/deepagents/test_session_index.py +++ b/tests/workflow/deepagents/test_session_index.py @@ -577,6 +577,33 @@ async def their_turn_ends() -> None: await connection.__aexit__(None, None, None) + @pytest.mark.parametrize("kind", ["memory", "sqlite"]) + async def test_it_leaves_a_kept_row_as_it_is(self, tmp_path, kind): + """A row ``keep`` wrote keeps its title and its mark when the scan finds + newer checkpoints of its conversation.""" + from agentic_cli.workflow.checkpointers import open_store + from agentic_cli.workflow.deepagents.sessions import _rows_of + + db = tmp_path / "c.db" + saver, saver_connection = await open_checkpointer(kind, sqlite_path=db) + store, store_connection = await open_store(kind, sqlite_path=db) + try: + kept = SessionRef("app", "u", "kept") + sessions = CheckpointSessions(saver, store) + await sessions.keep(kept, "Objective title.") + await say(saver, kept, "Typed later.") # a checkpoint newer than the row + + (row,) = await sessions.list("app", "u") + + assert (row.title, row.turns) == ("Objective title.", 0) + held = await store.aget(_rows_of("app", "u"), "kept") + assert held.value.get("kept") is True + finally: + for connection in (store_connection, saver_connection): + if connection is not None: + await connection.__aexit__(None, None, None) + + class SlowStore: """A store whose ``hold``-th write waits for ``release``, as a slow disk would; ``done`` names each write and delete as it completes.""" diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 03953e73..32d3b222 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -7624,6 +7624,26 @@ async def test_the_first_root_turn_after_it_logs_no_unknown_agent_warning( assert [r.getMessage() for r in caplog.records if "unknown agent" in r.getMessage()] == [] + async def test_a_new_conversation_and_its_instance_are_unmarked(self, make_crew): + """Storing the conversation is no outside content: a memory write in it is + approved as in any new conversation, not per call.""" + from agentic_cli.workflow.sessions import reset_active_turn, set_active_turn + + crew = make_crew(user_team(), subagents=STARTING, store="sqlite", + coordinator=[says("Noted.")], helper=[says("Helped.")]) + + await user_start(crew, "helper", "Objective title.") + await crew.turn("First typed prompt.") + + assert not crew.manager._outside_marks.get(crew.conversation) + assert not await crew.marked() + assert await crew.instance_mark("helper-1") == "" + token = set_active_turn(crew.conversation) + try: + assert crew.manager._per_call_capabilities(crew.manager.settings) == {} + finally: + reset_active_turn(token) + async def test_a_refusal_stores_nothing(self, make_crew): crew = make_crew(user_team(), subagents=STARTING, store="sqlite") From 4a776358cc5a5e586c916fdeffe7997c0eb84556 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:13:24 -0500 Subject: [PATCH 12/12] Tests: a window search starts on a ready manager The stop-as-the-stream-starts scenario of the user's new instance started on a manager that was not initialized, so its worker-thread service build ran inside the window search and the hop budget ran out on a slow runner. The manager is brought up first, the search runs to a deadline, and a miss says whether the start ended first. --- tests/workflow/test_subagents_contract.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 32d3b222..ffb4d692 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -7691,6 +7691,8 @@ async def test_ctrl_c_as_the_stream_starts_stops_the_run_by_the_user(self, make_ import inspect crew = make_crew(user_team(), subagents=STARTING, helper=[says("[never asked]")]) + # Ready first: only the start's own steps run inside the window searched. + await crew.manager.initialize_services() entered = watch_hook(crew) async def view() -> None: @@ -7698,8 +7700,10 @@ async def view() -> None: pass viewing = asyncio.create_task(view()) + loop = asyncio.get_running_loop() + deadline = loop.time() + 10 landed = False - for _ in range(10_000): + while loop.time() < deadline: await asyncio.sleep(0) pumps = [t for t in asyncio.all_tasks() if t.get_name() == live_events.PUMP_TASK] if pumps and inspect.getcoroutinestate(pumps[0].get_coro()) == inspect.CORO_CREATED: @@ -7708,7 +7712,13 @@ async def view() -> None: break if viewing.done(): break - assert landed, "the cancel could not be landed in the window" + if not landed: + ended = ( + f"the start ended first: {viewing.exception() or 'no error'}" + if viewing.done() and not viewing.cancelled() else "no window within 10 s" + ) + viewing.cancel() + raise AssertionError(f"the cancel could not be landed in the window: {ended}") with contextlib.suppress(asyncio.CancelledError): await asyncio.wait_for(viewing, 10)