From da31a9393bfb21c1d9d98e3e11e64aedb572721e Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:20:42 -0500 Subject: [PATCH 01/17] CLI: a sub-agent's run in its view, and the main agent's notice, as turns process_instance draws the user's line in a sub-agent's view as a turn whose source is run_instance: the instance's text is the reply and its lines name nobody, and each event of its run draws the status bar again. process_notice draws the main agent's notice after a view (tell_root) as a job's notice turn is. --- src/agentic_cli/cli/message_processor.py | 152 +++++++++++++++++++++-- tests/test_message_processor_render.py | 122 ++++++++++++++++++ 2 files changed, 265 insertions(+), 9 deletions(-) diff --git a/src/agentic_cli/cli/message_processor.py b/src/agentic_cli/cli/message_processor.py index 14cf1777..90cb0852 100644 --- a/src/agentic_cli/cli/message_processor.py +++ b/src/agentic_cli/cli/message_processor.py @@ -320,6 +320,9 @@ class _EventProcessingState: # names (``get_status``). at_work: str | None = None line_by: str | None = None + # The instance whose view the turn runs in (``process_instance``): its text + # is the reply and its lines name nobody, as the main agent's. + viewed: str | None = None def __setattr__(self, name: str, value: Any) -> None: # Whichever handler writes the status line, it writes the work of @@ -349,14 +352,24 @@ def get_status(self) -> str: } -def _at_work(event: "WorkflowEvent") -> str | None: +def _at_work(event: "WorkflowEvent", viewed: str | None = None) -> str | None: """The sub-agent run ``event`` is the work of (its instance), or None. None for the main agent's own (``root_run``), a depth-0 agent's (a native ADK YAML app's transfer target) and the manager's (no run): those lines - name nobody, as before. + name nobody, as before. None too for the instance in ``viewed``: in its + view it is the agent the user works with. """ - return instance_of(getattr(event, "run", None)) + instance = instance_of(getattr(event, "run", None)) + return None if instance == viewed else instance + + +def _in_view(event: "WorkflowEvent", state: _EventProcessingState) -> bool: + """Whether ``event`` is the work of the instance whose view the turn runs in.""" + return ( + state.viewed is not None + and instance_of(getattr(event, "run", None)) == state.viewed + ) # === Message Processor === @@ -572,6 +585,117 @@ def _source(wf): _source, workflow_controller, ui, settings, usage_tracker ) + async def process_instance( + self, + instance: str, + message: str, + workflow_controller: "WorkflowController", + ui: "ThinkingPromptSession", + settings: "BaseSettings", + usage_tracker: "UsageTracker | None" = None, + session_id: str | None = None, + ) -> TurnResult: + """Run the user's line as the next run of a sub-agent, in its view. + + The source is ``workflow.run_instance`` (``started_by: user``). It is + drawn as a turn is (events box, tool results, token accounting, + Ctrl+C), but the instance is the agent the user works with: its text + is the reply and its lines name nobody (``viewed``), and each event of + its run draws the status bar again, which names its status. A + follow-up that cannot run is the turn's one ``ERROR``. + + Args: + instance: The sub-agent instance in view (``researcher-2``). + message: The user's line. + workflow_controller: Controller managing workflow lifecycle. + ui: UI session for output. + settings: Application settings. + usage_tracker: Optional tracker for accumulating LLM token usage. + session_id: The conversation, the app's durable session. + + Returns: + The turn's outcome; ``TurnResult.delivered`` is True only when the + event stream ran to completion. + + Raises: + asyncio.CancelledError: Ctrl+C stopped it (the user's stop of the + run): ``CANCELLED_LINE`` has been said, once. + """ + async with _says_so_when_stopped(ui, lambda: _job_manager(workflow_controller)): + if not await workflow_controller.ensure_initialized(ui): + ui.add_error( + "Cannot process message - workflow not initialized. " + "Please check your API keys (GOOGLE_API_KEY or ANTHROPIC_API_KEY)." + ) + return TurnResult( + TurnStatus.UNAVAILABLE, error="workflow not initialized" + ) + + bind_context(user_id=settings.default_user) + logger.info( + "handling_instance_message", instance=instance, message_length=len(message) + ) + + def _source(workflow): + return workflow.run_instance( + instance, + message, + session_id=session_id, + user_id=settings.default_user, + ) + + return await self._run_turn( + _source, workflow_controller, ui, settings, usage_tracker, viewed=instance + ) + + async def process_notice( + self, + text: str, + workflow_controller: "WorkflowController", + ui: "ThinkingPromptSession", + settings: "BaseSettings", + usage_tracker: "UsageTracker | None" = None, + session_id: str | None = None, + ) -> TurnResult: + """Tell the main agent what the user did in a sub-agent's view. + + A notice the user did not type (``view_notice``): the source is + ``workflow.tell_root``, a turn of the main agent whose input is + ``text``, drawn as a job's notice turn is (its reply is the reply). + + Args: + text: The notice. + workflow_controller: Controller managing workflow lifecycle. + ui: UI session for output. + settings: Application settings. + usage_tracker: Optional tracker for accumulating LLM token usage. + session_id: The conversation, the app's durable session. + + Returns: + The turn's outcome; ``UNAVAILABLE`` when the workflow is not ready. + + Raises: + asyncio.CancelledError: Ctrl+C stopped it, as it stops a turn: + ``CANCELLED_LINE`` has been said, once. + """ + async with _says_so_when_stopped(ui, lambda: _job_manager(workflow_controller)): + if not await workflow_controller.ensure_initialized(ui): + return TurnResult( + TurnStatus.UNAVAILABLE, error="workflow not initialized" + ) + + bind_context(user_id=settings.default_user) + logger.info("handling_notice", notice_length=len(text)) + + def _source(workflow): + return workflow.tell_root( + text, session_id=session_id, user_id=settings.default_user + ) + + return await self._run_turn( + _source, workflow_controller, ui, settings, usage_tracker + ) + async def process_compact( self, focus: str | None, @@ -670,11 +794,15 @@ async def _run_turn( ui: "ThinkingPromptSession", settings: "BaseSettings", usage_tracker: "UsageTracker | None" = None, + *, + viewed: str | None = None, ) -> TurnResult: """Drive one turn from an event-source factory through the UI. - Shared by ``process`` (user message) and ``process_resume`` (job - result). ``source_factory(workflow)`` returns the WorkflowEvent async + Shared by ``process`` (user message), ``process_resume`` (job + result), ``process_instance`` (a sub-agent's run in its view, whose + instance is ``viewed``) and ``process_notice``. + ``source_factory(workflow)`` returns the WorkflowEvent async generator to consume; everything else (events box, HITL callback, Ctrl+C cancel, rate-limit retry, token accounting) is identical. @@ -722,6 +850,7 @@ async def _run_turn( state = _EventProcessingState( usage_tracker=usage_tracker, workflow_controller=workflow_controller, + viewed=viewed, ) workflow = workflow_controller.workflow dispatch = self._get_event_dispatch() @@ -813,7 +942,7 @@ async def _consume() -> None: async for event in events: handler = dispatch.get(event.type) if handler is not None: - state.at_work = _at_work(event) + state.at_work = _at_work(event, state.viewed) await handler( self, event, state, ui, settings, workflow ) @@ -1037,12 +1166,13 @@ async def _handle_text( ``metadata["subagent"]`` by the backend) is its work, which its parent reads as a tool result: it becomes the events box's status line, under its run's name (``researcher-2 › …``, ``get_status``), or its - agent's when the event names no run, and is no part of the reply. + agent's when the event names no run, and is no part of the reply. In a + sub-agent's view the instance in view replies (``_in_view``). """ # Text is already on screen, or in the durable session: replaying the # turn would emit it twice. state.side_effects_seen = True - if event.metadata.get("subagent"): + if event.metadata.get("subagent") and not _in_view(event, state): line = next( (line.strip() for line in event.content.splitlines() if line.strip()), "" ) @@ -1339,11 +1469,15 @@ async def _handle_agent_run( Under the run's name: ``queued`` (waiting for a free working slot), ``input_required`` (waiting on the user) and ``running`` each write the line (``_RUN_LINES``); a run's start and end write none, nor is - anything printed (``/agents`` lists the runs). + anything printed (``/agents`` lists the runs). In a sub-agent's view + each event of the instance's run draws the status bar again: it names + the instance's status. """ line = _RUN_LINES.get(event.metadata.get("status")) if line is not None: state.status_line = line + if _in_view(event, state) and state.workflow_controller is not None: + state.workflow_controller.update_status_bar(ui) async def _handle_llm_usage( self, diff --git a/tests/test_message_processor_render.py b/tests/test_message_processor_render.py index 3a47739b..cfcd34b7 100644 --- a/tests/test_message_processor_render.py +++ b/tests/test_message_processor_render.py @@ -612,3 +612,125 @@ async def test_a_sub_agents_text_without_a_run_keeps_its_agents_name(self): _, lines = await _watch([found]) assert lines == ["researcher: X is 42."] + + +# --- a sub-agent's view: its run, and the main agent's notice ------------------------ + + +RESEARCHER_1_2 = RunRef("researcher", "researcher-1", "researcher-1#2", None, 1) +WRITER_1 = RunRef("writer", "writer-1", "writer-1#1", "researcher-1#2", 2) + + +class _Viewing(_Watching): + """Replays events as an instance's run (``run_instance``) or as a notice + turn of the root (``tell_root``), noting what it was asked.""" + + def __init__(self, events: list[WorkflowEvent], ui: _Watched) -> None: + super().__init__(events, ui) + self.asked: list[tuple] = [] + + async def run_instance(self, instance, message, *, session_id=None, user_id=None): + self.asked.append(("run_instance", instance, message, session_id, user_id)) + async for event in self.process(message, user_id, session_id): + yield event + + async def tell_root(self, text, *, session_id=None, user_id=None): + self.asked.append(("tell_root", text, session_id, user_id)) + async for event in self.process(text, user_id, session_id): + yield event + + +def _text_of(run: RunRef, text: str) -> WorkflowEvent: + """A sub-agent run's text, marked as the backends mark it.""" + event = _by(run, WorkflowEvent.text(text)) + event.metadata.update(agent=run.agent, subagent=True) + return event + + +class TestAViewsRun: + """In a sub-agent's view the user's line is the instance's next run + (``process_instance``, ``run_instance``), drawn as a turn: the instance's + text is the reply and its lines name nobody (it is the agent in view); + a run it starts is shown as in any turn, under its name.""" + + async def test_the_instances_text_is_the_reply_and_its_lines_name_nobody(self): + events = [ + WorkflowEvent.agent_run(RESEARCHER_1_2, "started", input="Go on."), + _by(RESEARCHER_1_2, WorkflowEvent.tool_call("lookup", {"q": "x"})), + _by(WRITER_1, WorkflowEvent.tool_call("draft", {})), + _text_of(WRITER_1, "A draft.\nMore."), + _text_of(RESEARCHER_1_2, "Y is 7."), + WorkflowEvent.agent_run(RESEARCHER_1_2, "completed", result="Y is 7."), + ] + ui = _Watched() + workflow = _Viewing(events, ui) + + result = await MessageProcessor().process_instance( + "researcher-1", "Go on.", workflow_controller=ReplayController(workflow), ui=ui, + settings=_settings(), session_id="s1", + ) + + assert result.delivered + assert workflow.asked == [("run_instance", "researcher-1", "Go on.", "s1", "tester")] + assert workflow.lines == [ + "Processing...", "Calling: lookup", "writer-1 › Calling: draft", + "writer-1 › A draft.", "writer-1 › A draft.", "writer-1 › A draft.", + ] + assert ui.responses() == ["Y is 7."] + + async def test_each_of_its_run_events_draws_the_status_bar_again(self): + """The bar names the instance's status, which its run's start and end change.""" + ui = _Watched() + workflow = _Viewing([ + WorkflowEvent.agent_run(RESEARCHER_1_2, "started", input="Go on."), + WorkflowEvent.agent_run(WRITER_1, "started", title="Draft it."), + WorkflowEvent.agent_run(RESEARCHER_1_2, "completed", result="Y is 7."), + ], ui) + controller = ReplayController(workflow) + + await MessageProcessor().process_instance( + "researcher-1", "Go on.", workflow_controller=controller, ui=ui, + settings=_settings(), + ) + + assert controller.status_bar_updates == 3 # its start, its end, the turn's end + + async def test_a_turn_of_the_main_agent_still_shows_a_sub_agents_text_as_its_line(self): + """Outside a view nothing changed: the same run's text is a status line.""" + ui, lines = await _watch([_text_of(RESEARCHER_1_2, "Y is 7.")]) + + assert lines == ["researcher-1 › Y is 7."] + assert ui.responses() == [] + + async def test_a_refusal_is_the_turns_error(self): + ui = _Watched() + workflow = _Viewing([WorkflowEvent.error("researcher-1 is closed.")], ui) + + result = await MessageProcessor().process_instance( + "researcher-1", "Go on.", workflow_controller=ReplayController(workflow), ui=ui, + settings=_settings(), + ) + + assert not result.delivered + assert ui.errors() == ["researcher-1 is closed."] + + +class TestANoticeTurn: + """``process_notice``: the main agent told what the user did in a view + (``tell_root``), drawn as a job's notice turn is: its reply is the reply.""" + + async def test_the_root_reads_the_notice_and_its_answer_is_shown(self): + ui = _Watched() + workflow = _Viewing([WorkflowEvent.text("Noted: Y is 7.")], ui) + + result = await MessageProcessor().process_notice( + "The user worked with researcher-1 directly.", + workflow_controller=ReplayController(workflow), ui=ui, settings=_settings(), + session_id="s1", + ) + + assert result.delivered + assert workflow.asked == [ + ("tell_root", "The user worked with researcher-1 directly.", "s1", "tester"), + ] + assert ui.responses() == ["Noted: Y is 7."] From b169586e92af92a83e595952e607deed99dc2a46 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:22:32 -0500 Subject: [PATCH 02/17] CLI: a sub-agent's view: /agent , a line as its next run or a steer, /back /agent (and Enter in /agents' picker) opens one instance's view: a rule, a recap, the prompt > and a status bar naming the instance, its status, its own ctx and tokens. A line typed there is the instance's next run, started in a task of its own outside the input handler so the prompt stays open, or, while its run works, is given to that run before its next model step. /back leaves it. A closed instance's view is read-only. --- src/agentic_cli/cli/agent_view.py | 387 +++++++++++++++++++++ src/agentic_cli/cli/agents_command.py | 19 +- src/agentic_cli/cli/app.py | 44 +++ src/agentic_cli/cli/conversation.py | 78 +++++ src/agentic_cli/cli/workflow_controller.py | 16 +- tests/cli/test_agent_view.py | 324 +++++++++++++++++ tests/cli/test_agents_command.py | 32 +- 7 files changed, 865 insertions(+), 35 deletions(-) create mode 100644 src/agentic_cli/cli/agent_view.py create mode 100644 tests/cli/test_agent_view.py diff --git a/src/agentic_cli/cli/agent_view.py b/src/agentic_cli/cli/agent_view.py new file mode 100644 index 00000000..dbf23344 --- /dev/null +++ b/src/agentic_cli/cli/agent_view.py @@ -0,0 +1,387 @@ +"""A sub-agent's view: ``/agent `` and ``/back`` (provisional). + +The user works with one instance of the open conversation directly, as with +the main agent. Entering its view (``/agent ``, or Enter in ``/agents``' +picker) prints a rule, ``── researcher-2 · researcher · idle ──``, and a +recap of it: its brief's title and objective, its last run's status, the +first lines of its result and its tokens; nothing is replayed. The prompt +becomes ``researcher-2> `` and the status bar names it and its status, its +context (``ctx``: its own last prompt against its own summary trigger) and +its tokens, the jobs segment kept. + +A line typed there is the user's message to the instance: while it is idle +(or stopped: only the user may continue one) its next run (the manager's +``run_instance``), drawn as a turn is, its text the reply; while its run +works, given to that run before its next model step (``steer_instance``), +never queued as a turn. The run works in a task of its own, outside the +input handler: thinking-prompt takes no line while a handler runs, so the +prompt stays open for the lines that steer it. A closed instance's view is +read-only: no prompt, and a line typed there is refused. + +``/back`` leaves: it waits for a run still working and prints ``── back to +main ──``. While a view is open, ``/compact`` is refused, ``/new`` and +``/resume`` leave it first, and ``/status`` shows the instance's context. +""" + +from __future__ import annotations + +import asyncio +import dataclasses +from typing import TYPE_CHECKING, Any + +from rich.table import Table +from rich.text import Text + +from agentic_cli.cli.agents_command import ( + NO_SUCH_AGENT, + _first_lines, + _load, + _run_number, + _status, + _workflow, +) +from agentic_cli.cli.commands import Command, CommandCategory +from agentic_cli.cli.message_processor import MessageProcessor +from agentic_cli.cli.usage_tracker import UsageTracker, format_tokens +from agentic_cli.logging import Loggers +from agentic_cli.workflow.agents import INSTANCE_CLOSED, INSTANCE_RUNNING +from agentic_cli.workflow.usage import PURPOSE_SUBAGENT + +if TYPE_CHECKING: + from agentic_cli.workflow.agents import InstanceRecord, RunRecord + from agentic_cli.workflow.sessions import SessionRef + +logger = Loggers.cli() + +#: The rule a view opens with. +VIEW_RULE = "── {instance} · {agent} · {status} ──" +#: The rule ``/back`` prints. +BACK_RULE = "── back to main ──" +#: The prompt in an instance's view (a closed one's has none). +VIEW_PROMPT = "{instance}> " +#: What a line typed in a closed instance's view is told. +READ_ONLY = "{instance} is closed: its view is read-only. /back returns to the main conversation." +#: What ``/back`` says outside a view. +NOT_IN_VIEW = "Not in a sub-agent's view: /agent opens one." +#: What a line given to the run in view says. +STEERED = "Given to {instance}'s run before its next step." + + +class AgentView: + """One instance's view, open in the app (``BaseCLIApp.agent_view``). + + Args: + app: The app it is open in. + instance: The instance in view (``researcher-2``). + conversation: The conversation it belongs to (the app's). + told: The run of the user's whose envelope the main agent knows of + (``instance_result``'s, as the view opened): ``/back`` tells it + only of a later one. + """ + + def __init__( + self, app: Any, instance: str, conversation: "SessionRef", told: str | None + ) -> None: + self.app = app + self.instance = instance + self.conversation = conversation + self.told = told + #: The view's own message processor: its runs' task list is the + #: instance's, never the main agent's task box. + self.processor = MessageProcessor() + #: The prompt the app had: put back by ``/back``. + self.prompt_before: Any = None + self._runs: set[asyncio.Task[None]] = set() + + # -- what it shows --------------------------------------------------------------- + + def record(self) -> "InstanceRecord | None": + """The instance's record now; None when it is gone (or no workflow runs).""" + try: + return self.app.workflow.agent_runs.instance(self.conversation, self.instance) + except (RuntimeError, AttributeError): + return None + + def prompt(self) -> str: + """``researcher-2> ``; none for a closed instance's view, which is read-only.""" + record = self.record() + if record is not None and record.status == INSTANCE_CLOSED: + return "" + return VIEW_PROMPT.format(instance=self.instance) + + def status_segment(self) -> str: + """What the status bar says of the instance: ``researcher-2 · idle | + ctx 4k/170k (2%) | Tokens: 4.2k in / 310 out`` (its context and tokens + once it has any). Never raises: the bar is drawn from timers too.""" + try: + workflow = self.app.workflow + record = workflow.agent_runs.instance(self.conversation, self.instance) + if record is None: + return self.instance + parts = [f"{self.instance} · {record.status}"] + context = _context(workflow, self.conversation, record) + if context: + parts.append(context) + tokens_in, tokens_out = instance_tokens(workflow, self.conversation, self.instance) + if tokens_in or tokens_out: + parts.append( + f"Tokens: {format_tokens(tokens_in)} in / {format_tokens(tokens_out)} out" + ) + return " | ".join(parts) + except Exception: # noqa: BLE001 - the bar names the instance at least + logger.debug("view_status_failed", instance=self.instance, exc_info=True) + return self.instance + + def show(self, record: "InstanceRecord") -> None: + """Print the view's rule and the instance's recap.""" + session = self.app.session + session.add_message("system", VIEW_RULE.format( + instance=self.instance, agent=record.agent, status=record.status, + )) + session.add_rich(recap(self.app.workflow, self.conversation, self.instance)) + + def refresh(self) -> None: + """Draw its prompt and status bar again, while it is the app's view: + the instance's status may have changed (a run ended, ``/agent + close``).""" + app = self.app + if app.agent_view is not self: + return + app.session.message = self.prompt() + app._workflow_controller.update_status_bar(app.session) + + # -- its runs ---------------------------------------------------------------------- + + @property + def working(self) -> bool: + """Whether a run the user started here is still going (or waits to start).""" + return any(not run.done() for run in self._runs) + + async def take(self, line: str) -> None: + """A line the user typed in the view: given to the run that works, or + the instance's next run, started in a task of its own (``settled`` + waits for it). A closed instance's view refuses it.""" + app = self.app + workflow = _workflow(app) + if workflow is None: + return + record = workflow.agent_runs.instance(self.conversation, self.instance) + if record is not None and record.status == INSTANCE_CLOSED: + app.session.add_warning(READ_ONLY.format(instance=self.instance)) + return + app.session.add_message("user", line) + if ( + record is not None + and record.status == INSTANCE_RUNNING + and workflow.steer_instance( + self.instance, + line, + session_id=self.conversation.session_id, + user_id=self.conversation.user_id, + ) + ): + app.session.add_message("system", STEERED.format(instance=self.instance)) + return + run = asyncio.create_task(self._run(line), name=f"view run of {self.instance}") + self._runs.add(run) + run.add_done_callback(self._ended) + + async def _run(self, line: str) -> None: + """The instance's next run on ``line``: a write to the conversation + under its turn lock (``ConversationCore.run_instance``).""" + app = self.app + parts = dataclasses.replace(app._turn_parts(), processor=self.processor) + try: + await app._conversation.run_instance(self.instance, line, parts) + finally: + self.refresh() + + def _ended(self, run: "asyncio.Task[None]") -> None: + """A run's task ended: forgotten; a failure the turn did not report is said.""" + self._runs.discard(run) + if run.cancelled(): + return + error = run.exception() + if error is not None: + logger.info( + "view_run_failed", instance=self.instance, error=str(error), + error_type=type(error).__name__, + ) + self.app.session.add_error(f"Error: {str(error) or type(error).__name__}") + + def stop(self) -> bool: + """Stop the run in view (the user's stop: the instance is ``stopped``). + Whether one was working.""" + working = [run for run in self._runs if not run.done()] + for run in working: + run.cancel() + return bool(working) + + async def settled(self) -> None: + """Wait until no run the user started here works (none is stopped).""" + while self._runs: + await asyncio.wait(set(self._runs)) + + +# -- entering and leaving ------------------------------------------------------------ + + +async def open_view(app: Any, instance: str) -> bool: + """Open ``instance``'s view in ``app`` (``BaseCLIApp.open_agent_view``). + + The conversation's records are loaded first (one that cannot be read is + said, and no view opens), and an unknown id is said + (``NO_SUCH_AGENT``). In its own view it prints the rule and recap again; + in another's it leaves that one first, as ``/back`` does. + + Returns: + Whether the view is open. + """ + workflow = _workflow(app) + if workflow is None: + return False + conversation = workflow.session_ref(getattr(app, "session_id", None)) + if not await _load(app, workflow, conversation): + return False + record = workflow.agent_runs.instance(conversation, instance) + if record is None: + app.session.add_warning(NO_SUCH_AGENT.format(id=instance)) + return False + current = app.agent_view + if current is not None: + if current.instance == instance and current.conversation == conversation: + current.show(record) + current.refresh() + return True + await leave_view(app) + latest = workflow.instance_result( + instance, session_id=conversation.session_id, user_id=conversation.user_id + ) + view = AgentView(app, instance, conversation, told=(latest or {}).get("run")) + view.show(record) + view.prompt_before = app.session.message + app._agent_view = view + app._workflow_controller.view_segment = view.status_segment + view.refresh() + logger.info("agent_view_opened", instance=instance) + return True + + +async def leave_view(app: Any) -> bool: + """``/back`` (``BaseCLIApp.leave_agent_view``): leave the view open, back + to the main conversation; False, said, when none is. + + A run still working there ends first (Ctrl+C stops it); then the rule, + the app's prompt and status bar. + """ + view = app.agent_view + if view is None: + app.session.add_message("system", NOT_IN_VIEW) + return False + await view.settled() + app._agent_view = None + controller = app._workflow_controller + controller.view_segment = None + app.session.message = view.prompt_before + app.session.add_message("system", BACK_RULE) + controller.update_status_bar(app.session) + logger.info("agent_view_left", instance=view.instance) + return True + + +class BackCommand(Command): + """Leave a sub-agent's view, back to the main conversation.""" + + def __init__(self) -> None: + super().__init__( + name="back", + description="Leave a sub-agent's view (/agent ), back to the main conversation", + usage="/back", + category=CommandCategory.WORKFLOW, + ) + + async def execute(self, args: str, app: Any) -> None: + """Leave the view open (``leave_agent_view``), or say there is none.""" + await app.leave_agent_view() + + +# -- what the view reads --------------------------------------------------------------- + + +def recap(workflow: Any, conversation: "SessionRef", instance: str) -> Table: + """A view's recap of ``instance``: its title, its first brief's objective, + its last run's status, the first lines of its result, and its tokens.""" + runs = _runs_of(workflow, conversation, instance) + record = workflow.agent_runs.instance(conversation, instance) + table = Table(show_header=False, box=None, padding=(0, 2, 0, 0)) + table.add_column("Key", style="bold cyan", no_wrap=True) + table.add_column("Value") + table.add_row("Title", Text((record.title if record is not None else "") or "—")) + if runs: + objective = runs[0].brief.get("objective") + if objective: + table.add_row("Objective", Text(_first_lines(objective))) + last = runs[-1] + table.add_row("Last run", Text(f"{_run_number(last)} · {_status(last)}")) + if last.result: + table.add_row("Result", Text(_first_lines(last.result))) + tokens_in, tokens_out = instance_tokens(workflow, conversation, instance) + table.add_row( + "Tokens", Text(f"{format_tokens(tokens_in)} in / {format_tokens(tokens_out)} out") + ) + return table + + +def instance_tokens(workflow: Any, conversation: "SessionRef", instance: str) -> tuple[int, int]: + """The tokens ``instance``'s runs used, in and out: each run's from the + usage ledger, or its record's totals (a run from before a restart).""" + ledger = workflow.usage_of(conversation) + tokens_in = tokens_out = 0 + for record in _runs_of(workflow, conversation, instance): + by_model = ledger.by_model(run=record.ref.run) + if by_model: + tokens_in += sum(totals.input for totals in by_model.values()) + tokens_out += sum(totals.output for totals in by_model.values()) + else: + tokens_in += sum(totals.get("input", 0) for totals in record.usage.values()) + tokens_out += sum(totals.get("output", 0) for totals in record.usage.values()) + return tokens_in, tokens_out + + +def _runs_of(workflow: Any, conversation: "SessionRef", instance: str) -> list["RunRecord"]: + """``instance``'s runs, oldest first.""" + return [ + record for record in workflow.agent_runs.records(conversation) + if record.ref.instance == instance + ] + + +def _budget(workflow: Any, agent: str) -> Any: + """``agent``'s context budget; None when its manager manages none.""" + try: + return workflow.context_budget(agent) + except (KeyError, RuntimeError, AttributeError): + return None + + +def _last_prompt(workflow: Any, conversation: "SessionRef", record: "InstanceRecord") -> int: + """The instance's last prompt, in tokens: its last own step's in the ledger (0: none yet).""" + runs = set(record.runs) + return next( + ( + row.input for row in reversed(workflow.usage_of(conversation).rows) + if row.run in runs and row.purpose == PURPOSE_SUBAGENT + ), + 0, + ) + + +def _context(workflow: Any, conversation: "SessionRef", record: "InstanceRecord") -> str: + """The status bar's ``ctx`` for the instance: its last prompt against its + own trigger, as the main agent's is shown (``UsageTracker.format_context``).""" + budget = _budget(workflow, record.agent) + return UsageTracker( + last_prompt_tokens=_last_prompt(workflow, conversation, record), + context_trigger=budget.trigger if budget is not None else None, + window_known=budget.window_known if budget is not None else None, + ).format_context() diff --git a/src/agentic_cli/cli/agents_command.py b/src/agentic_cli/cli/agents_command.py index dd3395c9..6b188edb 100644 --- a/src/agentic_cli/cli/agents_command.py +++ b/src/agentic_cli/cli/agents_command.py @@ -3,7 +3,8 @@ ``/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 +deeper. Enter opens the view of the one picked (``/agent ``), Esc +nothing; ``/agents `` shows 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 @@ -14,7 +15,8 @@ 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 +``/agent `` opens one's view (``cli/agent_view.py``: the user works with +it directly, ``/back`` returns); ``/agent stop `` is the user's stop of an instance (its run, if one works, cancelled by the user; only the user may start its next run) and ``/agent close `` the user's close of it and its own sub-agents (no more runs; its work stays readable). Each says what it @@ -95,7 +97,7 @@ def __init__(self) -> None: ) async def execute(self, args: str, app: Any) -> None: - """The instances in a picker (Enter shows one), or, with an id, that one.""" + """The instances in a picker (Enter opens the view of one), or, with an id, shows that one.""" workflow = _workflow(app) if workflow is None: return @@ -112,23 +114,23 @@ async def execute(self, args: str, app: Any) -> None: 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]) + await app.open_agent_view(ids[picked]) class AgentCommand(Command): - """Show, stop or close one of the open conversation's sub-agents.""" + """Open, 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", + description="Open one of this conversation's sub-agents, or stop or close one", usage="/agent | stop | close ", examples=["/agent researcher-2", "/agent stop researcher-2", "/agent close researcher-2"], category=CommandCategory.WORKFLOW, ) async def execute(self, args: str, app: Any) -> None: - """``/agent `` shows one; ``stop `` and ``close `` stop and close it.""" + """``/agent `` opens its view; ``stop `` and ``close `` stop and close it.""" workflow = _workflow(app) if workflow is None: return @@ -139,8 +141,7 @@ async def execute(self, args: str, app: Any) -> None: return word = parts[0] if word not in ("stop", "close"): - await _load(app, workflow, conversation) - show(app, workflow, conversation, word) + await app.open_agent_view(word) return if len(parts) < 2: app.session.add_warning(SUBCOMMAND_USAGE.format(subcommand=word)) diff --git a/src/agentic_cli/cli/app.py b/src/agentic_cli/cli/app.py index 8f7936ef..5719c946 100644 --- a/src/agentic_cli/cli/app.py +++ b/src/agentic_cli/cli/app.py @@ -31,6 +31,7 @@ from thinking_prompt import AppInfo, ThinkingPromptSession, ThinkingPromptStyles +from agentic_cli.cli.agent_view import AgentView, leave_view, open_view from agentic_cli.cli.commands import Command, CommandRegistry from agentic_cli.cli.message_processor import MessageProcessor, _says_so_when_stopped from agentic_cli.cli.conversation import ( @@ -389,6 +390,10 @@ class BaseCLIApp: #: and the newer ones passed over; None when it chose nothing then. _chosen_at_start: "tuple[Hold | None, list[tuple[str, int]]] | None" = None + #: The sub-agent's view that is open (``open_agent_view``); None in the + #: main conversation. + _agent_view: AgentView | None = None + def __init__( self, app_info: AppInfo, @@ -617,6 +622,34 @@ def workflow(self) -> "BaseWorkflowManager": """ return self._workflow_controller.workflow + @property + def agent_view(self) -> AgentView | None: + """The sub-agent's view that is open (provisional), or None in the + main conversation: a line typed goes to it, and the prompt and status + bar are its.""" + return self._agent_view + + async def open_agent_view(self, instance: str) -> bool: + """Open the view of one of the conversation's sub-agents (provisional). + + What ``/agent `` and Enter in ``/agents``' picker call + (``cli/agent_view.py``). In another's view it leaves that one first. + + Returns: + Whether the view is open. False, said: an unknown id, records + that could not be read, or a workflow that does not run. + """ + return await open_view(self, instance) + + async def leave_agent_view(self) -> bool: + """Leave the open sub-agent's view, back to the main conversation + (provisional): what ``/back`` calls. + + Returns: + Whether a view was left. False, said, when none is open. + """ + return await leave_view(self) + @property def workflow_error(self) -> Exception | None: """Why the workflow is not running: the error its start, or its last @@ -897,6 +930,7 @@ def _register_builtin_commands(self) -> None: NewCommand, ModelsCommand, ) + from agentic_cli.cli.agent_view import BackCommand 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 @@ -909,6 +943,7 @@ def _register_builtin_commands(self) -> None: self.command_registry.register(JobsCommand()) self.command_registry.register(AgentsCommand()) self.command_registry.register(AgentCommand()) + self.command_registry.register(BackCommand()) self.command_registry.register(ResumeSessionCommand()) self.command_registry.register(SettingsCommand()) self.command_registry.register(PapersCommand()) @@ -921,6 +956,11 @@ def _register_builtin_commands(self) -> None: async def process_input(self, user_input: str) -> None: """Process user input. + A command runs as it does anywhere; when a sub-agent's view is open + its prompt and status bar are drawn again after it (the command may + have changed the instance). A line in a view goes to the view + (``AgentView.take``), any other to the conversation. + Args: user_input: The raw user input string """ @@ -932,6 +972,10 @@ async def process_input(self, user_input: str) -> None: # Route to appropriate handler if user_input.startswith("/"): await self._handle_command(user_input) + if self._agent_view is not None: + self._agent_view.refresh() + elif self._agent_view is not None: + await self._agent_view.take(user_input) else: await self._handle_message(user_input) diff --git a/src/agentic_cli/cli/conversation.py b/src/agentic_cli/cli/conversation.py index cb6259e6..501fbb48 100644 --- a/src/agentic_cli/cli/conversation.py +++ b/src/agentic_cli/cli/conversation.py @@ -624,6 +624,84 @@ async def run_turn(self, message: str, parts: TurnParts) -> bool: finally: self.turn_lock.release() + async def run_instance(self, instance: str, message: str, parts: TurnParts) -> bool: + """Run the user's ``message`` as the next run of a sub-agent, in its view. + + A write to the conversation under the turn lock, as a turn is: held + to write, the conversations ``/new`` left dropped around it + (``drop_left``), and ``written`` once it reached a ready workflow. It + is not ``turned``: the main agent's conversation, whose memories are + proposed, holds none of it. The view echoed the line. + + Args: + instance: The sub-agent instance (``researcher-2``). + message: What the user typed. + parts: The app's parts it runs on (the view's own processor). + + Returns: + Whether it ran: False when another process has the conversation + open (said), and nothing ran. + + Raises: + asyncio.CancelledError: Ctrl+C stopped it, as the processor says, + or while it waited for the turn lock. + """ + return await self._write( + parts, + lambda: parts.processor.process_instance( + instance, + message, + workflow_controller=parts.controller, + ui=parts.ui, + settings=parts.settings, + usage_tracker=parts.tracker, + session_id=self.session_id, + ), + turns=False, + ) + + async def _write(self, parts: TurnParts, run: Callable[[], Awaitable[Any]], *, turns: bool) -> bool: + """``run_turn``'s frame without the echo: ``run()`` under the turn lock. + + The conversation is held to write first; ``turned`` when ``turns`` + (the main agent answered in it); ``written`` once ``run`` reached a + ready workflow (its result's status is not ``UNAVAILABLE``; one that + raised or was cancelled counts when the workflow was ready). + + Returns: + Whether it ran: False when another process has the conversation + open (said). + + Raises: + asyncio.CancelledError: Ctrl+C stopped it, as the processor says, + or while it waited for the turn lock. + """ + ui = parts.ui + try: + await self.turn_lock.acquire() + except asyncio.CancelledError: + ui.add_message("system", CANCELLED_LINE) + raise + try: + if not self._held_to_write(ui): + return False + async with self._dropping_left(parts): + if turns: + self.turned = True + reached = False + try: + result = await run() + reached = getattr(result, "status", None) is not TurnStatus.UNAVAILABLE + except BaseException: + reached = parts.controller.is_ready # it may have begun + raise + finally: + if reached: + self.written = True + return True + finally: + self.turn_lock.release() + async def compact(self, focus: str | None, parts: TurnParts) -> "CompactResult | None": """Summarize the conversation now (``/compact [focus]``), as a turn runs. diff --git a/src/agentic_cli/cli/workflow_controller.py b/src/agentic_cli/cli/workflow_controller.py index 9ce415fc..2be92863 100644 --- a/src/agentic_cli/cli/workflow_controller.py +++ b/src/agentic_cli/cli/workflow_controller.py @@ -26,6 +26,8 @@ from agentic_cli.workflow.settings import OrchestratorType if TYPE_CHECKING: + from collections.abc import Callable + from agentic_cli.cli.usage_tracker import UsageTracker from agentic_cli.config import BaseSettings from agentic_cli.workflow.agents.policy import SubAgentPolicy @@ -221,6 +223,10 @@ def _create_workflow() -> "BaseWorkflowManager": self.usage_tracker: "UsageTracker | None" = None # Status-bar jobs segment, published by JobMonitor; None when idle. self.jobs_status_segment: str | None = None + # While a sub-agent's view is open, what the bar says of its instance, + # in place of the main agent's model and tokens; None in the main + # conversation. + self.view_segment: "Callable[[], str] | None" = None @property def agent_configs(self) -> tuple["AgentConfig", ...]: @@ -839,13 +845,21 @@ def update_status_bar(self, ui: "ThinkingPromptSession") -> None: """Update UI status bar with current workflow status. It names the model of the main agent, whose context the ``ctx`` - segment shows (``_main_model``). + segment shows (``_main_model``). In a sub-agent's view it names the + instance instead (``view_segment``: its status, its own ``ctx`` and + tokens), the jobs segment kept. Args: ui: UI session to update """ if self._init_error: ui.set_status("Init failed - check API keys") + elif self._workflow is not None and self.view_segment is not None: + parts = [self.view_segment()] + if self.jobs_status_segment: + parts.append(self.jobs_status_segment) + parts.extend(["Ctrl+C: cancel", "/back: main"]) + ui.set_status(" | ".join(parts)) elif self._workflow is not None: parts = [_main_model(self._workflow)] if self.usage_tracker: diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py new file mode 100644 index 00000000..e00c8430 --- /dev/null +++ b/tests/cli/test_agent_view.py @@ -0,0 +1,324 @@ +"""A sub-agent's view (``cli/agent_view.py``): ``/agent `` and ``/back``. + +The app is a real ``BaseCLIApp`` around a real manager, the shared +contract's crew (``tests/workflow/test_subagents_contract.py``: ADK on +``FakeAPI``, Deep Agents on ``ScriptedChat``), its session a fake. Entering a +view prints its rule and a recap of the instance, the prompt becomes +``> `` and the status bar names it, its context and its tokens; a line +typed there is the instance's next run (``run_instance``), drawn as a turn +and run in a task of its own, or, while its run works, given to that run +(``steer_instance``); Ctrl+C stops the run in view (``AgentView.stop``: the +user's stop). ``/back`` waits for a run still working, prints its rule and, +once a run the user started there ended, tells the main agent in a notice +turn (``tell_root``); the main agent's notices (finished jobs) wait while a +view is open. ``/compact`` is refused there, ``/new`` and ``/resume`` leave +it first, ``/status`` shows the instance's context, and a closed instance's +view is read-only. +""" + +from __future__ import annotations + +import asyncio + +import pytest + +from agentic_cli.cli import AppInfo +from agentic_cli.cli import app as app_module +from agentic_cli.cli.agent_view import ( + BACK_RULE, + NOT_IN_VIEW, + READ_ONLY, + STEERED, +) +from agentic_cli.cli.agents_command import NO_SUCH_AGENT +from agentic_cli.cli.app import BaseCLIApp +from agentic_cli.cli.message_processor import CANCELLED_LINE +from agentic_cli.cli.usage_tracker import UsageTracker +from agentic_cli.workflow.agents import ( + INSTANCE_IDLE, + INSTANCE_STOPPED, + RUN_CANCELLED, + RUN_COMPLETED, +) +from tests.cli.dialog_fakes import autospec_session, opening_boxes +from tests.workflow.test_subagents_contract import ( # noqa: F401 - fixtures + BLOCKING, + HELD, + SESSION, + Crew, + agent, + backend, + calls, + delegate, + follow_team, + make_crew, + parent_team, + project, + says, + use, +) + +RULE = "── researcher-1 · researcher · idle ──" + + +@pytest.fixture(autouse=True) +def quiet_app(monkeypatch): + """No global logging configuration or warning hook left behind.""" + monkeypatch.setattr(app_module, "configure_logging", lambda *a, **k: None) + monkeypatch.setattr(app_module, "install_log_filters", lambda: None) + + +async def app_on(crew: Crew) -> BaseCLIApp: + """A real app whose controller holds ``crew``'s manager (started), in the + crew's conversation; its session a fake, each box a box of its own.""" + await crew.manager.initialize_services() + app = BaseCLIApp( + app_info=AppInfo(name="View test", version="0"), + agent_configs=[agent("coordinator")], + settings=crew.manager.settings, + session_id=SESSION, + ) + app.session = opening_boxes(autospec_session()) + app.session.message = ">>> " + app._workflow_controller._workflow = crew.manager + return app + + +async def typed(app: BaseCLIApp, *lines: str) -> None: + """Each line as the user types it, the view's run waited for.""" + for line in lines: + await app.process_input(line) + if app.agent_view is not None: + await asyncio.wait_for(app.agent_view.settled(), 10) + + +async def in_a_view( + make_crew, *, researcher=(), coordinator=(), team=None, **crew_args +) -> tuple[Crew, BaseCLIApp]: + """A crew whose coordinator delegated once (``researcher-1``: "X is 42.", + 1,200 tokens in, 40 out), and an app in ``researcher-1``'s view.""" + crew = make_crew( + team or follow_team(), + coordinator=[calls(delegate("researcher", "Find X.\nIn the docs.", "c1")), + says("Done."), *coordinator], + researcher=[says("X is 42.", usage=(1_200, 40)), *researcher], + **crew_args, + ) + app = await app_on(crew) + await typed(app, "Find X.", "/agent researcher-1") + return crew, app + + +def said(session, method: str) -> list[str]: + """What the fake session was told through ``method``, in order.""" + made = getattr(session, method).call_args_list + return [c.args[1] if method == "add_message" else c.args[0] for c in made] + + +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)) + + +def status(app: BaseCLIApp) -> str: + """The status bar as last drawn.""" + return app.session.set_status.call_args.args[0] + + +def ctx(crew: Crew, prompt: int) -> str: + """``ctx``, for the researcher's last prompt against its own trigger.""" + budget = crew.manager.context_budget("researcher") + return UsageTracker( + last_prompt_tokens=prompt, context_trigger=budget.trigger, + window_known=budget.window_known, + ).format_context() + + +class TestEntering: + """``/agent `` (or Enter in ``/agents``' picker) opens the view: its + rule and recap, its prompt, its status bar.""" + + async def test_its_rule_and_recap_then_its_prompt_and_status_bar(self, make_crew): + crew, app = await in_a_view(make_crew) + + assert said(app.session, "add_message")[-2:] == ["/agent researcher-1", RULE] + (recap,) = app.session.add_rich.call_args.args + assert rows_of(recap) == [ + ("Title", "Find X."), ("Objective", "Find X.\nIn the docs."), + ("Last run", "#1 · completed"), ("Result", "X is 42."), + ("Tokens", "1.2k in / 40 out"), + ] + assert app.session.message == "researcher-1> " + assert app.agent_view.instance == "researcher-1" + assert status(app) == ( + f"researcher-1 · idle | {ctx(crew, 1_200)} | Tokens: 1.2k in / 40 out" + " | Ctrl+C: cancel | /back: main" + ) + + async def test_enter_in_the_agents_picker_opens_it(self, make_crew): + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[says("X is 42.")], + ) + app = await app_on(crew) + + async def first(dialog): + return dialog.fields[0].options[0] + + app.session.show_dialog.side_effect = first + await typed(app, "Find X.", "/agents") + + assert said(app.session, "add_message")[-1] == RULE + assert app.session.message == "researcher-1> " + + async def test_an_unknown_id_opens_nothing(self, make_crew): + _, app = await in_a_view(make_crew) + await typed(app, "/back", "/agent researcher-9") + + app.session.add_warning.assert_called_once_with( + NO_SUCH_AGENT.format(id="researcher-9") + ) + assert app.agent_view is None + assert app.session.message == ">>> " + + async def test_a_closed_instances_view_has_no_prompt_and_takes_no_line(self, make_crew): + crew, app = await in_a_view(make_crew, team=follow_team(continuable=False)) + await typed(app, "Go on.") + + assert said(app.session, "add_message")[-1] == "── researcher-1 · researcher · closed ──" + assert app.session.message == "" + app.session.add_warning.assert_called_once_with(READ_ONLY.format(instance="researcher-1")) + assert crew.requests("researcher") == 1 + await typed(app, "/back") + assert app.session.message == ">>> " + + +class TestALineTyped: + """A line typed in the view is the instance's next run, drawn as a turn, + or, while that run works, given to it; Ctrl+C stops the run in view.""" + + async def test_an_idle_ones_line_is_its_next_run_drawn_as_a_turn(self, make_crew): + crew, app = await in_a_view(make_crew, researcher=[says("Y is 7.", usage=(1_500, 20))]) + + await typed(app, "Now find Y.") + + assert said(app.session, "add_response") == ["Done.", "Y is 7."] + assert said(app.session, "add_message")[-1] == "Now find Y." + assert [(r.ref.run, r.status, r.started_by) for r in crew.records()] == [ + ("researcher-1#1", RUN_COMPLETED, "agent:root"), + ("researcher-1#2", RUN_COMPLETED, "user"), + ] + assert crew.requests("coordinator") == 2 # the main agent did not run + assert crew.last_message("researcher", 1) == "Now find Y." + assert "X is 42." in crew.bodies("researcher")[1] + assert app.session.message == "researcher-1> " + assert status(app).startswith( + f"researcher-1 · idle | {ctx(crew, 1_500)} | Tokens: 2.7k in / 60 out" + ) + + async def test_a_line_typed_while_its_run_works_is_given_to_that_run(self, make_crew): + crew, app = await in_a_view( + make_crew, team=parent_team(), + researcher=[calls(use("contract_hold", "r1")), says("X is 42; Z is 9.")], + ) + + await app.process_input("Hold on.") + await asyncio.wait_for(HELD["started"].wait(), 10) + await app.process_input("Also find Z.") + HELD["go"].set() + await asyncio.wait_for(app.agent_view.settled(), 10) + + assert said(app.session, "add_message")[-2:] == [ + "Also find Z.", STEERED.format(instance="researcher-1"), + ] + assert crew.last_message("researcher", -1) == "Also find Z." + assert [r.ref.run for r in crew.records()] == ["researcher-1#1", "researcher-1#2"] + assert said(app.session, "add_response")[-1] == "X is 42; Z is 9." + + async def test_ctrl_c_stops_the_run_in_view_the_users_stop(self, make_crew): + crew, app = await in_a_view( + make_crew, researcher=[calls(use("contract_block", "r1")), says("Went on.")], + ) + + await app.process_input("Wait here.") + await asyncio.wait_for(BLOCKING["started"].wait(), 10) + assert app.agent_view.stop() is True + await asyncio.wait_for(app.agent_view.settled(), 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)] + assert said(app.session, "add_message").count(CANCELLED_LINE) == 1 + assert app.session.message == "researcher-1> " + assert status(app).startswith("researcher-1 · stopped") + await typed(app, "Go on.") + assert crew.instances() == [("researcher-1", INSTANCE_IDLE)] + assert said(app.session, "add_response")[-1] == "Went on." + + async def test_after_a_model_switch_in_a_view_a_line_runs_on_the_new_model(self, make_crew): + crew, app = await in_a_view(make_crew, researcher=[says("Y is 7.")]) + + assert await app.apply_settings({"model": "claude-haiku-4-5"}) + await typed(app, "Now find Y.") + + assert crew.models("researcher") == ["claude-sonnet-4-6", "claude-haiku-4-5"] + assert "X is 42." in crew.bodies("researcher")[1] + assert [(r.ref.run, r.status) for r in crew.records()] == [ + ("researcher-1#1", RUN_COMPLETED), ("researcher-1#2", RUN_COMPLETED), + ] + assert app.agent_view.instance == "researcher-1" + assert app.session.message == "researcher-1> " + assert said(app.session, "add_response")[-1] == "Y is 7." + assert status(app).startswith("researcher-1 · idle") + + +class TestLeavingAndSwitching: + """``/back`` puts the prompt and the status bar back; ``/agent`` with + another id leaves this view for that one; an instance closed in its own + view leaves it read-only.""" + + async def test_back_prints_its_rule_and_puts_the_prompt_and_bar_back(self, make_crew): + _, app = await in_a_view(make_crew) + + await typed(app, "/back") + + assert said(app.session, "add_message")[-1] == BACK_RULE + assert app.agent_view is None + assert app.session.message == ">>> " + assert status(app).endswith("Ctrl+C: cancel | /help: commands") + + async def test_outside_a_view_it_says_so(self, make_crew): + crew = make_crew(follow_team()) + app = await app_on(crew) + + await typed(app, "/back") + + assert said(app.session, "add_message")[-1] == NOT_IN_VIEW + + async def test_agent_with_another_id_leaves_this_view_for_that_one(self, make_crew): + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1"), + delegate("researcher", "Find Y.", "c2")), says("Done.")], + researcher=[says("X is 42."), says("Y is 7.")], + ) + app = await app_on(crew) + + await typed(app, "Find X and Y.", "/agent researcher-1", "/agent researcher-2") + + assert said(app.session, "add_message")[-3:] == [ + "/agent researcher-2", BACK_RULE, "── researcher-2 · researcher · idle ──", + ] + assert app.session.message == "researcher-2> " + + async def test_closing_the_instance_in_view_leaves_its_view_read_only(self, make_crew): + crew, app = await in_a_view(make_crew) + + await typed(app, "/agent close researcher-1") + + assert app.session.message == "" + assert status(app).startswith("researcher-1 · closed") diff --git a/tests/cli/test_agents_command.py b/tests/cli/test_agents_command.py index 539468fb..c58aec36 100644 --- a/tests/cli/test_agents_command.py +++ b/tests/cli/test_agents_command.py @@ -1,11 +1,12 @@ """``/agents``: the open conversation's sub-agent runs (``cli/agents_command.py``). ``/agents`` is a picker of the instances (id, type, status, title, each -followed by the ones it started), and Enter shows one as ``/agents `` -does: one instance or run: its type, parent and title, then each run's +followed by the ones it started), and Enter opens its view, as ``/agent `` +does (``tests/cli/test_agent_view.py``). ``/agents `` 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 every run in its panel. ``/agent `` shows one, +followed up shows every run in its panel. ``/agent stop `` and ``/agent close `` 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 @@ -198,17 +199,6 @@ async def test_each_instance_its_type_status_and_title_its_sub_agents_under_it( ] session.add_rich.assert_not_called() - 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) @@ -496,17 +486,9 @@ async def unreadable(conversation: SessionRef) -> None: class TestTheAgentCommand: - """``/agent `` shows one sub-agent; ``/agent stop `` and ``/agent - close `` 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) + """``/agent stop `` and ``/agent close `` stop and close one + sub-agent, each saying what it did or why not (``/agent `` opens its + view: ``tests/cli/test_agent_view.py``).""" async def test_stop_stops_an_idle_one_and_says_only_the_user_continues_it(self, manager): crew_ran(manager) From ef62ca12e6f835d9acb8c76764778d731add6f6e Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:25:35 -0500 Subject: [PATCH 03/17] CLI: /back tells the main agent; its notices wait in a view; /compact, /new, /resume, /status there Leaving a view tells the main agent once, in a notice turn, when a run the user started there ended since it last heard of the instance. The main agent's own notices (finished jobs) wait while a view is open and are told after /back. In a view /compact is refused, /new and /resume leave it first, and /status shows the instance's context. --- src/agentic_cli/cli/agent_view.py | 71 ++++++++++- src/agentic_cli/cli/app.py | 14 ++- src/agentic_cli/cli/builtin_commands.py | 21 +++- src/agentic_cli/cli/conversation.py | 33 +++++ tests/cli/console_app.py | 109 ++++++++++++++++- tests/cli/test_agent_view.py | 153 +++++++++++++++++++++++- tests/cli/test_console_turns.py | 27 ++++- 7 files changed, 416 insertions(+), 12 deletions(-) diff --git a/src/agentic_cli/cli/agent_view.py b/src/agentic_cli/cli/agent_view.py index dbf23344..4e9da6d0 100644 --- a/src/agentic_cli/cli/agent_view.py +++ b/src/agentic_cli/cli/agent_view.py @@ -18,9 +18,14 @@ prompt stays open for the lines that steer it. A closed instance's view is read-only: no prompt, and a line typed there is refused. -``/back`` leaves: it waits for a run still working and prints ``── back to -main ──``. While a view is open, ``/compact`` is refused, ``/new`` and -``/resume`` leave it first, and ``/status`` shows the instance's context. +``/back`` leaves: it waits for a run still working, prints ``── back to main +──``, and, when a run the user started there ended since the main agent was +last told, tells the main agent once, in a notice turn (``tell_root`` with +``agents/envelope.py::view_notice``) drawn as a job's notice is; then the +finished jobs that waited for the conversation are told +(``job_auto_resume``). While a view is open the main agent's notices wait, +counted in ``↻N``. ``/compact`` is refused in a view; ``/new`` and +``/resume`` leave it first; ``/status`` shows the instance's context. """ from __future__ import annotations @@ -45,6 +50,7 @@ from agentic_cli.cli.usage_tracker import UsageTracker, format_tokens from agentic_cli.logging import Loggers from agentic_cli.workflow.agents import INSTANCE_CLOSED, INSTANCE_RUNNING +from agentic_cli.workflow.agents.envelope import view_notice from agentic_cli.workflow.usage import PURPOSE_SUBAGENT if TYPE_CHECKING: @@ -61,10 +67,16 @@ VIEW_PROMPT = "{instance}> " #: What a line typed in a closed instance's view is told. READ_ONLY = "{instance} is closed: its view is read-only. /back returns to the main conversation." +#: What ``/compact`` says in a view. +COMPACT_IN_VIEW = "/compact works in the main conversation only." #: What ``/back`` says outside a view. NOT_IN_VIEW = "Not in a sub-agent's view: /agent opens one." #: What a line given to the run in view says. STEERED = "Given to {instance}'s run before its next step." +#: The line before the main agent's notice turn after a view. +TELLING = "↻ Telling the main agent what you did with {instance}." +#: What ``/jobs resume`` says in a view. +JOBS_WAIT = "In a sub-agent's view the main agent's notices wait: /back tells them." class AgentView: @@ -132,6 +144,41 @@ def status_segment(self) -> str: logger.debug("view_status_failed", instance=self.instance, exc_info=True) return self.instance + def context_rows(self) -> list[tuple[str, str]]: + """``/status``' rows for the instance's context, in place of the main agent's. + + The instance, its type and status; its model, the model's window, + its input budget and the prompt size its transcript is summarized + (or trimmed) at, when its manager manages its context; its last + prompt and its tokens. + """ + from agentic_cli.workflow.context import UNKNOWN_WINDOW + + workflow = self.app.workflow + record = workflow.agent_runs.instance(self.conversation, self.instance) + if record is None: + return [("Sub-agent", f"{self.instance} (gone)")] + rows = [("Sub-agent", f"{self.instance} ({record.agent}, {record.status})")] + model = getattr(workflow, "agent_models", {}).get(record.agent) + if model is not None: + rows.append(("Model", str(model.ref))) + budget = _budget(workflow, record.agent) + if budget is not None: + window = ( + format_tokens(budget.window) if budget.window_known + else f"unknown, {format_tokens(UNKNOWN_WINDOW)} floor in use" + ) + rows += [ + ("Context Window", window), + ("Input Budget", format_tokens(budget.budget)), + ("Summarize At", format_tokens(budget.trigger)), + ] + last = _last_prompt(workflow, self.conversation, record) + rows.append(("Last Prompt", format_tokens(last) if last else "—")) + tokens_in, tokens_out = instance_tokens(workflow, self.conversation, self.instance) + rows.append(("Tokens", f"{format_tokens(tokens_in)} in / {format_tokens(tokens_out)} out")) + return rows + def show(self, record: "InstanceRecord") -> None: """Print the view's rule and the instance's recap.""" session = self.app.session @@ -272,7 +319,10 @@ async def leave_view(app: Any) -> bool: to the main conversation; False, said, when none is. A run still working there ends first (Ctrl+C stops it); then the rule, - the app's prompt and status bar. + the app's prompt and status bar; then, when a run the user started there + ended since the main agent last heard of the instance, one notice turn + (``ConversationCore.tell_root``) with its latest envelope; then the + finished jobs that waited (``job_auto_resume``). """ view = app.agent_view if view is None: @@ -286,6 +336,19 @@ async def leave_view(app: Any) -> bool: app.session.add_message("system", BACK_RULE) controller.update_status_bar(app.session) logger.info("agent_view_left", instance=view.instance) + workflow = _workflow(app) + if workflow is None: + return True + latest = workflow.instance_result( + view.instance, session_id=view.conversation.session_id, + user_id=view.conversation.user_id, + ) + if latest is not None and latest.get("run") != view.told: + app.session.add_message("system", TELLING.format(instance=view.instance)) + await app._conversation.tell_root( + view_notice(view.instance, latest), app._turn_parts() + ) + await app._tell_its_finished_jobs() return True diff --git a/src/agentic_cli/cli/app.py b/src/agentic_cli/cli/app.py index 5719c946..ffc00578 100644 --- a/src/agentic_cli/cli/app.py +++ b/src/agentic_cli/cli/app.py @@ -1071,8 +1071,12 @@ async def resume_finished_jobs(self) -> int: one that could not be told now (its conversation's lookup failed, before any claim), the failure said. Whether each one was delivered is recorded on the job and reported by ``/jobs``; a - failed delivery is surfaced to the user by the turn itself. + failed delivery is surfaced to the user by the turn itself. 0 + in a sub-agent's view: the main agent's notices wait for + ``/back`` (``leave_agent_view``), which tells them. """ + if self._agent_view is not None: + return 0 return await self._conversation.deliver_finished_jobs(self._turn_parts()) async def _kept_elsewhere(self, record: Any) -> bool: @@ -1183,6 +1187,7 @@ async def start_new_session(self, backend: str | None = None) -> str: install it); nothing changed. """ target = check_backend(backend).value if backend is not None else None + await self._leave_view_first() async with _says_so_when_stopped(self.session): async with self._turn_lock: return await self._new_conversation(target) @@ -1323,6 +1328,7 @@ async def resume_session(self, session_id: str) -> bool: if not self._place().kept: # one conversation at a time: none to go back to self.session.add_error(NOT_KEPT) return False + await self._leave_view_first() backend = getattr(session_id, "backend", None) # the picker's async with _says_so_when_stopped(self.session): opened = await self._open_conversation(str(session_id), backend) @@ -1367,6 +1373,12 @@ async def _name_its_waiting_jobs(self) -> None: "/jobs resume tells them now.", ) + async def _leave_view_first(self) -> None: + """Leave the open sub-agent's view, if one is: ``/new`` and ``/resume`` + change the conversation from the main one.""" + if self._agent_view is not None: + await self.leave_agent_view() + async def _tell_its_finished_jobs(self) -> None: """Once a conversation is open, its finished jobs resume (``job_auto_resume``). diff --git a/src/agentic_cli/cli/builtin_commands.py b/src/agentic_cli/cli/builtin_commands.py index 2fc05144..3cf9dee3 100644 --- a/src/agentic_cli/cli/builtin_commands.py +++ b/src/agentic_cli/cli/builtin_commands.py @@ -9,6 +9,7 @@ from rich.table import Table from rich.text import Text +from agentic_cli.cli.agent_view import COMPACT_IN_VIEW, JOBS_WAIT from agentic_cli.cli.commands import Command, CommandCategory from agentic_cli.cli.conversation import NOT_KEPT from agentic_cli.cli.message_processor import _says_so_when_stopped @@ -224,7 +225,13 @@ async def execute(self, args: str, app: Any) -> None: table.add_row("Session ID", workflow.session_id) services = "Initialized" if workflow.is_initialized else "Not initialized" table.add_row("Services", services) - for label, value in _context_rows(workflow, getattr(app, "usage_tracker", None)): + view = getattr(app, "agent_view", None) + # In a sub-agent's view, its context is what the user works with. + rows = ( + view.context_rows() if view is not None + else _context_rows(workflow, getattr(app, "usage_tracker", None)) + ) + for label, value in rows: table.add_row(label, value) except (RuntimeError, AttributeError): # Why it did not start (or its last rebuild failed), when it did @@ -434,7 +441,10 @@ async def execute(self, args: str, app: Any) -> None: if parts and parts[0] == "resume": # Each finished, resume-flagged job resumes its agent (a turn). resume = getattr(app, "resume_finished_jobs", None) - if resume is None: + if getattr(app, "agent_view", None) is not None: + # In a sub-agent's view they wait for /back, which tells them. + app.session.add_message("system", JOBS_WAIT) + elif resume is None: app.session.add_warning("Resume is not supported by this app.") elif await resume() == 0: app.session.add_message("system", "No finished background jobs to resume.") @@ -794,8 +804,13 @@ async def execute(self, args: str, app: Any) -> None: One request at a time (the app's turn lock), with the turn's events box and status line; Ctrl+C stops it and nothing is written. The rest - of the line, if any, is what the summary should keep above all. + of the line, if any, is what the summary should keep above all. Refused + in a sub-agent's view (``COMPACT_IN_VIEW``): it is the main + conversation's. """ + if getattr(app, "agent_view", None) is not None: + app.session.add_warning(COMPACT_IN_VIEW) + return await app.compact(args.strip() or None) diff --git a/src/agentic_cli/cli/conversation.py b/src/agentic_cli/cli/conversation.py index 501fbb48..980f89db 100644 --- a/src/agentic_cli/cli/conversation.py +++ b/src/agentic_cli/cli/conversation.py @@ -660,6 +660,39 @@ async def run_instance(self, instance: str, message: str, parts: TurnParts) -> b turns=False, ) + async def tell_root(self, text: str, parts: TurnParts) -> bool: + """Tell the main agent what the user did in a sub-agent's view, as a turn. + + A notice the user did not type (``view_notice``): under the turn + lock as ``run_instance``, held to write, ``turned`` (the main agent + answered in the conversation) and ``written`` once it reached a + ready workflow. + + Args: + text: The notice. + parts: The app's parts it runs on. + + Returns: + Whether it ran: False when another process has the conversation + open (said), and nothing ran. + + Raises: + asyncio.CancelledError: Ctrl+C stopped it, as the processor says, + or while it waited for the turn lock. + """ + return await self._write( + parts, + lambda: parts.processor.process_notice( + text, + workflow_controller=parts.controller, + ui=parts.ui, + settings=parts.settings, + usage_tracker=parts.tracker, + session_id=self.session_id, + ), + turns=True, + ) + async def _write(self, parts: TurnParts, run: Callable[[], Awaitable[Any]], *, turns: bool) -> bool: """``run_turn``'s frame without the echo: ``run()`` under the turn lock. diff --git a/tests/cli/console_app.py b/tests/cli/console_app.py index fa7ee274..8136724f 100644 --- a/tests/cli/console_app.py +++ b/tests/cli/console_app.py @@ -26,9 +26,19 @@ started without the loop's context, as an executor's is (``console_stdlib_warning``), and a Python warning (``console_python_warning``). +- ``delegate``: the main agent's sub-agent ``researcher-1`` runs once ("Find + X.", "X is 42."), then ``The researcher found X.``; ``/agent researcher-1`` + opens its view. - anything else: ``Echo: ``, at once, and the call's usage: a 4,000-token prompt against a 16,000-token trigger (``ctx 4k/16k (25%)``). +In ``researcher-1``'s view a line is its next run (``run_instance``): ``hold`` +says ``Holding.`` and waits for a line given to it (``steer_instance``), then +says ``Steered: ``; ``slow`` says ``Working on it.`` and waits until +Ctrl+C stops it (the user's stop: the instance is stopped); anything else +says ``Researched: ``. The main agent's notice after the view +(``tell_root``) is answered ``Told: ``. + ``/compact`` reports that a summary is being written, waits until a file named ``summarized`` appears, then reports its usage and what it did: 2 messages, 7,400 tokens before and 1,200 after. A session is stored once a @@ -64,10 +74,18 @@ from agentic_cli.cli import AppInfo, BaseCLIApp from agentic_cli.config import BaseSettings from agentic_cli.workflow import live_events +from agentic_cli.workflow.agents import AgentRuns from agentic_cli.workflow.config import AgentConfig from agentic_cli.workflow.context import CompactResult from agentic_cli.workflow.events import InputType, UserInputRequest, WorkflowEvent -from agentic_cli.workflow.sessions import SessionInfo, SessionRef, session_title +from agentic_cli.workflow.sessions import ( + SessionInfo, + SessionRef, + reset_active_turn, + session_title, + set_active_turn, +) +from agentic_cli.workflow.usage import UsageLedgers class ScriptedManager: @@ -86,6 +104,13 @@ class ScriptedManager: def __init__(self) -> None: self.is_initialized = False self._input_callback: Any = None + #: The sub-agent runs ``delegate`` and a view make (real records). + self.agent_runs = AgentRuns() + self._ledgers = UsageLedgers() + #: Each instance's latest envelope of a run the user started. + self._results: dict[tuple[SessionRef, str], dict] = {} + #: A ``hold`` run's wait for the line given to it. + self._holding: asyncio.Future[str] | None = None self._sessions: set[str | None] = set() #: Each stored conversation's messages and when it last changed. self._messages: dict[str, list[dict]] = {} @@ -173,10 +198,90 @@ async def compact(self, session, focus=None) -> CompactResult: )) return CompactResult(messages_summarized=2, tokens_before=7_400, tokens_after=1_200) + # -- sub-agents ------------------------------------------------------------------ + + def _observe(self, conversation: SessionRef, event: WorkflowEvent) -> None: + """Record ``event`` as a run reports it, under its conversation's turn.""" + token = set_active_turn(conversation) + try: + self.agent_runs.observe(event) + finally: + reset_active_turn(token) + + async def load_agents(self, conversation) -> None: + pass + + def usage_of(self, conversation): + return self._ledgers.ledger(conversation) + + def context_budget(self, agent_name=None): + raise KeyError(agent_name) # no context managed here + + def instance_result(self, instance, *, session_id=None, user_id=None): + return self._results.get((self.session_ref(session_id), instance)) + + def steer_instance(self, instance, message, *, session_id=None, user_id=None) -> bool: + if self._holding is None or self._holding.done(): + return False + self._holding.set_result(message) + return True + + async def run_instance(self, instance, message, *, session_id=None, user_id=None): + conversation = self.session_ref(session_id) # one user here + ref = self.agent_runs.next_run(conversation, instance, parent_run=None) + started = WorkflowEvent.agent_run(ref, "started", title=message, input=message, + started_by="user", mode="blocking") + self._observe(conversation, started) + yield started + ended = WorkflowEvent.agent_run(ref, "cancelled", error="stopped by the user", + cancelled_by="user", instance_status="stopped") + try: + if message == "hold": + yield self._instance_text(ref, "Holding.") + self._holding = asyncio.get_running_loop().create_future() + text = f"Steered: {await self._holding}" + elif message == "slow": + yield self._instance_text(ref, "Working on it.") + await asyncio.Event().wait() # until Ctrl+C stops the run + else: + text = f"Researched: {message}" + yield self._instance_text(ref, text) + ended = WorkflowEvent.agent_run(ref, "completed", result=text, instance_status="idle") + finally: + self._observe(conversation, ended) + self._results[(conversation, instance)] = { + "success": ended.metadata["status"] == "completed", "agent": instance, + "run": ref.run, "status": ended.metadata["status"], + "result": ended.metadata.get("result", ""), + } + yield ended + + @staticmethod + def _instance_text(ref, text: str) -> WorkflowEvent: + event = WorkflowEvent.text(text) + event.run = ref + event.metadata.update(agent=ref.agent, subagent=True) + return event + + async def tell_root(self, text, *, session_id=None, user_id=None): + yield WorkflowEvent.text(f"Told: {text.split(';')[0]}") + async def process(self, message: str, user_id: str, session_id: str | None = None): self._sessions.add(session_id) self._said(session_id, "user", message) - if message == "slow": + if message == "delegate": + conversation = self.session_ref(session_id) # as the CLI names it + ref = self.agent_runs.run_for(conversation, None, "c1", "researcher") + self._observe(conversation, WorkflowEvent.agent_run( + ref, "started", title="Find X.", call_id="c1", + brief={"title": "Find X.", "objective": "Find X."}, + started_by="agent:root", mode="blocking", + )) + self._observe(conversation, WorkflowEvent.agent_run( + ref, "completed", call_id="c1", result="X is 42.", instance_status="idle", + )) + yield WorkflowEvent.text("The researcher found X.") + elif message == "slow": yield WorkflowEvent.thinking("Working on it") await asyncio.Event().wait() # until Ctrl+C cancels the turn elif message == "ask": diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index e00c8430..6f35a4e8 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -26,35 +26,44 @@ from agentic_cli.cli import app as app_module from agentic_cli.cli.agent_view import ( BACK_RULE, + COMPACT_IN_VIEW, + JOBS_WAIT, NOT_IN_VIEW, READ_ONLY, STEERED, + TELLING, ) from agentic_cli.cli.agents_command import NO_SUCH_AGENT from agentic_cli.cli.app import BaseCLIApp from agentic_cli.cli.message_processor import CANCELLED_LINE -from agentic_cli.cli.usage_tracker import UsageTracker +from agentic_cli.cli.usage_tracker import UsageTracker, format_tokens +from agentic_cli.tools.jobs.backends import TERMINAL_STATES from agentic_cli.workflow.agents import ( INSTANCE_IDLE, INSTANCE_STOPPED, RUN_CANCELLED, RUN_COMPLETED, ) +from agentic_cli.workflow.agents.envelope import view_notice from tests.cli.dialog_fakes import autospec_session, opening_boxes +from tests.loop_guard import no_blocking_calls from tests.workflow.test_subagents_contract import ( # noqa: F401 - fixtures BLOCKING, HELD, SESSION, + USER, Crew, agent, backend, calls, + contract_start_job, delegate, follow_team, make_crew, parent_team, project, says, + until, use, ) @@ -322,3 +331,145 @@ async def test_closing_the_instance_in_view_leaves_its_view_read_only(self, make assert app.session.message == "" assert status(app).startswith("researcher-1 · closed") + + +# -- /back's notice; the main conversation's commands in a view ------------------------ + + +class TestTheMainAgentIsTold: + """``/back`` tells the main agent once, in a notice turn, when a run the + user started there ended; its own notices wait while a view is open.""" + + async def test_after_a_run_of_yours_the_main_agent_is_told_once(self, make_crew): + crew, app = await in_a_view( + make_crew, coordinator=[says("Noted: Y is 7.")], researcher=[says("Y is 7.")], + ) + + await typed(app, "Now find Y.", "/back") + + latest = crew.manager.instance_result("researcher-1", session_id=SESSION) + assert said(app.session, "add_message")[-3:] == [ + "/back", BACK_RULE, TELLING.format(instance="researcher-1"), + ] + assert crew.last_message("coordinator") == view_notice("researcher-1", latest) + assert said(app.session, "add_response")[-1] == "Noted: Y is 7." + assert app.agent_view is None + assert app.session.message == ">>> " + assert not status(app).startswith("researcher-1") + recent = await crew.manager.recent_messages(SESSION, user_id=USER) + assert [m["content"] for m in recent] == ["Find X.", "Done.", "Noted: Y is 7."] + # Back in the view and out again: nothing new to tell. + await typed(app, "/agent researcher-1", "/back") + assert crew.requests("coordinator") == 3 + + async def test_without_a_run_of_yours_nothing_is_told(self, make_crew): + crew, app = await in_a_view(make_crew) + + await typed(app, "/back") + + assert said(app.session, "add_message")[-1] == BACK_RULE + assert crew.requests("coordinator") == 2 + + async def test_it_waits_for_the_run_in_view_and_tells_its_result(self, make_crew): + crew, app = await in_a_view( + make_crew, team=parent_team(), coordinator=[says("Noted.")], + researcher=[calls(use("contract_hold", "r1")), says("Z is 9.")], + ) + + await app.process_input("Hold on.") + await asyncio.wait_for(HELD["started"].wait(), 10) + back = asyncio.create_task(app.process_input("/back")) + await asyncio.sleep(0.05) + assert not back.done() + HELD["go"].set() + await asyncio.wait_for(back, 10) + + assert '"result": "Z is 9."' in crew.last_message("coordinator") + assert app.agent_view is None + + async def test_the_main_agents_notices_wait_until_back(self, make_crew): + crew, app = await in_a_view( + make_crew, + team=[agent("coordinator", sub_agents=("researcher",)), + agent("researcher", tools=(contract_start_job,))], + coordinator=[says("Noted."), says("The build finished.")], + researcher=[calls(use("contract_start_job", "r1")), says("Started the build.")], + ) + app.settings.update_setting("job_auto_resume", True) + jobs = crew.manager.job_manager + + await typed(app, "Start the build.") + (record,) = jobs.list() + await until(lambda: jobs.get(record.job_id).state in TERMINAL_STATES) + await typed(app, "/jobs resume") + + assert said(app.session, "add_message")[-1] == JOBS_WAIT + assert crew.requests("coordinator") == 2 + await typed(app, "/back") + assert said(app.session, "add_response")[-2:] == ["Noted.", "The build finished."] + assert jobs.awaiting_resume() == [] + + +class TestTheMainConversationsCommands: + """In a view ``/compact`` is refused, ``/new`` and ``/resume`` leave it + first, and ``/status`` shows the instance's context.""" + + async def test_compact_is_refused(self, make_crew): + crew, app = await in_a_view(make_crew) + + await typed(app, "/compact") + + app.session.add_warning.assert_called_once_with(COMPACT_IN_VIEW) + assert crew.requests("coordinator") == 2 + assert app.agent_view is not None + + async def test_new_leaves_the_view_first(self, make_crew): + crew, app = await in_a_view(make_crew) + + await typed(app, "/new") + + messages = said(app.session, "add_message") + assert messages[-2] == BACK_RULE + assert messages[-1].startswith("New conversation ") + assert app.agent_view is None + assert app.session.message == ">>> " + + async def test_resume_leaves_the_view_first(self, make_crew): + crew, app = await in_a_view(make_crew, store="sqlite") + + await typed(app, "/resume zzz") + + assert BACK_RULE in said(app.session, "add_message") + assert said(app.session, "add_error")[-1].startswith("No conversation 'zzz' found") + assert app.agent_view is None + + async def test_status_shows_the_instances_context(self, make_crew): + crew, app = await in_a_view(make_crew) + budget = crew.manager.context_budget("researcher") + + await typed(app, "/status") + + (panel,) = app.session.add_rich.call_args.args + rows = dict(rows_of(panel.renderable)) + assert rows["Sub-agent"] == "researcher-1 (researcher, idle)" + assert rows["Summarize At"] == format_tokens(budget.trigger) + assert rows["Last Prompt"] == "1.2k" + assert rows["Tokens"] == "1.2k in / 40 out" + assert "Main Agent" not in rows + + +class TestOffTheLoop: + 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."), says("Y is 7.")], + ) + app = await app_on(crew) + await typed(app, "Find X.") + + with no_blocking_calls(): + await typed(app, "/agent researcher-1", "Now find Y.", "/back") + + assert said(app.session, "add_response") == ["Done.", "Y is 7.", "Noted."] diff --git a/tests/cli/test_console_turns.py b/tests/cli/test_console_turns.py index 2f126b1f..3911bbc6 100644 --- a/tests/cli/test_console_turns.py +++ b/tests/cli/test_console_turns.py @@ -1,5 +1,7 @@ """Turns on a real console, over a pty: Ctrl+C, a question, typing ahead, -``/new``, ``/resume``, ``/compact`` and the status bar's ``ctx``. +``/new``, ``/resume``, ``/compact``, the status bar's ``ctx`` and a +sub-agent's view (``/agent ``: a follow-up, a line that steers the run +that works, Ctrl+C on it, ``/back``). thinking-prompt 0.4's Ctrl+C cancels the turn's task, its dialogs are ``Dialog`` objects, drawn in a box or inline, and it refuses Enter while a @@ -544,3 +546,26 @@ def test_the_status_bar_shows_how_full_the_context_is(console): console.expect("Echo: hello") console.expect("ctx 4k/16k (25%)") console.exit() + + +def test_a_sub_agents_view_runs_a_follow_up_and_back_tells_the_main_agent(console): + """``/agent `` opens the view (its rule, its prompt); a line is the + sub-agent's next run, its reply shown; ``/back`` returns and the main + agent is told what the user did there.""" + console.type_line("delegate") + console.expect("The researcher found X.") + console.type_line("/agent researcher-1") + console.expect("── researcher-1 · researcher · idle ──") + console.expect("researcher-1>") + console.type_line("Find Y.") + console.expect("Researched: Find Y.") + console.type_line("/back") + console.expect("── back to main ──") + console.expect("Told: The user worked with researcher-1 directly") + console.type_line("which") + console.expect("Session: ") + console.exit() + + transcript = console.transcript + assert transcript.index("Researched: Find Y.") < transcript.index("── back to main ──") + assert "Busy" not in transcript From 8b4e21afce7c466fa3a4ae84ecb61635fe874828 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:28:30 -0500 Subject: [PATCH 04/17] CLI: Ctrl+C stops the run in a sub-agent's view; /exit stops one still working The view's run works outside the input handler, which thinking-prompt's Ctrl+C does not reach, so the session gets one more key binding, active only while that run works. A run still working at exit is the user's stop, waited for before the workflow is cleaned up. --- src/agentic_cli/cli/agent_view.py | 39 ++++++++++++- src/agentic_cli/cli/app.py | 13 ++++- tests/cli/test_agent_view.py | 92 +++++++++++++++++++++++++++++++ tests/cli/test_console_turns.py | 28 ++++++++++ 4 files changed, 169 insertions(+), 3 deletions(-) diff --git a/src/agentic_cli/cli/agent_view.py b/src/agentic_cli/cli/agent_view.py index 4e9da6d0..5866a467 100644 --- a/src/agentic_cli/cli/agent_view.py +++ b/src/agentic_cli/cli/agent_view.py @@ -15,8 +15,10 @@ works, given to that run before its next model step (``steer_instance``), never queued as a turn. The run works in a task of its own, outside the input handler: thinking-prompt takes no line while a handler runs, so the -prompt stays open for the lines that steer it. A closed instance's view is -read-only: no prompt, and a line typed there is refused. +prompt stays open for the lines that steer it, and Ctrl+C stops it through +the binding ``bind_ctrl_c`` adds (the user's stop: the instance is +``stopped``). A closed instance's view is read-only: no prompt, and a line +typed there is refused. ``/back`` leaves: it waits for a run still working, prints ``── back to main ──``, and, when a run the user started there ended since the main agent was @@ -32,8 +34,11 @@ import asyncio import dataclasses +from collections.abc import Callable from typing import TYPE_CHECKING, Any +from prompt_toolkit.filters import Condition +from prompt_toolkit.key_binding import KeyBindings from rich.table import Table from rich.text import Text @@ -352,6 +357,36 @@ async def leave_view(app: Any) -> bool: return True +def bind_ctrl_c(session: Any, view: Callable[[], AgentView | None]) -> bool: + """Make Ctrl+C stop the run in view (``AgentView.stop``) while one works. + + thinking-prompt's Ctrl+C cancels the input handler's task, and a view's + run works in a task of its own (the prompt stays open to steer it), so + the session's key bindings get one more, active only while that run + works; prompt_toolkit runs the last binding added whose filter holds. + Any other time Ctrl+C is thinking-prompt's. + + Returns: + Whether it was bound: a session whose application has no key + bindings of prompt_toolkit's own (a fake) gets none. + """ + bindings = getattr(getattr(session, "app", None), "key_bindings", None) + if not isinstance(bindings, KeyBindings): + return False + + def working() -> bool: + current = view() + return current is not None and current.working + + @bindings.add("c-c", filter=Condition(working)) + def stop_the_run_in_view(event: Any) -> None: + current = view() + if current is not None: + current.stop() + + return True + + class BackCommand(Command): """Leave a sub-agent's view, back to the main conversation.""" diff --git a/src/agentic_cli/cli/app.py b/src/agentic_cli/cli/app.py index ffc00578..0c100245 100644 --- a/src/agentic_cli/cli/app.py +++ b/src/agentic_cli/cli/app.py @@ -31,7 +31,7 @@ from thinking_prompt import AppInfo, ThinkingPromptSession, ThinkingPromptStyles -from agentic_cli.cli.agent_view import AgentView, leave_view, open_view +from agentic_cli.cli.agent_view import AgentView, bind_ctrl_c, leave_view, open_view from agentic_cli.cli.commands import Command, CommandRegistry from agentic_cli.cli.message_processor import MessageProcessor, _says_so_when_stopped from agentic_cli.cli.conversation import ( @@ -2333,6 +2333,10 @@ async def handle_input(text: str) -> None: return await self.process_input(text) + # Ctrl+C stops the run in a sub-agent's view, which works outside + # the input handler. + bind_ctrl_c(self.session, lambda: self._agent_view) + # Keep long-running jobs visible in the status bar while the # session runs, independent of the agent loop. async with job_monitor.running(): @@ -2346,6 +2350,13 @@ async def handle_input(text: str) -> None: finally: opening.cancel() await asyncio.gather(opening, return_exceptions=True) + # A view's run still working is the user's to stop: it ends, + # cancelled by the user, before the workflow goes (whose + # cleanup waits for that turn). + view = self._agent_view + if view is not None: + view.stop() + await view.settled() # Propose memories from the session (if enabled) while the workflow # is still alive: leaving this context closes the manager, and the diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index 6f35a4e8..7c84187f 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -19,11 +19,13 @@ from __future__ import annotations import asyncio +from types import SimpleNamespace import pytest from agentic_cli.cli import AppInfo from agentic_cli.cli import app as app_module +from agentic_cli.cli import workflow_controller from agentic_cli.cli.agent_view import ( BACK_RULE, COMPACT_IN_VIEW, @@ -32,6 +34,7 @@ READ_ONLY, STEERED, TELLING, + bind_ctrl_c, ) from agentic_cli.cli.agents_command import NO_SUCH_AGENT from agentic_cli.cli.app import BaseCLIApp @@ -473,3 +476,92 @@ async def test_it_blocks_no_event_loop(self, make_crew): await typed(app, "/agent researcher-1", "Now find Y.", "/back") assert said(app.session, "add_response") == ["Done.", "Y is 7.", "Noted."] + + +# -- Ctrl+C on the run in view --------------------------------------------------------- + + +class _Viewed: + """What the Ctrl+C binding reads of a view: whether its run works, and its stop.""" + + def __init__(self) -> None: + self.working = False + self.stopped = 0 + + def stop(self) -> bool: + self.stopped += 1 + return True + + +class TestCtrlCInAView: + """The run in view works outside the input handler (the prompt stays open + to steer it), so thinking-prompt's Ctrl+C, which cancels the handler, does + not reach it: a binding of the session's own stops it, active only while + that run works (``tests/cli/test_console_turns.py`` presses it).""" + + def test_it_stops_the_run_in_view_only_while_one_works(self): + from prompt_toolkit.keys import Keys + from thinking_prompt import ThinkingPromptSession + + session = ThinkingPromptSession(message=">>> ") + view = _Viewed() + + def runs_on_ctrl_c(): + """The handler prompt_toolkit runs: the last binding whose filter holds.""" + bound = session.app.key_bindings.get_bindings_for_keys((Keys.ControlC,)) + return [binding for binding in bound if binding.filter()][-1].handler + + assert bind_ctrl_c(session, lambda: view) is True + idle = runs_on_ctrl_c() + view.working = True + runs_on_ctrl_c()(None) + + assert idle.__name__ == "cancel" # thinking-prompt's own + assert view.stopped == 1 + + def test_a_fake_session_gets_none(self): + assert bind_ctrl_c(autospec_session(), lambda: None) is False + + +class TestExitInAView: + async def test_a_run_still_working_at_exit_is_the_users_stop(self, make_crew, monkeypatch): + """``/exit`` while the run in view works: the run is the user's to + stop, and is, before the workflow goes (whose cleanup waits for it).""" + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[says("X is 42."), calls(use("contract_block", "r1"))], + ) + monkeypatch.setattr( + workflow_controller, "create_workflow_manager_from_settings", + lambda **kwargs: crew.manager, + ) + app = BaseCLIApp( + app_info=AppInfo(name="View test", version="0"), + agent_configs=[agent("coordinator")], + settings=crew.manager.settings, + session_id=SESSION, + ) + app.session = opening_boxes(autospec_session()) + app.session.app = SimpleNamespace(is_running=True) + + async def then_exit() -> None: + """The user's lines, then ``/exit`` once the run in view works.""" + await app.process_input("Find X.") + await app.process_input("/agent researcher-1") + await app.process_input("Wait here.") + await asyncio.wait_for(BLOCKING["started"].wait(), 10) + + app.session.run_async.side_effect = then_exit + running = asyncio.create_task(app.run()) + exited, _ = await asyncio.wait({running}, timeout=20) + if not exited: # its workflow's cleanup waits for the run in view: unwind it + app.agent_view.stop() + await running + + assert exited, "the app did not exit: the run in view was still working" + last = crew.records()[-1] + assert (last.ref.run, last.status, last.cancelled_by) == ( + "researcher-1#2", RUN_CANCELLED, "user", + ) + assert crew.instances() == [("researcher-1", INSTANCE_STOPPED)] diff --git a/tests/cli/test_console_turns.py b/tests/cli/test_console_turns.py index 3911bbc6..44dac3b7 100644 --- a/tests/cli/test_console_turns.py +++ b/tests/cli/test_console_turns.py @@ -569,3 +569,31 @@ def test_a_sub_agents_view_runs_a_follow_up_and_back_tells_the_main_agent(consol transcript = console.transcript assert transcript.index("Researched: Find Y.") < transcript.index("── back to main ──") assert "Busy" not in transcript + + +def test_in_a_view_a_line_steers_the_run_that_works_and_ctrl_c_stops_it(console): + """A line typed while the sub-agent's run works is given to that run (the + prompt takes it: no "Busy"); Ctrl+C stops the run, said once, and the + user goes on with the stopped sub-agent.""" + console.type_line("delegate") + console.expect("The researcher found X.") + console.type_line("/agent researcher-1") + console.expect("── researcher-1 · researcher · idle ──") + console.type_line("hold") + console.expect("Holding.") + console.type_line("Also find Z.") + console.expect("Given to researcher-1's run before its next step.") + console.expect("Steered: Also find Z.") + console.type_line("slow") + console.expect("Working on it.") + + console.child.sendcontrol("c") + console.expect("Operation cancelled...") + console.expect("researcher-1 · stopped") + console.type_line("Go on.") + console.expect("Researched: Go on.") + console.exit() + + transcript = console.transcript + assert transcript.count("Operation cancelled...") == 1 + assert "Busy" not in transcript From 2cbba3863759eded3b00e21f30c952d588f969a4 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:29:18 -0500 Subject: [PATCH 05/17] Docs: a sub-agent's view --- CHANGELOG.md | 28 +++++++++++++++++++++++++--- CLAUDE.md | 15 ++++++++------- README.md | 21 ++++++++++++++++++--- 3 files changed, 51 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 452b2177..776e3708 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -575,6 +575,27 @@ the start of the entry's title. ### Added +- **A sub-agent's view: `/agent ` and `/back`.** `/agent ` (or Enter in + `/agents`' picker) opens one of the conversation's sub-agents to work with + directly: a rule (`── researcher-2 · researcher · idle ──`) and a recap (its + title and objective, its last run's status, the first lines of its result, + its tokens; nothing replayed), the prompt `researcher-2> `, and a status bar + that names it, its status, its own `ctx` and tokens, the jobs segment kept. + A line typed there is its next run (`run_instance`, `started_by: user`), its + text the reply; a line typed while that run works is given to it before its + next model step (`steer_instance`), not queued. The run works outside the + input handler, so the prompt stays open to steer it, and Ctrl+C stops it (a + key binding of the view's own, active only while its run works: the user's + stop, the sub-agent `stopped`). `/back` waits for a run still working, + prints `── back to main ──`, and, when a run you started there ended, the + main agent gets one notice turn with its latest envelope (`tell_root`), + drawn as a job's notice is; the main agent's notices (finished jobs) wait + while a view is open, counted in `↻N`, and are told after it + (`job_auto_resume`). In a view `/status` shows the sub-agent's context, + `/compact` is refused, `/new` and `/resume` leave it first; a closed + sub-agent's view is read-only (no prompt). The app's `agent_view`, + `open_agent_view(id)` and `leave_agent_view()` (provisional) are what the + commands call. - **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 @@ -623,7 +644,7 @@ the start of the entry's title. (`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 ` closes it and its own sub-agents: no more - runs, its work still shown by `/agents `. `/agent ` shows it. Each + runs, its work still shown by `/agents `. `/agent ` opens its view. 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 @@ -872,8 +893,9 @@ the start of the entry's title. - **`/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 ` shows one instance (`researcher-2`: - every run of it, its first and each follow-up) or run (`researcher-2#1`): + opens the view of the one picked (`/agent `). `/agents ` 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, diff --git a/CLAUDE.md b/CLAUDE.md index abf03be0..df058883 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,19 +30,20 @@ agentic-cli/ │ ├── protected_paths.py # The locations no tool reaches (credential stores, never-writable files and dirs, the project's .git/.env files/.{app_name}, ~/.{app_name} with its .env and settings.json): the engine's builtin denies and the OS sandbox's policy are both built from it (stdlib only) │ ├── logging.py # configure_logging (third-party loggers quieted there, google_genai.types too: no import sets a level); LOG_STREAM, which every logger writes to (structlog through _LineLogger, no lock); log_lines_to(sink): each line to a sink instead of stderr │ ├── cli/ -│ │ ├── app.py # BaseCLIApp (subagents=: the SubAgentPolicy every manager the app builds gets, through its WorkflowController; main(): the command line, add_arguments/from_args, exit_status; session_start: how run() begins, the run's own conversation loaded before the prompt, also when the workflow did not start (_adopt_its_own: an id the app was given held from the start, one the run made from its first write); its resume once the prompt is up (_open_on_startup, holding the turn lock from before the prompt takes a line: a turn typed ahead waits and runs there; Ctrl+C there ends the app; --continue passes over conversations another process holds, _newest_free, the one chosen held beside the run's own until the switch); --continue and --resume find the conversation's backend from every installed backend's reader before the workflow is built (_start_on_its_backend: the run builds that backend once); the --resume hint at exit (the run's store named after a session_store change; the backend only when no reader reads it, LangGraph: --resume opens a conversation on its own); the session it builds; get_theme(name); /settings: _build_ui_items, apply_settings and save_settings delegate to cli/settings_ui.py (SettingsUI: an app's override applies); run() installs the ADK log filters first (workflow/adk/log_filters.py: an app built but never run installs none), then the SIGHUP/SIGTERM handlers that kill live execute_python runs before chaining to the previous handler (_stop_runs_on_signals); the LangGraph deprecation notice; start_new_session(backend=None): /new [backend] (the settings' orchestrator by default; another backend: the memories proposed, WorkflowController.switch_backend, then the switch to the new id at its place; a Ctrl+C once it runs opens its conversation first); a line typed runs in ConversationCore.run_turn (on _turn_parts: the app's parts as they are), then the jobs at the turn's end through the app's own resume_finished_jobs(); compact() (ConversationCore.compact), start_new_session() and resume_session(): /compact, /new and /resume, under the conversation's turn lock (_turn_lock: ConversationCore.turn_lock; pick_session(), the picker, is not: it waits on a dialog); session_store=memory keeps one conversation at a time (Place.kept; session_store: the run's store): /new drops the one left once the switch is made, after its memories are proposed (_drop: its delete_session, shielded; on another backend the manager released takes it along; one it cannot confirm gone, the workflow down or its lookup or delete raising, is remembered and dropped once a workflow is ready: before the next turn, or right after the turn whose own start revives the workflow, and always before that turn's delivery of finished jobs, /compact and the next /new, never while it is the open one: ConversationCore.drop_left), and resume_session, pick_session, --resume (status 1) and --continue (a new conversation) are refused with NOT_KEPT, before any look-up; every installed backend's conversations (list_conversations, delete_conversation, session_backend; cli/stored_conversations.py): the picker names each row's backend and returns a PickedConversation, and /resume opens a conversation on the backend that keeps it (_open_elsewhere: held there, memories proposed, switch_backend with the run's services, then the switch at its place; an id two backends keep opens on the running one, the other named); every change of conversation through ConversationCore.switch (_conversation; _session_id and _turned forward to it); the session_id setter deprecated (its synchronous part, switch_now, and a DeprecationWarning); a conversation's memories proposed once per conversation used (_turned); the memory proposals waiting, said at startup and after /new and /resume (_name_waiting_proposals); resume_finished_jobs(): ConversationCore.deliver_finished_jobs, the jobs waiting named at startup by ConversationCore.waiting_jobs (_name_its_waiting_jobs)) +│ │ ├── app.py # BaseCLIApp (subagents=: the SubAgentPolicy every manager the app builds gets, through its WorkflowController; main(): the command line, add_arguments/from_args, exit_status; session_start: how run() begins, the run's own conversation loaded before the prompt, also when the workflow did not start (_adopt_its_own: an id the app was given held from the start, one the run made from its first write); its resume once the prompt is up (_open_on_startup, holding the turn lock from before the prompt takes a line: a turn typed ahead waits and runs there; Ctrl+C there ends the app; --continue passes over conversations another process holds, _newest_free, the one chosen held beside the run's own until the switch); --continue and --resume find the conversation's backend from every installed backend's reader before the workflow is built (_start_on_its_backend: the run builds that backend once); the --resume hint at exit (the run's store named after a session_store change; the backend only when no reader reads it, LangGraph: --resume opens a conversation on its own); the session it builds; get_theme(name); /settings: _build_ui_items, apply_settings and save_settings delegate to cli/settings_ui.py (SettingsUI: an app's override applies); run() installs the ADK log filters first (workflow/adk/log_filters.py: an app built but never run installs none), then the SIGHUP/SIGTERM handlers that kill live execute_python runs before chaining to the previous handler (_stop_runs_on_signals); the LangGraph deprecation notice; start_new_session(backend=None): /new [backend] (the settings' orchestrator by default; another backend: the memories proposed, WorkflowController.switch_backend, then the switch to the new id at its place; a Ctrl+C once it runs opens its conversation first); a line typed runs in ConversationCore.run_turn (on _turn_parts: the app's parts as they are), then the jobs at the turn's end through the app's own resume_finished_jobs(); compact() (ConversationCore.compact), start_new_session() and resume_session(): /compact, /new and /resume, under the conversation's turn lock (_turn_lock: ConversationCore.turn_lock; pick_session(), the picker, is not: it waits on a dialog); session_store=memory keeps one conversation at a time (Place.kept; session_store: the run's store): /new drops the one left once the switch is made, after its memories are proposed (_drop: its delete_session, shielded; on another backend the manager released takes it along; one it cannot confirm gone, the workflow down or its lookup or delete raising, is remembered and dropped once a workflow is ready: before the next turn, or right after the turn whose own start revives the workflow, and always before that turn's delivery of finished jobs, /compact and the next /new, never while it is the open one: ConversationCore.drop_left), and resume_session, pick_session, --resume (status 1) and --continue (a new conversation) are refused with NOT_KEPT, before any look-up; every installed backend's conversations (list_conversations, delete_conversation, session_backend; cli/stored_conversations.py): the picker names each row's backend and returns a PickedConversation, and /resume opens a conversation on the backend that keeps it (_open_elsewhere: held there, memories proposed, switch_backend with the run's services, then the switch at its place; an id two backends keep opens on the running one, the other named); every change of conversation through ConversationCore.switch (_conversation; _session_id and _turned forward to it); the session_id setter deprecated (its synchronous part, switch_now, and a DeprecationWarning); a conversation's memories proposed once per conversation used (_turned); the memory proposals waiting, said at startup and after /new and /resume (_name_waiting_proposals); resume_finished_jobs(): ConversationCore.deliver_finished_jobs, the jobs waiting named at startup by ConversationCore.waiting_jobs (_name_its_waiting_jobs), none in a sub-agent's view; a sub-agent's view (cli/agent_view.py, provisional: agent_view, open_agent_view(id), leave_agent_view()): process_input gives a line typed there to AgentView.take, and draws its prompt and status bar again after a command; start_new_session and resume_session leave it first (_leave_view_first); run() binds Ctrl+C to the run in view (bind_ctrl_c) and stops one still working at exit) │ │ ├── commands.py # Command, CommandRegistry │ │ ├── job_monitor.py # JobMonitor: the status bar's jobs segment (running, queued, a finished job's note, ↻N: waiting_jobs' rule, can_resume answers kept 30 s (the other backends' look too: kept_elsewhere), forgotten after /sessions --delete or when the workflow is replaced), one tick every 2 s, its JobManager.list() on a worker thread -│ │ ├── conversation.py # ConversationCore: the conversation the turns run in (its id, turned, its lock at its Place: the backend and store, the store the run's for its whole life (Place.kept: not the memory store, where the CLI keeps one conversation at a time and NOT_KEPT says why nothing else opens), the backend recorded as the app starts, for a new conversation on another backend, and on a /settings change of the orchestrator while the workflow is down, its next start builds afresh and nothing of the conversation is stored (SettingsUI._move_here, WorkflowController.next_start_builds), never read from the settings in between; deferred: an id this run made (the start's, /new's, an orchestrator change's) is in no store, so it is held from its first write, hold_to_write under the turn lock before a turn, a job's notice or /compact (_held_to_write; a run in which no turn runs makes no lock file: a line typed while the workflow is down takes the hold before its retried start; a lock that cannot be taken, an OSError, leaves it unheld, said once, and the write goes on); fresh: nothing of it stored, opened_empty (an id this run made, or one a load found empty) and not written (no turn of it ran on a ready workflow), the one condition for another backend); switch: the one protocol (/new on any backend, /resume, startup, the same id in another place while the workflow is down): the target's lock taken (another process's refused), memories proposed, the workflow loads it (a stored one gone: not made, or, made already in another place, opened empty: gone), then made at once (lock, id, task list, usage counters) or let go, a workflow that took it given the old one back; made before the load when there is no other conversation to stay in (the same id, or another place: a new or stored conversation on another backend); a Ctrl+C at any await leaves one conversation held; switch_now: the deprecated session_id setter's part; turn_lock: what writes to the conversation and every switch take it; run_turn, compact and run_job_resume: a turn (echoed, held to write, turned, written once it reached a ready workflow; run_turn says whether it ran, whatever the processor returns), /compact and a finished job's notice under it, on TurnParts (the app's parts as they are); deliver_finished_jobs: each job that waits here (cli/waiting_jobs.py's rule, which waiting_jobs names them by, the other backends' look through TurnParts.kept_elsewhere), every JobManager call on a worker thread, a delivery claimed only once it can reach the agent (process_resume(claim=), after the readiness check and can_resume; _claim_delivery: a claim a Ctrl+C stopped is handed back, JobManager.release_resume), a failure before the claim said once per job and conversation when the CLI tells jobs on its own (telling_on_its_own); to_drop/drop_left: the conversations /new left on the memory store that the store may still hold (the workflow down, a lookup or delete that raised), dropped through TurnParts.drop under the turn lock once a workflow is ready, before a turn, /compact or a delivery uses it (after a turn or /compact that started it), one try per point, done once the store has it no more (a workflow without supports_sessions has none), the open one skipped; a delivery with none to drop takes no turn lock +│ │ ├── conversation.py # ConversationCore: the conversation the turns run in (its id, turned, its lock at its Place: the backend and store, the store the run's for its whole life (Place.kept: not the memory store, where the CLI keeps one conversation at a time and NOT_KEPT says why nothing else opens), the backend recorded as the app starts, for a new conversation on another backend, and on a /settings change of the orchestrator while the workflow is down, its next start builds afresh and nothing of the conversation is stored (SettingsUI._move_here, WorkflowController.next_start_builds), never read from the settings in between; deferred: an id this run made (the start's, /new's, an orchestrator change's) is in no store, so it is held from its first write, hold_to_write under the turn lock before a turn, a job's notice or /compact (_held_to_write; a run in which no turn runs makes no lock file: a line typed while the workflow is down takes the hold before its retried start; a lock that cannot be taken, an OSError, leaves it unheld, said once, and the write goes on); fresh: nothing of it stored, opened_empty (an id this run made, or one a load found empty) and not written (no turn of it ran on a ready workflow), the one condition for another backend); switch: the one protocol (/new on any backend, /resume, startup, the same id in another place while the workflow is down): the target's lock taken (another process's refused), memories proposed, the workflow loads it (a stored one gone: not made, or, made already in another place, opened empty: gone), then made at once (lock, id, task list, usage counters) or let go, a workflow that took it given the old one back; made before the load when there is no other conversation to stay in (the same id, or another place: a new or stored conversation on another backend); a Ctrl+C at any await leaves one conversation held; switch_now: the deprecated session_id setter's part; turn_lock: what writes to the conversation and every switch take it; run_turn, compact and run_job_resume: a turn (echoed, held to write, turned, written once it reached a ready workflow; run_turn says whether it ran, whatever the processor returns), /compact and a finished job's notice under it, on TurnParts (the app's parts as they are); run_instance and tell_root (_write): a line typed in a sub-agent's view as its next run (process_instance; written, not turned) and the main agent's notice after a view (process_notice; turned), under it too; deliver_finished_jobs: each job that waits here (cli/waiting_jobs.py's rule, which waiting_jobs names them by, the other backends' look through TurnParts.kept_elsewhere), every JobManager call on a worker thread, a delivery claimed only once it can reach the agent (process_resume(claim=), after the readiness check and can_resume; _claim_delivery: a claim a Ctrl+C stopped is handed back, JobManager.release_resume), a failure before the claim said once per job and conversation when the CLI tells jobs on its own (telling_on_its_own); to_drop/drop_left: the conversations /new left on the memory store that the store may still hold (the workflow down, a lookup or delete that raised), dropped through TurnParts.drop under the turn lock once a workflow is ready, before a turn, /compact or a delivery uses it (after a turn or /compact that started it), one try per point, done once the store has it no more (a workflow without supports_sessions has none), the open one skipped; a delivery with none to drop takes no turn lock │ │ ├── conversation_lock.py # ConversationLock: one process per stored conversation (flock under /locks/; ConversationCore holds it and refuses one held elsewhere; /sessions --delete too, through conversation_held) -│ │ ├── builtin_commands.py # /help (by category; /help : its usage and examples), /status (the main agent's context rows: context_budget; why the workflow did not start: app.workflow_error; tokens by agent: the main agent, each sub-agent with its runs, the side calls by purpose, from the manager's usage ledger), /models (ModelsCommand: the list, each model's facts and sources, Status for an entry left out, the providers in use; /models searches the full listings; refresh), /sessions (every installed backend's, a Backend column; --delete= on the backend that keeps it, --backend= for an id two keep; on the memory store NOT_KEPT, no table, --delete refused), /resume [] (sessions; refused on the memory store), /jobs (resume: finished jobs), /compact [focus], /new [backend] (an unknown backend or a missing extra refused: check_backend), ... -│ │ ├── agents_command.py # /agents: the open conversation's sub-agent instances (agent_runs.instances under workflow.session_ref(app.session_id)) in a picker (a Dialog with one ChoiceField, as /resume's: `picker`), each followed by the ones it started (id · type · status · title), Enter showing the one picked as /agents does; /agent shows one, /agent stop and /agent close are the user's stop and close (stop_instance, close_instance, the app's conversation named), each saying what it did or why not (NO_SUCH_AGENT, ALREADY_TEXT), nothing tried on records not read; /agents (its panel: tokens in/out from the usage ledger, usage_of, live for a running run; time): one instance (every run of it) or run (type, parent, title; 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 +│ │ ├── builtin_commands.py # /help (by category; /help : its usage and examples), /status (the main agent's context rows: context_budget, in a sub-agent's view the instance's, AgentView.context_rows; why the workflow did not start: app.workflow_error; tokens by agent: the main agent, each sub-agent with its runs, the side calls by purpose, from the manager's usage ledger), /models (ModelsCommand: the list, each model's facts and sources, Status for an entry left out, the providers in use; /models searches the full listings; refresh), /sessions (every installed backend's, a Backend column; --delete= on the backend that keeps it, --backend= for an id two keep; on the memory store NOT_KEPT, no table, --delete refused), /resume [] (sessions; refused on the memory store), /jobs (resume: finished jobs; in a sub-agent's view JOBS_WAIT: they wait for /back), /compact [focus] (refused in a sub-agent's view: COMPACT_IN_VIEW), /new [backend] (an unknown backend or a missing extra refused: check_backend), ... +│ │ ├── agents_command.py # /agents: the open conversation's sub-agent instances (agent_runs.instances under workflow.session_ref(app.session_id)) in a picker (a Dialog with one ChoiceField, as /resume's: `picker`), each followed by the ones it started (id · type · status · title), Enter opening the view of the one picked (app.open_agent_view); /agent opens its view (open_agent_view: cli/agent_view.py), /agent stop and /agent close are the user's stop and close (stop_instance, close_instance, the app's conversation named), each saying what it did or why not (NO_SUCH_AGENT, ALREADY_TEXT), nothing tried on records not read; /agents (its panel: tokens in/out from the usage ledger, usage_of, live for a running run; time): one instance (every run of it) or run (type, parent, title; 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 +│ │ ├── agent_view.py # A sub-agent's view (provisional; open_view/leave_view behind BaseCLIApp.open_agent_view/leave_agent_view, /back: BackCommand): entering prints VIEW_RULE ("── researcher-2 · researcher · idle ──") and a recap (title, its first brief's objective, its last run's status, its result's first lines, its tokens: instance_tokens, each run's from the usage ledger or its record), the prompt "> " (none for a closed one: read-only, READ_ONLY) and WorkflowController.view_segment (its status, its ctx: its last own step's prompt against its own trigger, its tokens); AgentView.take: a line steers the run that works (steer_instance, STEERED) or starts the instance's next run in a task of its own (ConversationCore.run_instance on the view's own MessageProcessor), outside the input handler, so the prompt takes the lines that steer it (thinking-prompt takes none while a handler runs); bind_ctrl_c: Ctrl+C stops that run (AgentView.stop: the user's stop) through a prompt_toolkit binding on the session's application, active only while it works; leave_view (/back): waits for the run, BACK_RULE, the prompt and bar back, then one notice turn (ConversationCore.tell_root, view_notice, TELLING) when a run the user started there ended since the main agent last heard, then the finished jobs that waited (job_auto_resume); in a view /compact is refused (COMPACT_IN_VIEW), /jobs resume waits (JOBS_WAIT), /status shows its context_rows, /new and /resume leave it first │ │ ├── memory_command.py # /memory: the list (a picker like /resume's), one memory (Delete, History), /memory , history (Restore), inbox (Accept/Discard/Skip), stale; proposals_line; Enter's button is Close or Skip, and Delete acts only on the memory as shown -│ │ ├── workflow_controller.py # WorkflowController (lazy/background init; subagents=: the SubAgentPolicy every manager it builds gets, a switch_backend's too; the session store of every manager of the run, store, fixed at its first start; the backend it runs, backend: the settings' orchestrator at its first start, then switch_backend's (a conversation on another backend, new or opened: the new manager started first on the run's services lent, given over by the old one and published at once, the old one released in the controller's task, a cancel stops only the wait; a failed start or give leaves the old one with its services; while down, a manager a failed reinitialization kept lends its services to the next build, _lender, and is released once they are given); reinitialize, a model switch, always in place; the status bar names the main agent's model) +│ │ ├── workflow_controller.py # WorkflowController (lazy/background init; subagents=: the SubAgentPolicy every manager it builds gets, a switch_backend's too; the session store of every manager of the run, store, fixed at its first start; the backend it runs, backend: the settings' orchestrator at its first start, then switch_backend's (a conversation on another backend, new or opened: the new manager started first on the run's services lent, given over by the old one and published at once, the old one released in the controller's task, a cancel stops only the wait; a failed start or give leaves the old one with its services; while down, a manager a failed reinitialization kept lends its services to the next build, _lender, and is released once they are given); reinitialize, a model switch, always in place; the status bar names the main agent's model, or in a sub-agent's view what view_segment says of the instance, the jobs segment kept) │ │ ├── session_resume.py # What /resume shows: the picker (picker: each row's backend once one is another's; PickedConversation, the id a str naming its backend), the "Resumed:" line ("Resumed on :" on another backend), the replay of the last 10 messages │ │ ├── stored_conversations.py # StoredConversations: one look at every installed backend's stored conversations (the running workflow's own, each other backend's SessionReader, opened and closed with the look): rows merged newest first, each naming its backend; where(id), delete; a backend not read (its extra missing, its store failing) left out and named in notes; a failing store warned of in the log at each look the user asks for, once a run for the app's own (warned: the job monitor's, a finished job's) │ │ ├── session_args.py # --continue / --resume → SessionStart (BaseCLIApp.main() adds them; start: new, continue, resume; SessionArgumentParser: --resume without its id names --continue and /resume) -│ │ ├── message_processor.py # WorkflowEvent → ThinkingPromptSession rendering (a sub-agent run's events box lines and transcript tool results under its name, "researcher-2 › …": the event's run, _at_work; the main agent's unchanged; a run's AGENT_RUN queued, input_required and running each write its line: "Queued: waiting for a free slot", "Waiting for your answer", "Working..."); Ctrl+C stops the request being processed (its boxes end with it; "Operation cancelled..." once, then the background jobs it submitted that still run, named; CancelledError re-raised); tool questions as dialogs, one at a time (a sub-agent run's titled with its instance, "researcher-2 · Permission" or "researcher-2 asks", a question's text opening with its run_label; one whose asking task alone is cancelled, a run stopped by its limit, its parent or the user, withdrawn and the events box back, the turn going on); process_compact: /compact run as a turn (compact() as its event source, live events merged in); a success line for each memory write (save_memory, update_memory, delete_memory); a failed turn said once, from its ERROR as from a raise ("Rate limited: …" for rate_limited, "Send your message again" for a ConversationChangedError) +│ │ ├── message_processor.py # WorkflowEvent → ThinkingPromptSession rendering (a sub-agent run's events box lines and transcript tool results under its name, "researcher-2 › …": the event's run, _at_work; the main agent's unchanged; a run's AGENT_RUN queued, input_required and running each write its line: "Queued: waiting for a free slot", "Waiting for your answer", "Working..."); Ctrl+C stops the request being processed (its boxes end with it; "Operation cancelled..." once, then the background jobs it submitted that still run, named; CancelledError re-raised); tool questions as dialogs, one at a time (a sub-agent run's titled with its instance, "researcher-2 · Permission" or "researcher-2 asks", a question's text opening with its run_label; one whose asking task alone is cancelled, a run stopped by its limit, its parent or the user, withdrawn and the events box back, the turn going on); process_compact: /compact run as a turn (compact() as its event source, live events merged in); process_instance: a line in a sub-agent's view as a turn (run_instance as its source; viewed: the instance's text is the reply, its lines name nobody, each of its run events redraws the status bar); process_notice: the main agent's notice after a view (tell_root as its source); a success line for each memory write (save_memory, update_memory, delete_memory); a failed turn said once, from its ERROR as from a raise ("Rate limited: …" for rate_limited, "Send your message again" for a ConversationChangedError) │ │ ├── settings_command.py # /settings: a Dialog with Save and Cancel; the fields that changed → apply_settings, then save_settings(keys=changed) (an override that cannot take `keys` fails there: "Settings applied but not saved: …") │ │ ├── settings_introspection.py # Pydantic field → thinking-prompt form field (built complete: they are frozen) │ │ ├── settings_ui.py # SettingsUI(app), what BaseCLIApp's _build_ui_items/apply_settings/save_settings delegate to (it calls the app's hooks: get_ui_setting_keys, get_theme, start_new_session; keeps nothing): the fields (the model pickers: the list, catalog.offered with model_services.role_models, as /models has it; a role's model the list leaves out offered first as " (current)", "Not offered ()" starting the description, so a Save changes no model untouched); a Save all or nothing, each key as settings_persistence declares (an orchestrator change, check_backend first, starts a new conversation on the new backend through the app's start_new_session() when the open one is fresh, ConversationCore.fresh read under the turn lock, else "(applies to the next /new)"; while the workflow is down a fresh one moves there, _move_here, decided again under the turn lock); Ctrl+C wherever a Save waits says "Operation cancelled..." once (_says_so_when_stopped; a new conversation's own, as /new says it) and undoes it; the save on a worker thread @@ -252,7 +253,7 @@ Workflow: - **Tool error handling**: All tools return `{"success": bool, ...}` dicts. Never raise `ToolError`. An exception that still escapes a tool is a bug, but it costs one call rather than the turn: on ADK, `workflow/adk/tool_error_plugin.py::ToolErrorPlugin` turns it into an error dict; on Deep Agents, `workflow/deepagents/middleware.py::ToolCallErrorMiddleware`, inside the permission gate, gives the same result, `{"success": false, "error": " failed: : "}` cut to 500 characters (both use `workflow/tool_errors.py`). A call to a tool name the agent does not have gets ADK's own text, its first two lines (`unknown_tool_result`: "nope failed: ValueError: Tool 'nope' not found." and the agent's tools by name), logged `tool_not_found` at info (the model's mistake): on ADK the permission gate lets ADK's stand-in through (`is_unknown_tool`: a bare `BaseTool` described "Tool not found", which runs nothing; contract-tested) and `ToolErrorPlugin` answers its lookup error; on Deep Agents the gate answers it. It catches `Exception`, never `BaseException`, so cancelling still cancels (google-adk 2.15 hands a cancelled call's `CancelledError` to `ToolErrorPlugin` for cleanup, ignoring the answer: it answers nothing and logs `tool_cancelled` at debug, no warning). `task` raises nothing into it: a sub-agent's model or run failing (its summary or overflow included: its own tools' errors are results already) fails the run, whose envelope its parent reads (`error`: the provider's reason; on ADK out of ADK's plugin wrapper), reported at once through the turn's live events as one recoverable `ERROR`, ` failed: `, the run's: the coordinator carries on. A sub-agent's overflow (still too long after its summary or trim) fails its run, on both backends, in the words of ADK's overflow handler, `: the request no longer fits 's context window.` with `error_code` `CONTEXT_OVERFLOW` (`context.py::subagent_overflow_message`): ADK's `OverflowPlugin` answers the run's model call with it, Deep Agents' manager raises it (`RunFailed`). A refusal is no exception here (the framework adds no `ModelRefusalMiddleware`): a sub-agent whose final answer a model refused ends its run `refused`, and its parent reads, as its envelope's result, Deep Agents 0.7.34's notice ("The subagent stopped because a model refused the request. … Retrying the same request is unlikely to succeed; rephrase it or continue without it."), on both backends and whichever deepagents the pin installs (0.7.28 has no notice of its own; 0.7.34+ finds no refusal block left to word again); an answer cut at the output limit keeps its text, followed by `[cut off at the output limit]`, and its run ends `completed` and `partial`, with one recoverable warning ("'s answer was cut off at the output limit"); the answer's thoughts or reasoning are kept. ADK's `SubAgentOutcomePlugin` and Deep Agents' `SubAgentOutcomeMiddleware` rewrite and mark the answer, by `workflow/agents/outcome.py`. On ADK the plugin reads the answer's `finish_reason` (Claude's `refusal` and a Chat Completions `content_filter` arrive as `SAFETY`, `max_tokens` and `length` as `MAX_TOKENS`, Gemini's as themselves), the `error_code` ADK sets on an answer with no content (a Gemini prompt's `block_reason`), the `reason` an `OTHER` stop names in its JSON error message (ADK's OpenAI Responses adapter's `incomplete_details`, `content_filter` among them) and a text part `OpenAI refusal: ` (that adapter's refusal, and `OpenAICompatibleLlm`'s of a Chat Completions `refusal`, which ADK's class drops). On Deep Agents the middleware reads `response_metadata`'s `stop_reason` (ChatAnthropic), `finish_reason` (ChatOpenAI, ChatGoogleGenerativeAI), `incomplete_details.reason` (the Responses API) and `prompt_feedback.block_reason` (a Gemini prompt block), and a refusal the answer holds (a refusal block, standard or `non_standard`, or `additional_kwargs["refusal"]`). The root's own answers reach the user as their model gave them: on ADK a root's refusal with no answer (Claude's, Gemini's) is still the turn's one `ERROR` (" returned no answer"), and a root on OpenRouter or an OpenAI-compatible server replies "OpenAI refusal: ". On both backends the root's own failure leaves the run: the turn's one `ERROR`. A gate or error result goes back as the call's `ToolMessage` with `status="error"`. LangGraph's `ToolNode` runs with `handle_tool_errors=True`. - **Tool result cap**: every tool result passes `workflow/tool_output.py::cap_tool_result` (registered, MCP and skill tools, `job_result`, a delegation's envelope on either backend): one over `tool_result_max_chars` is cut to its shape and as much of its head and tail as fits (the kept length is bisected, since JSON escapes vary), with a note (under `truncated`, or appended to a string) pointing at its full output in `./.{app_name}/tool-output/`, written for `read_file` to page by lines (lines over 2,000 characters split). A string that holds a JSON object (`json_object`: a delegation's envelope, which both task tools write unescaped, `ensure_ascii=False`; a framework tool's dict in a Deep Agents `ToolMessage`) is cut as that dict and given back as its JSON text, so the parent reads JSON still, on both backends. On ADK, `workflow/adk/tool_result_cap_plugin.py::ToolResultCapPlugin` is registered after `InterruptedCallsPlugin`, since ADK stops at the first `after_tool_callback` that returns a value, and it leaves out an agent with `after_tool_callback`s of its own (a native YAML app's, `build.own_after_tool_agents`), which ADK would skip once the cap answered. ADK's Claude and OpenAI Responses adapters send only a result's `content`, else its `result`, so the plugin also puts the note there (`_note_where_sent`). On Deep Agents, `ToolResultCapMiddleware` sits between the permission gate and `ToolCallErrorMiddleware`, so an error result is capped too, and reads a `ToolMessage` (its text cut by the cap's string rule, text blocks joined into the first) and each `ToolMessage` of a `Command`. A call of the framework's `read_file` (by identity, as each gate resolves tools) on a saved output is cut without a second save. Saving never fails the call (`tool_output_not_saved` warns once per folder, then debug), and a cap that raises leaves the result uncut (`tool_result_cap_failed` at warning, its traceback at debug). - **Summarizing on ADK (main agent only)**: every app's App (a native ADK YAML app's too, when its root's model has a context budget) has ADK's `EventsCompactionConfig` with `workflow/adk/compaction.py::AgentCliSummarizer` at the root's trigger (`context_budget`, as on Deep Agents); ADK checks before every agent's model call, and `MainAgentPlugin` (the first plugin) records the running agent in a ContextVar, so the summarizer writes only for the root (a sub-agent's run, on its type's runner, has no compaction config at all: a sub-agent compacting the shared session lost its brief and looped, 100 requests in one turn, offline). The summarizer picks its own range before paying for anything (`summary_range`: the newest `keep` tokens and the current turn kept, a cut only where a user turn starts, never parting a call from its result, long-running calls excepted since ADK re-injects them, nor leaving a kept event stamped inside the range; none for a saving under 20% of the trigger, the seed left out of it), writes on the root's own model (`_simple_model(SUMMARY_MAX_TOKENS, agent=root)`, thinking off) with `workflow/summary_prompt.py`, the rendering sized to that model's window (the middle cut, `MIDDLE_OMITTED`, the seed kept whole), and returns **user-role** text starting `SUMMARY_PREFIX` (a model-role first message is one Claude refuses), which the fit guard folds, after the memory index and the roster when the request has them, into the next user text (`fold_summary`), so no request holds two user messages in a row. `last_kept_turns` and `last_error` are for its callers: a manual summarizer warns of nothing itself. It reports through the turn's live events (`_run_and_stream` iterates the runner through `live_events.merged` under `reporting(live)`); any failure is one recoverable `ERROR` a turn, never raised to ADK. `NoAfterTurnCompactionRunner` overrides ADK's private `Runner._run_post_invocation_compaction` (contract-tested), so the prompt never waits for a summary after the answer. `FitGuardPlugin` is the last plugin (but `SentRequestLoggingPlugin`, which logs a request as sent, and `CallSentPlugin`, which starts the call's clock) and `OverflowPlugin` the one before it (`MemoryIndexPlugin`, when the root has a memory tool and `memory_index_enabled` is on, the one before that: it puts the conversation's memory index snapshot first in the root's requests, never in the session): the guard leaves a request's oldest turns out when it is over its agent's budget (keeping the newest turn and what opens the conversation, the memory index, the roster of the root's open sub-agents (`RosterPlugin`, before `MemoryIndexPlugin`, for a root with `message_agent`), then a summary: `protected_head`; in a sub-agent type's chain also the run's task message and its instance's brief, `brief_of`) and keeps each request as it came in (`request_as_seen`: one copy per model call, under the call's `EventActions`, which ADK passes to all three of its callbacks: each sub-agent run is an invocation of its own on a child session, but two runs of one type share that type's runner and its plugins, and a run drops only what its own cancelled calls left, as it ends), and the overflow handler, on a provider's overflow, summarizes now (the root, through `compact_session`, ADK's private `_run_compaction_for_token_threshold_config`; `_summarize_now` returns `WrittenSummary(text, kept_turns)`, and the retry is the index, the roster, the summary and those turns) or trims to half the budget (a sub-agent, or nothing to summarize), builds the retry from the guard's copy without the context cache, retries once on the agent's `canonical_model`, then answers the root with `LlmResponse(error_code="CONTEXT_OVERFLOW")`, never model text (ADK would store it as the reply), which `ADKEventProcessor` maps to the turn's `ERROR`; a retry that fails otherwise propagates, and `_run_and_stream` unwraps ADK's plugin-manager `RuntimeError` to the provider's error; a sub-agent's call that still does not fit is answered with an error response too, `CONTEXT_OVERFLOW` and `subagent_overflow_message`, which its run's processor keeps as the run's failure: the run ends `failed` with those words (`RunFailed`), its parent reads them in the envelope, and the user is warned once, by the framework's delegation (`agents/delegate.py`), as on Deep Agents. A native ADK YAML app gets all of it: only the building of its agents differs (`workflow/adk/build.py`). Its chat-mode sub-agents keep transferring, and an agent the root transfers to replies to the user (`build.reply_agents`: its text is the reply, recent_messages reads it, its overflow is the turn's clear error, its calls write the outside-content mark); the summary and the memory index stay the root's, so such an agent is trimmed by the fit guard, not summarized. An agent's own callbacks (a native app's) run after every plugin, and only when none answered: its before-model callbacks see the request after the fit guard, and the cap leaves out an agent with after-tool callbacks. A main agent whose model does not resolve through the catalog has no budget and no summary. -- **Sub-agents delegate and return**: on both backends a sub-agent run is a call of its parent's `task` tool (the framework's: `tools/_core/delegation.py` declares it, `workflow/agents/delegate.py` runs it) that returns in the same turn; only the root replies to the user (a sub-agent's `TEXT` carries `metadata["subagent"]`, and the CLI shows it as the events box's status line, under its run's name: `researcher-2 › …`; `/agents` picks among a conversation's instances), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the caller's own sub-agents) and a brief (`workflow/agents/brief.py`: `title`, `objective`, `deliverable`, `constraints`, `known`, `done_when`), its schema and description the same on both backends (`task_parameters`, `task_description`: a line per type with its description, "The agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both: it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents `, never written to the conversation. It ends as the `RunAnswer` says: its last text (a reply that also called a tool included; none at all, an empty result shown `No answer`), `refused` or `partial` by the outcome mark, `failed` for an error or a raise (one recoverable `ERROR`, ` failed: `, or the hook's own words, `RunFailed`: an overflow's; its result the text it wrote before it failed: a failed model call is the hook's `RunAnswer.error`, `failure_reason`, its warning's code `RunAnswer.error_code`, the error's type, and `RunFailed` carries `text=`); and the call's result is the run's envelope as JSON (`workflow/agents/envelope.py`), shown by `show_as_delegation`. A cancel of the caller's task stops the run's task first and ends the run `interrupted`. Each run works under its `RunControl` (`workflow/agents/control.py`, `AgentRun.control`), with its type's `AgentConfig.limits` over the policy's (`SubAgentPolicy.limits`, `DEFAULT_LIMITS`: 100 model calls): `Delegations.cancel(run_id, by=, error=)` cancels the run alone (its parent, the user or a limit), and the hook, seeing its own cancel (`own_cancel`), stops the run as a stopped turn's (ADK: its abort signal, its open calls sealed in its child session; Deep Agents: its stream closed) and returns what it has: the run ends `cancelled` with `cancelled_by` and that text, `partial`, while its siblings and the turn go on; the turn's own cancel still wins (`interrupted`). Past its `timeout` (counted from when its hook starts, `timing`) the run is cancelled by its limit (`time limit reached`); each model call is counted before it is made (`RunControlPlugin` in each sub-agent chain, `RunControlMiddleware` on each sub-agent's model side) and the last allowed one gets `STEP_LIMIT_NOTE` after its last message, its tools still declared (Claude refuses tool calls in a request that defines no tools); its answer's calls are dropped, never run, so the run completes `partial`, `step limit reached`; each call's tokens are counted after it, with what the run's other calls used (`RunControl(side_tokens=)`: its tools' side calls and its summaries, the ledger's rows of the run that are no agent step, `UsageLedger.by_purpose(run=)`), so the limit is the run's total as its usage record counts it, and past `max_tokens` an answer that makes tool calls is the run's last, its calls dropped, `cancelled` by its limit (`token limit reached`), while one that makes none ends the run as it would, `completed`, its result whole (a model that reports no usage counts none of its own). A turn starts at most `max_runs_per_turn` runs, at any depth (`sessions.runs_this_turn`): a call past it is the error result, no run started; `task`'s description says so (`limit_sentences`). At most `max_active` runs of a conversation work at once, at any depth (`workflow/agents/slots.py::SlotPool`, one per conversation, `Delegations.slots`; the root takes no slot): a run takes a slot right before its hook and its time limit start and gives it back at its end, however it ends; one that finds none waits `queued` (an `AGENT_RUN` and its record say so, then `running`), not counted against its `timeout`. A run lends its slot while it waits on its children (one lend for all it waits on at once; the child that ends last hands its slot straight back, so the tree in progress goes on ahead of the runs that have not started) or on the user (`waiting_on_user`: `input_required`, `queued` once answered while it waits for its slot back, then `running`, in `request_user_input` and in the permission engine from before its one-prompt lock until after it: a run waiting for a slot while holding the lock would hold every other run's prompt; a prompt no one can be shown, no input callback or its turn ended, lends nothing: `can_request_user_input`), so nested fan-out never deadlocks; a cancel, queued or lending, leaves no waiter in the heap and no slot taken. A message steered to a working run (`RunControl.steer`, through `Delegations.control(run)`) is added after its last message, as the user's, before its next model call, and stays in its transcript (ADK: appended to its child session, the run's later events stamped after it so a durable store reads them back in order; Deep Agents: added to its state); a sub-agent run's task message is never trimmed, on ADK neither by the fit guard nor by the overflow handler's retry, whatever was steered after it. A dialog whose run is stopped is withdrawn, the turn going on (`MessageProcessor`). `AgentConfig.inherit_context` sets what a run sees: False (the default) its task alone, True its parent's conversation too, read once as the run starts (the conversation after any summary; Deep Agents' less the message that called `task`, which ADK's copy keeps), before the task message, which then ends with `INHERITED_CONTEXT_NOTE` (whose conversation it reads, which message is its task); `validate_agent_graph` refuses a value that is not True or False, `inherit_context=True` on the root, on an agent with sub-agents and below another sub-agent. On ADK (`workflow/adk/task_tool.py::TaskTool`) every config-built agent is built on its own, with no ADK `sub_agents`, so ADK offers none `transfer_to_agent`, and gets ADK's identity line ("You are an agent. Your internal name is …"); a delegating agent has one `TaskTool`. A sub-agent is an instance that outlives its run: `idle` when the run ends, its next run a follow-up (`Delegations.follow_up`, through the same hook with `AgentRun.follow_up`, the message as written and no history), one run per instance at a time; a run's end leaves its instance `stopped` (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 `; on ADK a follow-up continues the instance's child session, the calls an earlier run left open answered first (`left_open_by`, from the instance's record), on Deep Agents the instance's own checkpointer thread (`instance_run_config`: its input the message and the caller's mark, the shared keys it changed compared with the thread's state as the run started). Each sub-agent type runs on its own runner (`App(name=child_app(app_name))`, the type's agent its root, `_agent_plugin_chain`: the main chain configured for a sub-agent, no memory index, no summary, `RunControlPlugin` and `SubAgentOutcomePlugin`; every plugin's per-call state keyed by invocation) over the manager's session service, on a child session per instance (`child_session_id`: `/`, the conversation id's `%` and `/` percent-encoded; an inheriting instance's gets the conversation's events copied once, at its first run, `task_tool.inherited_events`), under an app no conversation list reads. On Deep Agents (`workflow/deepagents/task_tool.py::build_task_tool`) each type's graph is built on its own, and a run `astream`s it in its task with `var_child_runnable_config` cleared, so its chunks reach its own loop alone, never its parent's stream; an inheriting run's history is the parent's messages with Deep Agents' summary event applied (`SummarizationMiddleware._apply_event_to_messages`, private: `tests/workflow/deepagents/test_compact.py` pins it), and `ForeignReasoningMiddleware(kind, agent=...)` leaves out the reasoning of AI messages another agent wrote. A native ADK YAML app keeps transferring (chat-mode sub-agents); a task-mode agent in one is refused at validation, since ADK runs its delegation outside the tool pipeline and keeps the call open across turns. With `SubAgentPolicy(follow_ups=True)` every agent with sub-agents also gets `message_agent`, `stop_agent` and `check_agents` beside `task` (`workflow/agents/follow_ups.py::call_follow_up_tool` over `Delegations.message`/`stop`/`check`; ADK's `FollowUpTool`, Deep Agents' `build_follow_up_tools`; an own tool of one of their names fails the build, a Deep Agents MCP tool of one is skipped): `message_agent` continues an idle instance, steers a running one (before its next step; a run already stopping or finished is waited for, then the message follows the instance up or is refused; one being closed is refused as closed at once) or, with `interrupt` (refused, nothing cancelled, when no follow-up could start; an agent's keeps the turn's run it checked for), replaces its run (the user's interrupt is the user's stop); `stop_agent` cancels a running run by its parent (the instance idle; only the user's stop makes one `stopped`) and, with `close`, closes it and its descendants; a message steered to a run and not in its transcript when it ends goes to the instance's next run (`RunControl.stored`/`unstored`: ADK counts one stored as its child-session append returns, Deep Agents once the model call after it holds it); a run that did not complete fully names its open tasks in its envelope (`open_tasks`); a run whose parent's run was stopped by its control ends `cancelled` by its parent, not `interrupted`. +- **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 agent." with a warning, `subagent_without_description`, for one without, and the fields `AgentConfig.brief_required` asks for); `read_brief` checks a call against them, and one that cannot start a run is the call's `{"success": false, "error": …}`, no run started or numbered. `Delegations.delegate` (the manager's `_delegations`) does the rest, alike on both: it names the run (`AgentRuns.run_for`), reports its `AGENT_RUN` start (title, brief, `started_by`, `mode`) and end through the turn's live events and the records, and runs the backend's hook, `_run_agent(AgentRun)`, in a task of its own, where the run is the active run and no tool call is, so each run ends at its own end. The run's first message is the task message (`task_message`); it starts with no plan and no task list of its own, and only the outside-content mark comes from the caller's state (`AgentRun.state`) and, when the run changed it, goes back (`RunAnswer.state`): the run's own last plan and tasks are `RunAnswer.plan`/`tasks`, on its end event and its `RunRecord`, shown by `/agents `, never written to the conversation. It ends as the `RunAnswer` says: its last text (a reply that also called a tool included; none at all, an empty result shown `No answer`), `refused` or `partial` by the outcome mark, `failed` for an error or a raise (one recoverable `ERROR`, ` failed: `, or the hook's own words, `RunFailed`: an overflow's; its result the text it wrote before it failed: a failed model call is the hook's `RunAnswer.error`, `failure_reason`, its warning's code `RunAnswer.error_code`, the error's type, and `RunFailed` carries `text=`); and the call's result is the run's envelope as JSON (`workflow/agents/envelope.py`), shown by `show_as_delegation`. A cancel of the caller's task stops the run's task first and ends the run `interrupted`. Each run works under its `RunControl` (`workflow/agents/control.py`, `AgentRun.control`), with its type's `AgentConfig.limits` over the policy's (`SubAgentPolicy.limits`, `DEFAULT_LIMITS`: 100 model calls): `Delegations.cancel(run_id, by=, error=)` cancels the run alone (its parent, the user or a limit), and the hook, seeing its own cancel (`own_cancel`), stops the run as a stopped turn's (ADK: its abort signal, its open calls sealed in its child session; Deep Agents: its stream closed) and returns what it has: the run ends `cancelled` with `cancelled_by` and that text, `partial`, while its siblings and the turn go on; the turn's own cancel still wins (`interrupted`). Past its `timeout` (counted from when its hook starts, `timing`) the run is cancelled by its limit (`time limit reached`); each model call is counted before it is made (`RunControlPlugin` in each sub-agent chain, `RunControlMiddleware` on each sub-agent's model side) and the last allowed one gets `STEP_LIMIT_NOTE` after its last message, its tools still declared (Claude refuses tool calls in a request that defines no tools); its answer's calls are dropped, never run, so the run completes `partial`, `step limit reached`; each call's tokens are counted after it, with what the run's other calls used (`RunControl(side_tokens=)`: its tools' side calls and its summaries, the ledger's rows of the run that are no agent step, `UsageLedger.by_purpose(run=)`), so the limit is the run's total as its usage record counts it, and past `max_tokens` an answer that makes tool calls is the run's last, its calls dropped, `cancelled` by its limit (`token limit reached`), while one that makes none ends the run as it would, `completed`, its result whole (a model that reports no usage counts none of its own). A turn starts at most `max_runs_per_turn` runs, at any depth (`sessions.runs_this_turn`): a call past it is the error result, no run started; `task`'s description says so (`limit_sentences`). At most `max_active` runs of a conversation work at once, at any depth (`workflow/agents/slots.py::SlotPool`, one per conversation, `Delegations.slots`; the root takes no slot): a run takes a slot right before its hook and its time limit start and gives it back at its end, however it ends; one that finds none waits `queued` (an `AGENT_RUN` and its record say so, then `running`), not counted against its `timeout`. A run lends its slot while it waits on its children (one lend for all it waits on at once; the child that ends last hands its slot straight back, so the tree in progress goes on ahead of the runs that have not started) or on the user (`waiting_on_user`: `input_required`, `queued` once answered while it waits for its slot back, then `running`, in `request_user_input` and in the permission engine from before its one-prompt lock until after it: a run waiting for a slot while holding the lock would hold every other run's prompt; a prompt no one can be shown, no input callback or its turn ended, lends nothing: `can_request_user_input`), so nested fan-out never deadlocks; a cancel, queued or lending, leaves no waiter in the heap and no slot taken. A message steered to a working run (`RunControl.steer`, through `Delegations.control(run)`) is added after its last message, as the user's, before its next model call, and stays in its transcript (ADK: appended to its child session, the run's later events stamped after it so a durable store reads them back in order; Deep Agents: added to its state); a sub-agent run's task message is never trimmed, on ADK neither by the fit guard nor by the overflow handler's retry, whatever was steered after it. A dialog whose run is stopped is withdrawn, the turn going on (`MessageProcessor`). `AgentConfig.inherit_context` sets what a run sees: False (the default) its task alone, True its parent's conversation too, read once as the run starts (the conversation after any summary; Deep Agents' less the message that called `task`, which ADK's copy keeps), before the task message, which then ends with `INHERITED_CONTEXT_NOTE` (whose conversation it reads, which message is its task); `validate_agent_graph` refuses a value that is not True or False, `inherit_context=True` on the root, on an agent with sub-agents and below another sub-agent. On ADK (`workflow/adk/task_tool.py::TaskTool`) every config-built agent is built on its own, with no ADK `sub_agents`, so ADK offers none `transfer_to_agent`, and gets ADK's identity line ("You are an agent. Your internal name is …"); a delegating agent has one `TaskTool`. A sub-agent is an instance that outlives its run: `idle` when the run ends, its next run a follow-up (`Delegations.follow_up`, through the same hook with `AgentRun.follow_up`, the message as written and no history), one run per instance at a time; a run's end leaves its instance `stopped` (once the user stopped it: its run cancelled by the user, or an idle one; only the user continues it), `closed` (`AgentConfig.continuable` False, or past `SubAgentPolicy.max_open`: the oldest idle one) or `idle`, `Delegations.close` closes an idle or stopped one and its descendants, and `AGENT_INSTANCE` carries a change without a run; the user controls any instance of the open conversation through the manager (`run_instance`: a follow-up as a turn of its own, its Ctrl+C the user's stop; `stop_instance`, `close_instance`, `steer_instance`; `tell_root`: a notice turn of the root, marked as a job's) and the CLI's `/agents` picker, `/agent stop|close ` and `/agent `'s view (`cli/agent_view.py`: a line typed there is the instance's next run or a steer of the run that works, Ctrl+C the user's stop, `/back` the root's notice); on ADK a follow-up continues the instance's child session, the calls an earlier run left open answered first (`left_open_by`, from the instance's record), on Deep Agents the instance's own checkpointer thread (`instance_run_config`: its input the message and the caller's mark, the shared keys it changed compared with the thread's state as the run started). Each sub-agent type runs on its own runner (`App(name=child_app(app_name))`, the type's agent its root, `_agent_plugin_chain`: the main chain configured for a sub-agent, no memory index, no summary, `RunControlPlugin` and `SubAgentOutcomePlugin`; every plugin's per-call state keyed by invocation) over the manager's session service, on a child session per instance (`child_session_id`: `/`, the conversation id's `%` and `/` percent-encoded; an inheriting instance's gets the conversation's events copied once, at its first run, `task_tool.inherited_events`), under an app no conversation list reads. On Deep Agents (`workflow/deepagents/task_tool.py::build_task_tool`) each type's graph is built on its own, and a run `astream`s it in its task with `var_child_runnable_config` cleared, so its chunks reach its own loop alone, never its parent's stream; an inheriting run's history is the parent's messages with Deep Agents' summary event applied (`SummarizationMiddleware._apply_event_to_messages`, private: `tests/workflow/deepagents/test_compact.py` pins it), and `ForeignReasoningMiddleware(kind, agent=...)` leaves out the reasoning of AI messages another agent wrote. A native ADK YAML app keeps transferring (chat-mode sub-agents); a task-mode agent in one is refused at validation, since ADK runs its delegation outside the tool pipeline and keeps the call open across turns. With `SubAgentPolicy(follow_ups=True)` every agent 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 ca9846a1..3dd2813c 100644 --- a/README.md +++ b/README.md @@ -1428,7 +1428,8 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", ``, 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; +- **The user's control.** `/agents` picks a sub-agent and opens its view, as + `/agent ` does (next bullet); `/agent stop ` (its run cancelled by you, `cancelled_by: user`; it is then `stopped`: its parent's messages are refused, only you can start its next run) and `/agent close ` (it and its own sub-agents). The @@ -1439,6 +1440,19 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", `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). +- **A sub-agent's view.** `/agent ` opens one to work with directly: a + rule (`── researcher-2 · researcher · idle ──`) and a recap (its title and + objective, its last run's status, the first lines of its result, its + tokens), the prompt `researcher-2> `, and a status bar naming it, its + status, its own `ctx` and tokens (the jobs segment kept). A line you type is + its next run, streamed as a turn, its text the reply; a line typed while + that run works is given to it before its next model step. Ctrl+C stops the + run (it is then `stopped`; your next line continues it). `/back` prints + `── back to main ──` and, when a run you started there ended, tells the main + agent its latest result in one notice turn; finished jobs wait while you are + in a view (`↻N`) and are told after `/back`. In a view `/status` shows the + sub-agent's context, `/compact` is refused, and `/new` and `/resume` leave + the view first; a closed sub-agent's view has no prompt (`/back` only). - **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 @@ -2276,10 +2290,11 @@ 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 ` 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 `, `/jobs cancel `, `/jobs clean`; `/jobs resume` tells the agent this conversation's finished jobs) | -| `/agents` | | Pick one of this conversation's sub-agents, each under the one that started it: id, type, status (`running`, `idle`, `stopped`, `closed`), title; Enter shows it (`/agents `: 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 ` shows it, `/agent stop ` stops it (its run, if one works; only you can start its next run), `/agent close ` closes it and its own sub-agents (no more runs; its work stays readable) | +| `/agents` | | Pick one of this conversation's sub-agents, each under the one that started it: id, type, status (`running`, `idle`, `stopped`, `closed`), title; Enter opens its view (`/agents ` shows one instance or run, each run's status and time, the first lines of its result, its error and its tokens by model) | +| `/agent` | | One sub-agent: `/agent ` opens its view (a line typed there is its next run, or steers the run that works; `/back` returns), `/agent stop ` stops it (its run, if one works; only you can start its next run), `/agent close ` closes it and its own sub-agents (no more runs; its work stays readable) | | `/papers` | `/docs` | List knowledge-base documents (filter by source, query, --global) | | `/sessions` | `/sess` | List the saved sessions of every installed backend: backend, title, turns, last update (delete one with `--delete=`; `--backend=` picks one of an id two backends keep); on the memory store it says none are kept | +| `/back` | | Leave a sub-agent's view, back to the main conversation; the main agent is told what you did there | | `/compact` | | Summarize the conversation now, keeping the newest turns word for word (`/compact `: what the summary should keep above all) | | `/new [backend]` | | Start a new conversation, on the backend named (`adk`, `deepagents`, `langgraph`) or the settings' `orchestrator`; the current one stays in `/sessions` (on the memory store it is dropped) | | `/resume` | | Reopen a saved conversation, on the backend that keeps it: pick one (Enter opens it, Esc cancels), or `/resume `; the last messages are shown again (refused on the memory store) | From 38b3e12fbb5a1f7b0ad8d56c574b2f665af7d8b4 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:09:54 -0500 Subject: [PATCH 06/17] CLI: one dialog at a time on the session A sub-agent's view runs its run outside the input handler, so a command may open a dialog while the run asks its question. thinking-prompt raises on a second dialog, which would turn a permission prompt into a denial the user never saw, or fail the command. Every dialog now takes the session's one lock while it is open: the commands' through show_dialog, a run's question inside the message processor. Whichever comes second waits for the first. --- src/agentic_cli/cli/agents_command.py | 3 +- src/agentic_cli/cli/app.py | 3 +- src/agentic_cli/cli/dialogs.py | 41 ++++++++ src/agentic_cli/cli/memory_command.py | 15 +-- src/agentic_cli/cli/message_processor.py | 10 +- src/agentic_cli/cli/settings_command.py | 3 +- tests/cli/test_agent_view.py | 115 +++++++++++++++++++++++ 7 files changed, 177 insertions(+), 13 deletions(-) create mode 100644 src/agentic_cli/cli/dialogs.py diff --git a/src/agentic_cli/cli/agents_command.py b/src/agentic_cli/cli/agents_command.py index 6b188edb..820addd9 100644 --- a/src/agentic_cli/cli/agents_command.py +++ b/src/agentic_cli/cli/agents_command.py @@ -45,6 +45,7 @@ from thinking_prompt import ChoiceField, Dialog from agentic_cli.cli.commands import Command, CommandCategory +from agentic_cli.cli.dialogs import show_dialog from agentic_cli.cli.usage_tracker import format_tokens, format_usage from agentic_cli.tools._core.tasks import task_progress_data from agentic_cli.workflow.agents import RUN_COMPLETED, RUN_INPUT_REQUIRED, RUN_STARTED @@ -112,7 +113,7 @@ async def execute(self, args: str, app: Any) -> None: app.session.add_message("system", NO_RUNS) return dialog, ids = picker(instances, placement=_placement(app)) - picked = await app.session.show_dialog(dialog) + picked = await show_dialog(app.session, dialog) if picked is not None and picked in ids: await app.open_agent_view(ids[picked]) diff --git a/src/agentic_cli/cli/app.py b/src/agentic_cli/cli/app.py index 0c100245..6bdbfe88 100644 --- a/src/agentic_cli/cli/app.py +++ b/src/agentic_cli/cli/app.py @@ -33,6 +33,7 @@ from agentic_cli.cli.agent_view import AgentView, bind_ctrl_c, leave_view, open_view from agentic_cli.cli.commands import Command, CommandRegistry +from agentic_cli.cli.dialogs import show_dialog from agentic_cli.cli.message_processor import MessageProcessor, _says_so_when_stopped from agentic_cli.cli.conversation import ( NOT_KEPT, @@ -1681,7 +1682,7 @@ async def pick_session(self) -> str | None: rows, datetime.now(timezone.utc), placement=self._settings.dialog_placement, backends=any(info.backend != running for info in rows), ) - picked = await self.session.show_dialog(dialog) + picked = await show_dialog(self.session, dialog) return None if picked is None else ids.get(picked) async def list_conversations(self, limit: int | None = None) -> "list[SessionInfo]": diff --git a/src/agentic_cli/cli/dialogs.py b/src/agentic_cli/cli/dialogs.py new file mode 100644 index 00000000..72af0249 --- /dev/null +++ b/src/agentic_cli/cli/dialogs.py @@ -0,0 +1,41 @@ +"""One dialog at a time on a session. + +thinking-prompt shows one dialog and raises on a second ``show_dialog``. A +turn and a command used to run one at a time, in the input handler, so they +never met. A sub-agent's view runs its run outside the handler (the prompt +stays open to steer it), so a command may open a dialog while the run asks +its question, or the run may ask while a command's dialog is open: a second +dialog that raised would be a permission prompt answered by a denial the +user never saw, or a command that fails. + +Every dialog of the app takes the session's one lock (``dialog_lock``) for as +long as it is open: whichever comes second waits for the user to answer the +first. The commands show theirs through ``show_dialog``; the message +processor holds the lock around a question's dialog. +""" + +from __future__ import annotations + +import asyncio +import weakref +from typing import Any + +_LOCKS: "weakref.WeakKeyDictionary[Any, asyncio.Lock]" = weakref.WeakKeyDictionary() + + +def dialog_lock(ui: Any) -> asyncio.Lock: + """The lock every dialog of the session ``ui`` takes while it is open.""" + lock = _LOCKS.get(ui) + if lock is None: + lock = _LOCKS[ui] = asyncio.Lock() + return lock + + +async def show_dialog(ui: Any, dialog: Any) -> Any: + """``ui.show_dialog(dialog)``, once no other dialog of the session is open. + + Returns: + What the dialog returns (the button's result, or None on Escape). + """ + async with dialog_lock(ui): + return await ui.show_dialog(dialog) diff --git a/src/agentic_cli/cli/memory_command.py b/src/agentic_cli/cli/memory_command.py index 6a5e28e5..d05a0b2d 100644 --- a/src/agentic_cli/cli/memory_command.py +++ b/src/agentic_cli/cli/memory_command.py @@ -24,6 +24,7 @@ from thinking_prompt import ButtonConfig, ChoiceField, Dialog from agentic_cli.cli.commands import Command, CommandCategory +from agentic_cli.cli.dialogs import show_dialog if TYPE_CHECKING: from thinking_prompt import Placement @@ -243,7 +244,7 @@ async def _list(self, app: Any, store: "MemoryStore", *, stale: bool = False) -> memories, problems, waiting, "Stale memories" if stale else "Memory", placement=_placement(app), ) - picked = await app.session.show_dialog(dialog) + picked = await show_dialog(app.session, dialog) key = rows.get(picked) if picked is not None else None if key == _PROBLEMS: await self._problems(app, problems) @@ -252,7 +253,7 @@ async def _list(self, app: Any, store: "MemoryStore", *, stale: bool = False) -> async def _problems(self, app: Any, problems: list["Problem"]) -> None: body = "\n".join(f"{p.path}\n {p.kind}: {p.detail}" for p in problems) - await app.session.show_dialog(Dialog( + await show_dialog(app.session, Dialog( "Memory files that cannot be used", body=body, buttons=[ButtonConfig("Close", result=None)], placement=_placement(app), )) @@ -263,8 +264,8 @@ async def _show(self, app: Any, store: "MemoryStore", memory_id: str) -> None: await self._missing(app, store, memory_id, shown=False) return versions = await asyncio.to_thread(store.history, memory.id) - choice = await app.session.show_dialog( - memory_view(memory, bool(versions), placement=_placement(app)) + choice = await show_dialog( + app.session, memory_view(memory, bool(versions), placement=_placement(app)) ) if choice == "delete": await self._delete(app, store, memory) @@ -328,7 +329,7 @@ async def _history(self, app: Any, store: "MemoryStore", memory_id: str | None) label += " ·" rows[label] = version title = "Memory history" + (f" of {memory_id}" if memory_id else "") - picked = await app.session.show_dialog(Dialog( + picked = await show_dialog(app.session, Dialog( title, fields=[ChoiceField("version", "", options=list(rows))], placement=_placement(app), )) @@ -337,7 +338,7 @@ async def _history(self, app: Any, store: "MemoryStore", memory_id: str | None) return current = await asyncio.to_thread(store.read, version.memory_id) unusable = None if current is not None else await asyncio.to_thread(_claiming, store, version.memory_id) - choice = await app.session.show_dialog(Dialog( + choice = await show_dialog(app.session, Dialog( f"Version of {version.memory_id}", body=version_body(version, current, unusable), buttons=[ButtonConfig("Restore", result="restore"), ButtonConfig("Close", result=None, focused=True)], @@ -366,7 +367,7 @@ async def _inbox(self, app: Any, store: "MemoryStore") -> None: current = await asyncio.to_thread(store.read, proposal.target or "") if current is None: unusable = await asyncio.to_thread(_claiming, store, proposal.target or "") - choice = await app.session.show_dialog(Dialog( + choice = await show_dialog(app.session, Dialog( f"Memory proposal {number} of {len(proposals)}", body=proposal_body(proposal, current, unusable), buttons=[ diff --git a/src/agentic_cli/cli/message_processor.py b/src/agentic_cli/cli/message_processor.py index 90cb0852..722d55c9 100644 --- a/src/agentic_cli/cli/message_processor.py +++ b/src/agentic_cli/cli/message_processor.py @@ -15,6 +15,7 @@ from thinking_prompt import ButtonConfig, Dialog, TextField +from agentic_cli.cli.dialogs import dialog_lock from agentic_cli.constants import truncate from agentic_cli.logging import Loggers, bind_context from agentic_cli.workflow.agents.runs import RUN_INPUT_REQUIRED, RUN_QUEUED, RUN_RUNNING @@ -907,9 +908,12 @@ async def _handle_input(request: "UserInputRequest") -> str: # The placement is read now: /settings may have changed it # since the session started with its own. try: - response = await self._prompt_user_input( - request, ui, settings.dialog_placement - ) + # Behind any dialog a command has open (a view's run + # asks while the prompt takes commands). + async with dialog_lock(ui): + response = await self._prompt_user_input( + request, ui, settings.dialog_placement + ) except asyncio.CancelledError: # The asking task alone was stopped (a sub-agent run's # limit, its parent, the user), not the turn: the dialog diff --git a/src/agentic_cli/cli/settings_command.py b/src/agentic_cli/cli/settings_command.py index 65dd1804..d713183a 100644 --- a/src/agentic_cli/cli/settings_command.py +++ b/src/agentic_cli/cli/settings_command.py @@ -11,6 +11,7 @@ from thinking_prompt import ButtonConfig, Dialog from agentic_cli.cli.commands import Command, CommandCategory +from agentic_cli.cli.dialogs import show_dialog if TYPE_CHECKING: from agentic_cli.cli.app import BaseCLIApp @@ -55,7 +56,7 @@ async def execute(self, args: str, app: "BaseCLIApp") -> None: placement=app.settings.dialog_placement, ) # Save returns True; Cancel and Escape return None. - if not await app.session.show_dialog(dialog): + if not await show_dialog(app.session, dialog): app.session.add_message("system", _UNCHANGED) return diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index 7c84187f..73a275b6 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -59,6 +59,8 @@ agent, backend, calls, + contract_ask, + contract_hold, contract_start_job, delegate, follow_team, @@ -565,3 +567,116 @@ async def then_exit() -> None: "researcher-1#2", RUN_CANCELLED, "user", ) assert crew.instances() == [("researcher-1", INSTANCE_STOPPED)] + + +# -- one dialog at a time: a run's question and a command's dialog ------------------------ + + +class Dialogs: + """``show_dialog`` as thinking-prompt's: one dialog at a time, a second + one raises. Each dialog stays open until its title's gate is set.""" + + def __init__(self) -> None: + self.open: str | None = None + self.shown: list[str] = [] + self.refused: list[str] = [] + self.gates: dict[str, asyncio.Event] = {} + self.released = False + + def gate(self, title: str) -> asyncio.Event: + gate = self.gates.setdefault(title, asyncio.Event()) + if self.released: + gate.set() + return gate + + def release_all(self) -> None: + """Let every dialog, now or later, close: a failing test must not leave + a run waiting for the user.""" + self.released = True + HELD["go"].set() + for gate in self.gates.values(): + gate.set() + + async def show(self, dialog): + if self.open is not None: + self.refused.append(dialog.title) + raise RuntimeError("A dialog is already being shown") + self.open = dialog.title + self.shown.append(dialog.title) + try: + await self.gate(dialog.title).wait() + return None if dialog.title == "Sub-agents" else True + finally: + self.open = None + + +async def asking_view(make_crew) -> tuple[Crew, BaseCLIApp, Dialogs]: + """A view of ``researcher-1`` whose next run holds, then asks the user.""" + team = [ + agent("coordinator", sub_agents=("researcher",)), + agent("researcher", tools=(contract_hold, contract_ask)), + ] + crew, app = await in_a_view( + make_crew, team=team, + researcher=[calls(use("contract_hold", "r1")), calls(use("contract_ask", "r2")), + says("Asked.")], + ) + dialogs = Dialogs() + app.session.show_dialog.side_effect = dialogs.show + return crew, app, dialogs + + +class TestOneDialogAtATime: + """The view's run works outside the input handler, so a command can open + a dialog while the run asks its question. Whichever comes second waits + for the first: a question is never answered unseen (a second + ``show_dialog`` raises, and a permission prompt that raised is a denial), + and a command's dialog never fails because a question is open.""" + + async def test_a_question_waits_for_an_open_picker(self, make_crew): + crew, app, dialogs = await asking_view(make_crew) + try: + await app.process_input("Ask me.") + await asyncio.wait_for(HELD["started"].wait(), 10) + picker = asyncio.create_task(app.process_input("/agents")) + await until(lambda: dialogs.shown == ["Sub-agents"]) + HELD["go"].set() + await asyncio.sleep(0.3) # the run reaches its question + + assert dialogs.refused == [] + assert dialogs.shown == ["Sub-agents"] + dialogs.gate("Sub-agents").set() + await asyncio.wait_for(picker, 10) + await until(lambda: "researcher-1 asks" in dialogs.shown) + dialogs.gate("researcher-1 asks").set() + await asyncio.wait_for(app.agent_view.settled(), 10) + + assert dialogs.refused == [] + assert crew.records()[-1].status == RUN_COMPLETED + app.session.add_error.assert_not_called() + finally: + dialogs.release_all() + + async def test_a_command_waits_for_an_open_question(self, make_crew): + crew, app, dialogs = await asking_view(make_crew) + try: + await app.process_input("Ask me.") + await asyncio.wait_for(HELD["started"].wait(), 10) + HELD["go"].set() + await until(lambda: dialogs.shown == ["researcher-1 asks"]) + picker = asyncio.create_task(app.process_input("/agents")) + await asyncio.sleep(0.3) # the command reaches its picker + + assert dialogs.refused == [] + assert dialogs.shown == ["researcher-1 asks"] + dialogs.gate("researcher-1 asks").set() + await until(lambda: "Sub-agents" in dialogs.shown) + dialogs.gate("Sub-agents").set() + await asyncio.wait_for(picker, 10) + await asyncio.wait_for(app.agent_view.settled(), 10) + + assert dialogs.refused == [] + assert crew.records()[-1].status == RUN_COMPLETED + app.session.add_error.assert_not_called() + finally: + dialogs.release_all() From f8a06d3427114c9bc6f266b6be1e2c1d010fd05a Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:11:50 -0500 Subject: [PATCH 07/17] CLI: run_turn goes through the conversation's one write frame _write was a copy of run_turn's frame without the echo. run_turn now calls it with the line to echo, shown once the turn lock is taken and before the cancelled line when the wait for the lock is stopped, so every write to the conversation follows the same rules for held, turned and written. --- src/agentic_cli/cli/conversation.py | 74 +++++++++++++---------------- 1 file changed, 34 insertions(+), 40 deletions(-) diff --git a/src/agentic_cli/cli/conversation.py b/src/agentic_cli/cli/conversation.py index 980f89db..efa4a14e 100644 --- a/src/agentic_cli/cli/conversation.py +++ b/src/agentic_cli/cli/conversation.py @@ -590,39 +590,19 @@ async def run_turn(self, message: str, parts: TurnParts) -> bool: asyncio.CancelledError: Ctrl+C stopped it, as the processor says, or while it waited for the turn lock. """ - ui = parts.ui - try: - await self.turn_lock.acquire() - except asyncio.CancelledError: - ui.add_message("user", message) - ui.add_message("system", CANCELLED_LINE) - raise - try: - ui.add_message("user", message) - if not self._held_to_write(ui): - return False - async with self._dropping_left(parts): - self.turned = True # the conversation now holds this message - reached = False # the turn reached a ready workflow, which stores it - try: - result = await parts.processor.process( - message=message, - workflow_controller=parts.controller, - ui=ui, - settings=parts.settings, - usage_tracker=parts.tracker, - session_id=self.session_id, - ) - reached = getattr(result, "status", None) is not TurnStatus.UNAVAILABLE - except BaseException: - reached = parts.controller.is_ready # it may have begun - raise - finally: - if reached: - self.written = True - return True - finally: - self.turn_lock.release() + return await self._write( + parts, + lambda: parts.processor.process( + message=message, + workflow_controller=parts.controller, + ui=parts.ui, + settings=parts.settings, + usage_tracker=parts.tracker, + session_id=self.session_id, + ), + turns=True, + echo=message, + ) async def run_instance(self, instance: str, message: str, parts: TurnParts) -> bool: """Run the user's ``message`` as the next run of a sub-agent, in its view. @@ -693,13 +673,23 @@ async def tell_root(self, text: str, parts: TurnParts) -> bool: turns=True, ) - async def _write(self, parts: TurnParts, run: Callable[[], Awaitable[Any]], *, turns: bool) -> bool: - """``run_turn``'s frame without the echo: ``run()`` under the turn lock. - - The conversation is held to write first; ``turned`` when ``turns`` - (the main agent answered in it); ``written`` once ``run`` reached a - ready workflow (its result's status is not ``UNAVAILABLE``; one that - raised or was cancelled counts when the workflow was ready). + async def _write( + self, + parts: TurnParts, + run: Callable[[], Awaitable[Any]], + *, + turns: bool, + echo: str | None = None, + ) -> bool: + """``run()`` under the turn lock: the frame of every write to the conversation. + + ``echo``, the line the user typed, is shown once the lock is taken, + and before ``CANCELLED_LINE`` when the wait for it is stopped (a line + Ctrl+C stops while it waits is shown and said cancelled, not dropped + unseen). The conversation is held to write first; ``turned`` when + ``turns`` (the main agent answered in it); ``written`` once ``run`` + reached a ready workflow (its result's status is not ``UNAVAILABLE``; + one that raised or was cancelled counts when the workflow was ready). Returns: Whether it ran: False when another process has the conversation @@ -713,9 +703,13 @@ async def _write(self, parts: TurnParts, run: Callable[[], Awaitable[Any]], *, t try: await self.turn_lock.acquire() except asyncio.CancelledError: + if echo is not None: + ui.add_message("user", echo) ui.add_message("system", CANCELLED_LINE) raise try: + if echo is not None: + ui.add_message("user", echo) if not self._held_to_write(ui): return False async with self._dropping_left(parts): From 00ac5be73f818c4dc7aa2b087bcfbfda54411875 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:12:04 -0500 Subject: [PATCH 08/17] Docs: the view's changelog bullet after the earlier sub-agent bullets --- CHANGELOG.md | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 776e3708..db6ef192 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -575,27 +575,6 @@ the start of the entry's title. ### Added -- **A sub-agent's view: `/agent ` and `/back`.** `/agent ` (or Enter in - `/agents`' picker) opens one of the conversation's sub-agents to work with - directly: a rule (`── researcher-2 · researcher · idle ──`) and a recap (its - title and objective, its last run's status, the first lines of its result, - its tokens; nothing replayed), the prompt `researcher-2> `, and a status bar - that names it, its status, its own `ctx` and tokens, the jobs segment kept. - A line typed there is its next run (`run_instance`, `started_by: user`), its - text the reply; a line typed while that run works is given to it before its - next model step (`steer_instance`), not queued. The run works outside the - input handler, so the prompt stays open to steer it, and Ctrl+C stops it (a - key binding of the view's own, active only while its run works: the user's - stop, the sub-agent `stopped`). `/back` waits for a run still working, - prints `── back to main ──`, and, when a run you started there ended, the - main agent gets one notice turn with its latest envelope (`tell_root`), - drawn as a job's notice is; the main agent's notices (finished jobs) wait - while a view is open, counted in `↻N`, and are told after it - (`job_auto_resume`). In a view `/status` shows the sub-agent's context, - `/compact` is refused, `/new` and `/resume` leave it first; a closed - sub-agent's view is read-only (no prompt). The app's `agent_view`, - `open_agent_view(id)` and `leave_agent_view()` (provisional) are what the - commands call. - **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 @@ -661,6 +640,27 @@ the start of the entry's title. after the user worked with a sub-agent is `agents/envelope.py::view_notice`: "The user worked with directly; its latest result: ". On both backends, contract-tested. +- **A sub-agent's view: `/agent ` and `/back`.** `/agent ` (or Enter in + `/agents`' picker) opens one of the conversation's sub-agents to work with + directly: a rule (`── researcher-2 · researcher · idle ──`) and a recap (its + title and objective, its last run's status, the first lines of its result, + its tokens; nothing replayed), the prompt `researcher-2> `, and a status bar + that names it, its status, its own `ctx` and tokens, the jobs segment kept. + A line typed there is its next run (`run_instance`, `started_by: user`), its + text the reply; a line typed while that run works is given to it before its + next model step (`steer_instance`), not queued. The run works outside the + input handler, so the prompt stays open to steer it, and Ctrl+C stops it (a + key binding of the view's own, active only while its run works: the user's + stop, the sub-agent `stopped`). `/back` waits for a run still working, + prints `── back to main ──`, and, when a run you started there ended, the + main agent gets one notice turn with its latest envelope (`tell_root`), + drawn as a job's notice is; the main agent's notices (finished jobs) wait + while a view is open, counted in `↻N`, and are told after it + (`job_auto_resume`). In a view `/status` shows the sub-agent's context, + `/compact` is refused, `/new` and `/resume` leave it first; a closed + sub-agent's view is read-only (no prompt). The app's `agent_view`, + `open_agent_view(id)` and `leave_agent_view()` (provisional) are what the + commands call. - **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 From 61f9c876a11146028ea8b2d97eec0231c9be8cbc Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:12:32 -0500 Subject: [PATCH 09/17] CLI: /status in a sub-agent's view shows one Model row, the instance's --- src/agentic_cli/cli/builtin_commands.py | 12 +++++++----- tests/cli/test_agent_view.py | 9 +++++++++ 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/agentic_cli/cli/builtin_commands.py b/src/agentic_cli/cli/builtin_commands.py index 3cf9dee3..c73f2f9d 100644 --- a/src/agentic_cli/cli/builtin_commands.py +++ b/src/agentic_cli/cli/builtin_commands.py @@ -220,17 +220,19 @@ async def execute(self, args: str, app: Any) -> None: workflow = app.workflow if workflow is None: raise RuntimeError("Workflow not initialized") - table.add_row("Model", workflow.model) - table.add_row("App Name", workflow.app_name) - table.add_row("Session ID", workflow.session_id) - services = "Initialized" if workflow.is_initialized else "Not initialized" - table.add_row("Services", services) view = getattr(app, "agent_view", None) # In a sub-agent's view, its context is what the user works with. rows = ( view.context_rows() if view is not None else _context_rows(workflow, getattr(app, "usage_tracker", None)) ) + # One Model row: the instance's in a view (its own, when it names one). + if view is None or not any(label == "Model" for label, _ in rows): + table.add_row("Model", workflow.model) + table.add_row("App Name", workflow.app_name) + table.add_row("Session ID", workflow.session_id) + services = "Initialized" if workflow.is_initialized else "Not initialized" + table.add_row("Services", services) for label, value in rows: table.add_row(label, value) except (RuntimeError, AttributeError): diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index 73a275b6..9d61c893 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -462,6 +462,15 @@ async def test_status_shows_the_instances_context(self, make_crew): assert rows["Tokens"] == "1.2k in / 40 out" assert "Main Agent" not in rows + async def test_status_has_one_model_row_the_instances(self, make_crew): + crew, app = await in_a_view(make_crew) + + await typed(app, "/status") + + (panel,) = app.session.add_rich.call_args.args + models = [value for label, value in rows_of(panel.renderable) if label == "Model"] + assert models == [str(crew.manager.agent_models["researcher"].ref)] + class TestOffTheLoop: async def test_it_blocks_no_event_loop(self, make_crew): From 059d173088b788d20a43c49c2352766adee0c418 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:16:05 -0500 Subject: [PATCH 10/17] CLI: a line in a view and /back start a workflow that is down, as a turn does After a model switch whose rebuild failed, a line typed in a sub-agent's view was refused where the main conversation retries the start, and /back skipped the main agent's notice. A line is now the instance's next run all the same (its start retries the workflow), and /back retries the start before it tells the main agent. --- src/agentic_cli/cli/agent_view.py | 15 +++++--- tests/cli/test_agent_view.py | 58 +++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 5 deletions(-) diff --git a/src/agentic_cli/cli/agent_view.py b/src/agentic_cli/cli/agent_view.py index 5866a467..b3a8cb35 100644 --- a/src/agentic_cli/cli/agent_view.py +++ b/src/agentic_cli/cli/agent_view.py @@ -214,10 +214,10 @@ async def take(self, line: str) -> None: the instance's next run, started in a task of its own (``settled`` waits for it). A closed instance's view refuses it.""" app = self.app - workflow = _workflow(app) - if workflow is None: - return - record = workflow.agent_runs.instance(self.conversation, self.instance) + # A workflow that is down (a model switch whose rebuild failed) has no + # record to read: the line is the next run all the same, whose start + # retries it as a turn of the main conversation does. + record = self.record() if record is not None and record.status == INSTANCE_CLOSED: app.session.add_warning(READ_ONLY.format(instance=self.instance)) return @@ -225,7 +225,7 @@ async def take(self, line: str) -> None: if ( record is not None and record.status == INSTANCE_RUNNING - and workflow.steer_instance( + and app.workflow.steer_instance( self.instance, line, session_id=self.conversation.session_id, @@ -341,6 +341,11 @@ async def leave_view(app: Any) -> bool: app.session.add_message("system", BACK_RULE) controller.update_status_bar(app.session) logger.info("agent_view_left", instance=view.instance) + # A workflow that is down (a model switch whose rebuild failed) is started + # again, as a turn would: the run the user did there is still to be told. + # Left down, the notice cannot be sent and the warning says why. + if not controller.is_ready: + await controller.ensure_initialized(app.session) workflow = _workflow(app) if workflow is None: return True diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index 9d61c893..93cc0b3e 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -689,3 +689,61 @@ async def test_a_command_waits_for_an_open_question(self, make_crew): app.session.add_error.assert_not_called() finally: dialogs.release_all() + + +# -- a workflow that is down ---------------------------------------------------------------- + + +class Starts: + """The manager's starts, failing while ``failing`` is set: a model switch + whose rebuild fails (and whose way back fails too) leaves the workflow + down until a start succeeds.""" + + def __init__(self, crew: Crew) -> None: + self.failing = True + self.tried = 0 + original = crew.manager._load_models + + async def load() -> None: + self.tried += 1 + if self.failing: + raise RuntimeError("scripted start failure") + await original() + + crew.manager._load_models = load + + +class TestAWorkflowThatIsDown: + """After a model switch whose rebuild failed, the main conversation's line + retries the start; a line in a view does too, and ``/back`` still tells the + main agent about a run the user started before.""" + + async def test_a_line_retries_the_start_as_the_main_conversations_does(self, make_crew): + crew, app = await in_a_view(make_crew, researcher=[says("Y is 7.")]) + starts = Starts(crew) + assert not await app.apply_settings({"model": "claude-haiku-4-5"}) + assert not app._workflow_controller.is_ready + starts.failing = False + + await typed(app, "Now find Y.") + + app.session.add_warning.assert_not_called() + assert [(r.ref.run, r.status) for r in crew.records()] == [ + ("researcher-1#1", RUN_COMPLETED), ("researcher-1#2", RUN_COMPLETED), + ] + assert said(app.session, "add_response")[-1] == "Y is 7." + + async def test_back_retries_the_start_and_tells_the_main_agent(self, make_crew): + crew, app = await in_a_view( + make_crew, coordinator=[says("Noted.")], researcher=[says("Y is 7.")], + ) + await typed(app, "Now find Y.") + starts = Starts(crew) + assert not await app.apply_settings({"model": "claude-haiku-4-5"}) + starts.failing = False + + await typed(app, "/back") + + assert app.agent_view is None + assert said(app.session, "add_response")[-1] == "Noted." + assert '"result": "Y is 7."' in crew.last_message("coordinator") From 5536a8c25540833c2191f59a9a6256aea08f4e44 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:17:45 -0500 Subject: [PATCH 11/17] CLI: Ctrl+C says it was cancelled once in a view, and its test fails rather than hangs A second line typed before the first run ended waited for the turn lock and said "Operation cancelled..." again when Ctrl+C stopped it. A queued line now waits for the run before it inside the view, where a stop is silent. The Ctrl+C test waits for the run with a bound and cancels what is left, so a stop that stops working fails the test instead of stalling teardown. --- src/agentic_cli/cli/agent_view.py | 19 +++++++++++++++---- tests/cli/test_agent_view.py | 27 ++++++++++++++++++++++++++- 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/src/agentic_cli/cli/agent_view.py b/src/agentic_cli/cli/agent_view.py index b3a8cb35..10ba8c01 100644 --- a/src/agentic_cli/cli/agent_view.py +++ b/src/agentic_cli/cli/agent_view.py @@ -109,6 +109,10 @@ def __init__( #: The prompt the app had: put back by ``/back``. self.prompt_before: Any = None self._runs: set[asyncio.Task[None]] = set() + # The run started last: a line typed before it ends is the next run, + # which waits for it here (and not for the turn lock, where a Ctrl+C + # would make it say "Operation cancelled..." once more). + self._last: asyncio.Task[None] | None = None # -- what it shows --------------------------------------------------------------- @@ -234,14 +238,21 @@ async def take(self, line: str) -> None: ): app.session.add_message("system", STEERED.format(instance=self.instance)) return - run = asyncio.create_task(self._run(line), name=f"view run of {self.instance}") + run = asyncio.create_task( + self._run(line, self._last), name=f"view run of {self.instance}" + ) + self._last = run self._runs.add(run) run.add_done_callback(self._ended) - async def _run(self, line: str) -> None: - """The instance's next run on ``line``: a write to the conversation - under its turn lock (``ConversationCore.run_instance``).""" + async def _run(self, line: str, after: "asyncio.Task[None] | None") -> None: + """The instance's next run on ``line``, once the run before it ended: a + write to the conversation under its turn lock + (``ConversationCore.run_instance``). A stop while it waits is silent: + the run that works says it.""" app = self.app + if after is not None: + await asyncio.wait({after}) parts = dataclasses.replace(app._turn_parts(), processor=self.processor) try: await app._conversation.run_instance(self.instance, line, parts) diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index 93cc0b3e..b6dd70d6 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -106,6 +106,17 @@ async def typed(app: BaseCLIApp, *lines: str) -> None: await asyncio.wait_for(app.agent_view.settled(), 10) +async def settled_or_fail(app: BaseCLIApp) -> None: + """Wait for the view's run to end; one that does not is the test's failure + (its tasks are cancelled so that teardown does not wait for them).""" + try: + await asyncio.wait_for(app.agent_view.settled(), 10) + except asyncio.TimeoutError: + for run in list(app.agent_view._runs): + run.cancel() + raise AssertionError("the run in view did not end within 10 s") from None + + async def in_a_view( make_crew, *, researcher=(), coordinator=(), team=None, **crew_args ) -> tuple[Crew, BaseCLIApp]: @@ -259,7 +270,7 @@ async def test_ctrl_c_stops_the_run_in_view_the_users_stop(self, make_crew): await app.process_input("Wait here.") await asyncio.wait_for(BLOCKING["started"].wait(), 10) assert app.agent_view.stop() is True - await asyncio.wait_for(app.agent_view.settled(), 10) + await settled_or_fail(app) second = crew.records()[-1] assert (second.ref.run, second.status, second.cancelled_by) == ( @@ -273,6 +284,20 @@ async def test_ctrl_c_stops_the_run_in_view_the_users_stop(self, make_crew): assert crew.instances() == [("researcher-1", INSTANCE_IDLE)] assert said(app.session, "add_response")[-1] == "Went on." + async def test_ctrl_c_with_a_second_line_waiting_says_so_once(self, make_crew): + crew, app = await in_a_view( + make_crew, researcher=[calls(use("contract_block", "r1")), says("Went on.")], + ) + + await app.process_input("Wait here.") + await app.process_input("And then this.") # waits for the first run + await asyncio.wait_for(BLOCKING["started"].wait(), 10) + assert app.agent_view.stop() is True + await settled_or_fail(app) + + assert said(app.session, "add_message").count(CANCELLED_LINE) == 1 + assert [r.ref.run for r in crew.records()] == ["researcher-1#1", "researcher-1#2"] + async def test_after_a_model_switch_in_a_view_a_line_runs_on_the_new_model(self, make_crew): crew, app = await in_a_view(make_crew, researcher=[says("Y is 7.")]) From 5bf08e096279c33c8734841aefd81f5dcb6214c2 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:19:17 -0500 Subject: [PATCH 12/17] CLI: say when Ctrl+C cannot be bound in a view; pin what the main conversation keeps run() logs at info when the session takes no Ctrl+C binding (Ctrl+C in a view is then thinking-prompt's own and the run goes on until it ends or /exit stops it). New tests: the main agent's ctx stays put after a view run, finished jobs are not told in a view (resume_finished_jobs, and the bar counts them). --- src/agentic_cli/cli/app.py | 7 +++- tests/cli/test_agent_view.py | 78 ++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 2 deletions(-) diff --git a/src/agentic_cli/cli/app.py b/src/agentic_cli/cli/app.py index 6bdbfe88..1ed20e0a 100644 --- a/src/agentic_cli/cli/app.py +++ b/src/agentic_cli/cli/app.py @@ -2335,8 +2335,11 @@ async def handle_input(text: str) -> None: await self.process_input(text) # Ctrl+C stops the run in a sub-agent's view, which works outside - # the input handler. - bind_ctrl_c(self.session, lambda: self._agent_view) + # the input handler. A session that takes no binding leaves Ctrl+C + # to thinking-prompt's own handling in a view: it ends the boxes + # and the run goes on, until /exit stops it or it ends. + if not bind_ctrl_c(self.session, lambda: self._agent_view): + logger.info("agent_view_ctrl_c_not_bound") # Keep long-running jobs visible in the status bar while the # session runs, independent of the agent loop. diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index b6dd70d6..120ef9f9 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -603,6 +603,40 @@ async def then_exit() -> None: assert crew.instances() == [("researcher-1", INSTANCE_STOPPED)] +class TestCtrlCNotBound: + async def test_a_session_that_cannot_take_the_binding_is_logged(self, make_crew, monkeypatch): + """Without the binding Ctrl+C in a view is thinking-prompt's own (it + ends the boxes, and the run goes on): the log says so at info.""" + crew = make_crew(follow_team()) + monkeypatch.setattr( + workflow_controller, "create_workflow_manager_from_settings", + lambda **kwargs: crew.manager, + ) + events: list[dict] = [] + + class Recorder: + def __getattr__(self, level: str): + def log(event: str, **fields) -> None: + events.append({"event": event, "log_level": level, **fields}) + + return log + + monkeypatch.setattr(app_module, "logger", Recorder()) + app = BaseCLIApp( + app_info=AppInfo(name="View test", version="0"), + agent_configs=[agent("coordinator")], + settings=crew.manager.settings, + session_id=SESSION, + ) + app.session = opening_boxes(autospec_session()) + app.session.app = SimpleNamespace(is_running=True) # no prompt_toolkit key bindings + + await asyncio.wait_for(app.run(), 20) + + (logged,) = [e for e in events if e["event"] == "agent_view_ctrl_c_not_bound"] + assert logged["log_level"] == "info" + + # -- one dialog at a time: a run's question and a command's dialog ------------------------ @@ -772,3 +806,47 @@ async def test_back_retries_the_start_and_tells_the_main_agent(self, make_crew): assert app.agent_view is None assert said(app.session, "add_response")[-1] == "Noted." assert '"result": "Y is 7."' in crew.last_message("coordinator") + + +# -- what the main conversation keeps while a view is open --------------------------------- + + +class TestTheMainConversationInAView: + async def test_the_main_agents_context_stays_put_after_a_view_run(self, make_crew): + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1"), usage=(900, 9)), + says("Done.", usage=(1_000, 10))], + researcher=[says("X is 42.", usage=(1_200, 40)), says("Y is 7.", usage=(5_000, 20))], + ) + app = await app_on(crew) + await typed(app, "Find X.") + before = app.usage_tracker.last_prompt_tokens + assert before # the main agent's own call moved it + + await typed(app, "/agent researcher-1", "Now find Y.") + + # The instance's call is a sub-agent's: it never moves the main agent's ctx. + assert app.usage_tracker.last_prompt_tokens == before + + async def test_finished_jobs_wait_in_a_view_and_the_bar_counts_them(self, make_crew): + crew, app = await in_a_view( + make_crew, + team=[agent("coordinator", sub_agents=("researcher",)), + agent("researcher", tools=(contract_start_job,))], + coordinator=[says("Noted."), says("The build finished.")], + researcher=[calls(use("contract_start_job", "r1")), says("Started the build.")], + ) + app.settings.update_setting("job_auto_resume", True) + jobs = crew.manager.job_manager + await typed(app, "Start the build.") + (record,) = jobs.list() + await until(lambda: jobs.get(record.job_id).state in TERMINAL_STATES) + + await app._new_job_monitor().poll_once() + + assert "↻1" in status(app) + assert status(app).startswith("researcher-1 · ") # still the view's bar + assert await app.resume_finished_jobs() == 0 + assert crew.requests("coordinator") == 2 + assert [r.job_id for r in jobs.awaiting_resume()] == [record.job_id] From d3bda3f23d40ee70925fc2b1ba05e229822f8838 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:29:49 -0500 Subject: [PATCH 13/17] Docs: dialogs.py and the view's queued lines in the structure notes --- CLAUDE.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index df058883..566e3981 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,7 +37,8 @@ agentic-cli/ │ │ ├── conversation_lock.py # ConversationLock: one process per stored conversation (flock under /locks/; ConversationCore holds it and refuses one held elsewhere; /sessions --delete too, through conversation_held) │ │ ├── builtin_commands.py # /help (by category; /help : its usage and examples), /status (the main agent's context rows: context_budget, in a sub-agent's view the instance's, AgentView.context_rows; why the workflow did not start: app.workflow_error; tokens by agent: the main agent, each sub-agent with its runs, the side calls by purpose, from the manager's usage ledger), /models (ModelsCommand: the list, each model's facts and sources, Status for an entry left out, the providers in use; /models searches the full listings; refresh), /sessions (every installed backend's, a Backend column; --delete= on the backend that keeps it, --backend= for an id two keep; on the memory store NOT_KEPT, no table, --delete refused), /resume [] (sessions; refused on the memory store), /jobs (resume: finished jobs; in a sub-agent's view JOBS_WAIT: they wait for /back), /compact [focus] (refused in a sub-agent's view: COMPACT_IN_VIEW), /new [backend] (an unknown backend or a missing extra refused: check_backend), ... │ │ ├── agents_command.py # /agents: the open conversation's sub-agent instances (agent_runs.instances under workflow.session_ref(app.session_id)) in a picker (a Dialog with one ChoiceField, as /resume's: `picker`), each followed by the ones it started (id · type · status · title), Enter opening the view of the one picked (app.open_agent_view); /agent opens its view (open_agent_view: cli/agent_view.py), /agent stop and /agent close are the user's stop and close (stop_instance, close_instance, the app's conversation named), each saying what it did or why not (NO_SUCH_AGENT, ALREADY_TEXT), nothing tried on records not read; /agents (its panel: tokens in/out from the usage ledger, usage_of, live for a running run; time): one instance (every run of it) or run (type, parent, title; 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 -│ │ ├── agent_view.py # A sub-agent's view (provisional; open_view/leave_view behind BaseCLIApp.open_agent_view/leave_agent_view, /back: BackCommand): entering prints VIEW_RULE ("── researcher-2 · researcher · idle ──") and a recap (title, its first brief's objective, its last run's status, its result's first lines, its tokens: instance_tokens, each run's from the usage ledger or its record), the prompt "> " (none for a closed one: read-only, READ_ONLY) and WorkflowController.view_segment (its status, its ctx: its last own step's prompt against its own trigger, its tokens); AgentView.take: a line steers the run that works (steer_instance, STEERED) or starts the instance's next run in a task of its own (ConversationCore.run_instance on the view's own MessageProcessor), outside the input handler, so the prompt takes the lines that steer it (thinking-prompt takes none while a handler runs); bind_ctrl_c: Ctrl+C stops that run (AgentView.stop: the user's stop) through a prompt_toolkit binding on the session's application, active only while it works; leave_view (/back): waits for the run, BACK_RULE, the prompt and bar back, then one notice turn (ConversationCore.tell_root, view_notice, TELLING) when a run the user started there ended since the main agent last heard, then the finished jobs that waited (job_auto_resume); in a view /compact is refused (COMPACT_IN_VIEW), /jobs resume waits (JOBS_WAIT), /status shows its context_rows, /new and /resume leave it first +│ │ ├── dialogs.py # One dialog at a time on a session: dialog_lock(ui), show_dialog(ui, dialog) (every command's dialog) and the message processor's question dialogs take it while open, so a sub-agent view's run (outside the input handler) asking while a command's dialog is open, or the reverse, waits instead of raising (thinking-prompt raises on a second dialog: a permission prompt would be a denial the user never saw) +│ │ ├── agent_view.py # A sub-agent's view (provisional; open_view/leave_view behind BaseCLIApp.open_agent_view/leave_agent_view, /back: BackCommand): entering prints VIEW_RULE ("── researcher-2 · researcher · idle ──") and a recap (title, its first brief's objective, its last run's status, its result's first lines, its tokens: instance_tokens, each run's from the usage ledger or its record), the prompt "> " (none for a closed one: read-only, READ_ONLY) and WorkflowController.view_segment (its status, its ctx: its last own step's prompt against its own trigger, its tokens); AgentView.take: a line steers the run that works (steer_instance, STEERED) or starts the instance's next run in a task of its own (ConversationCore.run_instance on the view's own MessageProcessor), outside the input handler, so the prompt takes the lines that steer it (thinking-prompt takes none while a handler runs); bind_ctrl_c: Ctrl+C stops that run (AgentView.stop: the user's stop) through a prompt_toolkit binding on the session's application, active only while it works; a line typed before the run ends waits for it inside the view (a stop says the cancel once), and one typed while the workflow is down is the next run all the same (its start retries); leave_view (/back): waits for the run, retries a workflow that is down, BACK_RULE, the prompt and bar back, then one notice turn (ConversationCore.tell_root, view_notice, TELLING) when a run the user started there ended since the main agent last heard, then the finished jobs that waited (job_auto_resume); in a view /compact is refused (COMPACT_IN_VIEW), /jobs resume waits (JOBS_WAIT), /status shows its context_rows, /new and /resume leave it first │ │ ├── memory_command.py # /memory: the list (a picker like /resume's), one memory (Delete, History), /memory , history (Restore), inbox (Accept/Discard/Skip), stale; proposals_line; Enter's button is Close or Skip, and Delete acts only on the memory as shown │ │ ├── workflow_controller.py # WorkflowController (lazy/background init; subagents=: the SubAgentPolicy every manager it builds gets, a switch_backend's too; the session store of every manager of the run, store, fixed at its first start; the backend it runs, backend: the settings' orchestrator at its first start, then switch_backend's (a conversation on another backend, new or opened: the new manager started first on the run's services lent, given over by the old one and published at once, the old one released in the controller's task, a cancel stops only the wait; a failed start or give leaves the old one with its services; while down, a manager a failed reinitialization kept lends its services to the next build, _lender, and is released once they are given); reinitialize, a model switch, always in place; the status bar names the main agent's model, or in a sub-agent's view what view_segment says of the instance, the jobs segment kept) │ │ ├── session_resume.py # What /resume shows: the picker (picker: each row's backend once one is another's; PickedConversation, the id a str naming its backend), the "Resumed:" line ("Resumed on :" on another backend), the replay of the last 10 messages From 95eddd09a2c5c8c2a3ddfe7c787efe23a455d021 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:40:46 -0500 Subject: [PATCH 14/17] CLI: /status keeps its fixed rows ahead of the context rows The context rows are read after the Model, App Name, Session ID and Services rows again, so rows that fail to read leave those shown. Only in a sub-agent's view are the instance's rows read first, to drop the main Model row. --- src/agentic_cli/cli/builtin_commands.py | 15 ++++++++------- tests/cli/test_status_command.py | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/agentic_cli/cli/builtin_commands.py b/src/agentic_cli/cli/builtin_commands.py index c73f2f9d..7133696e 100644 --- a/src/agentic_cli/cli/builtin_commands.py +++ b/src/agentic_cli/cli/builtin_commands.py @@ -221,18 +221,19 @@ async def execute(self, args: str, app: Any) -> None: if workflow is None: raise RuntimeError("Workflow not initialized") view = getattr(app, "agent_view", None) - # In a sub-agent's view, its context is what the user works with. - rows = ( - view.context_rows() if view is not None - else _context_rows(workflow, getattr(app, "usage_tracker", None)) - ) - # One Model row: the instance's in a view (its own, when it names one). - if view is None or not any(label == "Model" for label, _ in rows): + # In a sub-agent's view, its context is what the user works with, + # and one Model row is shown: the instance's, when it names one. + view_rows = view.context_rows() if view is not None else None + if view_rows is None or not any(label == "Model" for label, _ in view_rows): table.add_row("Model", workflow.model) table.add_row("App Name", workflow.app_name) table.add_row("Session ID", workflow.session_id) services = "Initialized" if workflow.is_initialized else "Not initialized" table.add_row("Services", services) + rows = ( + view_rows if view_rows is not None + else _context_rows(workflow, getattr(app, "usage_tracker", None)) + ) for label, value in rows: table.add_row(label, value) except (RuntimeError, AttributeError): diff --git a/tests/cli/test_status_command.py b/tests/cli/test_status_command.py index edb68f3f..8a0629b2 100644 --- a/tests/cli/test_status_command.py +++ b/tests/cli/test_status_command.py @@ -342,3 +342,23 @@ async def test_langgraph_shows_no_tokens_by_agent(tmp_path, monkeypatch): assert [e for e in events if e.type is EventType.LLM_USAGE] # it reported usage assert by_agent(rows) == [] + + +async def test_context_rows_that_raise_leave_the_fixed_rows(monkeypatch): + """The Model, App Name, Session ID and Services rows are shown before the + context rows are read: a failure reading them leaves those, and says the + workflow is not available.""" + from agentic_cli.cli import builtin_commands + + def raising(workflow, tracker): + raise RuntimeError("no context") + + monkeypatch.setattr(builtin_commands, "_context_rows", raising) + workflow = SimpleNamespace( + model="m:1", app_name="app", session_id="s1", is_initialized=True, + ) + + rows = await status_rows(workflow) + + labels = [label for label, _ in rows] + assert labels[:4] == ["Model", "App Name", "Session ID", "Services"] From 710056ffe16ae32f5b3a0768d6d44a69a3e9804f Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:40:50 -0500 Subject: [PATCH 15/17] CLI: the comment on /back's start retry says what the warning says --- src/agentic_cli/cli/agent_view.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/agentic_cli/cli/agent_view.py b/src/agentic_cli/cli/agent_view.py index 10ba8c01..063240aa 100644 --- a/src/agentic_cli/cli/agent_view.py +++ b/src/agentic_cli/cli/agent_view.py @@ -354,7 +354,8 @@ async def leave_view(app: Any) -> bool: logger.info("agent_view_left", instance=view.instance) # A workflow that is down (a model switch whose rebuild failed) is started # again, as a turn would: the run the user did there is still to be told. - # Left down, the notice cannot be sent and the warning says why. + # Left down, the notice cannot be sent: the main agent is not told of that + # run, and the warning says only that the workflow did not start. if not controller.is_ready: await controller.ensure_initialized(app.session) workflow = _workflow(app) From 3321d38ecc30b0ef4bf1aac1be84ec732e890714 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:41:47 -0500 Subject: [PATCH 16/17] Tests: the exit test fails instead of hanging when the view's stop stops working --- tests/cli/test_agent_view.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index 120ef9f9..9dcfd062 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -591,9 +591,16 @@ async def then_exit() -> None: app.session.run_async.side_effect = then_exit running = asyncio.create_task(app.run()) exited, _ = await asyncio.wait({running}, timeout=20) - if not exited: # its workflow's cleanup waits for the run in view: unwind it - app.agent_view.stop() - await running + if not exited: + # Its workflow's cleanup waits for the run in view: unwind it + # without the view's own stop (which is what failed), and bound + # the wait, so that this fails the test instead of stalling it. + for run in list(app.agent_view._runs): + run.cancel() + await asyncio.wait({running}, timeout=10) + if not running.done(): + running.cancel() + await asyncio.wait({running}, timeout=5) assert exited, "the app did not exit: the run in view was still working" last = crew.records()[-1] From a9fc629f6f0caf566ef9b61953cdf8fa5ebe2a58 Mon Sep 17 00:00:00 2001 From: Andrey Shiryaev <7615137+shoom1@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:46:29 -0500 Subject: [PATCH 17/17] CLI: the session's own dialog methods take the one dialog lock An app's command that calls app.session.show_dialog itself skipped the helper the framework's commands used, so a question of a view's run could still be refused. BaseCLIApp.session now wraps a real session's dialog methods once, on assignment: every caller is serialized. The commands call the session directly again, the helper is gone, and the lock lets the same task take it again, so the message processor's question lock and the wrapper never wait for each other. The one-dialog tests wait on conditions (the run's record reading input_required, the command's picker built), not on a sleep. --- CLAUDE.md | 2 +- src/agentic_cli/cli/agents_command.py | 3 +- src/agentic_cli/cli/app.py | 15 +++- src/agentic_cli/cli/dialogs.py | 98 ++++++++++++++++++++----- src/agentic_cli/cli/memory_command.py | 15 ++-- src/agentic_cli/cli/settings_command.py | 3 +- tests/cli/test_agent_view.py | 69 +++++++++++++++-- tests/cli/test_dialogs.py | 51 +++++++++++++ 8 files changed, 216 insertions(+), 40 deletions(-) create mode 100644 tests/cli/test_dialogs.py diff --git a/CLAUDE.md b/CLAUDE.md index 566e3981..d4d04197 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,7 +37,7 @@ agentic-cli/ │ │ ├── conversation_lock.py # ConversationLock: one process per stored conversation (flock under /locks/; ConversationCore holds it and refuses one held elsewhere; /sessions --delete too, through conversation_held) │ │ ├── builtin_commands.py # /help (by category; /help : its usage and examples), /status (the main agent's context rows: context_budget, in a sub-agent's view the instance's, AgentView.context_rows; why the workflow did not start: app.workflow_error; tokens by agent: the main agent, each sub-agent with its runs, the side calls by purpose, from the manager's usage ledger), /models (ModelsCommand: the list, each model's facts and sources, Status for an entry left out, the providers in use; /models searches the full listings; refresh), /sessions (every installed backend's, a Backend column; --delete= on the backend that keeps it, --backend= for an id two keep; on the memory store NOT_KEPT, no table, --delete refused), /resume [] (sessions; refused on the memory store), /jobs (resume: finished jobs; in a sub-agent's view JOBS_WAIT: they wait for /back), /compact [focus] (refused in a sub-agent's view: COMPACT_IN_VIEW), /new [backend] (an unknown backend or a missing extra refused: check_backend), ... │ │ ├── agents_command.py # /agents: the open conversation's sub-agent instances (agent_runs.instances under workflow.session_ref(app.session_id)) in a picker (a Dialog with one ChoiceField, as /resume's: `picker`), each followed by the ones it started (id · type · status · title), Enter opening the view of the one picked (app.open_agent_view); /agent opens its view (open_agent_view: cli/agent_view.py), /agent stop and /agent close are the user's stop and close (stop_instance, close_instance, the app's conversation named), each saying what it did or why not (NO_SUCH_AGENT, ALREADY_TEXT), nothing tried on records not read; /agents (its panel: tokens in/out from the usage ledger, usage_of, live for a running run; time): one instance (every run of it) or run (type, parent, title; each run's status and time, its brief's other fields (a follow-up's message in their place), its result's first lines, its own last plan and tasks, its error, its tokens by model); the records are the conversation's, kept beside it in its store and loaded with it (`workflow.load_agents`, asked by /agents too: a conversation resumed after a restart lists its runs before its first turn; a store that cannot be read is said, and the runs held shown), a run from before a restart showing its record's tokens by model (its usage, no call count); a module of its own, as /memory's -│ │ ├── dialogs.py # One dialog at a time on a session: dialog_lock(ui), show_dialog(ui, dialog) (every command's dialog) and the message processor's question dialogs take it while open, so a sub-agent view's run (outside the input handler) asking while a command's dialog is open, or the reverse, waits instead of raising (thinking-prompt raises on a second dialog: a permission prompt would be a denial the user never saw) +│ │ ├── dialogs.py # One dialog at a time on a session: serialize_dialogs (BaseCLIApp.session's setter wraps a real session's six dialog methods, whoever calls them: the framework's commands, an app's own, a question's dialog) and dialog_lock(ui) (the message processor holds it around a question's dialog; a task may take it again) make a sub-agent view's run (outside the input handler) asking while a command's dialog is open, or the reverse, wait instead of raising (thinking-prompt raises on a second dialog: a permission prompt would be a denial the user never saw); a stand-in whose methods are mocks is left as it is │ │ ├── agent_view.py # A sub-agent's view (provisional; open_view/leave_view behind BaseCLIApp.open_agent_view/leave_agent_view, /back: BackCommand): entering prints VIEW_RULE ("── researcher-2 · researcher · idle ──") and a recap (title, its first brief's objective, its last run's status, its result's first lines, its tokens: instance_tokens, each run's from the usage ledger or its record), the prompt "> " (none for a closed one: read-only, READ_ONLY) and WorkflowController.view_segment (its status, its ctx: its last own step's prompt against its own trigger, its tokens); AgentView.take: a line steers the run that works (steer_instance, STEERED) or starts the instance's next run in a task of its own (ConversationCore.run_instance on the view's own MessageProcessor), outside the input handler, so the prompt takes the lines that steer it (thinking-prompt takes none while a handler runs); bind_ctrl_c: Ctrl+C stops that run (AgentView.stop: the user's stop) through a prompt_toolkit binding on the session's application, active only while it works; a line typed before the run ends waits for it inside the view (a stop says the cancel once), and one typed while the workflow is down is the next run all the same (its start retries); leave_view (/back): waits for the run, retries a workflow that is down, BACK_RULE, the prompt and bar back, then one notice turn (ConversationCore.tell_root, view_notice, TELLING) when a run the user started there ended since the main agent last heard, then the finished jobs that waited (job_auto_resume); in a view /compact is refused (COMPACT_IN_VIEW), /jobs resume waits (JOBS_WAIT), /status shows its context_rows, /new and /resume leave it first │ │ ├── memory_command.py # /memory: the list (a picker like /resume's), one memory (Delete, History), /memory , history (Restore), inbox (Accept/Discard/Skip), stale; proposals_line; Enter's button is Close or Skip, and Delete acts only on the memory as shown │ │ ├── workflow_controller.py # WorkflowController (lazy/background init; subagents=: the SubAgentPolicy every manager it builds gets, a switch_backend's too; the session store of every manager of the run, store, fixed at its first start; the backend it runs, backend: the settings' orchestrator at its first start, then switch_backend's (a conversation on another backend, new or opened: the new manager started first on the run's services lent, given over by the old one and published at once, the old one released in the controller's task, a cancel stops only the wait; a failed start or give leaves the old one with its services; while down, a manager a failed reinitialization kept lends its services to the next build, _lender, and is released once they are given); reinitialize, a model switch, always in place; the status bar names the main agent's model, or in a sub-agent's view what view_segment says of the instance, the jobs segment kept) diff --git a/src/agentic_cli/cli/agents_command.py b/src/agentic_cli/cli/agents_command.py index 820addd9..6b188edb 100644 --- a/src/agentic_cli/cli/agents_command.py +++ b/src/agentic_cli/cli/agents_command.py @@ -45,7 +45,6 @@ from thinking_prompt import ChoiceField, Dialog from agentic_cli.cli.commands import Command, CommandCategory -from agentic_cli.cli.dialogs import show_dialog from agentic_cli.cli.usage_tracker import format_tokens, format_usage from agentic_cli.tools._core.tasks import task_progress_data from agentic_cli.workflow.agents import RUN_COMPLETED, RUN_INPUT_REQUIRED, RUN_STARTED @@ -113,7 +112,7 @@ async def execute(self, args: str, app: Any) -> None: app.session.add_message("system", NO_RUNS) return dialog, ids = picker(instances, placement=_placement(app)) - picked = await show_dialog(app.session, dialog) + picked = await app.session.show_dialog(dialog) if picked is not None and picked in ids: await app.open_agent_view(ids[picked]) diff --git a/src/agentic_cli/cli/app.py b/src/agentic_cli/cli/app.py index 1ed20e0a..bf31b71e 100644 --- a/src/agentic_cli/cli/app.py +++ b/src/agentic_cli/cli/app.py @@ -33,7 +33,7 @@ from agentic_cli.cli.agent_view import AgentView, bind_ctrl_c, leave_view, open_view from agentic_cli.cli.commands import Command, CommandRegistry -from agentic_cli.cli.dialogs import show_dialog +from agentic_cli.cli.dialogs import serialize_dialogs from agentic_cli.cli.message_processor import MessageProcessor, _says_so_when_stopped from agentic_cli.cli.conversation import ( NOT_KEPT, @@ -623,6 +623,17 @@ def workflow(self) -> "BaseWorkflowManager": """ return self._workflow_controller.workflow + @property + def session(self) -> ThinkingPromptSession: + """The session the app draws in. Its dialog methods take one lock, so a + question of a sub-agent's view run and a command's dialog never open + at once (``cli/dialogs.py``); a session assigned later gets it too.""" + return self._session + + @session.setter + def session(self, value: ThinkingPromptSession) -> None: + self._session = serialize_dialogs(value) + @property def agent_view(self) -> AgentView | None: """The sub-agent's view that is open (provisional), or None in the @@ -1682,7 +1693,7 @@ async def pick_session(self) -> str | None: rows, datetime.now(timezone.utc), placement=self._settings.dialog_placement, backends=any(info.backend != running for info in rows), ) - picked = await show_dialog(self.session, dialog) + picked = await self.session.show_dialog(dialog) return None if picked is None else ids.get(picked) async def list_conversations(self, limit: int | None = None) -> "list[SessionInfo]": diff --git a/src/agentic_cli/cli/dialogs.py b/src/agentic_cli/cli/dialogs.py index 72af0249..1a9986a1 100644 --- a/src/agentic_cli/cli/dialogs.py +++ b/src/agentic_cli/cli/dialogs.py @@ -1,41 +1,99 @@ """One dialog at a time on a session. -thinking-prompt shows one dialog and raises on a second ``show_dialog``. A -turn and a command used to run one at a time, in the input handler, so they -never met. A sub-agent's view runs its run outside the handler (the prompt -stays open to steer it), so a command may open a dialog while the run asks -its question, or the run may ask while a command's dialog is open: a second -dialog that raised would be a permission prompt answered by a denial the -user never saw, or a command that fails. - -Every dialog of the app takes the session's one lock (``dialog_lock``) for as -long as it is open: whichever comes second waits for the user to answer the -first. The commands show theirs through ``show_dialog``; the message -processor holds the lock around a question's dialog. +thinking-prompt shows one dialog and raises on a second. A turn and a command +used to run one at a time, in the input handler, so they never met. A +sub-agent's view runs its run outside the handler (the prompt stays open to +steer it), so a command may open a dialog while the run asks its question, or +the run may ask while a command's dialog is open: a second dialog that raised +would be a permission prompt answered by a denial the user never saw, or a +command that fails. + +Every dialog of the app's session takes the session's one lock +(``dialog_lock``) for as long as it is open: whichever comes second waits for +the user to answer the first. ``serialize_dialogs`` makes that true of the +session's own dialog methods, whoever calls them (the framework's commands, an +app's own, a question's dialog in the message processor), so no caller has a +path of its own to remember. """ from __future__ import annotations import asyncio +import functools +import inspect import weakref from typing import Any -_LOCKS: "weakref.WeakKeyDictionary[Any, asyncio.Lock]" = weakref.WeakKeyDictionary() +#: The session methods that open a dialog (thinking-prompt's public ones). +DIALOG_METHODS = ( + "show_dialog", + "yes_no_dialog", + "message_dialog", + "choice_dialog", + "dropdown_dialog", + "checklist_dialog", +) + + +class DialogLock: + """A lock a task may take again while it holds it. + + The message processor holds it for a question's whole dialog, and the + session's wrapped dialog method takes it again inside: the same task is + let through, so the two never wait for each other. + """ + + def __init__(self) -> None: + self._lock = asyncio.Lock() + self._owner: asyncio.Task[Any] | None = None + self._depth = 0 + + async def __aenter__(self) -> None: + task = asyncio.current_task() + if self._owner is not None and self._owner is task: + self._depth += 1 + return + await self._lock.acquire() + self._owner = task + self._depth = 1 + async def __aexit__(self, *exc: Any) -> None: + self._depth -= 1 + if self._depth == 0: + self._owner = None + self._lock.release() -def dialog_lock(ui: Any) -> asyncio.Lock: + +_LOCKS: "weakref.WeakKeyDictionary[Any, DialogLock]" = weakref.WeakKeyDictionary() + + +def dialog_lock(ui: Any) -> DialogLock: """The lock every dialog of the session ``ui`` takes while it is open.""" lock = _LOCKS.get(ui) if lock is None: - lock = _LOCKS[ui] = asyncio.Lock() + lock = _LOCKS[ui] = DialogLock() return lock -async def show_dialog(ui: Any, dialog: Any) -> Any: - """``ui.show_dialog(dialog)``, once no other dialog of the session is open. +def serialize_dialogs(session: Any) -> Any: + """Make each dialog method of ``session`` take its ``dialog_lock``. + + The methods are replaced on the instance. Only a real method is wrapped, + so a session already done is left as it is (its wrappers are functions), + and so is a stand-in whose attributes are not methods (a test's mock). Returns: - What the dialog returns (the button's result, or None on Escape). + ``session``. """ - async with dialog_lock(ui): - return await ui.show_dialog(dialog) + for name in DIALOG_METHODS: + original = getattr(session, name, None) + if not inspect.ismethod(original): + continue + + @functools.wraps(original) + async def locked(*args: Any, _original: Any = original, **kwargs: Any) -> Any: + async with dialog_lock(session): + return await _original(*args, **kwargs) + + setattr(session, name, locked) + return session diff --git a/src/agentic_cli/cli/memory_command.py b/src/agentic_cli/cli/memory_command.py index d05a0b2d..6a5e28e5 100644 --- a/src/agentic_cli/cli/memory_command.py +++ b/src/agentic_cli/cli/memory_command.py @@ -24,7 +24,6 @@ from thinking_prompt import ButtonConfig, ChoiceField, Dialog from agentic_cli.cli.commands import Command, CommandCategory -from agentic_cli.cli.dialogs import show_dialog if TYPE_CHECKING: from thinking_prompt import Placement @@ -244,7 +243,7 @@ async def _list(self, app: Any, store: "MemoryStore", *, stale: bool = False) -> memories, problems, waiting, "Stale memories" if stale else "Memory", placement=_placement(app), ) - picked = await show_dialog(app.session, dialog) + picked = await app.session.show_dialog(dialog) key = rows.get(picked) if picked is not None else None if key == _PROBLEMS: await self._problems(app, problems) @@ -253,7 +252,7 @@ async def _list(self, app: Any, store: "MemoryStore", *, stale: bool = False) -> async def _problems(self, app: Any, problems: list["Problem"]) -> None: body = "\n".join(f"{p.path}\n {p.kind}: {p.detail}" for p in problems) - await show_dialog(app.session, Dialog( + await app.session.show_dialog(Dialog( "Memory files that cannot be used", body=body, buttons=[ButtonConfig("Close", result=None)], placement=_placement(app), )) @@ -264,8 +263,8 @@ async def _show(self, app: Any, store: "MemoryStore", memory_id: str) -> None: await self._missing(app, store, memory_id, shown=False) return versions = await asyncio.to_thread(store.history, memory.id) - choice = await show_dialog( - app.session, memory_view(memory, bool(versions), placement=_placement(app)) + choice = await app.session.show_dialog( + memory_view(memory, bool(versions), placement=_placement(app)) ) if choice == "delete": await self._delete(app, store, memory) @@ -329,7 +328,7 @@ async def _history(self, app: Any, store: "MemoryStore", memory_id: str | None) label += " ·" rows[label] = version title = "Memory history" + (f" of {memory_id}" if memory_id else "") - picked = await show_dialog(app.session, Dialog( + picked = await app.session.show_dialog(Dialog( title, fields=[ChoiceField("version", "", options=list(rows))], placement=_placement(app), )) @@ -338,7 +337,7 @@ async def _history(self, app: Any, store: "MemoryStore", memory_id: str | None) return current = await asyncio.to_thread(store.read, version.memory_id) unusable = None if current is not None else await asyncio.to_thread(_claiming, store, version.memory_id) - choice = await show_dialog(app.session, Dialog( + choice = await app.session.show_dialog(Dialog( f"Version of {version.memory_id}", body=version_body(version, current, unusable), buttons=[ButtonConfig("Restore", result="restore"), ButtonConfig("Close", result=None, focused=True)], @@ -367,7 +366,7 @@ async def _inbox(self, app: Any, store: "MemoryStore") -> None: current = await asyncio.to_thread(store.read, proposal.target or "") if current is None: unusable = await asyncio.to_thread(_claiming, store, proposal.target or "") - choice = await show_dialog(app.session, Dialog( + choice = await app.session.show_dialog(Dialog( f"Memory proposal {number} of {len(proposals)}", body=proposal_body(proposal, current, unusable), buttons=[ diff --git a/src/agentic_cli/cli/settings_command.py b/src/agentic_cli/cli/settings_command.py index d713183a..65dd1804 100644 --- a/src/agentic_cli/cli/settings_command.py +++ b/src/agentic_cli/cli/settings_command.py @@ -11,7 +11,6 @@ from thinking_prompt import ButtonConfig, Dialog from agentic_cli.cli.commands import Command, CommandCategory -from agentic_cli.cli.dialogs import show_dialog if TYPE_CHECKING: from agentic_cli.cli.app import BaseCLIApp @@ -56,7 +55,7 @@ async def execute(self, args: str, app: "BaseCLIApp") -> None: placement=app.settings.dialog_placement, ) # Save returns True; Cancel and Escape return None. - if not await show_dialog(app.session, dialog): + if not await app.session.show_dialog(dialog): app.session.add_message("system", _UNCHANGED) return diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index 9dcfd062..e41a105b 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -19,7 +19,7 @@ from __future__ import annotations import asyncio -from types import SimpleNamespace +from types import MethodType, SimpleNamespace import pytest @@ -36,6 +36,7 @@ TELLING, bind_ctrl_c, ) +from agentic_cli.cli import agents_command from agentic_cli.cli.agents_command import NO_SUCH_AGENT from agentic_cli.cli.app import BaseCLIApp from agentic_cli.cli.message_processor import CANCELLED_LINE @@ -46,6 +47,7 @@ INSTANCE_STOPPED, RUN_CANCELLED, RUN_COMPLETED, + RUN_INPUT_REQUIRED, ) from agentic_cli.workflow.agents.envelope import view_notice from tests.cli.dialog_fakes import autospec_session, opening_boxes @@ -697,7 +699,13 @@ async def asking_view(make_crew) -> tuple[Crew, BaseCLIApp, Dialogs]: says("Asked.")], ) dialogs = Dialogs() - app.session.show_dialog.side_effect = dialogs.show + + async def show_dialog(session, dialog): + return await dialogs.show(dialog) + + # A real method, as a real session's is: the app serializes those. + app.session.show_dialog = MethodType(show_dialog, app.session) + app.session = app.session return crew, app, dialogs @@ -716,7 +724,7 @@ async def test_a_question_waits_for_an_open_picker(self, make_crew): picker = asyncio.create_task(app.process_input("/agents")) await until(lambda: dialogs.shown == ["Sub-agents"]) HELD["go"].set() - await asyncio.sleep(0.3) # the run reaches its question + await until(lambda: crew.records()[-1].status == RUN_INPUT_REQUIRED) assert dialogs.refused == [] assert dialogs.shown == ["Sub-agents"] @@ -732,15 +740,23 @@ async def test_a_question_waits_for_an_open_picker(self, make_crew): finally: dialogs.release_all() - async def test_a_command_waits_for_an_open_question(self, make_crew): + async def test_a_command_waits_for_an_open_question(self, make_crew, monkeypatch): crew, app, dialogs = await asking_view(make_crew) + reached = asyncio.Event() + built = agents_command.picker + + def noting(*args, **kwargs): + reached.set() + return built(*args, **kwargs) + + monkeypatch.setattr(agents_command, "picker", noting) try: await app.process_input("Ask me.") await asyncio.wait_for(HELD["started"].wait(), 10) HELD["go"].set() await until(lambda: dialogs.shown == ["researcher-1 asks"]) picker = asyncio.create_task(app.process_input("/agents")) - await asyncio.sleep(0.3) # the command reaches its picker + await until(reached.is_set) # the command has its picker and shows it assert dialogs.refused == [] assert dialogs.shown == ["researcher-1 asks"] @@ -756,6 +772,49 @@ async def test_a_command_waits_for_an_open_question(self, make_crew): finally: dialogs.release_all() + async def test_an_apps_own_command_waits_for_an_open_question(self, make_crew): + """A command of an app that calls ``app.session.show_dialog`` itself + is serialized too: the session's dialogs all take the one lock.""" + from thinking_prompt import Dialog + + from agentic_cli.cli.commands import Command, CommandCategory + + reached = asyncio.Event() + + class Mine(Command): + def __init__(self) -> None: + super().__init__( + name="mine", description="An app's own dialog", usage="/mine", + category=CommandCategory.WORKFLOW, + ) + + async def execute(self, args, app) -> None: + reached.set() + await app.session.show_dialog(Dialog("Mine", fields=[])) + + crew, app, dialogs = await asking_view(make_crew) + app.command_registry.register(Mine()) + try: + await app.process_input("Ask me.") + await asyncio.wait_for(HELD["started"].wait(), 10) + HELD["go"].set() + await until(lambda: dialogs.shown == ["researcher-1 asks"]) + mine = asyncio.create_task(app.process_input("/mine")) + await until(reached.is_set) + + assert dialogs.refused == [] + assert dialogs.shown == ["researcher-1 asks"] + dialogs.gate("researcher-1 asks").set() + await until(lambda: "Mine" in dialogs.shown) + dialogs.gate("Mine").set() + await asyncio.wait_for(mine, 10) + await settled_or_fail(app) + + assert dialogs.refused == [] + app.session.add_error.assert_not_called() + finally: + dialogs.release_all() + # -- a workflow that is down ---------------------------------------------------------------- diff --git a/tests/cli/test_dialogs.py b/tests/cli/test_dialogs.py new file mode 100644 index 00000000..baead374 --- /dev/null +++ b/tests/cli/test_dialogs.py @@ -0,0 +1,51 @@ +"""One dialog at a time (``cli/dialogs.py``): the session's dialog methods take +one lock, which the same task may take again.""" + +from __future__ import annotations + +import asyncio + +from thinking_prompt import ThinkingPromptSession + +from agentic_cli.cli.dialogs import DIALOG_METHODS, dialog_lock, serialize_dialogs +from tests.cli.dialog_fakes import autospec_session + + +def test_a_real_sessions_dialog_methods_are_wrapped_once(): + session = ThinkingPromptSession(message=">>> ") + originals = {name: getattr(session, name) for name in DIALOG_METHODS} + + assert serialize_dialogs(session) is session + wrapped = {name: getattr(session, name) for name in DIALOG_METHODS} + serialize_dialogs(session) + + assert all(wrapped[name] is not originals[name] for name in DIALOG_METHODS) + assert all(getattr(session, name) is wrapped[name] for name in DIALOG_METHODS) # not again + + +def test_a_stand_in_whose_methods_are_mocks_is_left_alone(): + session = autospec_session() + shown = session.show_dialog + + serialize_dialogs(session) + + assert session.show_dialog is shown + + +async def test_the_same_task_may_take_the_lock_again_and_another_waits(): + lock = dialog_lock(object.__new__(type("Ui", (), {}))) + order: list[str] = [] + + async def other() -> None: + async with lock: + order.append("other") + + async with lock: + async with lock: # the same task: let through + order.append("inner") + task = asyncio.create_task(other()) + await asyncio.sleep(0) + order.append("still held") + await task + + assert order == ["inner", "still held", "other"]