From 8413d004836244837b544d0579ef102d6f81b7b9 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:17:58 -0500 Subject: [PATCH 01/10] Delegations: the user's stop and close of any instance stop_by_user cancels a running instance's run by the user and waits for its end, which leaves the instance stopped; an idle one is stopped at once. close_by_user closes an instance and its descendants, a running one as its run ends. Only the user may start a stopped instance's next run. --- src/agentic_cli/workflow/agents/delegate.py | 98 +++++++++++ tests/workflow/test_agent_delegate.py | 177 ++++++++++++++++++++ 2 files changed, 275 insertions(+) diff --git a/src/agentic_cli/workflow/agents/delegate.py b/src/agentic_cli/workflow/agents/delegate.py index 21b307be..676548ce 100644 --- a/src/agentic_cli/workflow/agents/delegate.py +++ b/src/agentic_cli/workflow/agents/delegate.py @@ -200,6 +200,11 @@ REPLACED_BY_USER_ERROR = "stopped by the user for a new message" #: Why a parent's ``stop_agent`` closes an instance. CLOSED_BY_PARENT = "closed by its parent" +#: Why the user stopped an instance: its run's envelope's ``error``, or, for +#: an idle one, its ``AGENT_INSTANCE``'s reason (``stop_by_user``). +STOPPED_BY_USER_ERROR = "stopped by the user" +#: Why the user closed an instance (``AGENT_INSTANCE``'s reason; ``close_by_user``). +CLOSED_BY_USER = "closed by the user" #: The error of a run that ended with a parent's run its control stopped. WITH_ITS_PARENT_ERROR = "its parent's run was stopped" #: Who cancels a run for its parent's tools (``cancelled_by``). @@ -841,6 +846,99 @@ def steer(self, conversation: SessionRef | None, run_id: str, message: str) -> b control.steer(message) return True + async def stop_by_user(self, conversation: SessionRef | None, instance: str) -> bool: + """The user's stop of ``conversation``'s ``instance``, any of its instances. + + A running instance's run is cancelled by the user + (``STOPPED_BY_USER_ERROR``) and waited for to its end, which leaves + the instance ``stopped`` (``closed`` for a type that is not + ``continuable``); a run whose work had ended as the stop came + (``RunControl.finish``) ends as it went, and the instance is stopped + after its end. An idle instance is stopped at once (``AGENT_INSTANCE`` + ``stopped``, reason ``STOPPED_BY_USER_ERROR``). Only the user may + start a stopped instance's next run. ``conversation``, when not the + active turn's, is made the active turn for the events; None is the + active turn's. + + Returns: + True when it stopped the instance; False, doing nothing, for an + instance that is unknown, closed or stopped already. + """ + conversation = conversation if conversation is not None else get_active_turn() + with _as_turn(conversation): + record = self._runs.instance(conversation, instance) + if record is None or record.status in (INSTANCE_CLOSED, INSTANCE_STOPPED): + return False + stopped = await self._user_stops_run(conversation, record) + logger.info("subagent_stopped", instance=instance, run=stopped, by=USER) + record = self._runs.instance(conversation, instance) or record + if record.status not in (INSTANCE_STOPPED, INSTANCE_CLOSED): + # Idle, or its run ended as it went: stopped without a run. + self._emit_instance(conversation, record, INSTANCE_STOPPED, STOPPED_BY_USER_ERROR) + return True + + async def close_by_user(self, conversation: SessionRef | None, instance: str) -> list[str]: + """The user's close of ``conversation``'s ``instance`` and its descendants. + + An idle or stopped one is closed at once (``close``, reason + ``CLOSED_BY_USER``); a running one's run is cancelled by the user and + waited for, its end closing it, then its open descendants. Its + transcript stays readable; it takes no follow-up. ``conversation`` + as ``stop_by_user`` takes it. + + Returns: + The ids closed, ``instance`` first, then its descendants in the + order they started; none for an instance that is unknown or closed. + """ + conversation = conversation if conversation is not None else get_active_turn() + with _as_turn(conversation): + record = self._runs.instance(conversation, instance) + if record is None or record.status == INSTANCE_CLOSED: + return [] + if record.status != INSTANCE_RUNNING: + return self.close(conversation, instance, reason=CLOSED_BY_USER) + closing = [ + one.instance for one in (record, *self._descendants(conversation, instance)) + if one.status != INSTANCE_CLOSED + ] + self._closing[(conversation, instance)] = CLOSED_BY_USER + if await self._user_stops_run(conversation, record) is None: + # No run of this manager's works for it: closed as an open one is. + self._closing.pop((conversation, instance), None) + for one in (record, *self._descendants(conversation, instance)): + if one.instance == instance or one.status in _OPEN: + self._close(conversation, one, CLOSED_BY_USER) + return [ + one for one in closing + if (found := self._runs.instance(conversation, one)) is not None + and found.status == INSTANCE_CLOSED + ] + + async def _user_stops_run( + self, conversation: SessionRef | None, record: InstanceRecord + ) -> str | None: + """Cancel ``record``'s working run by the user and wait for its end; the run's id. + + None when no run of this manager works for it. + """ + control = self._working_control(conversation, record=record) + if control is None: + return None + run = control.ref.run or "" + ended = self._ends[(conversation, run)] + self.cancel(run, by=USER, error=STOPPED_BY_USER_ERROR, conversation=conversation) + await ended.wait() + return run + + def _emit_instance( + self, conversation: SessionRef | None, instance: InstanceRecord, status: str, reason: str + ) -> None: + """Report and record ``instance``'s change to ``status`` (``AGENT_INSTANCE``), + named by its last run.""" + last = self._runs.record(conversation, instance.instance) + if last is not None: + self._emit(WorkflowEvent.agent_instance(last.ref, status, reason=reason)) + def stop_cause(self, run: RunRef | None, *, conversation: SessionRef | None = None) -> str | None: """What stopped ``run``, for a call it left at its prompt (``interrupts.not_run``). diff --git a/tests/workflow/test_agent_delegate.py b/tests/workflow/test_agent_delegate.py index ac16c9a2..637d6979 100644 --- a/tests/workflow/test_agent_delegate.py +++ b/tests/workflow/test_agent_delegate.py @@ -3531,3 +3531,180 @@ async def started() -> None: assert made.stop_cause(RESEARCHER) is None # no working run finally: reset_active_turn(token) + + +# -- the user's stop and close: any instance of the conversation --------------------------- + + +def finishing() -> tuple[Hook, asyncio.Event, asyncio.Event]: + """A hook whose run's work ends (``RunControl.finish``) and which then + waits for ``go`` before it answers ``Done.``: a stop that comes meanwhile + cancels nothing. The event set once its work has ended, and ``go``.""" + ended, go = asyncio.Event(), asyncio.Event() + + async def hook(run: AgentRun) -> RunAnswer: + run.control.finish() + ended.set() + await go.wait() + return RunAnswer(text="Done.") + + return hook, ended, go + + +class TestTheUsersStop: + """``stop_by_user``: the user's stop of any instance of the conversation + (``/agent stop``): a running one's run cancelled by the user and waited for + to its end, an idle one stopped at once; only the user may start a stopped + instance's next run.""" + + async def test_a_running_ones_run_is_cancelled_by_the_user_and_waited_for(self): + hook, working, _ = blocking("researcher-1#1") + runs = AgentRuns() + made = delegations(hook, runs=runs) + turn = Turn(lambda: made.delegate(request())) + await asyncio.wait_for(working["researcher-1#1"].wait(), 5) + + stopped_it = await made.stop_by_user(CONVERSATION, "researcher-1") + + assert stopped_it is True + # It returned once the run had ended, outside any turn. + assert runs.instance(CONVERSATION, "researcher-1").status == INSTANCE_STOPPED + assert get_active_turn() is None + await asyncio.wait_for(turn.task, 5) + assert turn.result.result == { + "success": False, "agent": "researcher-1", "run": "researcher-1#1", + "status": RUN_CANCELLED, "partial": True, "result": "Half way.", + "error": "stopped by the user", "cancelled_by": "user", + } + ended = runs_of_status(turn.events, RUN_CANCELLED)[0] + assert ended.metadata["instance_status"] == INSTANCE_STOPPED + + async def test_an_idle_one_is_stopped_at_once_and_only_the_user_continues_it(self): + hook, asked = answering() + runs = AgentRuns() + made = delegations(hook, runs=runs) + await turned(lambda: made.delegate(request())) + + stopped_it, events = await turned(lambda: made.stop_by_user(CONVERSATION, "researcher-1")) + + assert stopped_it is True + assert instance_events(events) == [ + ("researcher-1", INSTANCE_STOPPED, "stopped by the user"), + ] + assert runs.instance(CONVERSATION, "researcher-1").status == INSTANCE_STOPPED + refused, _ = await turned(lambda: made.follow_up(follow())) + assert refused.result["error"] == ( + "researcher-1 was stopped by the user; only the user can continue it." + ) + went_on, _ = await turned(lambda: made.follow_up(users())) + assert went_on.result["status"] == RUN_COMPLETED + assert len(asked) == 2 + + async def test_a_run_whose_work_had_ended_ends_as_it_went_then_its_instance_is_stopped( + self, + ): + hook, ended, go = finishing() + runs = AgentRuns() + made = delegations(hook, runs=runs) + turn = Turn(lambda: made.delegate(request())) + await asyncio.wait_for(ended.wait(), 5) + + stopping = asyncio.create_task(made.stop_by_user(CONVERSATION, "researcher-1")) + await asyncio.sleep(0) + assert not stopping.done() # it waits for the run's end + go.set() + + assert await asyncio.wait_for(stopping, 5) is True + await asyncio.wait_for(turn.task, 5) + assert turn.result.result["status"] == RUN_COMPLETED + assert runs_of_status(turn.events, RUN_COMPLETED)[0].metadata["instance_status"] == ( + INSTANCE_IDLE + ) + assert runs.instance(CONVERSATION, "researcher-1").status == INSTANCE_STOPPED + + async def test_a_stopped_closed_or_unknown_one_is_left_as_it_is(self): + hook, working = waiting() + made = delegations(hook, types=WITH_CHECKER) + await stopped(made, working, by="user", error="stopped by the user") + made._hook, _ = answering() + await turned(lambda: made.delegate(request(CHECK, call_id="c2"))) + + async def each() -> list[bool]: + return [ + await made.stop_by_user(CONVERSATION, name) + for name in ("researcher-1", "checker-1", "writer-1") + ] + + results, events = await turned(each) + + assert (results, events) == ([False, False, False], []) + + +class TestTheUsersClose: + """``close_by_user``: the user's close of any instance of the conversation + (``/agent close``), with its descendants; a running one's run is stopped by + the user first and the instance closes as it ends.""" + + async def test_an_idle_one_is_closed_with_its_descendants(self): + made: Delegations + runs = AgentRuns() + made = delegations(with_a_leaf(lambda: made, {}), runs=runs) + await turned(lambda: made.delegate(request(PLAN))) + + closed, events = await turned(lambda: made.close_by_user(CONVERSATION, "middle-1")) + + assert closed == ["middle-1", "leaf-1"] + assert instance_events(events) == [ + ("middle-1", INSTANCE_CLOSED, "closed by the user"), + ("leaf-1", INSTANCE_CLOSED, "closed by the user"), + ] + + async def test_a_running_ones_run_is_stopped_and_it_closes_at_its_end(self): + made: Delegations + runs = AgentRuns() + working = {"middle-1#2": asyncio.Event()} + made = delegations(with_a_leaf(lambda: made, working), runs=runs) + await turned(lambda: made.delegate(request(PLAN))) + turn = Turn(lambda: made.follow_up(users("middle-1"))) + await asyncio.wait_for(working["middle-1#2"].wait(), 5) + + closed = await made.close_by_user(CONVERSATION, "middle-1") + + assert closed == ["middle-1", "leaf-1"] + await asyncio.wait_for(turn.task, 5) + ended = runs_of_status(turn.events, RUN_CANCELLED)[-1] + assert (ended.run.run, ended.metadata["cancelled_by"], ended.metadata["error"], + ended.metadata["instance_status"]) == ( + "middle-1#2", "user", "stopped by the user", INSTANCE_CLOSED, + ) + assert instance_events(turn.events) == [("leaf-1", INSTANCE_CLOSED, "closed by the user")] + assert {i.instance: i.status for i in runs.instances(CONVERSATION)} == { + "middle-1": INSTANCE_CLOSED, "leaf-1": INSTANCE_CLOSED, + } + + async def test_a_stopped_one_is_closed_and_a_closed_or_unknown_one_is_not(self): + hook, working = waiting() + made = delegations(hook) + await stopped(made, working, by="user", error="stopped by the user") + + async def each() -> list[list[str]]: + return [ + await made.close_by_user(CONVERSATION, name) + for name in ("researcher-1", "researcher-1", "writer-1") + ] + + results, _ = await turned(each) + + assert results == [["researcher-1"], [], []] + + async def test_neither_blocks_the_event_loop(self): + hook, working, _ = blocking("researcher-1#1") + made = delegations(hook) + turn = Turn(lambda: made.delegate(request())) + await asyncio.wait_for(working["researcher-1#1"].wait(), 5) + + with no_blocking_calls(): + assert await made.stop_by_user(CONVERSATION, "researcher-1") is True + assert await made.close_by_user(CONVERSATION, "researcher-1") == ["researcher-1"] + + await asyncio.wait_for(turn.task, 5) From ec4bedc9108cdab560439c145cf16129ab84aaf0 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:18:51 -0500 Subject: [PATCH 02/10] Contract: the user's follow-up, stop, close and steer of a sub-agent (failing) The harness makes the crew's conversation the manager's open one and stops any turn a failed scenario left running before the manager is cleaned up. The scenarios drive run_instance, stop_instance, close_instance and steer_instance on both backends. --- tests/workflow/test_subagents_contract.py | 305 +++++++++++++++++++++- 1 file changed, 303 insertions(+), 2 deletions(-) diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 5e3cfe45..1ec65e93 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -16,6 +16,10 @@ does. With ``SubAgentPolicy(follow_ups=True)`` (``FOLLOWING``) a parent has its own tools for its sub-agents, the real ones: ``message_agent`` (``message``), ``stop_agent`` (``stop``) and ``check_agents`` (``check``). +The user's control goes through the manager's entry points, on the open +conversation (the crew's: its settings' default user, its manager's session): +``run_instance`` (``user_turn``), ``stop_instance``, ``close_instance``, +``steer_instance`` and ``tell_root``. ``make_crew(..., store="sqlite")`` keeps the conversation in the default sqlite store, so a second crew is a restart: it loads the conversation's sub-agent records from the store; ``no_seals`` stops a turn @@ -487,6 +491,9 @@ class Crew: _instance_mark: Callable[[str], Awaitable[str]] | None = None _models: Callable[[str], list[str]] | None = None _opening: Callable[[str, int], list[str]] | None = None + #: The turns ``start`` started: one a failed test left running is stopped + #: before its manager is cleaned up (the cleanup waits for its turn). + started: list["asyncio.Task[Any]"] = field(default_factory=list) async def turn(self, text: str = "Go.") -> list[WorkflowEvent]: """One turn of the conversation, run to its end; its events.""" @@ -494,7 +501,9 @@ async def turn(self, text: str = "Go.") -> list[WorkflowEvent]: def start(self, text: str = "Go.") -> "asyncio.Task[list[WorkflowEvent]]": """A turn in a task of its own, to stop it as Ctrl+C does.""" - return asyncio.create_task(self.turn(text)) + task = asyncio.create_task(self.turn(text)) + self.started.append(task) + return task @staticmethod async def stop(turn: "asyncio.Task[Any]") -> None: @@ -651,8 +660,10 @@ def recorded(self, call_id: str, run: str | None = None) -> bool: def _settings(store: str = "memory", models: dict[str, Any] | None = None) -> BaseSettings: + """The crew's settings: its user is their default user, as the CLI's is.""" return BaseSettings( - session_store=store, default_model="claude-sonnet-4-6", models=dict(models or {}) + session_store=store, default_model="claude-sonnet-4-6", models=dict(models or {}), + default_user=USER, ) @@ -1079,11 +1090,16 @@ def make( complete[SUMMARIES] = list(scripts.get(SUMMARIES, ())) build = _adk_crew if backend == "adk" else _deepagents_crew crew = build(team, complete, monkeypatch, subagents, store, models) + # Its conversation is the open one (``session_ref()``), as the CLI's is. + crew.manager.session_id = SESSION made.append(crew) return crew yield make for crew in made: + for turn in crew.started: + if not turn.done(): + await Crew.stop(turn) await crew.manager.cleanup() @@ -5522,3 +5538,288 @@ async def test_at_most_its_cap_newest_first_in_whole_lines(self, make_crew): opened = crew.opening("coordinator", -1) assert opened == [roster(*fits), "Go."] assert 0 < len(fits) < 12 and len(opened[0]) <= ROSTER_MAX + + +# -- the user's control: a follow-up of the user's own, a stop, a close, a steer --------- + + +async def user_turn(crew: Crew, instance: str, message: str) -> list[WorkflowEvent]: + """The user's follow-up of ``instance`` (``run_instance``), run to its end; its events.""" + return [event async for event in crew.manager.run_instance(instance, message)] + + +class TestTheUsersFollowUp: + """``run_instance``: the user's follow-up of an instance, a turn of its own + on the open conversation: the instance's next run, ``started_by: user``, + on its transcript, counted toward no turn's runs; the root does not run.""" + + async def test_it_keeps_the_instances_history_and_streams_as_a_turn(self, make_crew): + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[calls(use("contract_lookup", "r1", q="X")), says("X is 42."), + says("Y is 7.")], + ) + await crew.turn() + + events = await user_turn(crew, "researcher-1", "Now find Y.") + + started, ended = runs_of(events) + assert started.run == SECOND + assert (started.metadata["started_by"], started.metadata["input"]) == ( + "user", "Now find Y." + ) + assert "call_id" not in started.metadata + assert (ended.metadata["status"], ended.metadata["result"], + ended.metadata["instance_status"]) == (RUN_COMPLETED, "Y is 7.", INSTANCE_IDLE) + assert [(e.content, e.run) for e in events if e.type is EventType.TEXT] == [ + ("Y is 7.", SECOND), + ] + # Its request holds the first run's work, the user's message last. + sent = crew.bodies("researcher")[2] + assert "Find X." in sent and "X is 42." in sent + assert crew.last_message("researcher", 2) == "Now find Y." + assert crew.requests("coordinator") == 2 + assert [(r.ref.run, r.status, r.started_by, r.input) for r in crew.records()] == [ + ("researcher-1#1", RUN_COMPLETED, "agent:root", ""), + ("researcher-1#2", RUN_COMPLETED, "user", "Now find Y."), + ] + assert crew.manager.instance_result("researcher-1") == { + "success": True, "agent": "researcher-1", "run": "researcher-1#2", + "status": RUN_COMPLETED, "partial": False, "result": "Y is 7.", "error": None, + } + + async def test_it_is_not_counted_toward_its_turns_runs(self, make_crew): + """With one run a turn, the instance's own delegation in the user's + turn runs: the user's follow-up took none of the turn's runs.""" + crew = make_crew( + nested_team(), + subagents=SubAgentPolicy(max_runs_per_turn=1), + coordinator=[calls(delegate("middle", "Plan X.", "c1")), says("Done.")], + middle=[says("Planned."), calls(delegate("leaf", "Look X up.", "m1")), + says("Looked it up.")], + leaf=[says("X is 42.")], + ) + await crew.turn() + + events = await user_turn(crew, "middle-1", "Look it up now.") + + assert [(e.run.run, e.metadata["status"]) for e in runs_of(events)] == [ + ("middle-1#2", RUN_STARTED), ("leaf-1#1", RUN_STARTED), + ("leaf-1#1", RUN_COMPLETED), ("middle-1#2", RUN_COMPLETED), + ] + assert envelope_read(crew.results_read("middle")["m1"])["result"] == "X is 42." + + async def test_it_starts_from_the_conversations_mark(self, make_crew): + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), + calls(use("contract_bring_outside_content", "c2")), says("Done.")], + researcher=[says("X is 42."), says("Went on.")], + ) + await crew.turn() + before = await crew.instance_mark("researcher-1") + + await user_turn(crew, "researcher-1", "Go on.") + + assert before == "" + assert await crew.instance_mark("researcher-1") == "contract_bring_outside_content" + + async def test_ctrl_c_stops_its_run_by_the_user_and_the_instance_is_stopped(self, make_crew): + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done."), + calls(follow("researcher-1", "Go on.", "c2")), says("Refused.")], + researcher=[says("X is 42."), calls(use("contract_block", "r1")), says("Went on.")], + ) + await crew.turn() + seen: list[WorkflowEvent] = [] + + async def view() -> None: + async for event in crew.manager.run_instance("researcher-1", "Wait here."): + seen.append(event) + + viewing = asyncio.create_task(view()) + await asyncio.wait_for(BLOCKING["started"].wait(), 10) + await Crew.stop(viewing) + + second = crew.records()[-1] + assert (second.ref.run, second.status, second.cancelled_by, second.error) == ( + "researcher-1#2", RUN_CANCELLED, "user", "stopped by the user", + ) + assert crew.instances() == [("researcher-1", INSTANCE_STOPPED)] + assert crew.manager.instance_result("researcher-1")["cancelled_by"] == "user" + # Its parent may not continue it; the user may, its stopped call answered once. + await crew.turn("Go on.") + assert json.loads(crew.results_read("coordinator")["c2"])["error"] == ( + "researcher-1 was stopped by the user; only the user can continue it." + ) + events = await user_turn(crew, "researcher-1", "Go on.") + assert runs_of(events)[-1].metadata["status"] == RUN_COMPLETED + assert [call for call, _ in crew.call_results("researcher", -1)] == ["r1"] + assert crew.instances() == [("researcher-1", INSTANCE_IDLE)] + + async def test_one_that_cannot_run_is_one_error_and_nothing_runs(self, make_crew): + crew = make_crew( + follow_team(continuable=False), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[says("X is 42.")], + ) + await crew.turn() + + refused = [ + [(e.type, e.content) for e in await user_turn(crew, instance, message)] + for instance, message in (("researcher-1", "Go on."), ("researcher-7", "Go on."), + ("researcher-1", " ")) + ] + + assert refused == [ + [(EventType.ERROR, "researcher-1 is closed; start a new one with task.")], + [(EventType.ERROR, "'researcher-7' is not one of your sub-agents. " + "Yours: researcher-1.")], + [(EventType.ERROR, "A follow-up needs a message.")], + ] + assert crew.requests("researcher") == 1 + assert crew.manager.instance_result("researcher-1") is None + + async def test_a_deleted_conversation_forgets_its_latest_result(self, make_crew): + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[says("X is 42."), says("Went on.")], + ) + await crew.turn() + await user_turn(crew, "researcher-1", "Go on.") + + await crew.manager.delete_session(SESSION, user_id=USER) + + assert crew.manager.instance_result("researcher-1") is None + + +class TestTheUsersStopAndClose: + """``stop_instance``: the user's stop (``cancelled_by: user``), the instance + ``stopped``, which only the user may continue; ``close_instance``: closed + with its descendants, its work kept. Both written to the store at once.""" + + async def test_a_running_one_is_stopped_from_outside_its_turn(self, make_crew): + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Wait.", "c1")), says("Stopped.")], + researcher=[calls(use("contract_block", "r1"))], + ) + turn = crew.start() + await asyncio.wait_for(BLOCKING["started"].wait(), 10) + + stopped = await crew.manager.stop_instance("researcher-1") + + assert stopped is True + assert crew.instances() == [("researcher-1", INSTANCE_STOPPED)] + await asyncio.wait_for(turn, 10) + read = envelope_read(crew.results_read("coordinator")["c1"]) + assert (read["status"], read["cancelled_by"], read["error"]) == ( + RUN_CANCELLED, "user", "stopped by the user" + ) + + async def test_an_idle_one_is_stopped_kept_so_and_its_parent_refused(self, make_crew): + crew = make_crew( + parent_team(), subagents=FOLLOWING, store="sqlite", + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done."), + calls(message("researcher-1", "Go on.", "c2")), says("Refused.")], + researcher=[says("X is 42."), says("Went on.")], + ) + await crew.turn() + + assert await crew.manager.stop_instance("researcher-1") is True + assert await crew.manager.stop_instance("researcher-1") is False + assert await crew.manager.stop_instance("researcher-9") is False + + stored = await crew.manager._load_agent_records(crew.conversation) + assert [(one["instance"], one["status"]) for one in stored["instances"]] == [ + ("researcher-1", INSTANCE_STOPPED), + ] + await crew.turn("Go on.") + assert json.loads(crew.results_read("coordinator")["c2"])["error"] == ( + "researcher-1 was stopped by the user; only the user can continue it." + ) + events = await user_turn(crew, "researcher-1", "Go on.") + assert runs_of(events)[-1].metadata["result"] == "Went on." + assert crew.instances() == [("researcher-1", INSTANCE_IDLE)] + + async def test_close_closes_it_and_its_sub_agents_and_nothing_runs_them(self, make_crew): + crew = make_crew( + [agent("coordinator", sub_agents=("researcher",)), + agent("researcher", sub_agents=("checker",)), agent("checker")], + store="sqlite", + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[calls(delegate("checker", "Check X.", "r1")), says("X is 42.")], + checker=[says("Checked.")], + ) + await crew.turn() + + closed = await crew.manager.close_instance("researcher-1") + + assert closed == ["researcher-1", "checker-1"] + assert await crew.manager.close_instance("researcher-1") == [] + assert crew.instances() == [ + ("researcher-1", INSTANCE_CLOSED), ("checker-1", INSTANCE_CLOSED), + ] + stored = await crew.manager._load_agent_records(crew.conversation) + assert {one["status"] for one in stored["instances"]} == {INSTANCE_CLOSED} + assert [(e.type, e.content) for e in await user_turn(crew, "researcher-1", "Again.")] == [ + (EventType.ERROR, "researcher-1 is closed; start a new one with task."), + ] + assert await crew.manager.stop_instance("researcher-1") is False + + async def test_a_running_one_closes_as_its_run_ends(self, make_crew): + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Wait.", "c1")), says("Closed.")], + researcher=[calls(use("contract_block", "r1"))], + ) + turn = crew.start() + await asyncio.wait_for(BLOCKING["started"].wait(), 10) + + closed = await crew.manager.close_instance("researcher-1") + + await asyncio.wait_for(turn, 10) + assert closed == ["researcher-1"] + assert crew.instances() == [("researcher-1", INSTANCE_CLOSED)] + assert envelope_read(crew.results_read("coordinator")["c1"])["cancelled_by"] == "user" + + +class TestTheUsersSteer: + async def test_a_running_run_takes_the_users_line_before_its_next_step(self, make_crew): + crew = make_crew( + parent_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[calls(use("contract_hold", "r1")), says("X is 42; Z is 9.")], + ) + turn = crew.start() + await asyncio.wait_for(HELD["started"].wait(), 10) + + steered = crew.manager.steer_instance("researcher-1", "Also find Z.") + HELD["go"].set() + await asyncio.wait_for(turn, 10) + + assert steered is True + assert crew.last_message("researcher", 1) == "Also find Z." + assert crew.manager.steer_instance("researcher-1", "Too late.") is False + assert crew.manager.steer_instance("researcher-9", "Who?") is False + + +class TestTheUsersControlOffTheLoop: + async def test_it_blocks_no_event_loop(self, make_crew): + crew = make_crew( + follow_team(), store="sqlite", + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[calls(use("contract_lookup", "r1", q="X")), says("X is 42."), + says("Went on.")], + ) + await crew.turn() + + with no_blocking_calls(): + events = await user_turn(crew, "researcher-1", "Go on.") + assert await crew.manager.stop_instance("researcher-1") is True + assert await crew.manager.close_instance("researcher-1") == ["researcher-1"] + + assert runs_of(events)[-1].metadata["result"] == "Went on." From cb2b3cf00afcc5842ac6c02fef51e72b30cb0794 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:21:11 -0500 Subject: [PATCH 03/10] Manager: the user's follow-up, stop, close and steer of a sub-agent run_instance runs the user's follow-up as a turn of its own, in a task it shields so that stopping its stream is the user's stop of the run (cancelled by the user, the instance stopped). stop_instance and close_instance cancel from outside, wait for the run's end and the records, and take no turn lock. steer_instance gives a running run the user's line. Each acts on the open conversation or the one session_id and user_id name. A run the user starts begins from the conversation's outside-content mark (_conversation_state, one hook per backend). --- src/agentic_cli/workflow/adk/manager.py | 16 ++ src/agentic_cli/workflow/base_manager.py | 214 +++++++++++++++++- .../workflow/deepagents/manager.py | 11 + 3 files changed, 237 insertions(+), 4 deletions(-) diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index 8a3d883b..1ce2e9ee 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -1778,6 +1778,22 @@ async def _conversation_exists(self, ref: SessionRef) -> bool: ) return session is not None + async def _conversation_state(self, ref: SessionRef) -> dict[str, Any]: + """The state a run the user starts in ``ref``'s conversation starts from. + + The conversation's outside-content mark: the session read whole (a + conversation from before 0.7.0 is told by its events) seeds the + marks as a turn does, then the mark the manager holds is the state's + ``OUTSIDE_CONTENT_KEY``, as a ``task`` call hands it to its run. + """ + session = await self._session_service.get_session( + app_name=ref.app_name, user_id=ref.user_id, session_id=ref.session_id, + ) + if session is not None: + self._seed_outside_content(ref, session) + mark = self._outside_marks.get(ref) + return {OUTSIDE_CONTENT_KEY: mark} if mark 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 aff43ceb..99318484 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -48,17 +48,27 @@ RoleMap, resolve_model, ) +from agentic_cli.workflow import live_events from agentic_cli.workflow.config import AgentConfig from agentic_cli.workflow.agents.delegate import ( + STOPPED_BY_USER_ERROR, + USER, AgentRun, + Delegated, Delegations, + FollowUpRequest, RunAnswer, waiting_on_user, ) from agentic_cli.workflow.agents.policy import SubAgentPolicy, as_policy from agentic_cli.workflow.agents.records import RecordsWriter from agentic_cli.workflow.agents.roster import Rosters -from agentic_cli.workflow.agents.runs import INSTANCE_CLOSED, RUN_END_STATUSES, AgentRuns +from agentic_cli.workflow.agents.runs import ( + INSTANCE_CLOSED, + INSTANCE_RUNNING, + RUN_END_STATUSES, + AgentRuns, +) from agentic_cli.workflow.usage import ( PURPOSE_MEMORY_EXTRACTION, PURPOSE_SIDE_CALL, @@ -214,7 +224,8 @@ class BaseWorkflowManager(ABC): Concurrency contract: A manager runs **one turn at a time**. ``process()``, - ``resume_with_job_result()`` and ``compact()`` enter through + ``resume_with_job_result()``, ``compact()`` and ``run_instance()`` + (the user's follow-up of a sub-agent) enter through ``_turn`` and serialize on an internal turn lock, so overlapping callers queue rather than interleave — the backend's per-invocation event buffers are manager-scoped, and interleaving would let one @@ -814,7 +825,8 @@ async def _deleting(self, conversation: SessionRef) -> AsyncGenerator[None, None marks it again). After it, unless it raised: its sub-agent records and their loading (``agent_runs``), the calls it recorded (``OpenCalls``: a failed - turn's too), its usage ledger, its main agent's roster and its + turn's too), its usage ledger, its main agent's roster, the latest + result of each instance the user ran (``instance_result``) and its numbering (``Delegations``), so a conversation of the same id starts as a new one. """ @@ -836,10 +848,204 @@ async def _deleting(self, conversation: SessionRef) -> AsyncGenerator[None, None open_calls.forget(conversation) self._usage_ledgers.forget(conversation) self._rosters.forget(conversation) + for key in [k for k in self._instance_results if k[0] == conversation]: + del self._instance_results[key] delegations = self.__dict__.get("_delegations_made") if delegations is not None: delegations.forget(conversation) + # ---- The user's control of the open conversation's sub-agents ---- + # + # What the CLI's ``/agent`` commands and an instance's view call + # (provisional). Each acts on the open conversation (``session_ref()``), + # or on the one its ``session_id`` and ``user_id`` name, as ``process`` + # takes them, on any of its instances, through ``Delegations``. + + @property + def _instance_results(self) -> dict[tuple[SessionRef, str], dict[str, Any]]: + """The latest envelope of each instance the user ran, by conversation and instance.""" + held = self.__dict__.get("_instance_results_held") + if held is None: + held = self.__dict__["_instance_results_held"] = {} + return held + + async def run_instance( + self, + instance: str, + message: str, + *, + session_id: str | None = None, + user_id: str | None = None, + ) -> AsyncGenerator[WorkflowEvent, None]: + """Run the user's follow-up of a sub-agent ``instance``, as a turn of its own (provisional). + + The instance's next run, on its transcript, ``started_by`` the user: + a turn of the conversation (``_turn``: the root does not run), whose + events are the run's (its ``AGENT_RUN`` start and end, its text, its + tool calls, its own sub-agents' runs). It is counted toward no + turn's runs (``max_runs_per_turn``) and starts from the + conversation's outside-content mark; a mark it brought marks the + conversation here. A stopped instance runs (only the user may); one + that is unknown, closed or running, or a blank message, is one + ``ERROR`` event and nothing runs. The run's full envelope is kept for + ``instance_result``. + + Stopping the stream (Ctrl+C cancels the consumer, or it closes the + generator) is the user's stop of the run: it ends ``cancelled`` by + the user and the instance is ``stopped``, inside the turn. + + Yields: + The run's ``WorkflowEvent``s. + + Raises: + Exception: The store's, when the conversation's sub-agent records + cannot be read (``load_agents``): nothing runs. + """ + async with self._turn(session_id, user_id) as ref: + request = FollowUpRequest( + instance=instance, message=message, started_by=USER, conversation=ref, + state=await self._conversation_state(ref), + ) + live = live_events.LiveEvents() + + def stop_it() -> None: + # Its consumer stopped (Ctrl+C): the user's stop of the run alone. + 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 source() -> AsyncGenerator[WorkflowEvent, None]: + # The run's own task: a stop cancels the run, not its caller, + # so it ends cancelled by the user, not interrupted. + work = asyncio.create_task( + self._delegations.follow_up(request), name=f"user run of {instance}" + ) + try: + delegated = await asyncio.shield(work) + except asyncio.CancelledError: + 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) + + 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 + + def _user_ran(self, ref: SessionRef, instance: str, delegated: Delegated) -> None: + """Take what a run the user started left: its mark on the conversation, its envelope.""" + for value in delegated.state.values(): + if isinstance(value, str) and value: + self._outside_marks.mark(ref, value) + self._instance_results[(ref, instance)] = dict(delegated.result) + + def instance_result( + self, instance: str, *, session_id: str | None = None, user_id: str | None = None + ) -> dict[str, Any] | None: + """The envelope of the latest run of ``instance`` that the user started (provisional). + + Kept in memory for the conversation (the records keep only the head + of a result); None when no run of the user's ended there, or after + the conversation was deleted. + """ + return self._instance_results.get((self.session_ref(session_id, user_id), instance)) + + async def stop_instance( + self, instance: str, *, session_id: str | None = None, user_id: str | None = None + ) -> bool: + """Stop the sub-agent ``instance`` for the user (provisional). + + A running instance's run (it works inside some turn, the root's or a + ``run_instance``'s) is cancelled from outside, ``cancelled_by`` the + user, and waited for: the instance is ``stopped`` and its records + written when this returns, which takes no turn lock. An idle one is + stopped at once. Only the user may start a stopped instance's next + run (``run_instance``); its parent's ``message_agent`` is refused. + + Returns: + False, doing nothing, for an instance that is unknown, closed or + stopped already. + + Raises: + Exception: The store's, when the conversation's sub-agent records + cannot be read: nothing is stopped. + """ + ref = self.session_ref(session_id, user_id) + await self.load_agents(ref) + stopped = await self._delegations.stop_by_user(ref, instance) + await self._agent_records_written(ref) + return stopped + + async def close_instance( + self, instance: str, *, session_id: str | None = None, user_id: str | None = None + ) -> list[str]: + """Close the sub-agent ``instance`` and its own sub-agents for the user (provisional). + + A closed instance takes no follow-up; its work stays readable. A + running one's run is stopped by the user first and the instance + closes as it ends, which this waits for; the records are written when + it returns, which takes no turn lock. + + Returns: + The ids closed, ``instance`` first; none for an instance that is + unknown or closed already. + + Raises: + Exception: The store's, when the conversation's sub-agent records + cannot be read: nothing is closed. + """ + ref = self.session_ref(session_id, user_id) + await self.load_agents(ref) + closed = await self._delegations.close_by_user(ref, instance) + await self._agent_records_written(ref) + return closed + + def steer_instance( + self, + instance: str, + message: str, + *, + session_id: str | None = None, + user_id: str | None = None, + ) -> bool: + """Give the user's ``message`` to ``instance``'s running run, before its next model step (provisional). + + Returns: + False when the instance has no running run (unknown, idle, + stopped, closed, or one that takes no more steps). + + Raises: + ValueError: ``message`` is not text, or blank. + """ + ref = self.session_ref(session_id, user_id) + record = self.agent_runs.instance(ref, instance) + if record is None or record.status != INSTANCE_RUNNING or not record.runs: + return False + steered = self._delegations.steer(ref, record.runs[-1], message) + if steered: + logger.info("subagent_steered", run=record.runs[-1], started_by=USER) + return steered + + async def _conversation_state(self, ref: SessionRef) -> dict[str, Any]: + """What a run the user starts in ``ref``'s conversation starts from (a backend hook). + + Its outside-content mark, under the key its backend's runs share it + by (the state a ``task`` call hands its run); the marks are seeded + from the conversation's own state first. The base has none. + """ + return {} + async def _run_agent(self, run: AgentRun) -> RunAnswer: """Run one sub-agent run to its end: the backend's hook (``Delegations``'s). @@ -2418,7 +2624,7 @@ 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``): the conversation is + ``resume_with_job_result``, ``compact``, ``run_instance``): 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 74df1c0a..21ce15db 100644 --- a/src/agentic_cli/workflow/deepagents/manager.py +++ b/src/agentic_cli/workflow/deepagents/manager.py @@ -506,6 +506,17 @@ async def _conversation_exists(self, ref: "SessionRef") -> bool: """ return self._sessions is not None and await self._sessions.exists(ref) + async def _conversation_state(self, ref: "SessionRef") -> dict[str, Any]: + """The state a run the user starts in ``ref``'s conversation starts from. + + The conversation's outside-content mark, seeded from its checkpoint + and read from the manager's marks, under the key its runs share it + by (the state a ``task`` call hands its run). + """ + self._outside_marks.seed(ref, await self._sessions.outside_content(ref)) + mark = self._outside_marks.get(ref) + return {"outside_content": mark} if mark else {} + async def _deliver_job_notice( self, notice: str, record: Any, result: Any, ref: "SessionRef" ) -> AsyncGenerator[WorkflowEvent, None]: From 0ac157b12bfc379131f477285355d58fa54f48b3 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:26:31 -0500 Subject: [PATCH 04/10] Manager: tell_root, a notice turn of the root, and the view's notice text tell_root runs the root on a notice the user did not type, marked as a job's notice is so recent_messages and the conversation's row leave it out; the outside-content mark a run the user started brought is written with it. On ADK the run carries RunConfig.custom_metadata, which ADK stamps on each event including the notice's user event; on Deep Agents the message's response_metadata says so. view_notice words what the root is told after the user worked with a sub-agent. --- src/agentic_cli/workflow/adk/manager.py | 54 +++++++++-- src/agentic_cli/workflow/adk/sessions.py | 23 ++++- src/agentic_cli/workflow/agents/envelope.py | 14 ++- src/agentic_cli/workflow/base_manager.py | 53 ++++++++++- .../workflow/deepagents/manager.py | 23 +++++ .../workflow/deepagents/sessions.py | 28 +++++- tests/workflow/deepagents/test_sessions.py | 22 +++++ tests/workflow/test_adk_session_rows.py | 7 ++ tests/workflow/test_agent_envelope.py | 19 ++++ tests/workflow/test_subagents_contract.py | 95 +++++++++++++++++++ 10 files changed, 319 insertions(+), 19 deletions(-) diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index 1ce2e9ee..34f3331c 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -70,9 +70,11 @@ from agentic_cli.workflow.adk.plugins import LLMLoggingPlugin, SentRequestLoggingPlugin from agentic_cli.workflow.adk.sessions import ( BRIEF_KEY, + NOTICE_METADATA, ServiceSessions, child_app, child_session_id, + is_notice, load_records, make_session_service, save_records, @@ -1394,14 +1396,16 @@ async def _run_and_stream( user_id: str, new_message: "types.Content", state_delta: dict[str, Any] | None = None, + custom_metadata: dict[str, Any] | None = None, ) -> AsyncGenerator[WorkflowEvent, None]: """Run the ADK runner for one invocation and stream WorkflowEvents. - Shared by ``process()`` (user message) and ``_deliver_job_notice()`` - (a job's notice). The caller - must already be inside the turn (the base's ``_turn``) with the + Shared by ``process()`` (user message), ``_deliver_job_notice()`` + (a job's notice) and ``_deliver_notice()`` (a notice to the root). The + caller must already be inside the turn (the base's ``_turn``) with the session prepared. ``state_delta`` is saved with ``new_message`` (a - user turn's row). + user turn's row). ``custom_metadata`` is stamped on every event of + the invocation by ADK (``RunConfig.custom_metadata``). What is reported from inside a model call (a summary that starts, its usage, what it did) is merged into the stream as it happens @@ -1427,13 +1431,18 @@ async def _run_and_stream( # Set when the turn is stopped: ADK then answers, as it closes, the # calls the invocation leaves open (InterruptedCallsPlugin words them). aborted = asyncio.Event() + run_config = self._run_config() + if custom_metadata: + run_config = (run_config or RunConfig()).model_copy( + update={"custom_metadata": custom_metadata} + ) with live_events.reporting(live): stream = self._runner.run_async( session_id=session_id, user_id=user_id, new_message=new_message, state_delta=state_delta, - run_config=self._run_config(), + run_config=run_config, abort_signal=aborted, ) try: @@ -1836,6 +1845,36 @@ async def _deliver_job_notice( async for event in events: yield event + async def _deliver_notice( + self, text: str, ref: SessionRef + ) -> AsyncGenerator[WorkflowEvent, None]: + """Run the agents on a notice to the root (the base's ``tell_root``). + + One user-role text, run as any user turn but not saved as a typed + prompt: its run is marked (``NOTICE_METADATA``), which ADK stamps on + the notice's own user event, so ``recent_messages`` and + ``typed_prompts`` leave it out. A call still open is answered first. + The mark this manager holds for the conversation is written with it + when the session's state lacks one: the root has read nothing of what + a run the user started brought before this notice. + """ + session = await self._get_or_create_session(ref.user_id, ref.session_id) + session = await self._answer_left_open(session) + state_delta = self._seed_outside_content(ref, session) + mark = self._outside_marks.get(ref) + if mark and not session.state.get(OUTSIDE_CONTENT_KEY): + state_delta[OUTSIDE_CONTENT_KEY] = mark + new_message = types.Content(role="user", parts=[types.Part.from_text(text=text)]) + async with contextlib.aclosing(self._run_and_stream( + session_id=ref.session_id, + user_id=ref.user_id, + new_message=new_message, + state_delta=state_delta or None, + custom_metadata=NOTICE_METADATA, + )) as events: + async for event in events: + yield event + @property def supports_compact(self) -> bool: """True unless the app is built and its main agent is not summarized. @@ -2005,7 +2044,8 @@ async def recent_messages( which its parent read as a tool result, not a reply. A job notice (``job_notice``) is left out, as on Deep Agents: nobody typed it. ADK keeps no mark on the message, so it is known by its - header. + header. A notice to the root (``tell_root``) is left out by its run's + mark (``is_notice``); the root's answer to it is kept. Args: session_id: Session to read. @@ -2036,7 +2076,7 @@ async def recent_messages( p.text for p in (getattr(content, "parts", None) or []) if getattr(p, "text", None) and not getattr(p, "thought", False) ) - if role == "user" and text.startswith(JOB_NOTICE_HEADER): + if role == "user" and (text.startswith(JOB_NOTICE_HEADER) or is_notice(event)): continue if text: out.append( diff --git a/src/agentic_cli/workflow/adk/sessions.py b/src/agentic_cli/workflow/adk/sessions.py index d50b15fd..cf6f6c3e 100644 --- a/src/agentic_cli/workflow/adk/sessions.py +++ b/src/agentic_cli/workflow/adk/sessions.py @@ -14,10 +14,11 @@ turn saves both, counting the turns it already had. Only what the user typed is a turn (``typed_prompts``): a text event of the -user's that is not a job's notice. ADK stores a summary (a compaction) as a -user event without content, a delegated request not at all, and a job's -result as a notice (``JOB_NOTICE_HEADER``), or, before the notice, a -function response; none of them is a typed prompt. +user's that is not a job's notice and not a notice to the root +(``NOTICE_METADATA``). ADK stores a summary (a compaction) as a user event +without content, a delegated request not at all, and a job's result as a +notice (``JOB_NOTICE_HEADER``), or, before the notice, a function response; +none of them is a typed prompt. The session hooks read the session service through ``ServiceSessions``, the manager's (``session_exists``, ``list_sessions``, ``session_info``, @@ -82,6 +83,12 @@ #: How many turns the user ran in it. TURNS_KEY = "agentic_cli.turns" +#: The mark of a notice to the root's run, which the user did not type +#: (``tell_root``): passed as ``RunConfig.custom_metadata``, which ADK stamps on +#: each event of the run, the notice's own user event among them, and stores +#: with it. +NOTICE_METADATA = {"agentic_cli": {"kind": "notice"}} + #: The state key of a conversation's sub-agent records, in its records session. RECORDS_KEY = "agentic_cli.agents" #: The state key an instance's first run sets with its message (the run's id), @@ -357,6 +364,12 @@ async def stored_instances( return counts +def is_notice(event: "Event") -> bool: + """Whether ``event`` was stored by a notice to the root's run (``NOTICE_METADATA``).""" + mark = (event.custom_metadata or {}).get("agentic_cli") + return isinstance(mark, dict) and mark.get("kind") == "notice" + + def typed_prompts(events: list["Event"]) -> list[str]: """The texts the user typed, oldest first.""" prompts: list[str] = [] @@ -364,6 +377,8 @@ def typed_prompts(events: list["Event"]) -> list[str]: content = event.content if event.author != "user" or content is None or content.role != "user": continue + if is_notice(event): + continue text = " ".join(part.text for part in content.parts or () if part.text and not part.thought) if text.strip() and not text.startswith(JOB_NOTICE_HEADER): prompts.append(text) diff --git a/src/agentic_cli/workflow/agents/envelope.py b/src/agentic_cli/workflow/agents/envelope.py index 520a5d78..4a212305 100644 --- a/src/agentic_cli/workflow/agents/envelope.py +++ b/src/agentic_cli/workflow/agents/envelope.py @@ -12,7 +12,9 @@ ``limit``). A run that did not complete fully (partial, failed, cancelled, interrupted) also names the tasks it left open, so its parent can continue it. ``read_envelope`` finds an envelope in a delegation's result as -either backend's ``TOOL_RESULT`` carries it. +either backend's ``TOOL_RESULT`` carries it. Once the user has worked with an +instance directly, the root is told its latest envelope in a notice +(``view_notice``). """ from __future__ import annotations @@ -35,6 +37,9 @@ #: Who may cancel a run: its parent, the user, or one of its limits. CANCELLED_BY = frozenset({"parent", "user", "limit"}) +#: What the root is told once the user has worked with one of its sub-agents directly. +VIEW_NOTICE = "The user worked with {instance} directly; its latest result: {envelope}" + #: The keys every envelope has, in the order it lists them. _KEYS = ("success", "agent", "run", "status", "partial", "result", "error") @@ -106,6 +111,13 @@ def open_task_descriptions(tasks: Sequence[Mapping[str, Any]]) -> list[str]: ] +def view_notice(instance: str, latest: Mapping[str, Any]) -> str: + """The notice that tells the root the user worked with ``instance``: its latest envelope as JSON.""" + return VIEW_NOTICE.format( + instance=instance, envelope=json.dumps(dict(latest), ensure_ascii=False) + ) + + def read_envelope(value: Any) -> dict[str, Any] | None: """The envelope in a delegation's result, as either backend's ``TOOL_RESULT`` carries it. diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index 99318484..5e9c8e20 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -224,8 +224,8 @@ class BaseWorkflowManager(ABC): Concurrency contract: A manager runs **one turn at a time**. ``process()``, - ``resume_with_job_result()``, ``compact()`` and ``run_instance()`` - (the user's follow-up of a sub-agent) enter through + ``resume_with_job_result()``, ``compact()``, ``run_instance()`` + (the user's follow-up of a sub-agent) and ``tell_root()`` enter through ``_turn`` and serialize on an internal turn lock, so overlapping callers queue rather than interleave — the backend's per-invocation event buffers are manager-scoped, and interleaving would let one @@ -1046,6 +1046,53 @@ async def _conversation_state(self, ref: SessionRef) -> dict[str, Any]: """ return {} + async def tell_root( + self, text: str, *, session_id: str | None = None, user_id: str | None = None + ) -> AsyncGenerator[WorkflowEvent, None]: + """Run the root agent on ``text``, a notice the user did not type (provisional). + + A turn of the conversation whose input is ``text`` as one user-role + message, marked as a job's notice is: ``recent_messages`` (and so + fact extraction) and the conversation's title and turns leave it out. + The root reads it and may answer; the outside-content mark this + manager holds for the conversation (what a run the user started + brought) is written with it. A turn that fails yields one ``ERROR``. + The notice after the user worked with a sub-agent is + ``agents/envelope.py::view_notice``. + + Yields: + The turn's ``WorkflowEvent``s. + + Raises: + NotImplementedError: The backend cannot (it has no + ``_deliver_notice``), raised as iteration starts, before any + turn. + """ + if type(self)._deliver_notice is BaseWorkflowManager._deliver_notice: + raise NotImplementedError( + f"{type(self).__name__} cannot tell its root agent a notice (tell_root)." + ) + async with self._turn(session_id, user_id) as ref: + async with contextlib.aclosing(self._deliver_notice(text, ref)) as events: + async for event in events: + yield event + + async def _deliver_notice( + self, text: str, ref: SessionRef + ) -> AsyncGenerator[WorkflowEvent, None]: + """Run the root agent on ``text`` as one user-role message marked as a notice (a backend hook). + + The base calls it inside the turn of ``ref``'s conversation (the + active turn, the services and the settings set). The message is + marked so ``recent_messages`` and the conversation's row leave it + out; the mark this manager holds for the conversation is written + with it when the conversation's state lacks one; each event goes + through ``_apply_event_hook``. Closing the generator stops the run. + """ + raise NotImplementedError(f"{type(self).__name__} cannot tell its root agent a notice.") + if False: # pragma: no cover - an async generator + yield # type: ignore[misc] + async def _run_agent(self, run: AgentRun) -> RunAnswer: """Run one sub-agent run to its end: the backend's hook (``Delegations``'s). @@ -2624,7 +2671,7 @@ 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``): the conversation is + ``resume_with_job_result``, ``compact``, ``run_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 21ce15db..bdb7f5ac 100644 --- a/src/agentic_cli/workflow/deepagents/manager.py +++ b/src/agentic_cli/workflow/deepagents/manager.py @@ -88,6 +88,7 @@ instance_run_config, instance_thread_id, job_notification, + notice_message, run_config, ) from agentic_cli.workflow.deepagents.summarization import ( @@ -547,6 +548,28 @@ async def _deliver_job_notice( async for event in events: yield event + async def _deliver_notice( + self, text: str, ref: "SessionRef" + ) -> AsyncGenerator[WorkflowEvent, None]: + """Run the root agent on a notice to it (the base's ``tell_root``). + + The turn's input is one ``HumanMessage`` (``sessions.notice_message``) + marked so ``recent_messages`` and the conversation's row leave it + out. A turn like any other: the pending notices open it, and the mark + this manager holds for the conversation (what a run the user started + brought) is written into the checkpoint with it, first write wins. + """ + self._outside_marks.seed(ref, await self._sessions.outside_content(ref)) + mark = self._outside_marks.get(ref) + for pending in self._take_notices(): + yield pending + async with contextlib.aclosing(self._run_turn( + ref, + {"messages": [notice_message(text)], **({"outside_content": mark} if mark else {})}, + )) as events: + async for event in events: + yield event + async def _compact_turn( self, session: "SessionRef", focus: str | None ) -> CompactResult | None: diff --git a/src/agentic_cli/workflow/deepagents/sessions.py b/src/agentic_cli/workflow/deepagents/sessions.py index 07844a56..9cdb7983 100644 --- a/src/agentic_cli/workflow/deepagents/sessions.py +++ b/src/agentic_cli/workflow/deepagents/sessions.py @@ -48,7 +48,8 @@ provider adapter sends. The model reads it as the rest of the conversation; ``recent`` leaves it out, because the user did not write it, and so does a conversation's row: its title is the first prompt the user typed, its turns -how many they typed. +how many they typed. A notice to the root (``notice_message``, ``tell_root``) +is marked and left out the same way (``is_notice``). ``open_sessions`` opens a store's conversations from the settings, without the manager, for ``workflow/session_readers.py``: the checkpointer and the @@ -119,6 +120,8 @@ #: The mark's ``kind`` on a job notification. JOB_RESULT = "job_result" +#: The mark's ``kind`` on a notice to the root the user did not type. +NOTICE = "notice" def thread_id(ref: SessionRef) -> str: @@ -210,6 +213,22 @@ def is_job_notification(message: BaseMessage) -> bool: return isinstance(mark, dict) and mark.get("kind") == JOB_RESULT +def notice_message(text: str) -> HumanMessage: + """The message that tells the root agent ``text``, a notice the user did not type. + + Marked in its ``response_metadata`` as a job notification is, which no + provider adapter sends: the model reads it, ``recent`` and a + conversation's row leave it out. + """ + return HumanMessage(content=text, response_metadata={_MARK: {"kind": NOTICE}}) + + +def is_notice(message: BaseMessage) -> bool: + """Whether ``message`` is a message the user did not type: a job notification or a notice to the root.""" + mark = message.response_metadata.get(_MARK) + return isinstance(mark, dict) and mark.get("kind") in (JOB_RESULT, NOTICE) + + class CheckpointSessions: """The session hooks, answered from a checkpointer and the index beside it. @@ -384,12 +403,13 @@ async def recent(self, ref: SessionRef, limit: int) -> list[dict]: Each is ``{"role": "user" | "assistant", "content": }``, the message's text blocks joined; tool calls and results, reasoning, - messages without text and job notifications are left out. + messages without text, job notifications and notices to the root + are left out. """ out: list[dict] = [] for message in _messages(await self._root(ref)): if isinstance(message, HumanMessage): - if is_job_notification(message): + if is_notice(message): continue role = "user" elif isinstance(message, AIMessage): @@ -679,7 +699,7 @@ def _row_of( typed = [ text for message in messages - if isinstance(message, HumanMessage) and not is_job_notification(message) + if isinstance(message, HumanMessage) and not is_notice(message) if (text := _text(message)) ] title = session_title(typed[0]) if typed else "" diff --git a/tests/workflow/deepagents/test_sessions.py b/tests/workflow/deepagents/test_sessions.py index 92f878b2..9dfd1b4c 100644 --- a/tests/workflow/deepagents/test_sessions.py +++ b/tests/workflow/deepagents/test_sessions.py @@ -53,6 +53,7 @@ instance_run_config, instance_thread_id, job_notification, + notice_message, ref_from_thread_id, run_config, thread_id, @@ -448,6 +449,17 @@ async def test_a_job_notification_is_no_turn(self, saver, store): assert (row.title, row.turns) == ("Build it.", 1) + async def test_a_notice_to_the_root_is_no_turn_and_no_title(self, saver, store): + root = _tree(saver, [SOLO], solo=[ai("Noted.")]) + await root.ainvoke({"messages": [notice_message("The user worked with x-1.")]}, + run_config(ref())) + await say(saver, ref(), "Build it.") + + (row,) = await CheckpointSessions(saver, store).list("app", "alice") + + assert (row.title, row.turns) == ("Build it.", 1) + + async def test_the_limit_keeps_the_newest(self, saver, store): await say(saver, ref(session="s1")) await say(saver, ref(session="s2")) @@ -659,6 +671,16 @@ async def test_an_unknown_session_has_none(self, saver, store): await say(saver, ref()) assert await CheckpointSessions(saver, store).recent(ref(user="bob"), 20) == [] + async def test_a_notice_to_the_root_is_left_out_and_its_answer_kept(self, saver, store): + await say(saver, ref(), "Tell me.", ai("Told.")) + root = _tree(saver, [SOLO], solo=[ai("Noted.")]) + await root.ainvoke({"messages": [notice_message("The user worked with x-1.")]}, + run_config(ref())) + + recent = await CheckpointSessions(saver, store).recent(ref(), 20) + + assert [m["content"] for m in recent] == ["Tell me.", "Told.", "Noted."] + # --- whole managers --------------------------------------------------------------------- diff --git a/tests/workflow/test_adk_session_rows.py b/tests/workflow/test_adk_session_rows.py index e5f58d55..5829e0a5 100644 --- a/tests/workflow/test_adk_session_rows.py +++ b/tests/workflow/test_adk_session_rows.py @@ -41,6 +41,7 @@ CHILD_APP_SUFFIX, MAX_KEY, TITLE_KEY, + NOTICE_METADATA, TURNS_KEY, child_app, child_session_id, @@ -130,6 +131,12 @@ def test_only_what_the_user_typed(self): assert typed_prompts(events) == ["Plan the trip.", "And the budget?"] + def test_a_notice_to_the_root_is_none(self): + notice = text_event("user", "The user worked with researcher-1 directly.") + notice.custom_metadata = dict(NOTICE_METADATA) + + assert typed_prompts([notice, text_event("user", "Go on.")]) == ["Go on."] + class TestRows: async def test_two_turns_give_the_first_prompt_and_two_turns(self, project, monkeypatch): diff --git a/tests/workflow/test_agent_envelope.py b/tests/workflow/test_agent_envelope.py index 18efa971..7407d96f 100644 --- a/tests/workflow/test_agent_envelope.py +++ b/tests/workflow/test_agent_envelope.py @@ -24,6 +24,7 @@ envelope, open_task_descriptions, read_envelope, + view_notice, ) from agentic_cli.workflow.agents.runs import ( RUN_CANCELLED, @@ -189,3 +190,21 @@ def test_a_cut_envelope_is_still_one(self): ]) def test_anything_else_is_none(self, value): assert read_envelope(value) is None + + +class TestTheViewNotice: + """What the root is told once the user has worked with one of its + sub-agents directly: the instance and its latest envelope, as JSON.""" + + def test_it_names_the_instance_and_carries_its_envelope_as_json(self): + latest = envelope(RESEARCHER, RUN_COMPLETED, result="Y is 7; ünïcode kept.") + + notice = view_notice("researcher-2", latest) + + assert notice == ( + "The user worked with researcher-2 directly; its latest result: " + '{"success": true, "agent": "researcher-2", "run": "researcher-2#1", ' + '"status": "completed", "partial": false, "result": "Y is 7; ünïcode kept.", ' + '"error": null}' + ) + assert json.loads(notice.split("its latest result: ", 1)[1]) == latest diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 1ec65e93..ccd1aeaf 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -87,6 +87,7 @@ TIME_LIMIT_ERROR, TOKEN_LIMIT_ERROR, read_envelope, + view_notice, ) from agentic_cli.workflow.config import AgentConfig from agentic_cli.workflow.events import ( @@ -5807,6 +5808,38 @@ async def test_a_running_run_takes_the_users_line_before_its_next_step(self, mak assert crew.manager.steer_instance("researcher-9", "Who?") is False +class TestTheConversationNamed: + """Each entry point acts on the open conversation (``session_ref()``), or + on the one its ``session_id`` and ``user_id`` name, as ``process`` takes + them: the CLI names its own.""" + + async def test_each_takes_the_conversation_its_ids_name(self, make_crew): + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done."), + says("Noted.")], + researcher=[says("X is 42."), says("Went on.")], + ) + await crew.turn() + crew.manager.session_id = "elsewhere" + named = {"session_id": SESSION, "user_id": USER} + + elsewhere = await user_turn(crew, "researcher-1", "Go on.") + events = [e async for e in crew.manager.run_instance("researcher-1", "Go on.", **named)] + + assert [e.type for e in elsewhere] == [EventType.ERROR] + assert runs_of(events)[-1].metadata["result"] == "Went on." + assert crew.manager.instance_result("researcher-1") is None + assert crew.manager.instance_result("researcher-1", **named)["result"] == "Went on." + assert crew.manager.steer_instance("researcher-1", "Also Z.", **named) is False + assert await crew.manager.stop_instance("researcher-1") is False + assert await crew.manager.stop_instance("researcher-1", **named) is True + assert await crew.manager.close_instance("researcher-1", **named) == ["researcher-1"] + told = [e async for e in crew.manager.tell_root("A notice.", **named)] + assert [e.content for e in told if e.type is EventType.TEXT] == ["Noted."] + + + class TestTheUsersControlOffTheLoop: async def test_it_blocks_no_event_loop(self, make_crew): crew = make_crew( @@ -5823,3 +5856,65 @@ async def test_it_blocks_no_event_loop(self, make_crew): assert await crew.manager.close_instance("researcher-1") == ["researcher-1"] assert runs_of(events)[-1].metadata["result"] == "Went on." + + +class TestANoticeToTheRoot: + """``tell_root``: a turn of the root on a notice the user did not type + (``view_notice``, once the user has worked with an instance), marked as + a job's notice is: left out of ``recent_messages`` and of the + conversation's row; the mark a user's run brought is written with it.""" + + async def test_the_root_answers_it_and_it_is_no_message_the_user_typed(self, make_crew): + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done."), + says("Noted: Y is 7.")], + researcher=[says("X is 42."), says("Y is 7.")], + ) + await crew.turn("Find X.") + await user_turn(crew, "researcher-1", "Now find Y.") + notice = view_notice("researcher-1", crew.manager.instance_result("researcher-1")) + + events = [event async for event in crew.manager.tell_root(notice)] + + assert [e.content for e in events if e.type is EventType.TEXT] == ["Noted: Y is 7."] + assert crew.last_message("coordinator") == notice + assert '"result": "Y is 7."' in notice + recent = await crew.manager.recent_messages(SESSION, user_id=USER) + assert [m["content"] for m in recent] == ["Find X.", "Done.", "Noted: Y is 7."] + info = await crew.manager.session_info(SESSION, user_id=USER) + assert (info.title, info.turns) == ("Find X.", 1) + + async def test_a_mark_a_users_run_brought_reaches_the_conversation_with_it(self, make_crew): + crew = make_crew( + [agent("coordinator", sub_agents=("researcher",)), + agent("researcher", tools=(contract_bring_outside_content,))], + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done."), + says("Noted.")], + researcher=[says("X is 42."), calls(use("contract_bring_outside_content", "r1")), + says("Read it.")], + ) + await crew.turn() + await user_turn(crew, "researcher-1", "Read the page.") + before = await crew.marked() + + [event async for event in crew.manager.tell_root( + view_notice("researcher-1", crew.manager.instance_result("researcher-1")) + )] + + assert before is False + assert await crew.marked() is True + + async def test_it_blocks_no_event_loop(self, make_crew): + crew = make_crew( + follow_team(), store="sqlite", + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done."), + says("Noted.")], + researcher=[says("X is 42.")], + ) + await crew.turn() + + with no_blocking_calls(): + events = [event async for event in crew.manager.tell_root("A notice.")] + + assert [e.content for e in events if e.type is EventType.TEXT] == ["Noted."] From 680b51dbee53976ba844ec2c6904b1e169d1bbd4 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:30:27 -0500 Subject: [PATCH 05/10] CLI: /agents picks a sub-agent; /agent shows, stops or closes one /agents is a picker of the conversation's instances, each followed by the ones it started; Enter shows the one picked as /agents does. /agent shows one, /agent stop and /agent close are the user's stop and close, each saying what it did or why not and acting on the app's own conversation. The runs table goes; its row checks move to the panel's tests. --- src/agentic_cli/cli/agents_command.py | 284 +++++++++++++++--------- src/agentic_cli/cli/app.py | 3 +- tests/cli/test_agents_command.py | 301 +++++++++++++++++++------- 3 files changed, 413 insertions(+), 175 deletions(-) diff --git a/src/agentic_cli/cli/agents_command.py b/src/agentic_cli/cli/agents_command.py index 000e89e1..4b99e82d 100644 --- a/src/agentic_cli/cli/agents_command.py +++ b/src/agentic_cli/cli/agents_command.py @@ -1,28 +1,34 @@ -"""``/agents``: the open conversation's sub-agent runs. - -``/agents`` lists them in a table, each run followed by the runs it -started, a level deeper: its instance (``researcher-2``), its type, its -status (while it works ``running``, ``queued`` waiting for a free working -slot, or ``needs you`` waiting on the user; a completion cut at its output -limit ``completed (partial)``), its run, its title, the tokens it used, and how -long it ran (or has been running). ``/agents `` shows one instance -(``researcher-2``) or one run (``researcher-2#1``): its type, its parent, -its title, then each run's status, the fields of its brief its parent filled -(its objective, deliverable, constraints, what was known, when it is done; a -follow-up's message in their place), -the first lines of its result, the plan and the task list it left (its own: -a run's plan and tasks are not its parent's), its error and its tokens by model. +"""``/agents`` and ``/agent``: the open conversation's sub-agents. + +``/agents`` is a picker of the conversation's instances: each one's id +(``researcher-2``), type, status (``running``, ``idle``, ``stopped`` or +``closed``) and title, each followed by the instances it started, a level +deeper. Enter shows the one picked, as ``/agents `` does: one instance +(``researcher-2``) or one run (``researcher-2#1``): its type, its parent, its +title, then each run's status (while it works ``running``, ``queued`` waiting +for a free working slot, or ``needs you`` waiting on the user; a completion +cut at its output limit ``completed (partial)``) and how long it ran (or has +been running), the fields of its brief its parent filled (its objective, +deliverable, constraints, what was known, when it is done; a follow-up's +message in their place), the first lines of its result, the plan and the +task list it left (its own: a run's plan and tasks are not its parent's), +its error and its tokens by model. + +``/agent `` shows one as well; ``/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. The runs are the manager's records (``BaseWorkflowManager.agent_runs``, ``workflow/agents/runs.py``), kept beside the conversation in its store and loaded with it (``load_agents``, asked here too, so a conversation resumed -from an earlier run of the app lists its runs before its first turn), and -the tokens its usage ledger's (``usage_of``), so a run still going shows +from an earlier run of the app lists its instances before its first turn), +and the tokens its usage ledger's (``usage_of``), so a run still going shows what it has used so far; a run from before a restart shows the totals its -record keeps, by model. An -instance runs again when it is followed up: a row per run, a follow-up titled -by its message's first line, and ``/agents `` of an instance shows every -run of it. +record keeps, by model. An instance runs again when it is followed up: +``/agents `` of an instance shows every run of it. The conversation the +commands act on is the app's own (``app.session_id``). """ from __future__ import annotations @@ -34,6 +40,7 @@ from rich.panel import Panel from rich.table import Table from rich.text import Text +from thinking_prompt import ChoiceField, Dialog from agentic_cli.cli.commands import Command, CommandCategory from agentic_cli.cli.usage_tracker import format_tokens, format_usage @@ -43,13 +50,29 @@ from agentic_cli.workflow.agents.runs import run_number if TYPE_CHECKING: - from agentic_cli.workflow.agents import RunRecord + from thinking_prompt import Placement + + from agentic_cli.workflow.agents import InstanceRecord, RunRecord + from agentic_cli.workflow.sessions import SessionRef from agentic_cli.workflow.usage import UsageLedger #: How many lines of a run's result ``/agents `` shows. RESULT_LINES = 3 #: What ``/agents`` says for a conversation with no run recorded. NO_RUNS = "No sub-agent runs in this conversation yet." +#: The title of ``/agents``'s picker. +PICKER_TITLE = "Sub-agents" +#: 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 " +SUBCOMMAND_USAGE = "Usage: /agent {subcommand} " +#: What ``/agent stop`` says it did. +STOPPED_TEXT = "Stopped {instance}: only you can start its next run." +#: What ``/agent close`` says it did (``whose``: ``its`` for one id, ``their`` for more). +CLOSED_TEXT = "Closed {ids}; /agents {instance} still shows {whose} work." +#: What ``/agent stop`` and ``/agent close`` say for an instance that is that already. +ALREADY_TEXT = "{instance} is {status} already." def _now() -> datetime: @@ -58,51 +81,152 @@ def _now() -> datetime: class AgentsCommand(Command): - """List the open conversation's sub-agent runs, or show one.""" + """Pick one of the open conversation's sub-agents, or show one.""" def __init__(self) -> None: super().__init__( name="agents", - description="List this conversation's sub-agent runs, or show one", + description="Pick one of this conversation's sub-agents, or show one", usage="/agents []", examples=["/agents", "/agents researcher-2", "/agents researcher-2#1"], category=CommandCategory.WORKFLOW, ) async def execute(self, args: str, app: Any) -> None: - """The runs in a table, or, with an instance or run id, that one.""" + """The instances in a picker (Enter shows one), or, with an id, that one.""" workflow = _workflow(app) if workflow is None: return conversation = workflow.session_ref(getattr(app, "session_id", None)) - try: - await workflow.load_agents(conversation) - except Exception as error: # noqa: BLE001 - the runs held are shown all the same - app.session.add_warning( - f"Sub-agent records not read from the store: {str(error) or type(error).__name__}" - ) - runs = workflow.agent_runs - records = runs.records(conversation) - ledger = workflow.usage_of(conversation) + await _load(app, workflow, conversation) parts = self.parse_args(args).positional.split() if parts: - wanted = parts[0] - found = runs.record(conversation, wanted) - if found is None: - app.session.add_warning( - f"No sub-agent {wanted} in this conversation. Type /agents for the list." - ) - return - # A run's id shows that run; an instance's, each of its runs. - mine = [found] if found.ref.run == wanted else [ - r for r in records if r.ref.instance == found.ref.instance - ] - app.session.add_rich(_one(mine, ledger)) + show(app, workflow, conversation, parts[0]) return - if not records: + instances = workflow.agent_runs.instances(conversation) + if not instances: app.session.add_message("system", NO_RUNS) return - app.session.add_rich(_table(records, ledger)) + dialog, ids = picker(instances, placement=_placement(app)) + picked = await app.session.show_dialog(dialog) + if picked is not None and picked in ids: + show(app, workflow, conversation, ids[picked]) + + +class AgentCommand(Command): + """Show, stop or close one of the open conversation's sub-agents.""" + + def __init__(self) -> None: + super().__init__( + name="agent", + description="Show, stop or close one of this conversation's sub-agents", + usage="/agent | stop | close ", + examples=["/agent researcher-2", "/agent stop researcher-2", "/agent close researcher-2"], + category=CommandCategory.WORKFLOW, + ) + + async def execute(self, args: str, app: Any) -> None: + """``/agent `` shows one; ``stop `` and ``close `` stop and close it.""" + workflow = _workflow(app) + if workflow is None: + return + conversation = workflow.session_ref(getattr(app, "session_id", None)) + parts = self.parse_args(args).positional.split() + if not parts: + app.session.add_warning(AGENT_USAGE) + return + word = parts[0] + if word not in ("stop", "close"): + await _load(app, workflow, conversation) + show(app, workflow, conversation, word) + return + if len(parts) < 2: + app.session.add_warning(SUBCOMMAND_USAGE.format(subcommand=word)) + return + wanted = parts[1] + if not await _load(app, workflow, conversation): + return # records that could not be read: nothing is tried on them + ids = {"session_id": conversation.session_id, "user_id": conversation.user_id} + if word == "stop": + if await workflow.stop_instance(wanted, **ids): + app.session.add_success(STOPPED_TEXT.format(instance=wanted)) + return + else: + closed = await workflow.close_instance(wanted, **ids) + if closed: + app.session.add_success(CLOSED_TEXT.format( + ids=", ".join(closed), instance=wanted, + whose="its" if len(closed) == 1 else "their", + )) + return + _left_as_it_is(app, workflow, conversation, wanted) + + +def picker( + instances: "list[InstanceRecord]", *, placement: "Placement | None" = None +) -> tuple[Dialog, dict[str, str]]: + """The dialog that lists ``instances``, and the instance id each option stands for. + + One option per instance, `` · · · ``, each + followed by the instances it started, two spaces deeper. Its only field + is a choice list, so Enter on an option closes it with that option, and + Esc with None. ``placement`` is where it is drawn (None: the session's). + """ + ids: dict[str, str] = {} + for level, one in _instances_in_tree(instances): + label = f"{' ' * level}{one.instance} · {one.agent} · {one.status}" + ids[f"{label} · {one.title}" if one.title else label] = one.instance + dialog = Dialog( + PICKER_TITLE, fields=[ChoiceField("agent", "", options=list(ids))], placement=placement + ) + return dialog, ids + + +def show(app: Any, workflow: Any, conversation: "SessionRef", wanted: str) -> None: + """Show the instance or run ``wanted`` (``researcher-2``, ``researcher-2#1``), or say there is none.""" + runs = workflow.agent_runs + found = runs.record(conversation, wanted) + if found is None: + app.session.add_warning(NO_SUCH_AGENT.format(id=wanted)) + return + # A run's id shows that run; an instance's, each of its runs. + mine = [found] if found.ref.run == wanted else [ + r for r in runs.records(conversation) if r.ref.instance == found.ref.instance + ] + app.session.add_rich(_one(mine, workflow.usage_of(conversation))) + + +async def _load(app: Any, workflow: Any, conversation: "SessionRef") -> bool: + """Load the conversation's records from its store; whether they were read. + + Not read: the user is told, and the runs the manager holds are shown all the same. + """ + try: + await workflow.load_agents(conversation) + except Exception as error: # noqa: BLE001 - the runs held are shown all the same + app.session.add_warning( + f"Sub-agent records not read from the store: {str(error) or type(error).__name__}" + ) + return False + return True + + +def _left_as_it_is(app: Any, workflow: Any, conversation: "SessionRef", wanted: str) -> None: + """Say why ``/agent stop`` or ``/agent close`` did nothing to ``wanted``.""" + record = workflow.agent_runs.instance(conversation, wanted) + if record is None: + app.session.add_warning(NO_SUCH_AGENT.format(id=wanted)) + return + app.session.add_message( + "system", ALREADY_TEXT.format(instance=wanted, status=record.status) + ) + + +def _placement(app: Any) -> "Placement | None": + """Where ``/agents``'s picker is drawn: the ``dialog_placement`` setting now + (``/settings`` may have changed it since the session started); the session's own without one.""" + settings = getattr(app, "settings", None) + return None if settings is None else settings.dialog_placement def _workflow(app: Any) -> Any: @@ -118,31 +242,6 @@ def _workflow(app: Any) -> Any: return workflow -def _table(records: list["RunRecord"], ledger: "UsageLedger") -> Table: - """``/agents``'s table: every run, each followed by the runs it started.""" - table = Table(title="Sub-agents", show_lines=False, padding=(0, 1)) - table.add_column("Agent", style="bold cyan", no_wrap=True) - table.add_column("Type", no_wrap=True) - table.add_column("Status", no_wrap=True) - table.add_column("Run", style="dim", no_wrap=True) - table.add_column("Title") # the terminal's own color: readable on every theme - table.add_column("Tokens in/out", style="dim", no_wrap=True, justify="right") - table.add_column("Time", style="dim", no_wrap=True, justify="right") - now = _now() - for level, record in _in_tree(records): - # Names and titles are data: Text, never markup. - table.add_row( - Text(" " * level + record.ref.instance), - Text(record.ref.agent), - _status(record), - _run_number(record), - Text(record.title), - _tokens(record, ledger), - _duration(record, now), - ) - return table - - def _one(records: list["RunRecord"], ledger: "UsageLedger") -> Panel: """``/agents <id>``'s panel: one instance's runs (one run's, for a run id).""" first = records[0] @@ -178,21 +277,21 @@ def _one(records: list["RunRecord"], ledger: "UsageLedger") -> Panel: ) -def _in_tree(records: list["RunRecord"]) -> list[tuple[int, "RunRecord"]]: - """The runs in the order they started, each followed by the runs it - started, one level deeper. A run whose parent is not listed (the root's, +def _instances_in_tree(instances: "list[InstanceRecord]") -> list[tuple[int, "InstanceRecord"]]: + """The instances in the order they started, each followed by the ones it + started, one level deeper. One whose parent is not listed (the root's, or one gone) is at the top.""" - listed = {record.ref.run for record in records} - started: dict[str | None, list["RunRecord"]] = {} - for record in records: - parent = record.ref.parent_run if record.ref.parent_run in listed else None - started.setdefault(parent, []).append(record) - ordered: list[tuple[int, "RunRecord"]] = [] + listed = {one.instance for one in instances} + started: dict[str | None, list["InstanceRecord"]] = {} + for one in instances: + parent = one.parent if one.parent in listed else None + started.setdefault(parent, []).append(one) + ordered: list[tuple[int, "InstanceRecord"]] = [] def follow(parent: str | None, level: int) -> None: - for record in started.get(parent, ()): - ordered.append((level, record)) - follow(record.ref.run, level + 1) + for one in started.get(parent, ()): + ordered.append((level, one)) + follow(one.instance, level + 1) follow(None, 0) return ordered @@ -221,23 +320,6 @@ def _run_number(record: "RunRecord") -> str: return "#" + run_number(record.ref.run or "") -def _tokens(record: "RunRecord", ledger: "UsageLedger") -> str: - """A run's tokens in and out; ``—`` before its first model call ends. - - The ledger's, else (a run from before a restart: the ledger is this - manager's) the totals its record keeps. - """ - totals = ledger.totals(run=record.ref.run) - if totals.calls: - return f"{format_tokens(totals.input)} / {format_tokens(totals.output)}" - if not record.usage: - return "—" - used = record.usage.values() - spent_in = sum(model.get("input", 0) for model in used) - spent_out = sum(model.get("output", 0) for model in used) - return f"{format_tokens(spent_in)} / {format_tokens(spent_out)}" - - def _tokens_by_model(record: "RunRecord", ledger: "UsageLedger") -> list[str]: """A run's tokens, a line per model: the ledger's, else its record's (no call count).""" by_model = ledger.by_model(run=record.ref.run) diff --git a/src/agentic_cli/cli/app.py b/src/agentic_cli/cli/app.py index 27f9d03a..8f7936ef 100644 --- a/src/agentic_cli/cli/app.py +++ b/src/agentic_cli/cli/app.py @@ -897,7 +897,7 @@ def _register_builtin_commands(self) -> None: NewCommand, ModelsCommand, ) - from agentic_cli.cli.agents_command import AgentsCommand + from agentic_cli.cli.agents_command import AgentCommand, AgentsCommand from agentic_cli.cli.memory_command import MemoryCommand from agentic_cli.cli.settings_command import SettingsCommand @@ -908,6 +908,7 @@ def _register_builtin_commands(self) -> None: self.command_registry.register(SandboxCommand()) self.command_registry.register(JobsCommand()) self.command_registry.register(AgentsCommand()) + self.command_registry.register(AgentCommand()) self.command_registry.register(ResumeSessionCommand()) self.command_registry.register(SettingsCommand()) self.command_registry.register(PapersCommand()) diff --git a/tests/cli/test_agents_command.py b/tests/cli/test_agents_command.py index ab10b0d8..49895f1f 100644 --- a/tests/cli/test_agents_command.py +++ b/tests/cli/test_agents_command.py @@ -1,15 +1,17 @@ """``/agents``: the open conversation's sub-agent runs (``cli/agents_command.py``). -``/agents`` is a table of the runs, each followed by the runs it started, a -level deeper: instance, type, status, run, title, tokens in/out, time. -``/agents <id>`` shows one instance or run: its type, parent and title, then -each run's status and time, its brief's other fields (a follow-up's message), -the first lines of its result, its error and its tokens by model. An instance -that was followed up shows a row per run. The runs are a real manager's records, filled as its event -processors fill them (``AgentRuns.observe`` under the conversation's turn), -and the tokens its usage ledger's; nothing reaches a provider. A manager that -did not run them (a restart) loads them from the conversation's store as -``/agents`` asks, each run's tokens its record's. +``/agents`` is a picker of the instances (id, type, status, title, each +followed by the ones it started), and Enter shows one as ``/agents <id>`` +does: one instance or run: its type, parent and title, then each run's +status and time, its brief's other fields (a follow-up's message), the first +lines of its result, its error and its tokens by model. An instance that was +followed up shows every run in its panel. ``/agent <id>`` shows one, +``/agent stop <id>`` and ``/agent close <id>`` are the user's stop and close, +each saying what it did or why not. The runs are a real manager's records, +filled as its event processors fill them (``AgentRuns.observe`` under the +conversation's turn), and the tokens its usage ledger's; nothing reaches a +provider. A manager that did not run them (a restart) loads them from the +conversation's store as ``/agents`` asks, each run's tokens its record's. """ from __future__ import annotations @@ -22,7 +24,7 @@ from rich.console import Console from agentic_cli.cli import agents_command -from agentic_cli.cli.agents_command import NO_RUNS, AgentsCommand +from agentic_cli.cli.agents_command import AGENT_USAGE, NO_RUNS, AgentCommand, AgentsCommand from agentic_cli.cli.commands import CommandCategory, CommandRegistry from agentic_cli.config import BaseSettings from agentic_cli.workflow.adk.manager import GoogleADKWorkflowManager @@ -142,60 +144,85 @@ def crew_ran(manager: GoogleADKWorkflowManager) -> None: runs.end(fetcher, "failed", at=55, error="overloaded") -async def agents(manager, args: str = "", *, session_id: str = "s1"): - """Run ``/agents <args>`` in an app whose conversation is ``session_id``.""" +async def agents(manager, args: str = "", *, session_id: str = "s1", picked=None): + """Run ``/agents <args>`` in an app whose conversation is ``session_id``; + its picker answers ``picked(options)`` (None: Esc).""" app = SimpleNamespace(workflow=manager, session_id=session_id, session=autospec_session()) + + async def show_dialog(dialog): + return picked(dialog.fields[0].options) if picked is not None else None + + app.session.show_dialog.side_effect = show_dialog await AgentsCommand().execute(args, app) return app.session +async def agent(manager, args: str, *, session_id: str = "s1"): + """Run ``/agent <args>`` in an app whose conversation is ``session_id`` + (the workflow's own is another: a workflow that started after the app + opened its conversation never loaded it).""" + app = SimpleNamespace(workflow=manager, session_id=session_id, session=autospec_session()) + await AgentCommand().execute(args, app) + return app.session + + + def rows_of(table) -> list[tuple[str, ...]]: """A rich table's rows, as text.""" columns = [[str(cell) for cell in column.cells] for column in table.columns] return list(zip(*columns)) -class TestTheList: - async def test_every_run_each_followed_by_the_runs_it_started(self, manager): +def options_of(session) -> list[str]: + """The options of the picker ``/agents`` showed.""" + (dialog,) = session.show_dialog.call_args.args + (field,) = dialog.fields + return list(field.options) + + +class TestThePicker: + async def test_each_instance_its_type_status_and_title_its_sub_agents_under_it( + self, manager + ): crew_ran(manager) session = await agents(manager) - (table,) = session.add_rich.call_args.args - assert table.title == "Sub-agents" - assert [column.header for column in table.columns] == [ - "Agent", "Type", "Status", "Run", "Title", "Tokens in/out", "Time", - ] - assert rows_of(table) == [ - ("researcher-1", "researcher", "completed", "#1", "Find X.", "1.3k / 310", "12s"), - (" writer-1", "writer", "completed (partial)", "#1", "Draft it.", "800 / 2k", "40s"), - ("researcher-2", "researcher", "running", "#1", "Find Y.", "—", "10s"), - ("checker-1", "checker", "refused", "#1", "Check it.", "—", "1s"), - ("fetcher-1", "fetcher", "failed", "#1", "Fetch Z.", "—", "2s"), + (dialog,) = session.show_dialog.call_args.args + assert dialog.title == "Sub-agents" + assert options_of(session) == [ + "researcher-1 · researcher · idle · Find X.", + " writer-1 · writer · idle · Draft it.", + "researcher-2 · researcher · running · Find Y.", + "checker-1 · checker · idle · Check it.", + "fetcher-1 · fetcher · idle · Fetch Z.", ] + session.add_rich.assert_not_called() - async def test_a_working_run_says_whether_it_works_waits_for_a_slot_or_needs_the_user( - self, manager - ): - runs = Runs(manager, manager.session_ref("s1")) - runs.start("researcher", "c1", "Find X.", at=0) - queued = runs.start("researcher", "c2", "Find Y.", at=1) - runs.now(queued, "queued", at=1) - asking = runs.start("researcher", "c3", "Find Z.", at=2) - runs.now(asking, "input_required", at=30) + async def test_enter_shows_the_one_picked_as_agents_id_does(self, manager): + crew_ran(manager) + + picked = await agents(manager, picked=lambda options: options[1]) + shown = await agents(manager, "writer-1") + + (panel,) = picked.add_rich.call_args.args + (same,) = shown.add_rich.call_args.args + assert str(panel.title) == "[bold]writer-1[/bold]" + assert rows_of(panel.renderable) == rows_of(same.renderable) + + async def test_escape_shows_nothing(self, manager): + crew_ran(manager) session = await agents(manager) - (table,) = session.add_rich.call_args.args - assert [(row[0], row[2]) for row in rows_of(table)] == [ - ("researcher-1", "running"), ("researcher-2", "queued"), ("researcher-3", "needs you"), - ] + session.add_rich.assert_not_called() + session.add_warning.assert_not_called() async def test_a_conversation_without_runs_says_so(self, manager): session = await agents(manager) session.add_message.assert_called_once_with("system", NO_RUNS) - session.add_rich.assert_not_called() + session.show_dialog.assert_not_called() async def test_another_conversations_runs_are_not_listed(self, manager): crew_ran(manager) @@ -204,31 +231,16 @@ async def test_another_conversations_runs_are_not_listed(self, manager): session.add_message.assert_called_once_with("system", NO_RUNS) - async def test_a_title_is_shown_as_written(self, manager): - """Titles are the model's words: markup in one is text, never style.""" + async def test_an_instance_with_follow_ups_is_one_option(self, manager): runs = Runs(manager, manager.session_ref("s1")) - runs.start("researcher", "c1", "Fix [/x] and [bold]this[/bold]", at=0) - - session = await agents(manager) - - (table,) = session.add_rich.call_args.args - out = io.StringIO() - Console(file=out, width=200, color_system=None).print(table) - assert "Fix [/x] and [bold]this[/bold]" in out.getvalue() - - @pytest.mark.parametrize( - "seconds, shown", - [(0, "0s"), (59, "59s"), (60, "1m 00s"), (185, "3m 05s"), (3_725, "1h 02m")], - ) - async def test_the_time_a_run_took(self, manager, seconds, shown): - runs = Runs(manager, manager.session_ref("s1")) - ref = runs.start("researcher", "c1", "Find X.", at=0) - runs.end(ref, "completed", at=seconds, result="X.") + first = runs.start("researcher", "c1", "Find X.", at=0) + runs.end(first, "completed", at=5, result="X is 42.") + second = runs.follow("researcher-1", "c2", "Now find Y.", at=10) + runs.end(second, "completed", at=15, result="Y is 7.") session = await agents(manager) - (table,) = session.add_rich.call_args.args - assert rows_of(table)[0][-1] == shown + assert options_of(session) == ["researcher-1 · researcher · idle · Find X."] class TestOne: @@ -347,14 +359,8 @@ async def test_an_instances_follow_up_shows_its_message(self, manager): second = runs.follow("researcher-1", "c2", "Now find Y.\nThe same way.", at=10) runs.end(second, "completed", at=15, result="Y is 7.") - listed = await agents(manager) shown = await agents(manager, "researcher-1") - (table,) = listed.add_rich.call_args.args - assert [row[:5] for row in rows_of(table)] == [ - ("researcher-1", "researcher", "completed", "#1", "Find X."), - ("researcher-1", "researcher", "completed", "#2", "Now find Y."), - ] (panel,) = shown.add_rich.call_args.args assert rows_of(panel.renderable) == [ ("Type", "researcher"), @@ -367,6 +373,55 @@ async def test_an_instances_follow_up_shows_its_message(self, manager): (" Result", "Y is 7."), ] + async def test_a_working_run_says_whether_it_works_waits_for_a_slot_or_needs_the_user( + self, manager + ): + runs = Runs(manager, manager.session_ref("s1")) + runs.start("researcher", "c1", "Find X.", at=0) + queued = runs.start("researcher", "c2", "Find Y.", at=1) + runs.now(queued, "queued", at=1) + asking = runs.start("researcher", "c3", "Find Z.", at=2) + runs.now(asking, "input_required", at=30) + + shown = [await agents(manager, name) + for name in ("researcher-1", "researcher-2", "researcher-3")] + + panels = [session.add_rich.call_args.args[0] for session in shown] + assert [rows_of(panel.renderable)[3] for panel in panels] == [ + ("Run #1", "running · 1m 00s"), ("Run #1", "queued · 59s"), + ("Run #1", "needs you · 58s"), + ] + + async def test_a_title_is_shown_as_written(self, manager): + """Titles are the model's words: markup in one is text, never style.""" + runs = Runs(manager, manager.session_ref("s1")) + runs.start("researcher", "c1", "Fix [/x] and [bold]this[/bold]", at=0) + + listed = await agents(manager) + shown = await agents(manager, "researcher-1") + + assert options_of(listed) == [ + "researcher-1 · researcher · running · Fix [/x] and [bold]this[/bold]", + ] + (panel,) = shown.add_rich.call_args.args + out = io.StringIO() + Console(file=out, width=200, color_system=None).print(panel) + assert "Fix [/x] and [bold]this[/bold]" in out.getvalue() + + @pytest.mark.parametrize( + "seconds, shown", + [(0, "0s"), (59, "59s"), (60, "1m 00s"), (185, "3m 05s"), (3_725, "1h 02m")], + ) + async def test_the_time_a_run_took(self, manager, seconds, shown): + runs = Runs(manager, manager.session_ref("s1")) + ref = runs.start("researcher", "c1", "Find X.", at=0) + runs.end(ref, "completed", at=seconds, result="X.") + + session = await agents(manager, "researcher-1") + + (panel,) = session.add_rich.call_args.args + assert rows_of(panel.renderable)[3] == ("Run #1", f"completed · {shown}") + async def test_an_unknown_id_says_so(self, manager): crew_ran(manager) @@ -397,13 +452,15 @@ async def test_the_stored_runs_are_listed_with_their_tokens(self, manager): ) listed = await agents(manager) + interrupted = await agents(manager, "researcher-2") shown = await agents(manager, "researcher-1") - (table,) = listed.add_rich.call_args.args - assert [row[:6] for row in rows_of(table)] == [ - ("researcher-1", "researcher", "completed", "#1", "Find X.", "1.3k / 310"), - ("researcher-2", "researcher", "interrupted", "#1", "Find Y.", "—"), + assert options_of(listed) == [ + "researcher-1 · researcher · idle · Find X.", + "researcher-2 · researcher · idle · Find Y.", ] + (label, value) = rows_of(interrupted.add_rich.call_args.args[0].renderable)[3] + assert (label, value.split(" · ")[0]) == ("Run #1", "interrupted") (panel,) = shown.add_rich.call_args.args assert rows_of(panel.renderable)[-2:] == [ (" Tokens", f"{SONNET}: 1.2k in / 300 out"), @@ -424,8 +481,7 @@ async def unreadable(conversation: SessionRef) -> None: session.add_warning.assert_called_once_with( "Sub-agent records not read from the store: disk unreadable" ) - (table,) = session.add_rich.call_args.args - assert len(rows_of(table)) == 5 + assert len(options_of(session)) == 5 async def test_an_error_without_a_message_is_named_by_its_type(self, manager, monkeypatch): @@ -439,6 +495,92 @@ async def unreadable(conversation: SessionRef) -> None: "Sub-agent records not read from the store: TimeoutError" ) +class TestTheAgentCommand: + """``/agent <id>`` shows one sub-agent; ``/agent stop <id>`` and ``/agent + close <id>`` stop and close it, each saying what it did or why not.""" + + async def test_an_id_alone_shows_it_as_agents_id_does(self, manager): + crew_ran(manager) + + shown = await agent(manager, "researcher-1") + same = await agents(manager, "researcher-1") + + (panel,) = shown.add_rich.call_args.args + assert rows_of(panel.renderable) == rows_of(same.add_rich.call_args.args[0].renderable) + + async def test_stop_stops_an_idle_one_and_says_only_the_user_continues_it(self, manager): + crew_ran(manager) + + session = await agent(manager, "stop researcher-1") + + session.add_success.assert_called_once_with( + "Stopped researcher-1: only you can start its next run." + ) + conversation = manager.session_ref("s1") + assert manager.agent_runs.instance(conversation, "researcher-1").status == "stopped" + assert options_of(await agents(manager))[0] == ( + "researcher-1 · researcher · stopped · Find X." + ) + + async def test_close_closes_it_and_its_sub_agents_and_says_its_work_stays(self, manager): + crew_ran(manager) + + session = await agent(manager, "close researcher-1") + + session.add_success.assert_called_once_with( + "Closed researcher-1, writer-1; /agents researcher-1 still shows their work." + ) + assert options_of(await agents(manager))[:2] == [ + "researcher-1 · researcher · closed · Find X.", + " writer-1 · writer · closed · Draft it.", + ] + + async def test_each_says_why_it_did_nothing(self, manager): + crew_ran(manager) + await agent(manager, "stop researcher-1") + await agent(manager, "close checker-1") + + said = [ + await agent(manager, args) + for args in ("stop researcher-1", "stop checker-1", "close checker-1", + "stop nobody-1", "close nobody-1") + ] + + assert [s.add_message.call_args.args for s in said[:3]] == [ + ("system", "researcher-1 is stopped already."), + ("system", "checker-1 is closed already."), + ("system", "checker-1 is closed already."), + ] + assert [s.add_warning.call_args.args for s in said[3:]] == [ + ("No sub-agent nobody-1 in this conversation. Type /agents for the list.",), + ] * 2 + assert not any(s.add_success.called for s in said) + + async def test_without_an_id_it_says_how(self, manager): + said = [await agent(manager, args) for args in ("", "stop", "close")] + + assert [s.add_warning.call_args.args for s in said] == [ + (AGENT_USAGE,), ("Usage: /agent stop <id>",), ("Usage: /agent close <id>",), + ] + + async def test_records_that_cannot_be_read_stop_nothing(self, manager, monkeypatch): + crew_ran(manager) + + async def unreadable(conversation: SessionRef) -> None: + raise OSError("disk unreadable") + + monkeypatch.setattr(manager, "load_agents", unreadable) + session = await agent(manager, "stop researcher-1") + + session.add_warning.assert_called_once_with( + "Sub-agent records not read from the store: disk unreadable" + ) + session.add_success.assert_not_called() + assert manager.agent_runs.instance(manager.session_ref("s1"), "researcher-1").status == ( + "idle" + ) + + class _Down: """An app whose workflow is not running.""" @@ -471,6 +613,15 @@ 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): + app = _Down(None) + + await AgentCommand().execute("stop researcher-1", app) + + app.session.add_warning.assert_called_once_with( + "Sub-agent runs not available (initializing...)." + ) + def test_it_is_a_built_in_workflow_command(): from agentic_cli.cli.app import BaseCLIApp @@ -482,3 +633,7 @@ def test_it_is_a_built_in_workflow_command(): assert isinstance(command, AgentsCommand) assert command.category is CommandCategory.WORKFLOW assert command.usage == "/agents [<id>]" + one = registry.get("agent") + assert isinstance(one, AgentCommand) + assert one.category is CommandCategory.WORKFLOW + assert one.usage == "/agent <id> | stop <id> | close <id>" From 4fe675284bd68bf8ecef238def36bc555b62fc36 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:31:13 -0500 Subject: [PATCH 06/10] Docs: the user's control of sub-agents --- CHANGELOG.md | 48 +++++++++++++++++++++++++++++++++++------------- CLAUDE.md | 12 ++++++------ README.md | 14 +++++++++++++- 3 files changed, 54 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38ea75a5..508c7678 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -575,6 +575,29 @@ the start of the entry's title. ### Added +- **The user's control of sub-agents: `/agent stop`, `/agent close`, and the + manager's entry points.** `/agent stop <id>` stops one of the + conversation's sub-agents: its run, if one works, is cancelled by the user + (`cancelled_by: user`), and the instance is `stopped` (an idle one at once): + its parent's `message_agent` is refused, and only the user may start its + next run. `/agent close <id>` closes it and its own sub-agents: no more + runs, its work still shown by `/agents <id>`. `/agent <id>` shows it. Each + says what it did, or why not. The manager's entry points (provisional; the + open conversation, or the one `session_id`/`user_id` name, any of its + instances): `run_instance(instance, message)`, the user's follow-up as a + turn of its own (`started_by: user`, counted toward no turn's runs, from the + conversation's outside-content mark; stopping its stream, Ctrl+C, is the + user's stop of the run, which ends `cancelled` and leaves the instance + `stopped`), `stop_instance`, `close_instance` (both written to the store + before they return), `steer_instance(instance, message)` (the user's message + to a running run, before its next step), `instance_result` (the envelope of + the latest run the user started) and `tell_root(text)`, a turn of the root + on a notice the user did not type (marked as a job's notice is, so fact + extraction and the conversation's title and turns leave it out; the + outside-content mark a user's run brought is written with it), whose notice + after the user worked with a sub-agent is + `agents/envelope.py::view_notice`: "The user worked with <id> directly; its + latest result: <envelope as JSON>". On both backends, contract-tested. - **The main agent's requests list its open sub-agents, when it can continue them.** With `SubAgentPolicy(follow_ups=True)` a main agent with sub-agents (it has `message_agent`) is told which of its own sub-agents are open: a @@ -846,19 +869,18 @@ the start of the entry's title. user's answer in the dialog approves: a brief, a tool result or a message saying the user approved changes nothing, and a sub-agent's question goes to the user, never to its parent (contract-tested on both backends). -- **`/agents`: the conversation's sub-agent runs.** A table of the open - conversation's sub-agent runs, each followed by the runs it started: - instance, type, status (`running`, `queued` waiting for a free working - slot, `needs you` waiting on the user, `completed`, `completed (partial)` - for an answer cut at its output limit, `refused`, `failed`, `cancelled`, - `interrupted`), - run, title, tokens in/out (from the usage ledger, so a run still going - shows what it has used so far) and time, a row for each run of an - instance (its first and each follow-up, titled by its message's first - line). `/agents <id>` shows one instance (`researcher-2`: every run of it) - or run (`researcher-2#1`): its type, parent and title, then each run's - status and time, the other fields of its brief (a follow-up's message), the - first lines of its result, its error and its tokens by model. The runs are the conversation's records, kept +- **`/agents`: the conversation's sub-agents.** A picker of the open + conversation's sub-agent instances, each followed by the ones it started: + id, type, status (`running`, `idle`, `stopped`, `closed`) and title; Enter + shows the one picked. `/agents <id>` shows one instance (`researcher-2`: + every run of it, its first and each follow-up) or run (`researcher-2#1`): + its type, parent and title, then each run's status (`running`, `queued` + waiting for a free working slot, `needs you` waiting on the user, + `completed`, `completed (partial)` for an answer cut at its output limit, + `refused`, `failed`, `cancelled`, `interrupted`) and time, the other fields + of its brief (a follow-up's message), the first lines of its result, its + error and its tokens by model (from the usage ledger, so a run still going + shows what it has used so far). The runs are the conversation's records, kept beside it in its store and loaded with it, so a conversation resumed from an earlier run of the app lists its runs, each with the tokens its record keeps. During a turn each line of the events diff --git a/CLAUDE.md b/CLAUDE.md index 34c70707..fcfac739 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,7 +36,7 @@ agentic-cli/ │ │ ├── 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); 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 <sessions_dir>/locks/; ConversationCore holds it and refuses one held elsewhere; /sessions --delete too, through conversation_held) │ │ ├── builtin_commands.py # /help (by category; /help <command>: its usage and examples), /status (the main agent's context rows: context_budget; 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 <text> searches the full listings; refresh), /sessions (every installed backend's, a Backend column; --delete=<id> on the backend that keeps it, --backend=<name> for an id two keep; on the memory store NOT_KEPT, no table, --delete refused), /resume [<id>] (sessions; refused on the memory store), /jobs (resume: finished jobs), /compact [focus], /new [backend] (an unknown backend or a missing extra refused: check_backend), ... -│ │ ├── agents_command.py # /agents: the open conversation's sub-agent runs (agent_runs.records under workflow.session_ref(app.session_id)) in a table, each followed by the runs it started (instance, type, status: running, queued (waiting for a free working slot), needs you (input_required: waiting on the user), completed (partial) for a cut answer, the end as recorded; run, title, tokens in/out from the usage ledger, usage_of, live for a running run; time); /agents <id>: one instance (every run of it) or run (type, parent, title; 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 showing the one picked as /agents <id> does; /agent <id> shows one, /agent stop <id> and /agent close <id> 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 <id> (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; 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 │ │ ├── memory_command.py # /memory: the list (a picker like /resume's), one memory (Delete, History), /memory <id>, 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) │ │ ├── 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 <backend>:" on another backend), the replay of the last 10 messages @@ -49,7 +49,7 @@ agentic-cli/ │ │ ├── waiting_jobs.py # Which finished jobs wait to be told in the open conversation: one rule (JobRecord.awaiting_resume, then its own, no conversation's, or a gone conversation's: can_resume, then the other installed backends' readers, opens_anywhere: one another backend keeps is not gone, its job waits for it) for the deliveries, ↻N and the startup line │ │ └── usage_tracker.py # Token usage / status bar: ctx = the main agent's last prompt over its context_trigger (a call with a purpose, a sub-agent's, a summary's or a side call's, never moves it); the token segment the open conversation's total, every call of its turns; format_usage: /status's rows by agent and /agents <id>'s tokens by model │ ├── workflow/ -│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none); the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget and the load mark dropped); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built: each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); 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); 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), 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', then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built: each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) │ │ ├── factory.py # create_workflow_manager_from_settings (_BACKENDS: orchestrator → "module:Class" + extra, imported when chosen; orchestrator=: another backend than the settings'; session_store=: the store a manager is built for, BaseWorkflowManager.session_store, the settings' by default; subagents=: the SubAgentPolicy the manager gets, checked before a backend is imported); orchestrator_of; check_backend (an unknown name, a missing extra) │ │ ├── session_readers.py # SessionReader: a backend's stored conversations read without its manager (list/info/exists/delete/aclose, rows naming the backend; delete deletes what the manager's does, ADK's sub-agent transcripts and records with the conversation), opened from the settings and a store (open_session_reader: the backend's own session code, adk/sessions.py::open_sessions and deepagents/sessions.py::open_sessions, imported on a worker thread; no agents, models or services; a sqlite store not made yet reads empty and is not made, Deep Agents not even imported for it; a database without its backend's tables, looked at read-only, reads empty, nothing written to it: no table, no journal mode); none for the memory store or LangGraph; ImportError (the install hint) for a missing extra; reader_backends │ │ ├── service_registry.py # get_service/require_service + ContextVar registry; the registry keys and KNOWN_SERVICE_KEYS, read from services.py's table @@ -82,7 +82,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), RunRecord (input: a follow-up's message as written, "" for a first run), AgentRuns (a manager's runs and instances by conversation: run_for names <agent>-<n> and its first run #1 per (conversation, parent run, call id), a new one once it ended; next_run: an instance's next run; instances/instance, kept from the events: a start makes or reopens the instance running, an end sets its status from instance_status, AGENT_INSTANCE a change without a run; number_from: past the instances a conversation's store keeps, a count never lowered; observe records AGENT_RUN under the turn it is reported in; interrupt_open; a record's usage: what the run used, by model, from its end event or the ledger; its plan and tasks: the run's own last, from its end event; RECORDS_VERSION, export (a conversation's records as JSON-safe data: v, saved, numbered, instances, runs) and restore (replaces them; a run found working ends interrupted, INTERRUPTED_ERROR, at the later of its start and saved, its instance idle, closed for a type that is not continuable; each run's end order stored (end), any time or field that does not read ValueError; counters never below an instance kept; ValueError for another version or records that do not read, nothing changed), stored_instance_ids (the instances stored records name; None for none), AgentRuns(on_change=): told each change, never by restore), run_title, result_head, run_instance and run_number (the one reader of a run id: researcher-2#1's instance and number), run_label (how a dialog names a run: researcher-2 (researcher, run 1)), SUBAGENT_ERROR_PREFIX (ADK's old words for a failed delegation, kept for callers), show_as_delegation(result, envelope) (a delegation's TOOL_RESULT shown alike on both backends: the result's first line, or Failed: <error>; metadata["result"] the envelope); a record's brief, started_by, mode and cancelled_by; delegate.py: Delegations (delegate(DelegationRequest) → Delegated and follow_up(FollowUpRequest) → Delegated: the one place a run starts and ends, on both backends (a follow-up is the instance's next run through the same hook, AgentRun.follow_up: refused as an error result, no run, for an unknown or not-yours instance (NOT_YOURS_ERROR, YOURS, NO_SUB_AGENTS), a closed one (CLOSED_ERROR), one the user stopped when an agent sends it (STOPPED_ERROR), a running one (RUNNING_ERROR), one whose type the app no longer has (TYPE_GONE_ERROR) and a blank message (NO_MESSAGE_ERROR); an agent's counts toward max_runs_per_turn, the user's (started_by USER) does not; a run's end carries the status it leaves its instance in: stopped for the user's cancel, closed for a type that is not continuable or the oldest idle one past max_open, else idle; close(conversation, instance, reason=): an idle or stopped instance and its descendants, AGENT_INSTANCE closed; open_calls=: the manager's OpenCalls, whose stop recorded for an instance is taken when the instance is left closed (its end, close, max_open, or a turn that stops a one-shot run), so its calls are freed; max_open ranks by AgentRuns.end_order, the order ends were recorded in, never the clock): the brief read against the caller's own sub-agents, the run named (a turn's first run past the instances its conversation's store keeps: stored=, asked once per conversation per turn, again after a failed or stopped ask), its AGENT_RUN start and end observed and reported, the backend's hook (RunHook: AgentRun → RunAnswer) run in a task of its own with the run active and no tool call, the end by the answer (completed, partial for a cut or the step limit, refused, failed for an error or a raise, with one recoverable ERROR <instance> failed: <reason>, or RunFailed's own words, its result the text the run wrote before it failed (RunFailed(text=); a failed model call the hook's RunAnswer.error, failure_reason, with error_code its type, the warning's code), cancelled by its control with what the hook had), interrupted on its turn's cancel, which wins; the envelope as the result; each run under its RunControl, the type's limits over the policy's, kept while it works: control(run), cancel(run_id, by=, error=), the run alone; a call past max_runs_per_turn the error result RUNS_PER_TURN_ERROR, no run; the stored instances asked under a lock per conversation; forget(conversation): a deleted one's slots, unread messages, waiting closes and asks; each run in a working slot of its conversation's SlotPool, slots(conversation): policy.max_active slots, made on first use and kept, the root taking none: taken right before its hook and its time limit, queued then running while it waits for one, given back at its end, straight back to a caller that waits on it alone; a caller that delegates lends its slot while it waits for its children), DelegationRequest, FollowUpRequest, AgentRun (control, follow_up), RunAnswer, RunFailed, started_by, waiting_on_user (a sub-agent run waiting on the user: input_required, its slot lent, queued while its take-back waits for a slot, then running; nested waits once; request_user_input and the permission engine); records.py: RecordsWriter (each conversation's records written to its store as they change: changed, one write at a time per conversation taking the records as it starts, so changes made meanwhile go together in the next; flush, flush_all, discard (a delete's: what waits dropped, the write under way waited for); a failed write warned once per conversation, subagent_records_not_saved, never raised); slots.py: SlotPool (acquire(priority): a free slot, else a future in a heap by priority, RETURNING before NEW, then arrival; release; lent(slot, on_wait=): the slot lent while its run waits, nested lends once, taken back at RETURNING after (on_wait called when that has to wait), at most one take-back waiting for a slot and none once it is held (a wait that starts while one is queued takes it over, and one handed the slot withdraws any queued since), nothing taken back after a cancel, so a tool's caught timeout around a question leaves its run working without a slot, input_required until its next question is answered (running again, still without a slot) or its end; hand_back(slot, to): a child's slot to its parent waiting on it alone; free, waiting; a cancelled waiter leaves the heap, one handed a slot as it is cancelled hands it on; not asyncio.Semaphore), Slot (held, lent), RETURNING, NEW; control.py: RunControl (one run's: cancel(by=, error=) its task, the first cancel winning, own_cancel for the hook that takes it and returns, finish: the hook's work ended, no cancel after it (ADK's state read loses no answer), timing: the time limit while the hook runs; model_call/at_step_limit/final_call: the step limit, STEP_LIMIT_NOTE on the last allowed call; used: the token limit, against its own calls and side_tokens (its side calls and summaries, from the ledger), an answer past it that makes calls the run's last, cancelled by it, one that makes none its result (calls=); model_call once final stays final; a cancel leaves a task its turn is cancelling alone; steer/take_steering), STEP_LIMIT_NOTE; outcome.py: a sub-agent's refused or cut answer (outcome_of, the refusal notice as Deep Agents 0.7.34 words it, cut_off, cut_off_warning, OPENAI_REFUSAL_PREFIX: how ADK's OpenAI adapters word a refusal); policy.py: SubAgentPolicy (max_active, max_runs_per_turn, limits, max_open) and AgentLimits (max_model_calls, timeout, max_tokens; over: a type's limits over the policy's, field by field, None taking the base's), DEFAULT_LIMITS (100 model calls), frozen and checked as they are made (a ValueError naming the field), as_policy (the one reading of a subagents= argument: a TypeError for anything but a policy or None); brief.py: BRIEF_FIELDS, Brief, BriefError, read_brief (a task call's agent type and brief, against the types its caller may start: the error texts), task_message (a run's first message, a section per filled field; an inheriting type's ends with INHERITED_CONTEXT_NOTE), task_parameters and task_description (task's schema and description, the same for both backends; limit_sentences: the limits it states, "At most <max_active> sub-agents work at once; more calls in one response wait for a free slot. At most <max_runs_per_turn> runs per turn."); envelope.py: envelope (a delegation run's result: success only for completed, a one-line error, cancelled_by for a cancelled run), read_envelope (a dict or its JSON text, else None; never raises), the limit and interrupted error texts; `Delegations.message` (an idle instance's follow-up; a running one's run steered, or with `interrupt` cancelled by its parent and followed up; one run per instance, so of two messages to one idle instance in one answer the first runs and the second is steered into it), `stop` (a running instance's run cancelled by its parent, the instance idle; `close` closes it and its descendants, a running one's at its run's end), `check`, `steer(conversation, run, message)`, `stop_cause(run)` and `cancel(..., conversation=)`; a message steered to a run that its transcript does not hold when it ends (`RunControl.unstored`) is kept for the instance's next run; a run whose parent's run its control stopped ends `cancelled` by its parent (`its parent's run was stopped`); a run that did not complete fully names its open tasks in its envelope (`envelope(open_tasks=)`, `open_task_descriptions`) and a cancelled run keeps its plan and tasks; `SubAgentPolicy.follow_ups`; brief.py: `follow_up_description`/`follow_up_parameters` (the parent's tools' texts); follow_ups.py: `call_follow_up_tool` (a message_agent, stop_agent or check_agents call as the run in progress); roster.py: roster_text (the main agent's open sub-agents, newest first, one line each, ROSTER_OPEN/ROSTER_HEADER/ROSTER_CLOSE, at most ROSTER_MAX characters in whole lines, "" for none open), Rosters (a snapshot per conversation, as MemoryIndex: now, forget, clear; the root's own instances, parent root) +│ │ ├── agents/ # Sub-agents: runs.py: the RUN_* statuses (a working run's: RUN_QUEUED, RUN_RUNNING, RUN_INPUT_REQUIRED, RUN_WORKING_STATUSES; a record says running from its start), INSTANCE_RUNNING/IDLE/STOPPED/CLOSED and INSTANCE_STATUSES, InstanceRecord (an instance: parent, depth, title, status, runs, continuable), RunRecord (input: a follow-up's message as written, "" for a first run), AgentRuns (a manager's runs and instances by conversation: run_for names <agent>-<n> and its first run #1 per (conversation, parent run, call id), a new one once it ended; next_run: an instance's next run; instances/instance, kept from the events: a start makes or reopens the instance running, an end sets its status from instance_status, AGENT_INSTANCE a change without a run; number_from: past the instances a conversation's store keeps, a count never lowered; observe records AGENT_RUN under the turn it is reported in; interrupt_open; a record's usage: what the run used, by model, from its end event or the ledger; its plan and tasks: the run's own last, from its end event; RECORDS_VERSION, export (a conversation's records as JSON-safe data: v, saved, numbered, instances, runs) and restore (replaces them; a run found working ends interrupted, INTERRUPTED_ERROR, at the later of its start and saved, its instance idle, closed for a type that is not continuable; each run's end order stored (end), any time or field that does not read ValueError; counters never below an instance kept; ValueError for another version or records that do not read, nothing changed), stored_instance_ids (the instances stored records name; None for none), AgentRuns(on_change=): told each change, never by restore), run_title, result_head, run_instance and run_number (the one reader of a run id: researcher-2#1's instance and number), run_label (how a dialog names a run: researcher-2 (researcher, run 1)), SUBAGENT_ERROR_PREFIX (ADK's old words for a failed delegation, kept for callers), show_as_delegation(result, envelope) (a delegation's TOOL_RESULT shown alike on both backends: the result's first line, or Failed: <error>; metadata["result"] the envelope); a record's brief, started_by, mode and cancelled_by; delegate.py: Delegations (delegate(DelegationRequest) → Delegated and follow_up(FollowUpRequest) → Delegated: the one place a run starts and ends, on both backends (a follow-up is the instance's next run through the same hook, AgentRun.follow_up: refused as an error result, no run, for an unknown or not-yours instance (NOT_YOURS_ERROR, YOURS, NO_SUB_AGENTS), a closed one (CLOSED_ERROR), one the user stopped when an agent sends it (STOPPED_ERROR), a running one (RUNNING_ERROR), one whose type the app no longer has (TYPE_GONE_ERROR) and a blank message (NO_MESSAGE_ERROR); an agent's counts toward max_runs_per_turn, the user's (started_by USER) does not; a run's end carries the status it leaves its instance in: stopped for the user's cancel, closed for a type that is not continuable or the oldest idle one past max_open, else idle; close(conversation, instance, reason=): an idle or stopped instance and its descendants, AGENT_INSTANCE closed; open_calls=: the manager's OpenCalls, whose stop recorded for an instance is taken when the instance is left closed (its end, close, max_open, or a turn that stops a one-shot run), so its calls are freed; max_open ranks by AgentRuns.end_order, the order ends were recorded in, never the clock): the brief read against the caller's own sub-agents, the run named (a turn's first run past the instances its conversation's store keeps: stored=, asked once per conversation per turn, again after a failed or stopped ask), its AGENT_RUN start and end observed and reported, the backend's hook (RunHook: AgentRun → RunAnswer) run in a task of its own with the run active and no tool call, the end by the answer (completed, partial for a cut or the step limit, refused, failed for an error or a raise, with one recoverable ERROR <instance> failed: <reason>, or RunFailed's own words, its result the text the run wrote before it failed (RunFailed(text=); a failed model call the hook's RunAnswer.error, failure_reason, with error_code its type, the warning's code), cancelled by its control with what the hook had), interrupted on its turn's cancel, which wins; the envelope as the result; each run under its RunControl, the type's limits over the policy's, kept while it works: control(run), cancel(run_id, by=, error=), the run alone; a call past max_runs_per_turn the error result RUNS_PER_TURN_ERROR, no run; the stored instances asked under a lock per conversation; forget(conversation): a deleted one's slots, unread messages, waiting closes and asks; each run in a working slot of its conversation's SlotPool, slots(conversation): policy.max_active slots, made on first use and kept, the root taking none: taken right before its hook and its time limit, queued then running while it waits for one, given back at its end, straight back to a caller that waits on it alone; a caller that delegates lends its slot while it waits for its children), DelegationRequest, FollowUpRequest, AgentRun (control, follow_up), RunAnswer, RunFailed, started_by, waiting_on_user (a sub-agent run waiting on the user: input_required, its slot lent, queued while its take-back waits for a slot, then running; nested waits once; request_user_input and the permission engine); records.py: RecordsWriter (each conversation's records written to its store as they change: changed, one write at a time per conversation taking the records as it starts, so changes made meanwhile go together in the next; flush, flush_all, discard (a delete's: what waits dropped, the write under way waited for); a failed write warned once per conversation, subagent_records_not_saved, never raised); slots.py: SlotPool (acquire(priority): a free slot, else a future in a heap by priority, RETURNING before NEW, then arrival; release; lent(slot, on_wait=): the slot lent while its run waits, nested lends once, taken back at RETURNING after (on_wait called when that has to wait), at most one take-back waiting for a slot and none once it is held (a wait that starts while one is queued takes it over, and one handed the slot withdraws any queued since), nothing taken back after a cancel, so a tool's caught timeout around a question leaves its run working without a slot, input_required until its next question is answered (running again, still without a slot) or its end; hand_back(slot, to): a child's slot to its parent waiting on it alone; free, waiting; a cancelled waiter leaves the heap, one handed a slot as it is cancelled hands it on; not asyncio.Semaphore), Slot (held, lent), RETURNING, NEW; control.py: RunControl (one run's: cancel(by=, error=) its task, the first cancel winning, own_cancel for the hook that takes it and returns, finish: the hook's work ended, no cancel after it (ADK's state read loses no answer), timing: the time limit while the hook runs; model_call/at_step_limit/final_call: the step limit, STEP_LIMIT_NOTE on the last allowed call; used: the token limit, against its own calls and side_tokens (its side calls and summaries, from the ledger), an answer past it that makes calls the run's last, cancelled by it, one that makes none its result (calls=); model_call once final stays final; a cancel leaves a task its turn is cancelling alone; steer/take_steering), STEP_LIMIT_NOTE; outcome.py: a sub-agent's refused or cut answer (outcome_of, the refusal notice as Deep Agents 0.7.34 words it, cut_off, cut_off_warning, OPENAI_REFUSAL_PREFIX: how ADK's OpenAI adapters word a refusal); policy.py: SubAgentPolicy (max_active, max_runs_per_turn, limits, max_open) and AgentLimits (max_model_calls, timeout, max_tokens; over: a type's limits over the policy's, field by field, None taking the base's), DEFAULT_LIMITS (100 model calls), frozen and checked as they are made (a ValueError naming the field), as_policy (the one reading of a subagents= argument: a TypeError for anything but a policy or None); brief.py: BRIEF_FIELDS, Brief, BriefError, read_brief (a task call's agent type and brief, against the types its caller may start: the error texts), task_message (a run's first message, a section per filled field; an inheriting type's ends with INHERITED_CONTEXT_NOTE), task_parameters and task_description (task's schema and description, the same for both backends; limit_sentences: the limits it states, "At most <max_active> sub-agents work at once; more calls in one response wait for a free slot. At most <max_runs_per_turn> runs per turn."); envelope.py: envelope (a delegation run's result: success only for completed, a one-line error, cancelled_by for a cancelled run), read_envelope (a dict or its JSON text, else None; never raises), view_notice (`VIEW_NOTICE`: what the root is told once the user worked with an instance), the limit and interrupted error texts; `Delegations.message` (an idle instance's follow-up; a running one's run steered, or with `interrupt` cancelled by its parent and followed up; one run per instance, so of two messages to one idle instance in one answer the first runs and the second is steered into it), `stop` (a running instance's run cancelled by its parent, the instance idle; `close` closes it and its descendants, a running one's at its run's end), `check`, `steer(conversation, run, message)`, `stop_by_user`/`close_by_user` (`STOPPED_BY_USER_ERROR`, `CLOSED_BY_USER`: a running run cancelled by the user and waited for), `stop_cause(run)` and `cancel(..., conversation=)`; a message steered to a run that its transcript does not hold when it ends (`RunControl.unstored`) is kept for the instance's next run; a run whose parent's run its control stopped ends `cancelled` by its parent (`its parent's run was stopped`); a run that did not complete fully names its open tasks in its envelope (`envelope(open_tasks=)`, `open_task_descriptions`) and a cancelled run keeps its plan and tasks; `SubAgentPolicy.follow_ups`; brief.py: `follow_up_description`/`follow_up_parameters` (the parent's tools' texts); follow_ups.py: `call_follow_up_tool` (a message_agent, stop_agent or check_agents call as the run in progress); roster.py: roster_text (the main agent's open sub-agents, newest first, one line each, ROSTER_OPEN/ROSTER_HEADER/ROSTER_CLOSE, at most ROSTER_MAX characters in whole lines, "" for none open), Rosters (a snapshot per conversation, as MemoryIndex: now, forget, clear; the root's own instances, parent root) │ │ ├── adk/ # ADK orchestrator │ │ │ ├── manager.py # GoogleADKWorkflowManager (the agents built from configs or, adk_config_path, by ADK from a native YAML (library-only: no BaseCLIApp starts one; loaded once per manager at the first _validate_agent_graph (_native_root: the settings' keys exported first; a retry, a model switch and a start after cleanup build on the same tree, whose toolsets the closed runner left reusable), its agents' models resolved leniently in _resolve_extra_models, the base's hook, its registered tools' services detected; configs passed with it ignored, adk_native_configs_ignored): the only difference; _do_initialize builds the app from the tree alone, _build_app → ADKBuild, through the hooks _plugin_chain (the whole chain, top to bottom, its head _init_plugins), _compaction_config (None for a root without a budget), _context_cache_config, _agent_model_refs; the event processor built from the build; a config-built agent's prompt as an instruction provider, sent as written: no `{name}` state injection; _compact_turn: ADK's compaction once, in the base's compact turn; supports_compact False once built for a root without a budget (_no_compact_support says why); the job resume hooks: _conversation_exists (the session read without its events, num_recent_events=0), _deliver_job_notice (the notice, for every app); _run_config: the agents' synchronous tools run in ADK's tool thread pool, 8 workers; _run_and_stream: a run that fails yields the turn's one ERROR, last, none after an ERROR already yielded, and keeps the record of its calls that returned for the next turn (OpenCalls.failed; _answer_left_open forgets it once its answers are stored); the agents: _create_agents builds each config's agent on its own (_agents, by name; no ADK sub_agents), a delegating one with a TaskTool (its own tool named task: AgentGraphError); a runner per sub-agent type (_agent_runners: NoAfterTurnCompactionRunner on App(name=child_app(app_name), root_agent=the type's agent, plugins=_agent_plugin_chain(agent), the app's context cache, no compaction) over the session service, closed with the main runner by _detach_backend, rebuilt by every initialization); _run_agent, the base's hook: the instance's child session (_child_session: a first run makes it from run.state and an inheriting instance's copied events, once; never one the store keeps, whose instance numbering goes past: ADK's create_session refuses it, and the run fails; a follow-up takes the stored session, answers the calls an earlier run left open there (left_open_by) and passes the caller's mark when it holds none; one the store lost is made as a first run's), _stored_instances (the base's hook: the highest instance number of each type the conversation's child sessions keep), the type's runner on the task message (a follow-up's own message) with an abort signal set before it is closed, a run-mode ADKEventProcessor, the raw log's records reported as they come (_report_raw_log); a model's failure raised as the provider's (_plugin_cause), an overflow RunFailed, a reply that is no answer RunAnswer(error=), the shared keys it changed read back) │ │ │ ├── build.py # ADKBuild (root, reply_agents, plugins, compaction, cache, models); load_native_root (from_config at validation; what ADK cannot load, wrapped as AgentGraphError naming the file, ADK's error the cause; a root that is not an LlmAgent, a name used twice in the tree and a task-mode agent refused, AgentGraphError naming it; ensure_direct_anthropic); what the run reads of any tree: reply_agents (the root and the chat-mode agents it can transfer to), own_after_tool_agents (left out by the cap) @@ -92,7 +92,7 @@ agentic-cli/ │ │ │ ├── overflow_plugin.py # OverflowPlugin (OVERFLOW_PLUGIN_FAILED: ADK's wrapper of its errors, which the manager unwraps): a provider's overflow summarized (the root; the retry: the memory index and roster that open the request, the summary and the turns it kept) or trimmed (a sub-agent's keeping its task message and its instance's brief), retried once (the retry timed around its own request: call_clock.mark_latency), then CONTEXT_OVERFLOW: overflow_message for an agent that replies (reply_agents), subagent_overflow_message for a sub-agent's run (root None on its runner), which fails it; a sub-agent's trimmed retry keeps its task message (keep_task) │ │ │ ├── memory_index_plugin.py # MemoryIndexPlugin: the conversation's memory index first in the root's requests (before the overflow handler and the fit guard, which keep and fold it) │ │ │ ├── roster_plugin.py # RosterPlugin: the conversation's roster of the root's open sub-agents first in the root's requests, before MemoryIndexPlugin (which puts the index ahead of it), for a root with message_agent -│ │ │ ├── sessions.py # A conversation's row in its session state (agentic_cli.title, agentic_cli.turns), saved with each user turn (run_async(state_delta=)); typed_prompts; ServiceSessions: the session hooks over a session service (the manager's and its reader's); make_session_service, session_db_url; open_sessions (a reader's store: empty without ADK's sessions table, looked at read-only); CHILD_APP_SUFFIX, child_app (<app_name>--agents: the sub-agent runs' app, which no conversation list reads), child_session_id (<conversation id>/<instance>, the conversation id's % and / percent-encoded, so its first / always ends the conversation and no two conversations share an id; child_of reads one back; a ValueError past ADK's 128 characters; the instance's follow-up runs continue it), delete_children (a conversation's child sessions, events and all: those its records name and every one a listing finds), stored_instances (the highest instance number of each type a conversation's child sessions keep: by the instances its records name, else a listing); BRIEF_KEY (agentic_cli.brief): set by an instance's first run with its message, marking it as the instance's brief; RECORDS_KEY (agentic_cli.agents): a conversation's sub-agent records, in the child app's session named as the conversation, encoded (records_session_id, a ValueError past ADK's 128 characters; load_records, save_records: the header under RECORDS_KEY and a key for each instance and run, made at the first write, then one event per write whose state delta holds only the keys that changed; delete_records); ServiceSessions.delete: the transcripts, then the records, then the conversation, whatever its look found +│ │ │ ├── sessions.py # A conversation's row in its session state (agentic_cli.title, agentic_cli.turns), saved with each user turn (run_async(state_delta=)); typed_prompts, NOTICE_METADATA and is_notice (a notice to the root's run, left out of both typed_prompts and recent_messages); ServiceSessions: the session hooks over a session service (the manager's and its reader's); make_session_service, session_db_url; open_sessions (a reader's store: empty without ADK's sessions table, looked at read-only); CHILD_APP_SUFFIX, child_app (<app_name>--agents: the sub-agent runs' app, which no conversation list reads), child_session_id (<conversation id>/<instance>, the conversation id's % and / percent-encoded, so its first / always ends the conversation and no two conversations share an id; child_of reads one back; a ValueError past ADK's 128 characters; the instance's follow-up runs continue it), delete_children (a conversation's child sessions, events and all: those its records name and every one a listing finds), stored_instances (the highest instance number of each type a conversation's child sessions keep: by the instances its records name, else a listing); BRIEF_KEY (agentic_cli.brief): set by an instance's first run with its message, marking it as the instance's brief; RECORDS_KEY (agentic_cli.agents): a conversation's sub-agent records, in the child app's session named as the conversation, encoded (records_session_id, a ValueError past ADK's 128 characters; load_records, save_records: the header under RECORDS_KEY and a key for each instance and run, made at the first write, then one event per write whose state delta holds only the keys that changed; delete_records); ServiceSessions.delete: the transcripts, then the records, then the conversation, whatever its look found │ │ │ ├── event_processor.py # ADKEventProcessor (each call's LLM_USAGE normalized by its model's provider kind, kinds (an agent without one: an unknown kind's), with its latency (call_clock's mark), and recorded in the conversation's ledger before on_event, a run's end with what it used; reply_agents: the agents whose text is the reply; another's, a sub-agent's, marked as activity; a reply that is no answer, NO_ANSWER_CODES, → the turn's ERROR; a failed result, an MCP isError one too, → a failed TOOL_RESULT naming its error, as on Deep Agents; TASK_PROGRESS after a tool call that changed the task list, its state delta's tasks, as on Deep Agents: start_turn forgets the list reported; every event names its run, the agent's own at depth 0, TOOL_CALL and TOOL_RESULT their tool_call_id; a task call's TOOL_RESULT shown as on Deep Agents, from its envelope: show_as_delegation; run=: a processor for one sub-agent run, on its child session, every event that run's, a sub-agent's text activity, no TASK_PROGRESS (a run's list is its own: only the root's is reported), its last answer with text, its outcome mark and its failure kept (answer, outcome, failure: an overflow, a reply that is no answer but an empty one) for _run_agent) │ │ │ ├── model_factory.py # build_adk_model: ResolvedModel → ADK model, config, planner │ │ │ ├── openai_compatible.py # OpenAICompatibleLlm (the configured providers: openrouter and openai_compatible kinds; reasoning text; OpenRouter's reasoning_details kept on the thought part (thought_signature, with the model that wrote them) and sent back on that turn's assistant message to that model only; a Chat Completions refusal, streamed or not, as the text ADK's Responses adapter makes of one, "OpenAI refusal: <text>"; no field sent as null; OpenRouter's cache writes, which ADK's usage mapping drops, kept on the usage as cache_creation_input_tokens) @@ -116,7 +116,7 @@ agentic-cli/ │ │ │ ├── tools.py # to_langchain_tools: a callable → StructuredTool whose .func/.coroutine is it │ │ │ ├── task_tool.py # build_task_tool: the framework's task on Deep Agents (a StructuredTool over task_parameters' JSON schema, bound to the task declaration): a call → Delegations.delegate, whose shared-key change (the outside-content mark) and envelope (JSON, the ToolMessage) come back as one Command; SHARED_KEYS; inherited_messages (an inheriting run's history: the state's messages, the summary event applied, less the message that called task); build_follow_up_tools (with follow_ups: message_agent, stop_agent, check_agents, each a StructuredTool bound to its declaration, answering as task does) │ │ │ ├── event_processor.py # DeepAgentsEventProcessor (stream → WorkflowEvent, each call's LLM_USAGE, with its latency (answer_latency), recorded in the conversation's usage ledger before on_event, a run's end with what it used; every event its processor's agent's and run's (run=: a processor for one sub-agent run, its text activity, no TASK_PROGRESS), from the root namespace's items only (a graph a tool runs streams in its own); the task call's TOOL_RESULT shown as on ADK, from its envelope: show_as_delegation); RunCallback (every model call timed, its answer marked with its latency before any middleware sees it; a summary's usage recorded in the conversation's ledger; what a node reports inside itself, through the turn's `LiveEvents`: required; `compact()` called outside a reporting context gets one nobody reads) -│ │ │ ├── sessions.py # thread_id(SessionRef), instance_thread_id and instance_run_config (a sub-agent instance's thread, [app, user, session, instance], its checkpoints' metadata carrying instance and thread_kind: instance), CheckpointSessions (instances: read from the instance threads' first input checkpoints (source input, step -1: no message in them, so the saver unpickles no transcript); stored_instances: those threads and the stored records' ids and counters; agent_records/save_agent_records/delete_agent_records: a conversation's sub-agent records, an item of the store beside the checkpointer under (agentic_cli, agents, <app>, <user>), keyed by the session id; delete: those threads first, then the records, then the conversation; a first run onto a thread the store keeps fails (the manager's check); rows from an index in the store beside the checkpointer, written as a turn starts (its input counted: a killed process still lists it), then from the newest root checkpoint as it ends and after /compact; a database from before it scanned once per app and user), job notifications; open_sessions: a store's conversations for a reader, without the manager (empty without the checkpoints table, looked at read-only before any setup) +│ │ │ ├── sessions.py # thread_id(SessionRef), instance_thread_id and instance_run_config (a sub-agent instance's thread, [app, user, session, instance], its checkpoints' metadata carrying instance and thread_kind: instance), CheckpointSessions (instances: read from the instance threads' first input checkpoints (source input, step -1: no message in them, so the saver unpickles no transcript); stored_instances: those threads and the stored records' ids and counters; agent_records/save_agent_records/delete_agent_records: a conversation's sub-agent records, an item of the store beside the checkpointer under (agentic_cli, agents, <app>, <user>), keyed by the session id; delete: those threads first, then the records, then the conversation; a first run onto a thread the store keeps fails (the manager's check); rows from an index in the store beside the checkpointer, written as a turn starts (its input counted: a killed process still lists it), then from the newest root checkpoint as it ends and after /compact; a database from before it scanned once per app and user), job notifications and notices to the root (`notice_message`, `tell_root`; `is_notice`: either, left out of recent and a row); open_sessions: a store's conversations for a reader, without the manager (empty without the checkpoints table, looked at read-only before any setup) │ │ │ ├── summarization.py # Each agent's thresholds from its budget (the manager's _budgets, given to build_agent_tree(budgets=); context_budget when none); NoArchiveBackend; history filters; compact()'s cut, summary and event (marked: the count reported before it is no trigger, _should_summarize); OverflowMapped: the summary model's overflows as ContextOverflowError, inside its retry; a request's count includes the memory index (index=) and the roster (roster=), and a summary written drops their snapshots before the request goes on (on_written=); an instance's brief (brief_message: its first run's task message, marked; is_brief, brief_of: the last marked), restated first in each summary message of its thread that stands for it (_partition_messages, _build_new_messages_with_path, per call through _BRIEF) │ │ │ ├── mcp_tools.py # MCPSessions: one owner task per (agent, server); the mcp identity map; a call fails once its session ends (_while_open: mcp's stdio client can leave one unanswered) │ │ │ └── state.py # AgentCliState: plan, tasks (last write wins), outside_content (first write wins) @@ -252,7 +252,7 @@ Workflow: - **Tool error handling**: All tools return `{"success": bool, ...}` dicts. Never raise `ToolError`. An exception that still escapes a tool is a bug, but it costs one call rather than the turn: on ADK, `workflow/adk/tool_error_plugin.py::ToolErrorPlugin` turns it into an error dict; on Deep Agents, `workflow/deepagents/middleware.py::ToolCallErrorMiddleware`, inside the permission gate, gives the same result, `{"success": false, "error": "<tool> failed: <Type>: <message>"}` cut to 500 characters (both use `workflow/tool_errors.py`). A call to a tool name the agent does not have gets ADK's own text, its first two lines (`unknown_tool_result`: "nope failed: ValueError: Tool 'nope' not found." and the agent's tools by name), logged `tool_not_found` at info (the model's mistake): on ADK the permission gate lets ADK's stand-in through (`is_unknown_tool`: a bare `BaseTool` described "Tool not found", which runs nothing; contract-tested) and `ToolErrorPlugin` answers its lookup error; on Deep Agents the gate answers it. It catches `Exception`, never `BaseException`, so cancelling still cancels (google-adk 2.15 hands a cancelled call's `CancelledError` to `ToolErrorPlugin` for cleanup, ignoring the answer: it answers nothing and logs `tool_cancelled` at debug, no warning). `task` raises nothing into it: a sub-agent's model or run failing (its summary or overflow included: its own tools' errors are results already) fails the run, whose envelope its parent reads (`error`: the provider's reason; on ADK out of ADK's plugin wrapper), reported at once through the turn's live events as one recoverable `ERROR`, `<instance> failed: <reason>`, the run's: the coordinator carries on. A sub-agent's overflow (still too long after its summary or trim) fails its run, on both backends, in the words of ADK's overflow handler, `<agent>: the request no longer fits <model>'s context window.` with `error_code` `CONTEXT_OVERFLOW` (`context.py::subagent_overflow_message`): ADK's `OverflowPlugin` answers the run's model call with it, Deep Agents' manager raises it (`RunFailed`). A refusal is no exception here (the framework adds no `ModelRefusalMiddleware`): a sub-agent whose final answer a model refused ends its run `refused`, and its parent reads, as its envelope's result, Deep Agents 0.7.34's notice ("The subagent stopped because a model refused the request. … Retrying the same request is unlikely to succeed; rephrase it or continue without it."), on both backends and whichever deepagents the pin installs (0.7.28 has no notice of its own; 0.7.34+ finds no refusal block left to word again); an answer cut at the output limit keeps its text, followed by `[cut off at the output limit]`, and its run ends `completed` and `partial`, with one recoverable warning ("<instance>'s answer was cut off at the output limit"); the answer's thoughts or reasoning are kept. ADK's `SubAgentOutcomePlugin` and Deep Agents' `SubAgentOutcomeMiddleware` rewrite and mark the answer, by `workflow/agents/outcome.py`. On ADK the plugin reads the answer's `finish_reason` (Claude's `refusal` and a Chat Completions `content_filter` arrive as `SAFETY`, `max_tokens` and `length` as `MAX_TOKENS`, Gemini's as themselves), the `error_code` ADK sets on an answer with no content (a Gemini prompt's `block_reason`), the `reason` an `OTHER` stop names in its JSON error message (ADK's OpenAI Responses adapter's `incomplete_details`, `content_filter` among them) and a text part `OpenAI refusal: <text>` (that adapter's refusal, and `OpenAICompatibleLlm`'s of a Chat Completions `refusal`, which ADK's class drops). On Deep Agents the middleware reads `response_metadata`'s `stop_reason` (ChatAnthropic), `finish_reason` (ChatOpenAI, ChatGoogleGenerativeAI), `incomplete_details.reason` (the Responses API) and `prompt_feedback.block_reason` (a Gemini prompt block), and a refusal the answer holds (a refusal block, standard or `non_standard`, or `additional_kwargs["refusal"]`). The root's own answers reach the user as their model gave them: on ADK a root's refusal with no answer (Claude's, Gemini's) is still the turn's one `ERROR` ("<model> returned no answer"), and a root on OpenRouter or an OpenAI-compatible server replies "OpenAI refusal: <text>". On both backends the root's own failure leaves the run: the turn's one `ERROR`. A gate or error result goes back as the call's `ToolMessage` with `status="error"`. LangGraph's `ToolNode` runs with `handle_tool_errors=True`. - **Tool result cap**: every tool result passes `workflow/tool_output.py::cap_tool_result` (registered, MCP and skill tools, `job_result`, a delegation's envelope on either backend): 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` lists a conversation's runs), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the caller's own sub-agents) and a brief (`workflow/agents/brief.py`: `title`, `objective`, `deliverable`, `constraints`, `known`, `done_when`), its schema and description the same on both backends (`task_parameters`, `task_description`: a line per type with its description, "The <name> agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both: it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents <id>`, never written to the conversation. It ends as the `RunAnswer` says: its last text (a reply that also called a tool included; none at all, an empty result shown `No answer`), `refused` or `partial` by the outcome mark, `failed` for an error or a raise (one recoverable `ERROR`, `<instance> failed: <reason>`, or the hook's own words, `RunFailed`: an overflow's; its result the text it wrote before it failed: a failed model call is the hook's `RunAnswer.error`, `failure_reason`, its warning's code `RunAnswer.error_code`, the error's type, and `RunFailed` carries `text=`); and the call's result is the run's envelope as JSON (`workflow/agents/envelope.py`), shown by `show_as_delegation`. A cancel of the caller's task stops the run's task first and ends the run `interrupted`. Each run works under its `RunControl` (`workflow/agents/control.py`, `AgentRun.control`), with its type's `AgentConfig.limits` over the policy's (`SubAgentPolicy.limits`, `DEFAULT_LIMITS`: 100 model calls): `Delegations.cancel(run_id, by=, error=)` cancels the run alone (its parent, the user or a limit), and the hook, seeing its own cancel (`own_cancel`), stops the run as a stopped turn's (ADK: its abort signal, its open calls sealed in its child session; Deep Agents: its stream closed) and returns what it has: the run ends `cancelled` with `cancelled_by` and that text, `partial`, while its siblings and the turn go on; the turn's own cancel still wins (`interrupted`). Past its `timeout` (counted from when its hook starts, `timing`) the run is cancelled by its limit (`time limit reached`); each model call is counted before it is made (`RunControlPlugin` in each sub-agent chain, `RunControlMiddleware` on each sub-agent's model side) and the last allowed one gets `STEP_LIMIT_NOTE` after its last message, its tools still declared (Claude refuses tool calls in a request that defines no tools); its answer's calls are dropped, never run, so the run completes `partial`, `step limit reached`; each call's tokens are counted after it, with what the run's other calls used (`RunControl(side_tokens=)`: its tools' side calls and its summaries, the ledger's rows of the run that are no agent step, `UsageLedger.by_purpose(run=)`), so the limit is the run's total as its usage record counts it, and past `max_tokens` an answer that makes tool calls is the run's last, its calls dropped, `cancelled` by its limit (`token limit reached`), while one that makes none ends the run as it would, `completed`, its result whole (a model that reports no usage counts none of its own). A turn starts at most `max_runs_per_turn` runs, at any depth (`sessions.runs_this_turn`): a call past it is the error result, no run started; `task`'s description says so (`limit_sentences`). At most `max_active` runs of a conversation work at once, at any depth (`workflow/agents/slots.py::SlotPool`, one per conversation, `Delegations.slots`; the root takes no slot): a run takes a slot right before its hook and its time limit start and gives it back at its end, however it ends; one that finds none waits `queued` (an `AGENT_RUN` and its record say so, then `running`), not counted against its `timeout`. A run lends its slot while it waits on its children (one lend for all it waits on at once; the child that ends last hands its slot straight back, so the tree in progress goes on ahead of the runs that have not started) or on the user (`waiting_on_user`: `input_required`, `queued` once answered while it waits for its slot back, then `running`, in `request_user_input` and in the permission engine from before its one-prompt lock until after it: a run waiting for a slot while holding the lock would hold every other run's prompt; a prompt no one can be shown, no input callback or its turn ended, lends nothing: `can_request_user_input`), so nested fan-out never deadlocks; a cancel, queued or lending, leaves no waiter in the heap and no slot taken. A message steered to a working run (`RunControl.steer`, through `Delegations.control(run)`) is added after its last message, as the user's, before its next model call, and stays in its transcript (ADK: appended to its child session, the run's later events stamped after it so a durable store reads them back in order; Deep Agents: added to its state); a sub-agent run's task message is never trimmed, on ADK neither by the fit guard nor by the overflow handler's retry, whatever was steered after it. A dialog whose run is stopped is withdrawn, the turn going on (`MessageProcessor`). `AgentConfig.inherit_context` sets what a run sees: False (the default) its task alone, True its parent's conversation too, read once as the run starts (the conversation after any summary; Deep Agents' less the message that called `task`, which ADK's copy keeps), before the task message, which then ends with `INHERITED_CONTEXT_NOTE` (whose conversation it reads, which message is its task); `validate_agent_graph` refuses a value that is not True or False, `inherit_context=True` on the root, on an agent with sub-agents and below another sub-agent. On ADK (`workflow/adk/task_tool.py::TaskTool`) every config-built agent is built on its own, with no ADK `sub_agents`, so ADK offers none `transfer_to_agent`, and gets ADK's identity line ("You are an agent. Your internal name is …"); a delegating agent has one `TaskTool`. A sub-agent is an instance that outlives its run: `idle` when the run ends, its next run a follow-up (`Delegations.follow_up`, through the same hook with `AgentRun.follow_up`, the message as written and no history), one run per instance at a time; a run's end leaves its instance `stopped` (the user's cancel), `closed` (`AgentConfig.continuable` False, or past `SubAgentPolicy.max_open`: the oldest idle one) or `idle`, `Delegations.close` closes an idle or stopped one and its descendants, and `AGENT_INSTANCE` carries a change without a run; on ADK a follow-up continues the instance's child session, the calls an earlier run left open answered first (`left_open_by`, from the instance's record), on Deep Agents the instance's own checkpointer thread (`instance_run_config`: its input the message and the caller's mark, the shared keys it changed compared with the thread's state as the run started). Each sub-agent type runs on its own runner (`App(name=child_app(app_name))`, the type's agent its root, `_agent_plugin_chain`: the main chain configured for a sub-agent, no memory index, no summary, `RunControlPlugin` and `SubAgentOutcomePlugin`; every plugin's per-call state keyed by invocation) over the manager's session service, on a child session per instance (`child_session_id`: `<conversation id>/<instance>`, the conversation id's `%` and `/` percent-encoded; an inheriting instance's gets the conversation's events copied once, at its first run, `task_tool.inherited_events`), under an app no conversation list reads. On Deep Agents (`workflow/deepagents/task_tool.py::build_task_tool`) each type's graph is built on its own, and a run `astream`s it in its task with `var_child_runnable_config` cleared, so its chunks reach its own loop alone, never its parent's stream; an inheriting run's history is the parent's messages with Deep Agents' summary event applied (`SummarizationMiddleware._apply_event_to_messages`, private: `tests/workflow/deepagents/test_compact.py` pins it), and `ForeignReasoningMiddleware(kind, agent=...)` leaves out the reasoning of AI messages another agent wrote. A native ADK YAML app keeps transferring (chat-mode sub-agents); a task-mode agent in one is refused at validation, since ADK runs its delegation outside the tool pipeline and keeps the call open across turns. With `SubAgentPolicy(follow_ups=True)` every agent with sub-agents also gets `message_agent`, `stop_agent` and `check_agents` beside `task` (`workflow/agents/follow_ups.py::call_follow_up_tool` over `Delegations.message`/`stop`/`check`; ADK's `FollowUpTool`, Deep Agents' `build_follow_up_tools`; an own tool of one of their names fails the build, a Deep Agents MCP tool of one is skipped): `message_agent` continues an idle instance, steers a running one (before its next step; a run already stopping or finished is waited for, then the message follows the instance up or is refused; one being closed is refused as closed at once) or, with `interrupt` (refused, nothing cancelled, when no follow-up could start; an agent's keeps the turn's run it checked for), replaces its run (the user's interrupt is the user's stop); `stop_agent` cancels a running run by its parent (the instance idle; only the user's stop makes one `stopped`) and, with `close`, closes it and its descendants; a message steered to a run and not in its transcript when it ends goes to the instance's next run (`RunControl.stored`/`unstored`: ADK counts one stored as its child-session append returns, Deep Agents once the model call after it holds it); a run that did not complete fully names its open tasks in its envelope (`open_tasks`); a run whose parent's run was stopped by its control ends `cancelled` by its parent, not `interrupted`. +- **Sub-agents delegate and return**: on both backends a sub-agent run is a call of its parent's `task` tool (the framework's: `tools/_core/delegation.py` declares it, `workflow/agents/delegate.py` runs it) that returns in the same turn; only the root replies to the user (a sub-agent's `TEXT` carries `metadata["subagent"]`, and the CLI shows it as the events box's status line, under its run's name: `researcher-2 › …`; `/agents` picks among a conversation's instances), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the caller's own sub-agents) and a brief (`workflow/agents/brief.py`: `title`, `objective`, `deliverable`, `constraints`, `known`, `done_when`), its schema and description the same on both backends (`task_parameters`, `task_description`: a line per type with its description, "The <name> agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both: it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents <id>`, never written to the conversation. It ends as the `RunAnswer` says: its last text (a reply that also called a tool included; none at all, an empty result shown `No answer`), `refused` or `partial` by the outcome mark, `failed` for an error or a raise (one recoverable `ERROR`, `<instance> failed: <reason>`, or the hook's own words, `RunFailed`: an overflow's; its result the text it wrote before it failed: a failed model call is the hook's `RunAnswer.error`, `failure_reason`, its warning's code `RunAnswer.error_code`, the error's type, and `RunFailed` carries `text=`); and the call's result is the run's envelope as JSON (`workflow/agents/envelope.py`), shown by `show_as_delegation`. A cancel of the caller's task stops the run's task first and ends the run `interrupted`. Each run works under its `RunControl` (`workflow/agents/control.py`, `AgentRun.control`), with its type's `AgentConfig.limits` over the policy's (`SubAgentPolicy.limits`, `DEFAULT_LIMITS`: 100 model calls): `Delegations.cancel(run_id, by=, error=)` cancels the run alone (its parent, the user or a limit), and the hook, seeing its own cancel (`own_cancel`), stops the run as a stopped turn's (ADK: its abort signal, its open calls sealed in its child session; Deep Agents: its stream closed) and returns what it has: the run ends `cancelled` with `cancelled_by` and that text, `partial`, while its siblings and the turn go on; the turn's own cancel still wins (`interrupted`). Past its `timeout` (counted from when its hook starts, `timing`) the run is cancelled by its limit (`time limit reached`); each model call is counted before it is made (`RunControlPlugin` in each sub-agent chain, `RunControlMiddleware` on each sub-agent's model side) and the last allowed one gets `STEP_LIMIT_NOTE` after its last message, its tools still declared (Claude refuses tool calls in a request that defines no tools); its answer's calls are dropped, never run, so the run completes `partial`, `step limit reached`; each call's tokens are counted after it, with what the run's other calls used (`RunControl(side_tokens=)`: its tools' side calls and its summaries, the ledger's rows of the run that are no agent step, `UsageLedger.by_purpose(run=)`), so the limit is the run's total as its usage record counts it, and past `max_tokens` an answer that makes tool calls is the run's last, its calls dropped, `cancelled` by its limit (`token limit reached`), while one that makes none ends the run as it would, `completed`, its result whole (a model that reports no usage counts none of its own). A turn starts at most `max_runs_per_turn` runs, at any depth (`sessions.runs_this_turn`): a call past it is the error result, no run started; `task`'s description says so (`limit_sentences`). At most `max_active` runs of a conversation work at once, at any depth (`workflow/agents/slots.py::SlotPool`, one per conversation, `Delegations.slots`; the root takes no slot): a run takes a slot right before its hook and its time limit start and gives it back at its end, however it ends; one that finds none waits `queued` (an `AGENT_RUN` and its record say so, then `running`), not counted against its `timeout`. A run lends its slot while it waits on its children (one lend for all it waits on at once; the child that ends last hands its slot straight back, so the tree in progress goes on ahead of the runs that have not started) or on the user (`waiting_on_user`: `input_required`, `queued` once answered while it waits for its slot back, then `running`, in `request_user_input` and in the permission engine from before its one-prompt lock until after it: a run waiting for a slot while holding the lock would hold every other run's prompt; a prompt no one can be shown, no input callback or its turn ended, lends nothing: `can_request_user_input`), so nested fan-out never deadlocks; a cancel, queued or lending, leaves no waiter in the heap and no slot taken. A message steered to a working run (`RunControl.steer`, through `Delegations.control(run)`) is added after its last message, as the user's, before its next model call, and stays in its transcript (ADK: appended to its child session, the run's later events stamped after it so a durable store reads them back in order; Deep Agents: added to its state); a sub-agent run's task message is never trimmed, on ADK neither by the fit guard nor by the overflow handler's retry, whatever was steered after it. A dialog whose run is stopped is withdrawn, the turn going on (`MessageProcessor`). `AgentConfig.inherit_context` sets what a run sees: False (the default) its task alone, True its parent's conversation too, read once as the run starts (the conversation after any summary; Deep Agents' less the message that called `task`, which ADK's copy keeps), before the task message, which then ends with `INHERITED_CONTEXT_NOTE` (whose conversation it reads, which message is its task); `validate_agent_graph` refuses a value that is not True or False, `inherit_context=True` on the root, on an agent with sub-agents and below another sub-agent. On ADK (`workflow/adk/task_tool.py::TaskTool`) every config-built agent is built on its own, with no ADK `sub_agents`, so ADK offers none `transfer_to_agent`, and gets ADK's identity line ("You are an agent. Your internal name is …"); a delegating agent has one `TaskTool`. A sub-agent is an instance that outlives its run: `idle` when the run ends, its next run a follow-up (`Delegations.follow_up`, through the same hook with `AgentRun.follow_up`, the message as written and no history), one run per instance at a time; a run's end leaves its instance `stopped` (once the user stopped it: its run cancelled by the user, or an idle one; only the user continues it), `closed` (`AgentConfig.continuable` False, or past `SubAgentPolicy.max_open`: the oldest idle one) or `idle`, `Delegations.close` closes an idle or stopped one and its descendants, and `AGENT_INSTANCE` carries a change without a run; the user controls any instance of the open conversation through the manager (`run_instance`: a follow-up as a turn of its own, its Ctrl+C the user's stop; `stop_instance`, `close_instance`, `steer_instance`; `tell_root`: a notice turn of the root, marked as a job's) and the CLI's `/agents` picker and `/agent stop|close <id>`; on ADK a follow-up continues the instance's child session, the calls an earlier run left open answered first (`left_open_by`, from the instance's record), on Deep Agents the instance's own checkpointer thread (`instance_run_config`: its input the message and the caller's mark, the shared keys it changed compared with the thread's state as the run started). Each sub-agent type runs on its own runner (`App(name=child_app(app_name))`, the type's agent its root, `_agent_plugin_chain`: the main chain configured for a sub-agent, no memory index, no summary, `RunControlPlugin` and `SubAgentOutcomePlugin`; every plugin's per-call state keyed by invocation) over the manager's session service, on a child session per instance (`child_session_id`: `<conversation id>/<instance>`, the conversation id's `%` and `/` percent-encoded; an inheriting instance's gets the conversation's events copied once, at its first run, `task_tool.inherited_events`), under an app no conversation list reads. On Deep Agents (`workflow/deepagents/task_tool.py::build_task_tool`) each type's graph is built on its own, and a run `astream`s it in its task with `var_child_runnable_config` cleared, so its chunks reach its own loop alone, never its parent's stream; an inheriting run's history is the parent's messages with Deep Agents' summary event applied (`SummarizationMiddleware._apply_event_to_messages`, private: `tests/workflow/deepagents/test_compact.py` pins it), and `ForeignReasoningMiddleware(kind, agent=...)` leaves out the reasoning of AI messages another agent wrote. A native ADK YAML app keeps transferring (chat-mode sub-agents); a task-mode agent in one is refused at validation, since ADK runs its delegation outside the tool pipeline and keeps the call open across turns. With `SubAgentPolicy(follow_ups=True)` every agent with sub-agents also gets `message_agent`, `stop_agent` and `check_agents` beside `task` (`workflow/agents/follow_ups.py::call_follow_up_tool` over `Delegations.message`/`stop`/`check`; ADK's `FollowUpTool`, Deep Agents' `build_follow_up_tools`; an own tool of one of their names fails the build, a Deep Agents MCP tool of one is skipped): `message_agent` continues an idle instance, steers a running one (before its next step; a run already stopping or finished is waited for, then the message follows the instance up or is refused; one being closed is refused as closed at once) or, with `interrupt` (refused, nothing cancelled, when no follow-up could start; an agent's keeps the turn's run it checked for), replaces its run (the user's interrupt is the user's stop); `stop_agent` cancels a running run by its parent (the instance idle; only the user's stop makes one `stopped`) and, with `close`, closes it and its descendants; a message steered to a run and not in its transcript when it ends goes to the instance's next run (`RunControl.stored`/`unstored`: ADK counts one stored as its child-session append returns, Deep Agents once the model call after it holds it); a run that did not complete fully names its open tasks in its envelope (`open_tasks`); a run whose parent's run was stopped by its control ends `cancelled` by its parent, not `interrupted`. - **Token usage**: every model call the framework makes is one `LLM_USAGE`, on both backends, side calls included (`generate_simple`: `summarize`'s, `purpose` `tool`; `on_session_end`'s, `memory_extraction`, outside any turn; an app's own, `side_call`, or what its caller names with `workflow/usage.py::side_call`), its counts normalized where it is made (`normalized_tokens`: `prompt_tokens` every input token, cache reads and writes included; `completion_tokens` every output token, thinking included; ADK's read by its model's provider kind, `adk_usage_event`/`adk_tokens`, since Gemini and ADK's Claude adapter keep the thinking apart from the candidates and OpenAI's count it inside, an agent of no known kind read as apart; Deep Agents' by LangChain's one convention, `langchain_tokens`; the raw log's usage records alike), and timed (`latency_ms`: on ADK from the request to the answer, `workflow/adk/call_clock.py`'s plugins marking the answer's `custom_metadata`; on Deep Agents by the turn's `RunCallback`, which marks the answer's `response_metadata["agentic_cli"]`, beside the outcome mark; a side call, a summary and the overflow retry around their own request; no adapter sends either mark). Each is recorded in its conversation's ledger (`UsageLedger`; `BaseWorkflowManager.usage`/`usage_of`, in memory for the manager's life: a backend switch's new manager starts afresh, as with `agent_runs`) where it is made, before `on_event` (the event processors, ADK's summarizer, as soon as its call answers, Deep Agents' `RunCallback`, `_report_side_call`), under the run it is made in and its conversation's turn while one runs (as the manager counts them, `/compact` and job notices included: not `SessionInfo.turns`; none in another conversation's turn or from a task its turn outlived, which `_report_side_call` reports to no one); a sub-agent run's `AGENT_RUN` end carries what it used, by model (`metadata["usage"]`, `RunRecord.usage`). The CLI's status bar sums the events it sees (the open conversation's total, on any backend); `/status` shows the ledger by agent. LangGraph (deprecated) records no ledger. - **Tool registration**: Use `@register_tool(category=..., capabilities=..., description=...)` decorator. `capabilities=` is required — pass `EXEMPT` for tools that need no permission check or a list of `Capability(name, target_arg=...)` tuples the engine matches against rules. Tools are auto-discovered via the global `ToolRegistry`. A tool in `AgentConfig.tools` that the registry did not issue is denied at every call; building the agents names it once (`tool_not_registered`, per agent and tool: `BaseWorkflowManager._name_unregistered`): a plain callable, a `FunctionTool`/`StructuredTool` judged by the function it runs (as the gates unwrap it), an app's own tool class; ADK's own tool objects excepted (a built-in runs inside the model). `outside_content=True` (or a function of the call's arguments) declares that a call brings content from outside the user and the project into the conversation (a page, a document, a program's output): once the gate allows one, a memory write in that conversation is approved per call (see Permissions); an application's tools are unmarked unless they declare it, and a variant must declare the same flag as its tool. - **Async tools never block the event loop**: a synchronous tool runs on a worker thread on both backends; an async tool runs on the event loop itself, where a blocking call (DNS, a connect, a file lock's wait, a sleep, a subprocess wait, PDF parsing, page conversion, embedding) freezes the whole app, Ctrl+C included. An async tool runs its slow work with `asyncio.to_thread`. `tests/tools/test_async_tools_never_block.py` lists every async tool (the registry's, the factories' service-bound variants, Deep Agents' skill tools), so a new one fails until it is listed, and calls each through the loop guard (`tests/loop_guard.py`). diff --git a/README.md b/README.md index 4995d17e..ca9846a1 100644 --- a/README.md +++ b/README.md @@ -1428,6 +1428,17 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", `</agents>`, at most 2,000 characters. The list is taken once and kept, as the memory index is, so the prompt stays cached: it is taken again when the conversation is opened, after a summary and after `/compact`. +- **The user's control.** `/agents` picks a sub-agent and shows it; + `/agent stop <id>` (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 <id>` (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), + `stop_instance(id)`, `close_instance(id)`, `steer_instance(id, message)`, + `instance_result(id)`, `tell_root(text)` (with `view_notice(id, + envelope)`'s text, left out of fact extraction and of the conversation's + title and turns, as a job's notice is). - **What the agent graph refuses.** `inherit_context` is for sub-agents only, and only for the main agent's own sub-agents that have none of their own. A coordinator cannot have a tool of its own named `task` (nor, with @@ -2265,7 +2276,8 @@ Built-in slash commands available in all apps: | `/models` | | The list the model pickers offer, each model's facts and why an entry is left out, and the providers in use (`/models <text>` searches the full listings, `/models refresh` lists again) | | `/sandbox` | `/sb` | List / reset stateful sandbox sessions | | `/jobs` | | List and manage long-running background jobs (`/jobs all`, `/jobs <id>`, `/jobs cancel <id>`, `/jobs clean`; `/jobs resume` tells the agent this conversation's finished jobs) | -| `/agents` | | This conversation's sub-agent runs, each under the run that started it: status, title, tokens in/out, time (`/agents <id>`: one instance or run, the first lines of its result, its error and its tokens by model) | +| `/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 shows it (`/agents <id>`: 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 <id>` shows it, `/agent stop <id>` stops it (its run, if one works; only you can start its next run), `/agent close <id>` 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=<id>`; `--backend=<name>` picks one of an id two backends keep); on the memory store it says none are kept | | `/compact` | | Summarize the conversation now, keeping the newest turns word for word (`/compact <focus>`: what the summary should keep above all) | From c9da8366295060c92e2d7de53f6951a2f50ff1c2 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:55:42 -0500 Subject: [PATCH 07/10] Manager: a stop that lands as the user's run starts still stops it A cancel of run_instance's consumer that came after the pump was made but before the follow-up's first step found the instance idle and cancelled nothing, so the run completed and the instance stayed idle. The source looks again when it is cancelled. Also pins that stop_instance and close_instance load the records first, that the base tell_root refuses without a notice hook, and that a blank steer is a ValueError. --- src/agentic_cli/workflow/base_manager.py | 1 + tests/workflow/test_base_manager_tell_root.py | 16 ++++ tests/workflow/test_subagents_contract.py | 89 ++++++++++++++++++- 3 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 tests/workflow/test_base_manager_tell_root.py diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index 5e9c8e20..68b918ee 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -925,6 +925,7 @@ async def source() -> AsyncGenerator[WorkflowEvent, None]: try: delegated = await asyncio.shield(work) except asyncio.CancelledError: + 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()) diff --git a/tests/workflow/test_base_manager_tell_root.py b/tests/workflow/test_base_manager_tell_root.py new file mode 100644 index 00000000..ac819656 --- /dev/null +++ b/tests/workflow/test_base_manager_tell_root.py @@ -0,0 +1,16 @@ +"""The base manager's ``tell_root``: a backend without a notice hook cannot tell its root.""" + +from __future__ import annotations + +import pytest + +from agentic_cli.workflow.base_manager import BaseWorkflowManager + + +async def test_a_backend_without_a_notice_hook_raises_as_iteration_starts(): + class Bare: + _deliver_notice = BaseWorkflowManager._deliver_notice + + with pytest.raises(NotImplementedError, match="cannot tell its root agent a notice"): + async for _ in BaseWorkflowManager.tell_root(Bare(), "A notice."): # type: ignore[arg-type] + pass diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index ccd1aeaf..87f84dec 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -5839,7 +5839,6 @@ async def test_each_takes_the_conversation_its_ids_name(self, make_crew): assert [e.content for e in told if e.type is EventType.TEXT] == ["Noted."] - class TestTheUsersControlOffTheLoop: async def test_it_blocks_no_event_loop(self, make_crew): crew = make_crew( @@ -5918,3 +5917,91 @@ async def test_it_blocks_no_event_loop(self, make_crew): events = [event async for event in crew.manager.tell_root("A notice.")] assert [e.content for e in events if e.type is EventType.TEXT] == ["Noted."] + + +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 + that starts then is still stopped by the user.""" + + async def test_ctrl_c_as_the_stream_starts_stops_the_run_by_the_user(self, make_crew): + import inspect + + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[says("X is 42."), says("Went on.")], + ) + await crew.turn() + + async def view() -> None: + async for _ in crew.manager.run_instance("researcher-1", "Go on."): + 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) + + second = crew.records()[-1] + assert (second.ref.run, second.status, second.cancelled_by) == ( + "researcher-1#2", RUN_CANCELLED, "user", + ) + assert crew.instances() == [("researcher-1", INSTANCE_STOPPED)] + + +class TestTheUsersControlAfterARestart: + async def test_stop_and_close_load_the_records_first(self, make_crew): + first = make_crew( + follow_team(), store="sqlite", + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[says("X is 42.")], + ) + await first.turn() + await first.manager.cleanup() + second = make_crew(follow_team(), store="sqlite") + await second.manager.initialize_services() + + assert await second.manager.stop_instance("researcher-1") is True + assert second.instances() == [("researcher-1", INSTANCE_STOPPED)] + assert await second.manager.close_instance("researcher-1") == ["researcher-1"] + + async def test_close_alone_loads_the_records_first(self, make_crew): + first = make_crew( + follow_team(), store="sqlite", + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[says("X is 42.")], + ) + await first.turn() + await first.manager.cleanup() + second = make_crew(follow_team(), store="sqlite") + await second.manager.initialize_services() + + assert await second.manager.close_instance("researcher-1") == ["researcher-1"] + + +class TestTheEntryPointsRefusals: + async def test_a_blank_steer_is_a_value_error(self, make_crew): + crew = make_crew( + parent_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[calls(use("contract_hold", "r1")), says("X is 42.")], + ) + turn = crew.start() + await asyncio.wait_for(HELD["started"].wait(), 10) + + with pytest.raises(ValueError): + crew.manager.steer_instance("researcher-1", " ") + + HELD["go"].set() + await asyncio.wait_for(turn, 10) From c94f8246bfe2c87c2623425d6e812995ac5bdd0f Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:57:21 -0500 Subject: [PATCH 08/10] Contract: the user's run's mark and the notice's write are each pinned alone The manager's hold of a mark a user's run changed, and ADK's write of the held mark with the notice (the root's model call fails, so the permission plugin never writes it), each fail a test when removed. --- tests/workflow/test_subagents_contract.py | 40 ++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 87f84dec..2d95262c 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -78,7 +78,7 @@ SubAgentPolicy, ) from agentic_cli.workflow.agents.control import STEP_LIMIT_NOTE, RunControl -from agentic_cli.workflow.agents.delegate import FollowUpRequest, started_by +from agentic_cli.workflow.agents.delegate import Delegated, FollowUpRequest, started_by from agentic_cli.workflow.agents.roster import ROSTER_CLOSE, ROSTER_HEADER, ROSTER_MAX, ROSTER_OPEN from agentic_cli.workflow.agents.slots import SlotPool from agentic_cli.workflow.agents.envelope import ( @@ -6005,3 +6005,41 @@ async def test_a_blank_steer_is_a_value_error(self, make_crew): HELD["go"].set() await asyncio.wait_for(turn, 10) + + +class TestTheMarkAUsersRunBrought: + """Each path that carries it to the conversation, pinned alone.""" + + async def test_the_manager_holds_the_mark_a_users_run_changed(self, make_crew): + crew = make_crew(follow_team(), coordinator=[], researcher=[]) + key = "outside_content" + assert not crew.manager._outside_marks.get(crew.conversation) + + crew.manager._user_ran( + crew.conversation, "researcher-1", + Delegated(result={"success": True}, state={key: "contract_bring_outside_content"}, + run=None), + ) + + assert crew.manager._outside_marks.get(crew.conversation) == ( + "contract_bring_outside_content" + ) + + async def test_the_notice_writes_the_held_mark_before_the_root_answers(self, make_crew): + """The root's model call fails: the mark is in the conversation's + state all the same, written with the notice.""" + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done."), + fails("overloaded")], + researcher=[says("X is 42.")], + ) + await crew.turn() + crew.manager._outside_marks.mark(crew.conversation, "contract_bring_outside_content") + before = await crew.marked() + + events = [event async for event in crew.manager.tell_root("A notice.")] + + assert before is False + assert any(e.type is EventType.ERROR for e in events) + assert await crew.marked() is True From 90ca4945c63659cc85e94aaea7b88d53ef362d65 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:57:21 -0500 Subject: [PATCH 09/10] CLI: /agent stop says when the instance ended up closed A type that takes no more runs closes as its stopped run ends; the line is worded from the instance's status after the stop. Also a blank-line slip in two test files. --- src/agentic_cli/cli/agents_command.py | 9 ++++++-- tests/cli/test_agents_command.py | 26 +++++++++++++++++++++- tests/workflow/deepagents/test_sessions.py | 1 - 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/agentic_cli/cli/agents_command.py b/src/agentic_cli/cli/agents_command.py index 4b99e82d..dd3395c9 100644 --- a/src/agentic_cli/cli/agents_command.py +++ b/src/agentic_cli/cli/agents_command.py @@ -47,7 +47,7 @@ from agentic_cli.tools._core.tasks import task_progress_data from agentic_cli.workflow.agents import RUN_COMPLETED, RUN_INPUT_REQUIRED, RUN_STARTED from agentic_cli.workflow.agents.brief import BRIEF_FIELDS -from agentic_cli.workflow.agents.runs import run_number +from agentic_cli.workflow.agents.runs import INSTANCE_CLOSED, run_number if TYPE_CHECKING: from thinking_prompt import Placement @@ -69,6 +69,8 @@ SUBCOMMAND_USAGE = "Usage: /agent {subcommand} <id>" #: 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). +STOPPED_CLOSED_TEXT = "Stopped {instance}: it is closed, as it takes no more runs." #: What ``/agent close`` says it did (``whose``: ``its`` for one id, ``their`` for more). CLOSED_TEXT = "Closed {ids}; /agents {instance} still shows {whose} work." #: What ``/agent stop`` and ``/agent close`` say for an instance that is that already. @@ -149,7 +151,10 @@ async def execute(self, args: str, app: Any) -> None: ids = {"session_id": conversation.session_id, "user_id": conversation.user_id} if word == "stop": if await workflow.stop_instance(wanted, **ids): - app.session.add_success(STOPPED_TEXT.format(instance=wanted)) + record = workflow.agent_runs.instance(conversation, wanted) + closed = record is not None and record.status == INSTANCE_CLOSED + text = STOPPED_CLOSED_TEXT if closed else STOPPED_TEXT + app.session.add_success(text.format(instance=wanted)) return else: closed = await workflow.close_instance(wanted, **ids) diff --git a/tests/cli/test_agents_command.py b/tests/cli/test_agents_command.py index 49895f1f..539468fb 100644 --- a/tests/cli/test_agents_command.py +++ b/tests/cli/test_agents_command.py @@ -166,7 +166,6 @@ async def agent(manager, args: str, *, session_id: str = "s1"): return app.session - def rows_of(table) -> list[tuple[str, ...]]: """A rich table's rows, as text.""" columns = [[str(cell) for cell in column.cells] for column in table.columns] @@ -495,6 +494,7 @@ async def unreadable(conversation: SessionRef) -> None: "Sub-agent records not read from the store: TimeoutError" ) + class TestTheAgentCommand: """``/agent <id>`` shows one sub-agent; ``/agent stop <id>`` and ``/agent close <id>`` stop and close it, each saying what it did or why not.""" @@ -522,6 +522,30 @@ async def test_stop_stops_an_idle_one_and_says_only_the_user_continues_it(self, "researcher-1 · researcher · stopped · Find X." ) + async def test_a_stop_that_leaves_it_closed_says_so(self, manager, monkeypatch): + """A type that is not continuable closes as its stopped run ends.""" + crew_ran(manager) + conversation = manager.session_ref("s1") + + async def stops_and_closes(instance, **ids): + last = manager.agent_runs.record(conversation, instance) + token = set_active_turn(conversation) + try: + manager.agent_runs.observe( + WorkflowEvent.agent_instance(last.ref, "closed", reason="ended") + ) + finally: + reset_active_turn(token) + return True + + monkeypatch.setattr(manager, "stop_instance", stops_and_closes) + + session = await agent(manager, "stop researcher-1") + + session.add_success.assert_called_once_with( + "Stopped researcher-1: it is closed, as it takes no more runs." + ) + async def test_close_closes_it_and_its_sub_agents_and_says_its_work_stays(self, manager): crew_ran(manager) diff --git a/tests/workflow/deepagents/test_sessions.py b/tests/workflow/deepagents/test_sessions.py index 9dfd1b4c..58964c1b 100644 --- a/tests/workflow/deepagents/test_sessions.py +++ b/tests/workflow/deepagents/test_sessions.py @@ -459,7 +459,6 @@ async def test_a_notice_to_the_root_is_no_turn_and_no_title(self, saver, store): assert (row.title, row.turns) == ("Build it.", 1) - async def test_the_limit_keeps_the_newest(self, saver, store): await say(saver, ref(session="s1")) await say(saver, ref(session="s2")) From 2b2ebfd851bda65198c56e7551389a64f6368c18 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:57:21 -0500 Subject: [PATCH 10/10] Docs: changelog order, a lost comma and the turn entry points PR-order of the Added bullets (the roster and brief bullets first), the comma in the base manager's delete clause, and run_instance and tell_root among what enters through _turn. --- CHANGELOG.md | 46 +++++++++++++++++++++++----------------------- CLAUDE.md | 4 ++-- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 508c7678..452b2177 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -575,29 +575,6 @@ the start of the entry's title. ### Added -- **The user's control of sub-agents: `/agent stop`, `/agent close`, and the - manager's entry points.** `/agent stop <id>` stops one of the - conversation's sub-agents: its run, if one works, is cancelled by the user - (`cancelled_by: user`), and the instance is `stopped` (an idle one at once): - its parent's `message_agent` is refused, and only the user may start its - next run. `/agent close <id>` closes it and its own sub-agents: no more - runs, its work still shown by `/agents <id>`. `/agent <id>` shows it. Each - says what it did, or why not. The manager's entry points (provisional; the - open conversation, or the one `session_id`/`user_id` name, any of its - instances): `run_instance(instance, message)`, the user's follow-up as a - turn of its own (`started_by: user`, counted toward no turn's runs, from the - conversation's outside-content mark; stopping its stream, Ctrl+C, is the - user's stop of the run, which ends `cancelled` and leaves the instance - `stopped`), `stop_instance`, `close_instance` (both written to the store - before they return), `steer_instance(instance, message)` (the user's message - to a running run, before its next step), `instance_result` (the envelope of - the latest run the user started) and `tell_root(text)`, a turn of the root - on a notice the user did not type (marked as a job's notice is, so fact - extraction and the conversation's title and turns leave it out; the - outside-content mark a user's run brought is written with it), whose notice - after the user worked with a sub-agent is - `agents/envelope.py::view_notice`: "The user worked with <id> directly; its - latest result: <envelope as JSON>". On both backends, contract-tested. - **The main agent's requests list its open sub-agents, when it can continue them.** With `SubAgentPolicy(follow_ups=True)` a main agent with sub-agents (it has `message_agent`) is told which of its own sub-agents are open: a @@ -640,6 +617,29 @@ the start of the entry's title. of its trigger is not written (the brief restated in each summary can keep a long brief near the trigger), as ADK's is not. The main agent's summaries are unchanged. +- **The user's control of sub-agents: `/agent stop`, `/agent close`, and the + manager's entry points.** `/agent stop <id>` stops one of the + conversation's sub-agents: its run, if one works, is cancelled by the user + (`cancelled_by: user`), and the instance is `stopped` (an idle one at once): + its parent's `message_agent` is refused, and only the user may start its + next run. `/agent close <id>` closes it and its own sub-agents: no more + runs, its work still shown by `/agents <id>`. `/agent <id>` shows it. Each + says what it did, or why not. The manager's entry points (provisional; the + open conversation, or the one `session_id`/`user_id` name, any of its + instances): `run_instance(instance, message)`, the user's follow-up as a + turn of its own (`started_by: user`, counted toward no turn's runs, from the + conversation's outside-content mark; stopping its stream, Ctrl+C, is the + user's stop of the run, which ends `cancelled` and leaves the instance + `stopped`), `stop_instance`, `close_instance` (both written to the store + before they return), `steer_instance(instance, message)` (the user's message + to a running run, before its next step), `instance_result` (the envelope of + the latest run the user started) and `tell_root(text)`, a turn of the root + on a notice the user did not type (marked as a job's notice is, so fact + extraction and the conversation's title and turns leave it out; the + outside-content mark a user's run brought is written with it), whose notice + after the user worked with a sub-agent is + `agents/envelope.py::view_notice`: "The user worked with <id> directly; its + latest result: <envelope as JSON>". On both backends, contract-tested. - **A parent's tools that continue its sub-agents, `message_agent`, `stop_agent` and `check_agents`, on both backends, with `SubAgentPolicy(follow_ups=True)`.** Every agent with sub-agents gets them diff --git a/CLAUDE.md b/CLAUDE.md index fcfac739..abf03be0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -49,7 +49,7 @@ agentic-cli/ │ │ ├── waiting_jobs.py # Which finished jobs wait to be told in the open conversation: one rule (JobRecord.awaiting_resume, then its own, no conversation's, or a gone conversation's: can_resume, then the other installed backends' readers, opens_anywhere: one another backend keeps is not gone, its job waits for it) for the deliveries, ↻N and the startup line │ │ └── usage_tracker.py # Token usage / status bar: ctx = the main agent's last prompt over its context_trigger (a call with a purpose, a sub-agent's, a summary's or a side call's, never moves it); the token segment the open conversation's total, every call of its turns; format_usage: /status's rows by agent and /agents <id>'s tokens by model │ ├── workflow/ -│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none); the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget 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), 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', then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built: each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) +│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none); the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, 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), 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', then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built: each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) │ │ ├── factory.py # create_workflow_manager_from_settings (_BACKENDS: orchestrator → "module:Class" + extra, imported when chosen; orchestrator=: another backend than the settings'; session_store=: the store a manager is built for, BaseWorkflowManager.session_store, the settings' by default; subagents=: the SubAgentPolicy the manager gets, checked before a backend is imported); orchestrator_of; check_backend (an unknown name, a missing extra) │ │ ├── session_readers.py # SessionReader: a backend's stored conversations read without its manager (list/info/exists/delete/aclose, rows naming the backend; delete deletes what the manager's does, ADK's sub-agent transcripts and records with the conversation), opened from the settings and a store (open_session_reader: the backend's own session code, adk/sessions.py::open_sessions and deepagents/sessions.py::open_sessions, imported on a worker thread; no agents, models or services; a sqlite store not made yet reads empty and is not made, Deep Agents not even imported for it; a database without its backend's tables, looked at read-only, reads empty, nothing written to it: no table, no journal mode); none for the memory store or LangGraph; ImportError (the install hint) for a missing extra; reader_backends │ │ ├── service_registry.py # get_service/require_service + ContextVar registry; the registry keys and KNOWN_SERVICE_KEYS, read from services.py's table @@ -262,7 +262,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()`, and `compact()` (`/compact`), 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) 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.