diff --git a/CHANGELOG.md b/CHANGELOG.md index db6ef192..032b26af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -630,10 +630,14 @@ the start of the entry's title. turn of its own (`started_by: user`, counted toward no turn's runs, from the conversation's outside-content mark; stopping its stream, Ctrl+C, is the user's stop of the run, which ends `cancelled` and leaves the instance - `stopped`), `stop_instance`, `close_instance` (both written to the store + `stopped`), `interrupt_instance(instance)` (that run ends as a turn's + cancel ends its runs, `interrupted`, the instance `idle`, as at a process + exit; its stream raises `asyncio.CancelledError`), `stop_instance`, + `close_instance` (both written to the store before they return), `steer_instance(instance, message)` (the user's message to a running run, before its next step), `instance_result` (the envelope of - the latest run the user started) and `tell_root(text)`, a turn of the root + the latest run the user started, through the tool result cap) and + `tell_root(text)`, a turn of the root on a notice the user did not type (marked as a job's notice is, so fact extraction and the conversation's title and turns leave it out; the outside-content mark a user's run brought is written with it), whose notice @@ -651,7 +655,9 @@ the start of the entry's title. 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, + stop, the sub-agent `stopped`); `/exit` while it works interrupts it, as a + process exit does (`interrupted`, the sub-agent `idle`, so its parent may + continue it). `/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 @@ -660,7 +666,13 @@ the start of the entry's title. `/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. + commands call. The app's session (`BaseCLIApp.session`) has its six + dialog methods (`show_dialog`, `yes_no_dialog`, `message_dialog`, + `choice_dialog`, `dropdown_dialog`, `checklist_dialog`) wrapped as it is + assigned, so one dialog opens at a time: a command's dialog and a run's + question wait for each other, where thinking-prompt raises on a second + (a task may open one inside its own). An app keeps that by assigning its + session through `self.session`, not as a class attribute with a value. - **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 @@ -721,8 +733,10 @@ the start of the entry's title. working (the app was killed in it) reads `interrupted` and its instance `idle` (`closed` for a type that is not continuable), so a follow-up continues it, new instances are numbered past them (on Deep Agents past the - records' counters and ids and the checkpointer's instance threads, whose - first checkpoint holds no message, and a first run whose thread the store + records' counters and ids and the checkpointer's instance threads, read + from each thread's first checkpoint, which holds its first run's input: + the brief, and an inheriting instance's copy of its parent's + conversation; and a first run whose thread the store keeps all the same fails rather than continue it), and records of another version, or that do not read, are ignored with one warning (`subagent_records_ignored`) and never written over: that conversation's @@ -775,8 +789,9 @@ the start of the entry's title. transcript is a checkpointer thread of its own (`[app, user, session, ""]`), which its follow-ups continue, the calls an earlier run left open answered as its next run starts: from the record when one - returned, as the user's when the run was stopped, `INTERRUPTED` after a - crash. A model switch keeps the instances, their transcripts and their + returned, with what stopped the run when it was stopped (the user, its + parent, a limit), `INTERRUPTED` after a crash. A model switch keeps the + instances, their transcripts and their records. - **`SubAgentPolicy` and `AgentLimits`: an app's sub-agent policy and a run's limits, enforced on both backends** (`agentic_cli.workflow`, and @@ -868,11 +883,27 @@ the start of the entry's title. on, and its parent reads `{"status": "cancelled", "cancelled_by": ..., "error": ..., "partial": , "result": ""}`; the run's record and its `AGENT_RUN` end say who cancelled it - (`cancelled_by`). Ctrl+C still stops the whole turn, every run + (`cancelled_by`). A run working below a run cancelled so (one it + started, at any depth) ends `cancelled`, `cancelled_by: "parent"`, + `error: "its parent's run was stopped"`, its instance idle. A call a + stopped run left says what stopped it, on both backends: one at its + permission prompt `Not run: its parent stopped the run before this call + ran.` (or `its time limit`, `its token limit`), the user's stop `Not run: + the user cancelled it.`; one that was running `Interrupted: its parent + stopped the run before this call finished; it may have partly run. Check + before running it again.` (`interrupts.interrupted_by`, `INTERRUPTED_BY`), + the user's stop `Interrupted by the user before it finished; …`. Ctrl+C + still stops the whole turn, every run `interrupted`. `steer(message)` gives a working run a message, added after its last message, as the user's, before its next model call, where - it stays (ADK: in its child session). A sub-agent's dialog is withdrawn - when its run is stopped, and the turn goes on with its events box. + it stays (ADK: in its child session). A steered message is never lost: + one the run's transcript does not hold when the run ends (no model call + came after it, or the run was stopped before it was stored) goes to the + instance's next run, which takes it at its first model call, after its + own message; a closed instance's are dropped (logged). ADK counts each + one stored as its child session's append returns, Deep Agents once the + model call after it holds it. A sub-agent's dialog is withdrawn when its + run is stopped, and the turn goes on with its events box. - **A sub-agent's questions and permission prompts name it, on both backends.** `UserInputRequest.run` is the sub-agent run that asks (a `RunRef`; None for the root's own), filled by `request_user_input` from @@ -1534,9 +1565,11 @@ the start of the entry's title. and the log warns once per folder. Reading a saved output back cuts it again without a second file. Every result is covered: registered, MCP and skill tools, `job_result`, and a sub-agent run's envelope (`task`'s - result, on both backends). A string that holds a JSON object (the - envelope, a framework tool's dict in a Deep Agents `ToolMessage`) is cut - as that dict and given back as JSON, so its parent reads JSON still. ADK's + result, on both backends, and the one the notice after a sub-agent's + view carries, saved under the instance's name). A string that holds a + JSON object (the envelope, a framework tool's dict in a Deep Agents + `ToolMessage`) is cut as that dict and given back as JSON, so its parent + reads JSON still. ADK's `ToolResultCapPlugin` caps every agent but one with `after_tool_callback`s of its own (a native ADK YAML app's), which ADK would skip once it cut; Deep Agents' `ToolResultCapMiddleware` sits between the permission gate @@ -1822,18 +1855,11 @@ the start of the entry's title. ### Changed -- **A sub-agent run that did not complete fully names its open tasks.** The - envelope of a run that ended partial (its step limit, a cut answer), - failed or cancelled ends with `"open_tasks"`: the descriptions of its own - tasks whose status is not `completed`, in its list's order, when it has - any (`envelope(open_tasks=)`, `open_task_descriptions`), so its parent can - continue it with `message_agent`. A cancelled run's end keeps its plan - and tasks, on its `AGENT_RUN` and its record, as any other end does. - - **A sub-agent's plan and task list are its own, on both backends.** An instance's first run starts with no plan and no tasks (its follow-ups - continue its own), keeps what it saves (its last plan and - tasks are on its record, and `/agents ` shows them after its result), + continue its own), keeps what it saves (its last plan and tasks are on + its record and its `AGENT_RUN` end, a cancelled run's too, and `/agents + ` shows them after its result), and writes nothing of them to its caller: the conversation's plan and task list, and the status bar's task box, are the coordinator's alone, and two runs at once no longer overwrite each other's. Only the outside-content @@ -1848,15 +1874,23 @@ the start of the entry's title. ""]`; every sub-agent is compiled on the manager's checkpointer, where it had none), which its follow-ups continue and no conversation list, `/resume` picker or `--continue` shows. Deleting the conversation - deletes them, events and all, whoever deletes it: `delete_session`, a + deletes them first, events and all, then its sub-agent records, then the + conversation, so a delete cut short leaves the conversation, by which the + rest is found again, whoever deletes it: `delete_session`, a `SessionReader` (`/sessions --delete` on another backend's conversation), `/new` on the memory store, and a conversation already gone leaves none - behind (`adk/sessions.py::delete_children`; Deep Agents deletes the - instances' threads before the conversation's). Instances are numbered - from the conversation's stored records, and each turn's first run past the - instances the conversation's store keeps besides - (`BaseWorkflowManager._stored_instances`, asked once per conversation per - turn; `AgentRuns.number_from`), whoever ran them: a manager before a + behind (`adk/sessions.py::delete_children`: the child sessions its records + name and every one that names the conversation, a transcript whose start + write was lost too; Deep Agents deletes the instances' threads). The + manager forgets the conversation it deletes (its sub-agent records, the + record of a failed turn's calls and every stop, its usage ledger, its + numbering), so a conversation of the same id starts from `researcher-1`. + Instances are numbered from the conversation's stored records, and each + turn's first run past the instances the conversation's store keeps + besides (`BaseWorkflowManager._stored_instances`, asked once per + conversation per turn, under a lock of the conversation's own; on ADK the + child sessions its records name, a listing's for one without records; + `AgentRuns.number_from`), whoever ran them: a manager before a restart or a switch of backend or store, or another process that had the conversation between two turns. `researcher-2` follows a stored `researcher-1`, whose transcript stays as @@ -1899,7 +1933,12 @@ the start of the entry's title. "Dynamic node failed"), its `result` the text it wrote before it failed, a refused run's `a model refused the request` with the refusal notice as its `result`, an interrupted run's - `interrupted before it finished`. No delegation is an error result any + `interrupted before it finished`. The envelope of a run that ended + partial (its step limit, a cut answer), failed or cancelled ends with + `"open_tasks"`: the descriptions of its own tasks whose status is not + `completed`, in its list's order, when it has any + (`envelope(open_tasks=)`, `open_task_descriptions`), so its parent can + continue it with `message_agent`. No delegation is an error result any more ("Error running sub-agent: …" is gone): the envelope says how the run ended. A run's result is its last text, a reply that also called a tool included, so an empty final answer after it leaves that text; a run @@ -3206,35 +3245,6 @@ step; each entry says what to use instead. ### Fixed -- **A message steered to a sub-agent run is never lost.** One its - transcript does not hold when the run ends (no model call came after it, - or the run was stopped before it was stored) goes to the instance's next - run, which takes it at its first model call, after its own message; a - closed instance's are dropped (logged). ADK counts each one stored as its - child session's append returns, Deep Agents once the model call after it - holds it. -- **A call a stopped sub-agent run left at its prompt says what stopped it.** - `Not run: its parent stopped the run before this call ran.` (or `its time - limit`, `its token limit`) where every stop read "Not run: the user - cancelled it.", which the user's stop still reads, on both backends. -- **A sub-agent whose parent's run is stopped says so.** A run working when - a run above it is cancelled by its control (its parent's stop, a limit, - the user's stop of that run) ends `cancelled`, `cancelled_by: "parent"`, - `error: "its parent's run was stopped"`, its instance idle, where it ended - `interrupted` as on Ctrl+C, which still makes every run the turn's. -- **Deleting a conversation leaves nothing of its sub-agents behind.** Its - instances' transcripts are deleted first (on ADK they were deleted after - the conversation, so a delete cut short left ones nothing could reach), - then its records, then the conversation; the manager forgets the - conversation (its sub-agent records, the record of a failed turn's calls - and every stop, its usage ledger, its numbering), so a conversation of - the same id starts from `researcher-1`. On ADK each turn finds a - conversation's transcripts to number past by the instances its records - name, where every child session of the user was listed, a delete removes - those and every child session that names the conversation (a transcript - whose start write was lost goes too), and the stored instances of one - conversation are read under a lock of its own, not one shared by all. - - **google-adk 2.15: a Claude refusal reads as before, Deep Agents' `load_skill` answers as ADK's, and Ctrl+C during a tool call warns of nothing.** From 2.15, ADK's Claude adapter gives a reply with nothing in diff --git a/CLAUDE.md b/CLAUDE.md index d4d04197..1bc2a327 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,7 +30,7 @@ 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), 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) +│ │ ├── app.py # BaseCLIApp (subagents=: the SubAgentPolicy every manager the app builds gets, through its WorkflowController; main(): the command line, add_arguments/from_args, exit_status; session_start: how run() begins, the run's own conversation loaded before the prompt, also when the workflow did not start (_adopt_its_own: an id the app was given held from the start, one the run made from its first write); its resume once the prompt is up (_open_on_startup, holding the turn lock from before the prompt takes a line: a turn typed ahead waits and runs there; Ctrl+C there ends the app; --continue passes over conversations another process holds, _newest_free, the one chosen held beside the run's own until the switch); --continue and --resume find the conversation's backend from every installed backend's reader before the workflow is built (_start_on_its_backend: the run builds that backend once); the --resume hint at exit (the run's store named after a session_store change; the backend only when no reader reads it, LangGraph: --resume opens a conversation on its own); the session it builds; get_theme(name); /settings: _build_ui_items, apply_settings and save_settings delegate to cli/settings_ui.py (SettingsUI: an app's override applies); run() installs the ADK log filters first (workflow/adk/log_filters.py: an app built but never run installs none), then the SIGHUP/SIGTERM handlers that kill live execute_python runs before chaining to the previous handler (_stop_runs_on_signals); the LangGraph deprecation notice; start_new_session(backend=None): /new [backend] (the settings' orchestrator by default; another backend: the memories proposed, WorkflowController.switch_backend, then the switch to the new id at its place; a Ctrl+C once it runs opens its conversation first); a line typed runs in ConversationCore.run_turn (on _turn_parts: the app's parts as they are), then the jobs at the turn's end through the app's own resume_finished_jobs(); compact() (ConversationCore.compact), start_new_session() and resume_session(): /compact, /new and /resume, under the conversation's turn lock (_turn_lock: ConversationCore.turn_lock; pick_session(), the picker, is not: it waits on a dialog); session_store=memory keeps one conversation at a time (Place.kept; session_store: the run's store): /new drops the one left once the switch is made, after its memories are proposed (_drop: its delete_session, shielded; on another backend the manager released takes it along; one it cannot confirm gone, the workflow down or its lookup or delete raising, is remembered and dropped once a workflow is ready: before the next turn, or right after the turn whose own start revives the workflow, and always before that turn's delivery of finished jobs, /compact and the next /new, never while it is the open one: ConversationCore.drop_left), and resume_session, pick_session, --resume (status 1) and --continue (a new conversation) are refused with NOT_KEPT, before any look-up; every installed backend's conversations (list_conversations, delete_conversation, session_backend; cli/stored_conversations.py): the picker names each row's backend and returns a PickedConversation, and /resume opens a conversation on the backend that keeps it (_open_elsewhere: held there, memories proposed, switch_backend with the run's services, then the switch at its place; an id two backends keep opens on the running one, the other named); every change of conversation through ConversationCore.switch (_conversation; _session_id and _turned forward to it); the session_id setter deprecated (its synchronous part, switch_now, and a DeprecationWarning); a conversation's memories proposed once per conversation used (_turned); the memory proposals waiting, said at startup and after /new and /resume (_name_waiting_proposals); resume_finished_jobs(): ConversationCore.deliver_finished_jobs, the jobs waiting named at startup by ConversationCore.waiting_jobs (_name_its_waiting_jobs), none in a sub-agent's view; a sub-agent's view (cli/agent_view.py, provisional: agent_view, open_agent_view(id), leave_agent_view()): process_input gives a line typed there to AgentView.take, and draws its prompt and status bar again after a command; start_new_session and resume_session leave it first (_leave_view_first); run() binds Ctrl+C to the run in view (bind_ctrl_c) and interrupts one still working at exit, as a process exit does, waited for before the workflow closes (AgentView.interrupt: not the user's stop, the run interrupted and its sub-agent idle)) │ │ ├── commands.py # Command, CommandRegistry │ │ ├── job_monitor.py # JobMonitor: the status bar's jobs segment (running, queued, a finished job's note, ↻N: waiting_jobs' rule, can_resume answers kept 30 s (the other backends' look too: kept_elsewhere), forgotten after /sessions --delete or when the workflow is replaced), one tick every 2 s, its JobManager.list() on a worker thread │ │ ├── conversation.py # ConversationCore: the conversation the turns run in (its id, turned, its lock at its Place: the backend and store, the store the run's for its whole life (Place.kept: not the memory store, where the CLI keeps one conversation at a time and NOT_KEPT says why nothing else opens), the backend recorded as the app starts, for a new conversation on another backend, and on a /settings change of the orchestrator while the workflow is down, its next start builds afresh and nothing of the conversation is stored (SettingsUI._move_here, WorkflowController.next_start_builds), never read from the settings in between; deferred: an id this run made (the start's, /new's, an orchestrator change's) is in no store, so it is held from its first write, hold_to_write under the turn lock before a turn, a job's notice or /compact (_held_to_write; a run in which no turn runs makes no lock file: a line typed while the workflow is down takes the hold before its retried start; a lock that cannot be taken, an OSError, leaves it unheld, said once, and the write goes on); fresh: nothing of it stored, opened_empty (an id this run made, or one a load found empty) and not written (no turn of it ran on a ready workflow), the one condition for another backend); switch: the one protocol (/new on any backend, /resume, startup, the same id in another place while the workflow is down): the target's lock taken (another process's refused), memories proposed, the workflow loads it (a stored one gone: not made, or, made already in another place, opened empty: gone), then made at once (lock, id, task list, usage counters) or let go, a workflow that took it given the old one back; made before the load when there is no other conversation to stay in (the same id, or another place: a new or stored conversation on another backend); a Ctrl+C at any await leaves one conversation held; switch_now: the deprecated session_id setter's part; turn_lock: what writes to the conversation and every switch take it; run_turn, compact and run_job_resume: a turn (echoed, held to write, turned, written once it reached a ready workflow; run_turn says whether it ran, whatever the processor returns), /compact and a finished job's notice under it, on TurnParts (the app's parts as they are); run_instance and tell_root (_write): a line typed in a sub-agent's view as its next run (process_instance; written, not turned) and the main agent's notice after a view (process_notice; turned), under it too; deliver_finished_jobs: each job that waits here (cli/waiting_jobs.py's rule, which waiting_jobs names them by, the other backends' look through TurnParts.kept_elsewhere), every JobManager call on a worker thread, a delivery claimed only once it can reach the agent (process_resume(claim=), after the readiness check and can_resume; _claim_delivery: a claim a Ctrl+C stopped is handed back, JobManager.release_resume), a failure before the claim said once per job and conversation when the CLI tells jobs on its own (telling_on_its_own); to_drop/drop_left: the conversations /new left on the memory store that the store may still hold (the workflow down, a lookup or delete that raised), dropped through TurnParts.drop under the turn lock once a workflow is ready, before a turn, /compact or a delivery uses it (after a turn or /compact that started it), one try per point, done once the store has it no more (a workflow without supports_sessions has none), the open one skipped; a delivery with none to drop takes no turn lock @@ -38,7 +38,7 @@ agentic-cli/ │ │ ├── builtin_commands.py # /help (by category; /help : its usage and examples), /status (the main agent's context rows: context_budget, in a sub-agent's view the instance's, AgentView.context_rows; why the workflow did not start: app.workflow_error; tokens by agent: the main agent, each sub-agent with its runs, the side calls by purpose, from the manager's usage ledger), /models (ModelsCommand: the list, each model's facts and sources, Status for an entry left out, the providers in use; /models searches the full listings; refresh), /sessions (every installed backend's, a Backend column; --delete= on the backend that keeps it, --backend= for an id two keep; on the memory store NOT_KEPT, no table, --delete refused), /resume [] (sessions; refused on the memory store), /jobs (resume: finished jobs; in a sub-agent's view JOBS_WAIT: they wait for /back), /compact [focus] (refused in a sub-agent's view: COMPACT_IN_VIEW), /new [backend] (an unknown backend or a missing extra refused: check_backend), ... │ │ ├── agents_command.py # /agents: the open conversation's sub-agent instances (agent_runs.instances under workflow.session_ref(app.session_id)) in a picker (a Dialog with one ChoiceField, as /resume's: `picker`), each followed by the ones it started (id · type · status · title), Enter opening the view of the one picked (app.open_agent_view); /agent opens its view (open_agent_view: cli/agent_view.py), /agent 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: 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 +│ │ ├── 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; AgentView.interrupt (at exit): the manager's interrupt_instance, then the view's tasks cancelled; a line typed before the run ends waits for it inside the view (a stop says the cancel once), and one typed while the workflow is down is the next run all the same (its start retries); leave_view (/back): waits for the run, retries a workflow that is down, BACK_RULE, the prompt and bar back, then one notice turn (ConversationCore.tell_root, view_notice, TELLING) when a run the user started there ended since the main agent last heard, then the finished jobs that waited (job_auto_resume); in a view /compact is refused (COMPACT_IN_VIEW), /jobs resume waits (JOBS_WAIT), /status shows its context_rows, /new and /resume leave it first │ │ ├── memory_command.py # /memory: the list (a picker like /resume's), one memory (Delete, History), /memory , history (Restore), inbox (Accept/Discard/Skip), stale; proposals_line; Enter's button is Close or Skip, and Delete acts only on the memory as shown │ │ ├── workflow_controller.py # WorkflowController (lazy/background init; subagents=: the SubAgentPolicy every manager it builds gets, a switch_backend's too; the session store of every manager of the run, store, fixed at its first start; the backend it runs, backend: the settings' orchestrator at its first start, then switch_backend's (a conversation on another backend, new or opened: the new manager started first on the run's services lent, given over by the old one and published at once, the old one released in the controller's task, a cancel stops only the wait; a failed start or give leaves the old one with its services; while down, a manager a failed reinitialization kept lends its services to the next build, _lender, and is released once they are given); reinitialize, a model switch, always in place; the status bar names the main agent's model, or in a sub-agent's view what view_segment says of the instance, the jobs segment kept) │ │ ├── session_resume.py # What /resume shows: the picker (picker: each row's backend once one is another's; PickedConversation, the id a str naming its backend), the "Resumed:" line ("Resumed on :" on another backend), the replay of the last 10 messages @@ -51,7 +51,7 @@ agentic-cli/ │ │ ├── waiting_jobs.py # Which finished jobs wait to be told in the open conversation: one rule (JobRecord.awaiting_resume, then its own, no conversation's, or a gone conversation's: can_resume, then the other installed backends' readers, opens_anywhere: one another backend keeps is not gone, its job waits for it) for the deliveries, ↻N and the startup line │ │ └── usage_tracker.py # Token usage / status bar: ctx = the main agent's last prompt over its context_trigger (a call with a purpose, a sub-agent's, a summary's or a side call's, never moves it); the token segment the open conversation's total, every call of its turns; format_usage: /status's rows by agent and /agents 's tokens by model │ ├── workflow/ -│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none); the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built: each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) +│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none); the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built: each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) │ │ ├── factory.py # create_workflow_manager_from_settings (_BACKENDS: orchestrator → "module:Class" + extra, imported when chosen; orchestrator=: another backend than the settings'; session_store=: the store a manager is built for, BaseWorkflowManager.session_store, the settings' by default; subagents=: the SubAgentPolicy the manager gets, checked before a backend is imported); orchestrator_of; check_backend (an unknown name, a missing extra) │ │ ├── session_readers.py # SessionReader: a backend's stored conversations read without its manager (list/info/exists/delete/aclose, rows naming the backend; delete deletes what the manager's does, ADK's sub-agent transcripts and records with the conversation), opened from the settings and a store (open_session_reader: the backend's own session code, adk/sessions.py::open_sessions and deepagents/sessions.py::open_sessions, imported on a worker thread; no agents, models or services; a sqlite store not made yet reads empty and is not made, Deep Agents not even imported for it; a database without its backend's tables, looked at read-only, reads empty, nothing written to it: no table, no journal mode); none for the memory store or LangGraph; ImportError (the install hint) for a missing extra; reader_backends │ │ ├── service_registry.py # get_service/require_service + ContextVar registry; the registry keys and KNOWN_SERVICE_KEYS, read from services.py's table @@ -61,7 +61,7 @@ agentic-cli/ │ │ ├── events.py # WorkflowEvent, EventType; WorkflowEvent.turn_failed: a failed turn's one ERROR (rate_limited, error_type); WorkflowEvent.run: the agent run that wrote it (RunRef; None: the manager's own); AGENT_RUN (WorkflowEvent.agent_run): a sub-agent run's start (brief=, started_by=, mode=; a first run's inherit_context=, continuable=; a follow-up's input=), how it works meanwhile (queued, running, input_required) and end (an end with what the run used, by model: usage=; cancelled_by= for a cancelled run; instance_status=: the status it leaves its instance in); AGENT_INSTANCE (WorkflowEvent.agent_instance): an instance's status changing without a run (a close); UserInputRequest.run: the sub-agent run that asks (request_user_input fills it from get_active_run()) │ │ ├── live_events.py # LiveEvents, merged: events reported inside a turn (reporting/report) reach its stream as they happen; on_stop: a consumer that stops early, before the source is cancelled; emit gives an event that names no run the active one (get_active_run) │ │ ├── usage.py # Token usage: normalized_tokens, the one place a provider's report becomes the counts every LLM_USAGE carries (prompt_tokens every input token, cache included; completion_tokens every output token, thinking included): adk_tokens (ADK's, by provider kind: Gemini's and ADK's Claude adapter's thinking apart from the candidates, OpenAI's inside; an unknown kind's apart), adk_usage_event (the one place ADK's usage becomes an LLM_USAGE: the event processor, the summarizer, generate_simple, the raw log), langchain_tokens (every partner package's, langchain-openai's priority and flex tiers' parts too), llm_usage_event; PURPOSE_* (none: the root's step; subagent, summarization, tool, memory_extraction, side_call) and side_call (what a caller's side calls are for); UsageLedger (a conversation's calls, a row each, each with its latency_ms: totals by run, agent, model, purpose and turn; a row's turn its conversation's while a turn of it runs, as the manager counts them, None in another conversation's turn or a task its turn outlived; by_agent, by_purpose, by_model, run_usage), UsageLedgers (a manager's, by conversation, filed under the turn a call is made in; for the manager's life: a backend switch's new manager starts afresh, a run's totals by model kept with its record; forget: a deleted conversation's) -│ │ ├── interrupts.py # What a call a cancel or a crash left open is answered with; OpenCalls (each manager's record, kept by conversation: only that conversation's turns clear it; within it by the instance whose run made each call, run=, the active run by default, so an instance's next run reads what an earlier one recorded; cancelled/take_cancel with instance=: a stopped run of an instance, whose calls a conversation's clear keeps until its next run takes the stop); forget(ref): everything of a deleted conversation, a failed turn's calls and every stop with its cause; unrecorded: a call no record holds; job_for_call: a job of the turn's conversation and of the run whose call it answers (started_by) only; fresh_call_id: the id a call whose provider reused one gets (the old one and a short suffix, `[A-Za-z0-9_-]`, at most 40 characters); `cancelled(cause=)`/`answer(cause=)`: what a call left at its prompt in a sub-agent run stopped by its parent or a limit is told stopped it (`not_run(cause)`: `Not run: its parent stopped the run before this call ran.`, `its time limit`, `its token limit`), kept with the instance's stop until its next run takes it +│ │ ├── interrupts.py # What a call a cancel or a crash left open is answered with; OpenCalls (each manager's record, kept by conversation: only that conversation's turns clear it; within it by the instance whose run made each call, run=, the active run by default, so an instance's next run reads what an earlier one recorded; cancelled/take_cancel with instance=: a stopped run of an instance, whose calls a conversation's clear keeps until its next run takes the stop); forget(ref): everything of a deleted conversation, a failed turn's calls and every stop with its cause; unrecorded: a call no record holds; job_for_call: a job of the turn's conversation and of the run whose call it answers (started_by) only; fresh_call_id: the id a call whose provider reused one gets (the old one and a short suffix, `[A-Za-z0-9_-]`, at most 40 characters); `cancelled(cause=)`/`answer(cause=)`: what a call left at its prompt, or running, in a sub-agent run stopped by its parent or a limit is told stopped it (`not_run(cause)`: `Not run: its parent stopped the run before this call ran.`, `its time limit`, `its token limit`; `interrupted_by(cause)`, `INTERRUPTED_BY`: `Interrupted: its parent stopped the run before this call finished; …`), kept with the instance's stop until its next run takes it │ │ ├── config.py # AgentConfig (brief_required: the brief fields it asks a delegation to fill; limits: its own AgentLimits, over the policy's; continuable: False makes a type one-shot, closed when its run ends), AgentGraph, validate_agent_graph (rules 1-14, the first failure the most fundamental; 11-14: brief_required names brief fields, limits is an AgentLimits, continuable is True or False, the root sets none of the three) │ │ ├── agent_loader.py # load_agents_from_yaml: the framework's agent YAML → AgentConfig (unknown keys refused; brief_required, continuable, limits: {max_model_calls, timeout, max_tokens} read strictly, AgentLimits checking them); create_workflow_manager_from_yaml │ │ ├── settings.py # Workflow/tool settings schema; models, model_providers, model_roles and permissions in Annotated form (an app's override warns nothing); _merge_shipped_entries: the app's models and model_providers, then the sources', field by field, and the app's permissions before the sources' (at load only); permissions: the union of every trusted source's rules, each list concatenated, a duplicate once (_source_sections reads each source's value as the sources hook filed it) @@ -118,7 +118,7 @@ agentic-cli/ │ │ │ ├── tools.py # to_langchain_tools: a callable → StructuredTool whose .func/.coroutine is it │ │ │ ├── task_tool.py # build_task_tool: the framework's task on Deep Agents (a StructuredTool over task_parameters' JSON schema, bound to the task declaration): a call → Delegations.delegate, whose shared-key change (the outside-content mark) and envelope (JSON, the ToolMessage) come back as one Command; SHARED_KEYS; inherited_messages (an inheriting run's history: the state's messages, the summary event applied, less the message that called task); build_follow_up_tools (with follow_ups: message_agent, stop_agent, check_agents, each a StructuredTool bound to its declaration, answering as task does) │ │ │ ├── event_processor.py # DeepAgentsEventProcessor (stream → WorkflowEvent, each call's LLM_USAGE, with its latency (answer_latency), recorded in the conversation's usage ledger before on_event, a run's end with what it used; every event its processor's agent's and run's (run=: a processor for one sub-agent run, its text activity, no TASK_PROGRESS), from the root namespace's items only (a graph a tool runs streams in its own); the task call's TOOL_RESULT shown as on ADK, from its envelope: show_as_delegation); RunCallback (every model call timed, its answer marked with its latency before any middleware sees it; a summary's usage recorded in the conversation's ledger; what a node reports inside itself, through the turn's `LiveEvents`: required; `compact()` called outside a reporting context gets one nobody reads) -│ │ │ ├── sessions.py # thread_id(SessionRef), instance_thread_id and instance_run_config (a sub-agent instance's thread, [app, user, session, instance], its checkpoints' metadata carrying instance and thread_kind: instance), CheckpointSessions (instances: read from the instance threads' first input checkpoints (source input, step -1: no message in them, so the saver unpickles no transcript); stored_instances: those threads and the stored records' ids and counters; agent_records/save_agent_records/delete_agent_records: a conversation's sub-agent records, an item of the store beside the checkpointer under (agentic_cli, agents, , ), keyed by the session id; delete: those threads first, then the records, then the conversation; a first run onto a thread the store keeps fails (the manager's check); rows from an index in the store beside the checkpointer, written as a turn starts (its input counted: a killed process still lists it), then from the newest root checkpoint as it ends and after /compact; a database from before it scanned once per app and user), job notifications and notices to the root (`notice_message`, `tell_root`; `is_notice`: either, left out of recent and a row); open_sessions: a store's conversations for a reader, without the manager (empty without the checkpoints table, looked at read-only before any setup) +│ │ │ ├── sessions.py # thread_id(SessionRef), instance_thread_id and instance_run_config (a sub-agent instance's thread, [app, user, session, instance], its checkpoints' metadata carrying instance and thread_kind: instance), CheckpointSessions (instances: read from the instance threads' first input checkpoints (source input, step -1: one a thread, no later one; each holds its first run's input, which the saver decodes: the brief, and an inheriting instance's copy of its parent's conversation); stored_instances: those threads and the stored records' ids and counters; agent_records/save_agent_records/delete_agent_records: a conversation's sub-agent records, an item of the store beside the checkpointer under (agentic_cli, agents, , ), keyed by the session id; delete: those threads first, then the records, then the conversation; a first run onto a thread the store keeps fails (the manager's check); rows from an index in the store beside the checkpointer, written as a turn starts (its input counted: a killed process still lists it), then from the newest root checkpoint as it ends and after /compact; a database from before it scanned once per app and user), job notifications and notices to the root (`notice_message`, `tell_root`; `is_notice`: either, left out of recent and a row); open_sessions: a store's conversations for a reader, without the manager (empty without the checkpoints table, looked at read-only before any setup) │ │ │ ├── summarization.py # Each agent's thresholds from its budget (the manager's _budgets, given to build_agent_tree(budgets=); context_budget when none); NoArchiveBackend; history filters; compact()'s cut, summary and event (marked: the count reported before it is no trigger, _should_summarize); OverflowMapped: the summary model's overflows as ContextOverflowError, inside its retry; a request's count includes the memory index (index=) and the roster (roster=), and a summary written drops their snapshots before the request goes on (on_written=); an instance's brief (brief_message: its first run's task message, marked; is_brief, brief_of: the last marked), restated first in each summary message of its thread that stands for it (_partition_messages, _build_new_messages_with_path, per call through _BRIEF) │ │ │ ├── mcp_tools.py # MCPSessions: one owner task per (agent, server); the mcp identity map; a call fails once its session ends (_while_open: mcp's stdio client can leave one unanswered) │ │ │ └── state.py # AgentCliState: plan, tasks (last write wins), outside_content (first write wins) @@ -252,7 +252,7 @@ Workflow: ### Key Design Patterns - **Tool error handling**: All tools return `{"success": bool, ...}` dicts. Never raise `ToolError`. An exception that still escapes a tool is a bug, but it costs one call rather than the turn: on ADK, `workflow/adk/tool_error_plugin.py::ToolErrorPlugin` turns it into an error dict; on Deep Agents, `workflow/deepagents/middleware.py::ToolCallErrorMiddleware`, inside the permission gate, gives the same result, `{"success": false, "error": " failed: : "}` cut to 500 characters (both use `workflow/tool_errors.py`). A call to a tool name the agent does not have gets ADK's own text, its first two lines (`unknown_tool_result`: "nope failed: ValueError: Tool 'nope' not found." and the agent's tools by name), logged `tool_not_found` at info (the model's mistake): on ADK the permission gate lets ADK's stand-in through (`is_unknown_tool`: a bare `BaseTool` described "Tool not found", which runs nothing; contract-tested) and `ToolErrorPlugin` answers its lookup error; on Deep Agents the gate answers it. It catches `Exception`, never `BaseException`, so cancelling still cancels (google-adk 2.15 hands a cancelled call's `CancelledError` to `ToolErrorPlugin` for cleanup, ignoring the answer: it answers nothing and logs `tool_cancelled` at debug, no warning). `task` raises nothing into it: a sub-agent's model or run failing (its summary or overflow included: its own tools' errors are results already) fails the run, whose envelope its parent reads (`error`: the provider's reason; on ADK out of ADK's plugin wrapper), reported at once through the turn's live events as one recoverable `ERROR`, ` failed: `, the run's: the coordinator carries on. A sub-agent's overflow (still too long after its summary or trim) fails its run, on both backends, in the words of ADK's overflow handler, `: the request no longer fits 's context window.` with `error_code` `CONTEXT_OVERFLOW` (`context.py::subagent_overflow_message`): ADK's `OverflowPlugin` answers the run's model call with it, Deep Agents' manager raises it (`RunFailed`). A refusal is no exception here (the framework adds no `ModelRefusalMiddleware`): a sub-agent whose final answer a model refused ends its run `refused`, and its parent reads, as its envelope's result, Deep Agents 0.7.34's notice ("The subagent stopped because a model refused the request. … Retrying the same request is unlikely to succeed; rephrase it or continue without it."), on both backends and whichever deepagents the pin installs (0.7.28 has no notice of its own; 0.7.34+ finds no refusal block left to word again); an answer cut at the output limit keeps its text, followed by `[cut off at the output limit]`, and its run ends `completed` and `partial`, with one recoverable warning ("'s answer was cut off at the output limit"); the answer's thoughts or reasoning are kept. ADK's `SubAgentOutcomePlugin` and Deep Agents' `SubAgentOutcomeMiddleware` rewrite and mark the answer, by `workflow/agents/outcome.py`. On ADK the plugin reads the answer's `finish_reason` (Claude's `refusal` and a Chat Completions `content_filter` arrive as `SAFETY`, `max_tokens` and `length` as `MAX_TOKENS`, Gemini's as themselves), the `error_code` ADK sets on an answer with no content (a Gemini prompt's `block_reason`), the `reason` an `OTHER` stop names in its JSON error message (ADK's OpenAI Responses adapter's `incomplete_details`, `content_filter` among them) and a text part `OpenAI refusal: ` (that adapter's refusal, and `OpenAICompatibleLlm`'s of a Chat Completions `refusal`, which ADK's class drops). On Deep Agents the middleware reads `response_metadata`'s `stop_reason` (ChatAnthropic), `finish_reason` (ChatOpenAI, ChatGoogleGenerativeAI), `incomplete_details.reason` (the Responses API) and `prompt_feedback.block_reason` (a Gemini prompt block), and a refusal the answer holds (a refusal block, standard or `non_standard`, or `additional_kwargs["refusal"]`). The root's own answers reach the user as their model gave them: on ADK a root's refusal with no answer (Claude's, Gemini's) is still the turn's one `ERROR` (" returned no answer"), and a root on OpenRouter or an OpenAI-compatible server replies "OpenAI refusal: ". On both backends the root's own failure leaves the run: the turn's one `ERROR`. A gate or error result goes back as the call's `ToolMessage` with `status="error"`. LangGraph's `ToolNode` runs with `handle_tool_errors=True`. -- **Tool result cap**: every tool result passes `workflow/tool_output.py::cap_tool_result` (registered, MCP and skill tools, `job_result`, a delegation's envelope on either backend): one over `tool_result_max_chars` is cut to its shape and as much of its head and tail as fits (the kept length is bisected, since JSON escapes vary), with a note (under `truncated`, or appended to a string) pointing at its full output in `./.{app_name}/tool-output/`, written for `read_file` to page by lines (lines over 2,000 characters split). A string that holds a JSON object (`json_object`: a delegation's envelope, which both task tools write unescaped, `ensure_ascii=False`; a framework tool's dict in a Deep Agents `ToolMessage`) is cut as that dict and given back as its JSON text, so the parent reads JSON still, on both backends. On ADK, `workflow/adk/tool_result_cap_plugin.py::ToolResultCapPlugin` is registered after `InterruptedCallsPlugin`, since ADK stops at the first `after_tool_callback` that returns a value, and it leaves out an agent with `after_tool_callback`s of its own (a native YAML app's, `build.own_after_tool_agents`), which ADK would skip once the cap answered. ADK's Claude and OpenAI Responses adapters send only a result's `content`, else its `result`, so the plugin also puts the note there (`_note_where_sent`). On Deep Agents, `ToolResultCapMiddleware` sits between the permission gate and `ToolCallErrorMiddleware`, so an error result is capped too, and reads a `ToolMessage` (its text cut by the cap's string rule, text blocks joined into the first) and each `ToolMessage` of a `Command`. A call of the framework's `read_file` (by identity, as each gate resolves tools) on a saved output is cut without a second save. Saving never fails the call (`tool_output_not_saved` warns once per folder, then debug), and a cap that raises leaves the result uncut (`tool_result_cap_failed` at warning, its traceback at debug). +- **Tool result cap**: every tool result passes `workflow/tool_output.py::cap_tool_result` (registered, MCP and skill tools, `job_result`, a delegation's envelope on either backend, and the envelope a view's notice carries: `BaseWorkflowManager._user_ran` keeps `instance_result` capped): one over `tool_result_max_chars` is cut to its shape and as much of its head and tail as fits (the kept length is bisected, since JSON escapes vary), with a note (under `truncated`, or appended to a string) pointing at its full output in `./.{app_name}/tool-output/`, written for `read_file` to page by lines (lines over 2,000 characters split). A string that holds a JSON object (`json_object`: a delegation's envelope, which both task tools write unescaped, `ensure_ascii=False`; a framework tool's dict in a Deep Agents `ToolMessage`) is cut as that dict and given back as its JSON text, so the parent reads JSON still, on both backends. On ADK, `workflow/adk/tool_result_cap_plugin.py::ToolResultCapPlugin` is registered after `InterruptedCallsPlugin`, since ADK stops at the first `after_tool_callback` that returns a value, and it leaves out an agent with `after_tool_callback`s of its own (a native YAML app's, `build.own_after_tool_agents`), which ADK would skip once the cap answered. ADK's Claude and OpenAI Responses adapters send only a result's `content`, else its `result`, so the plugin also puts the note there (`_note_where_sent`). On Deep Agents, `ToolResultCapMiddleware` sits between the permission gate and `ToolCallErrorMiddleware`, so an error result is capped too, and reads a `ToolMessage` (its text cut by the cap's string rule, text blocks joined into the first) and each `ToolMessage` of a `Command`. A call of the framework's `read_file` (by identity, as each gate resolves tools) on a saved output is cut without a second save. Saving never fails the call (`tool_output_not_saved` warns once per folder, then debug), and a cap that raises leaves the result uncut (`tool_result_cap_failed` at warning, its traceback at debug). - **Summarizing on ADK (main agent only)**: every app's App (a native ADK YAML app's too, when its root's model has a context budget) has ADK's `EventsCompactionConfig` with `workflow/adk/compaction.py::AgentCliSummarizer` at the root's trigger (`context_budget`, as on Deep Agents); ADK checks before every agent's model call, and `MainAgentPlugin` (the first plugin) records the running agent in a ContextVar, so the summarizer writes only for the root (a sub-agent's run, on its type's runner, has no compaction config at all: a sub-agent compacting the shared session lost its brief and looped, 100 requests in one turn, offline). The summarizer picks its own range before paying for anything (`summary_range`: the newest `keep` tokens and the current turn kept, a cut only where a user turn starts, never parting a call from its result, long-running calls excepted since ADK re-injects them, nor leaving a kept event stamped inside the range; none for a saving under 20% of the trigger, the seed left out of it), writes on the root's own model (`_simple_model(SUMMARY_MAX_TOKENS, agent=root)`, thinking off) with `workflow/summary_prompt.py`, the rendering sized to that model's window (the middle cut, `MIDDLE_OMITTED`, the seed kept whole), and returns **user-role** text starting `SUMMARY_PREFIX` (a model-role first message is one Claude refuses), which the fit guard folds, after the memory index and the roster when the request has them, into the next user text (`fold_summary`), so no request holds two user messages in a row. `last_kept_turns` and `last_error` are for its callers: a manual summarizer warns of nothing itself. It reports through the turn's live events (`_run_and_stream` iterates the runner through `live_events.merged` under `reporting(live)`); any failure is one recoverable `ERROR` a turn, never raised to ADK. `NoAfterTurnCompactionRunner` overrides ADK's private `Runner._run_post_invocation_compaction` (contract-tested), so the prompt never waits for a summary after the answer. `FitGuardPlugin` is the last plugin (but `SentRequestLoggingPlugin`, which logs a request as sent, and `CallSentPlugin`, which starts the call's clock) and `OverflowPlugin` the one before it (`MemoryIndexPlugin`, when the root has a memory tool and `memory_index_enabled` is on, the one before that: it puts the conversation's memory index snapshot first in the root's requests, never in the session): the guard leaves a request's oldest turns out when it is over its agent's budget (keeping the newest turn and what opens the conversation, the memory index, the roster of the root's open sub-agents (`RosterPlugin`, before `MemoryIndexPlugin`, for a root with `message_agent`), then a summary: `protected_head`; in a sub-agent type's chain also the run's task message and its instance's brief, `brief_of`) and keeps each request as it came in (`request_as_seen`: one copy per model call, under the call's `EventActions`, which ADK passes to all three of its callbacks: each sub-agent run is an invocation of its own on a child session, but two runs of one type share that type's runner and its plugins, and a run drops only what its own cancelled calls left, as it ends), and the overflow handler, on a provider's overflow, summarizes now (the root, through `compact_session`, ADK's private `_run_compaction_for_token_threshold_config`; `_summarize_now` returns `WrittenSummary(text, kept_turns)`, and the retry is the index, the roster, the summary and those turns) or trims to half the budget (a sub-agent, or nothing to summarize), builds the retry from the guard's copy without the context cache, retries once on the agent's `canonical_model`, then answers the root with `LlmResponse(error_code="CONTEXT_OVERFLOW")`, never model text (ADK would store it as the reply), which `ADKEventProcessor` maps to the turn's `ERROR`; a retry that fails otherwise propagates, and `_run_and_stream` unwraps ADK's plugin-manager `RuntimeError` to the provider's error; a sub-agent's call that still does not fit is answered with an error response too, `CONTEXT_OVERFLOW` and `subagent_overflow_message`, which its run's processor keeps as the run's failure: the run ends `failed` with those words (`RunFailed`), its parent reads them in the envelope, and the user is warned once, by the framework's delegation (`agents/delegate.py`), as on Deep Agents. A native ADK YAML app gets all of it: only the building of its agents differs (`workflow/adk/build.py`). Its chat-mode sub-agents keep transferring, and an agent the root transfers to replies to the user (`build.reply_agents`: its text is the reply, recent_messages reads it, its overflow is the turn's clear error, its calls write the outside-content mark); the summary and the memory index stay the root's, so such an agent is trimmed by the fit guard, not summarized. An agent's own callbacks (a native app's) run after every plugin, and only when none answered: its before-model callbacks see the request after the fit guard, and the cap leaves out an agent with after-tool callbacks. A main agent whose model does not resolve through the catalog has no budget and no summary. - **Sub-agents delegate and return**: on both backends a sub-agent run is a call of its parent's `task` tool (the framework's: `tools/_core/delegation.py` declares it, `workflow/agents/delegate.py` runs it) that returns in the same turn; only the root replies to the user (a sub-agent's `TEXT` carries `metadata["subagent"]`, and the CLI shows it as the events box's status line, under its run's name: `researcher-2 › …`; `/agents` picks among a conversation's instances), and the next turn starts at the root; fact extraction reads only the user's and the root's text. `task` takes `agent_type` (one of the 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. @@ -268,7 +268,7 @@ Workflow: - **HITL callback is context-local**: `set_input_callback()` stores into a per-manager `ContextVar`, so a second consumer installing its callback cannot capture a running turn's prompt, and one consumer's `clear_input_callback()` cannot unregister another's. `MessageProcessor` cancels and awaits its consumer task **before** clearing the callback, so no tool is left asking a question nobody owns. And the callback answers only inside its turn: a task a turn started (`asyncio.create_task` copies the context, the callback with it) that asks after the turn ended gets `UserInputUnavailable` (`request_user_input`; the turn's span, `workflow/sessions.py::open_turn_scope`/`close_turn_scope`, opened and closed by `_workflow_context`, which the copy carries), as with no approver: a question goes unanswered and a permission ASK is denied by the engine's no-approver rule. - **Code that may run on the host is approved per call**: CPython has no in-process sandbox, so `execute_python` runs inside the OS sandbox or not at all by default (`os_sandbox_strict` true: no backend, a failed wrap, or a sandbox tool that fails as it starts (the runner's first stderr line, `_STARTED_MARKER`, never came) is a refusal that keeps its cause and ends with `executor.how_to_run`: sandbox-exec, bwrap and Ubuntu 24.04's user namespaces, none on Windows, and the opt-out where it lives, `exec_policy.sandbox_opt_out`: `~/.{app_name}/settings.json` or the env variable, since the project file and `/settings` cannot set it), and the module set is chosen from the path a call takes (`executor.py::_choose_run`, then `validate_code(allowed_modules=)`). The engine never imports `tools/`: `BaseWorkflowManager` passes `PermissionEngine(uncontained=tools.exec_policy.uncontained_exec_capabilities)`, called with the settings at each check (a settings change applies at once). For a capability it names, `engine.unstorable_reason` is `UNCONTAINED` (the one decision, shared with the prompt: only "Allow once" and "Deny", with its note), and `_evaluate` skips allow rules from grants (`SESSION`, and `PROJECT`, the user's `project_grants.json`), so a grant from when the code ran contained approves nothing; a `USER` rule still applies. A prompt for `*.exec` shows all of the code (the dialog body scrolls). - **No harness-level turn replay**: ADK persists a turn's input during invocation setup, and Deep Agents' checkpointer at the turn's first step, so the CLI never re-invokes an event source. Retries belong to the provider client (`HttpRetryOptions`). `MessageProcessor` returns a typed `TurnResult`. A turn that fails yields one `ERROR` and returns, on both backends (the base `process()`'s contract; `WorkflowEvent.turn_failed`: the error's text, `rate_limited`, `error_type`); an `ERROR` the turn already yielded that is not recoverable is its one; a cancel still raises, and a turn that cannot start (initialization, admission, or its conversation cannot be read) raises before any event. The CLI says a rate limit from the event as it does from a manager that raises. -- **Interrupted calls**: Ctrl+C stops the whole turn (loop, model calls, tools, sub-agents), and every call the model made gets exactly one result (`workflow/interrupts.py`, the texts and `OpenCalls`, each manager's record, kept by conversation and by the instance whose run made each call (the root's own, or a sub-agent's, so its next run reads what an earlier one left: a provider that numbers its call ids per agent gives a sub-agent's call its parent's delegation's id): a call's result as it finished, a call `asking` at its permission prompt, both gates marking it; a conversation whose turn the user cancelled): a finished call keeps its result, a running one or a delegation is `INTERRUPTED_BY_USER`, one at its prompt `NOT_RUN`, one whose job was submitted the job's state (`job_started`); a cancel with no call open leaves `MARKER` as the main agent's reply; a call nothing answered (a crash, an old session) is `INTERRUPTED`. All of it pairs a result with its call by id, as the providers do, so a call id the agent's conversation already holds (a provider that numbers its ids per response, `call_0` in every one) is renamed as the model's answer arrives, `fresh_call_id`, before it is stored or run (ADK: `InterruptedCallsPlugin.after_model_callback`, the session's events the agent sees; Deep Agents: `InterruptedCallsMiddleware.awrap_model_call`, the agent's whole state), and a conversation stored with an id twice is paired by position. On ADK the turn runs with `abort_signal`, set by `live_events.merged(on_stop=)` before the runner is cancelled, so ADK seals the invocation in its own branches; `merged` waits for its source to close, a repeated cancel too (up to `STOP_GRACE`), and `process()`/`resume_with_job_result()` close their inner generators with `aclosing`, so a run never outlives its turn. `adk/interrupted_calls_plugin.py::InterruptedCallsPlugin` (before `ToolResultCapPlugin`, every app) sets the active tool call around each call (`before_tool_callback`, so a question marks it `asking`), records results with their `state_delta`/`artifact_delta` in `after_tool_callback` (not a long-running starter's `None`: its job answers it), keeps the cap's cut of one (`ToolResultCapPlugin.on_cut`, so a seal sends that cut and its full output is saved once) and rewrites the seals (`error_code` `INVOCATION_ABORTED`, contract-tested) in `on_event_callback`, carrying those deltas, each seal answered from the record of the active run (a sub-agent run's runner stops, and seals its child session, in the run's own task; a follow-up answers what is left open there before its message, `left_open_by`, and on Deep Agents `InterruptedCallsMiddleware.before_agent` answers an instance's calls on its thread as its next run starts, as the user's when that run was stopped: `cancelled(instance=)`). ADK's seals pair a result with a call by id alone, so a call whose id another call's result used, on another branch of the session (a native ADK YAML app's agents), is left open: the manager answers those as the stopped turn ends, before it clears the record, the same way (`_answer_unsealed`, shielded; `unsealed`, once ADK's seals are written), so a call that finished keeps its result. `left_open` answers leftovers when `process()` starts (every app: a task-mode agent's delegation, which ADK keeps open on purpose, is refused at build, and ADK's client calls for a human, `adk_request_confirmation`/`_credential`/`_input`, are answered as interrupted, since the manager offers no way to answer them), a result pairing with a call on its own branch only; one a stop left because its answers could not be written is answered `INTERRUPTED_BY_USER` (the manager records the stop). A turn that fails (its one `ERROR`) keeps the record of its calls that returned (`OpenCalls.failed`), on both backends: ADK stores a step's parallel results together, after the last, and Deep Agents' graph drops a failed step's writes, so a call that returned beside one the failure stopped is answered at the next turn with its result and the state it changed (ADK: `left_open`, the root's own calls, the record forgotten once its answers are stored), any other `INTERRUPTED`. On Deep Agents `InterruptedCallsMiddleware` takes `PatchToolCallsMiddleware`'s place, first in every stack: it records each final `ToolMessage` with the rest of its `Command` update (outermost tool wrapper) and answers open calls in `before_agent`, returning those updates too; the root adds `MARKER` before the new input when the message before it is no reply (a `HumanMessage` or a tool result). Background jobs are not part of the turn: they keep running. Nor is a synchronous tool's function (a sandbox cell, `compile_document`, `execute_python`): it runs in a worker thread on both backends (ADK's tool thread pool, LangChain's executor), which Python cannot stop, so its call is answered at once but the function runs on to its end, keeps its sandbox session busy (the session's next call waits for it) and holds the process's exit until it returns (the sandbox's cleanup stops a cell). So is a knowledge-base ingest's store step (`kb_ingest_text`, `kb_ingest_file`, `ingest_arxiv_paper`: `KnowledgeBase._store` runs `ingest_document` in `asyncio.to_thread`): a cancelled ingest is answered `INTERRUPTED_BY_USER` and still stores its document, so a model that retries it stores a second copy; a cancelled `sidecar` or `backfill_sidecars` keeps its lock or flag until its thread's call ends (`memory/kb/manager.py::_Threads`). A call a sub-agent run left at its permission prompt is `NOT_RUN` for the user's stop, but `not_run(cause)` (`Not run: its parent stopped the run before this call ran.`, or `its time limit`, `its token limit`) when its parent or a limit stopped the run: ADK words it at the seal (`InterruptedCallsPlugin(stop_cause=)`), Deep Agents records the cause with the instance's stop (`OpenCalls.cancelled(..., cause=)`). +- **Interrupted calls**: Ctrl+C stops the whole turn (loop, model calls, tools, sub-agents), and every call the model made gets exactly one result (`workflow/interrupts.py`, the texts and `OpenCalls`, each manager's record, kept by conversation and by the instance whose run made each call (the root's own, or a sub-agent's, so its next run reads what an earlier one left: a provider that numbers its call ids per agent gives a sub-agent's call its parent's delegation's id): a call's result as it finished, a call `asking` at its permission prompt, both gates marking it; a conversation whose turn the user cancelled): a finished call keeps its result, a running one or a delegation is `INTERRUPTED_BY_USER`, one at its prompt `NOT_RUN`, one whose job was submitted the job's state (`job_started`); a cancel with no call open leaves `MARKER` as the main agent's reply; a call nothing answered (a crash, an old session) is `INTERRUPTED`. All of it pairs a result with its call by id, as the providers do, so a call id the agent's conversation already holds (a provider that numbers its ids per response, `call_0` in every one) is renamed as the model's answer arrives, `fresh_call_id`, before it is stored or run (ADK: `InterruptedCallsPlugin.after_model_callback`, the session's events the agent sees; Deep Agents: `InterruptedCallsMiddleware.awrap_model_call`, the agent's whole state), and a conversation stored with an id twice is paired by position. On ADK the turn runs with `abort_signal`, set by `live_events.merged(on_stop=)` before the runner is cancelled, so ADK seals the invocation in its own branches; `merged` waits for its source to close, a repeated cancel too (up to `STOP_GRACE`), and `process()`/`resume_with_job_result()` close their inner generators with `aclosing`, so a run never outlives its turn. `adk/interrupted_calls_plugin.py::InterruptedCallsPlugin` (before `ToolResultCapPlugin`, every app) sets the active tool call around each call (`before_tool_callback`, so a question marks it `asking`), records results with their `state_delta`/`artifact_delta` in `after_tool_callback` (not a long-running starter's `None`: its job answers it), keeps the cap's cut of one (`ToolResultCapPlugin.on_cut`, so a seal sends that cut and its full output is saved once) and rewrites the seals (`error_code` `INVOCATION_ABORTED`, contract-tested) in `on_event_callback`, carrying those deltas, each seal answered from the record of the active run (a sub-agent run's runner stops, and seals its child session, in the run's own task; a follow-up answers what is left open there before its message, `left_open_by`, and on Deep Agents `InterruptedCallsMiddleware.before_agent` answers an instance's calls on its thread as its next run starts, as the user's when that run was stopped: `cancelled(instance=)`). ADK's seals pair a result with a call by id alone, so a call whose id another call's result used, on another branch of the session (a native ADK YAML app's agents), is left open: the manager answers those as the stopped turn ends, before it clears the record, the same way (`_answer_unsealed`, shielded; `unsealed`, once ADK's seals are written), so a call that finished keeps its result. `left_open` answers leftovers when `process()` starts (every app: a task-mode agent's delegation, which ADK keeps open on purpose, is refused at build, and ADK's client calls for a human, `adk_request_confirmation`/`_credential`/`_input`, are answered as interrupted, since the manager offers no way to answer them), a result pairing with a call on its own branch only; one a stop left because its answers could not be written is answered `INTERRUPTED_BY_USER` (the manager records the stop). A turn that fails (its one `ERROR`) keeps the record of its calls that returned (`OpenCalls.failed`), on both backends: ADK stores a step's parallel results together, after the last, and Deep Agents' graph drops a failed step's writes, so a call that returned beside one the failure stopped is answered at the next turn with its result and the state it changed (ADK: `left_open`, the root's own calls, the record forgotten once its answers are stored), any other `INTERRUPTED`. On Deep Agents `InterruptedCallsMiddleware` takes `PatchToolCallsMiddleware`'s place, first in every stack: it records each final `ToolMessage` with the rest of its `Command` update (outermost tool wrapper) and answers open calls in `before_agent`, returning those updates too; the root adds `MARKER` before the new input when the message before it is no reply (a `HumanMessage` or a tool result). Background jobs are not part of the turn: they keep running. Nor is a synchronous tool's function (a sandbox cell, `compile_document`, `execute_python`): it runs in a worker thread on both backends (ADK's tool thread pool, LangChain's executor), which Python cannot stop, so its call is answered at once but the function runs on to its end, keeps its sandbox session busy (the session's next call waits for it) and holds the process's exit until it returns (the sandbox's cleanup stops a cell). So is a knowledge-base ingest's store step (`kb_ingest_text`, `kb_ingest_file`, `ingest_arxiv_paper`: `KnowledgeBase._store` runs `ingest_document` in `asyncio.to_thread`): a cancelled ingest is answered `INTERRUPTED_BY_USER` and still stores its document, so a model that retries it stores a second copy; a cancelled `sidecar` or `backfill_sidecars` keeps its lock or flag until its thread's call ends (`memory/kb/manager.py::_Threads`). A call a sub-agent run left at its permission prompt is `NOT_RUN` for the user's stop, but `not_run(cause)` (`Not run: its parent stopped the run before this call ran.`, or `its time limit`, `its token limit`) when its parent or a limit stopped the run, and a call it left running `INTERRUPTED_BY_USER`, or `interrupted_by(cause)` (`Interrupted: its parent stopped the run before this call finished; …`): ADK words them at the seal (`InterruptedCallsPlugin(stop_cause=)`), Deep Agents records the cause with the instance's stop (`OpenCalls.cancelled(..., cause=)`). - **Session identity**: durable sessions are addressed by `SessionRef(app_name, user_id, session_id)` (`workflow/sessions.py`). Every session hook (`session_exists`/`list_sessions`/`session_info`/`delete_session`/`recent_messages`/`load_session`) takes an optional `user_id`, defaulting to `settings.default_user` only when the caller omits it. `list_sessions(limit=)` returns `SessionInfo` rows, newest first, and `session_info` one conversation's or None: the title is the first prompt (`session_title`), the turns what the user typed (a job's notice or resume, a delegated request and a summary are none), `updated` when it last changed. ADK keeps the title and the turns in two session-state keys saved with each user turn (`workflow/adk/sessions.py`, `run_async(state_delta=)`; a conversation from before them is read from its events and never written back, which would move it in the list), Deep Agents keeps them in a session index, a LangGraph store beside the checkpointer (`workflow/deepagents/sessions.py`: each row written as a turn starts, its input counted, then from the newest root checkpoint as it ends and after `/compact`, so a listing reads no checkpoint; a database from before the index scanned once per app and user), LangGraph knows only the id; ADK's `delete_session` looks the session up first, so an unknown id is False. ADK keeps each sub-agent instance's transcript, which its follow-ups continue, in a child session of its conversation (`adk/sessions.py`: app `child_app(app_name)`, `--agents`, id `/`, the conversation id's `%` and `/` percent-encoded, the conversation's user), under an app no listing reads, so none lists or opens as a conversation (`list_sessions`, `session_info`, `session_exists`, a reader's, the CLI's look, `--continue`; `recent_messages` reads the conversation's own session); `ServiceSessions.delete` (the manager's `delete_session` and a reader's, so `/sessions --delete` and the memory store's `/new` too) deletes them, events and all, before the conversation's records and the conversation itself, whatever its look found (`delete_children`: the instances its records name, else every child id whose decoded conversation it is, `child_of`). Instances are numbered per manager, so a manager numbers a conversation's past the ones its store keeps (`_stored_instances`, the highest number of each type, read from the child session ids; `Delegations` asks it once per conversation per turn, before the turn's first run, and again after an ask that failed: another process may have run the conversation between two turns; `AgentRuns.number_from`, which never lowers a count): after a restart, a switch of backend or store, or another process's turns, the next run is never a second `researcher-1` (a model switch keeps the manager, and its numbering), and a stored transcript is never replaced (ADK's `create_session` refuses its id: the run fails). Deep Agents keeps each instance's transcript in a checkpointer thread of its own (`instance_thread_id`: `[app, user, session, instance]`, its checkpoints' metadata carrying `instance` and `thread_kind`, no conversation list reading it), so its manager numbers past the stored instances from those threads and the conversation's records (`_stored_instances`), and a first run refuses a thread the store keeps. Backends without a session store leave `supports_sessions` False, and the base hooks raise `NotImplementedError` rather than answering with a misleading `False`/`[]`. Deep Agents keys each conversation's checkpointer thread by the whole triple (`workflow/deepagents/sessions.py::thread_id`, `json.dumps([app_name, user_id, session_id])`) and stores it in each checkpoint's metadata, so the backfill's scan filters by app and user and keeps the root namespace; every agent is compiled on the manager's checkpointer, a sub-agent's runs on its instance's thread, and `delete_session` deletes the instances' threads before the conversation's records and its thread, whatever else it finds (an older version's sub-agent checkpoints sit under `tools:`, and `delete_session` removes them with the thread and the row, returning False for an unknown id). A conversation's sub-agent records (`AgentRuns.export`: its instances, its runs with their briefs, envelopes and tokens by model, its id counters) are kept beside it, written as each run event changes them (`agents/records.py::RecordsWriter`, through the base's `_save_agent_records`): on ADK in the child app's session named as the conversation, encoded (`records_session_id`; `RECORDS_KEY`, a session of its own since ADK takes no second writer on the conversation's while a turn runs; a first run's start is written before its child session is made, so the records name every transcript, and the children are found by them), on Deep Agents an item of the store beside the checkpointer (`("agentic_cli", "agents", , )`, keyed by the session id); the memory store keeps them for the process. They load with the conversation (`load_agents`: `load_session`, a turn's start, `/agents`), a run found working read `interrupted` and its instance `idle`, numbering from their counters (on Deep Agents with the instance threads' as a floor, ADK's from the instances they name, the store refusing a first run onto a transcript they missed); a delete removes them after the transcripts and before the conversation, and the manager forgets the conversation (`_deleting`). A backend's conversations are read without its manager through its `SessionReader` (`workflow/session_readers.py::open_session_reader`: the backend's own session code over its store, opened from the settings), so the CLI lists, opens and deletes the conversations of every installed backend (`cli/stored_conversations.py`): each row names its backend (`SessionInfo.backend`), and a conversation another backend keeps opens there (no index joins the stores, and an id two backends keep is two conversations). - **Active turn**: the in-flight `(user, session)` is a `ContextVar` (`workflow/sessions.py::get_active_turn`), set with a token by `_workflow_context()`, which every turn enters through `_turn()` — concurrent turns on one manager stay isolated and nesting restores the outer turn. The tool call in progress is another (`get_active_tool_call()`, a `ToolCallRef(call_id, name)`), set by Deep Agents' `ActiveToolCallMiddleware`, innermost in the tool stack (after the gate and the error middleware, so only a call the gate let through runs as one); on ADK, `InterruptedCallsPlugin.before_tool_callback` sets it around each call (ADK's stand-in for an unknown tool name excepted) and its `after_tool_callback` resets it. The sub-agent run in progress is a third (`get_active_run()`, a `RunRef`; None in the root's own calls), set by `Delegations.delegate` in the run's own task (`workflow/agents/delegate.py`), on both backends, where the run's runner or graph runs (with no tool call active there): a sub-agent's model calls, tool calls, permission checks and questions see it. `JobManager.submit(resume_on_complete=True)` takes `call_id` from the active tool call when the tool passed none, and `call_name` when that is None too; every `submit` records the sub-agent run in progress as the job's `started_by` (`instance_of(get_active_run())`). - **Job notifications**: both backends tell a finished job through the base's `resume_with_job_result` (a template: the record names its conversation, a turn of it (`_turn`), the conversation there (`_conversation_exists`), the job's result read on a worker thread (`JobManager.result` takes the jobs directory's cross-process lock), the notice `job_notice`, told by the backend's `_deliver_job_notice`; `can_resume` makes the same checks without the turn), and the CLI resumes where `supports_job_resume` and `can_resume` say so. On ADK a finished job is told to the conversation (the root, or a native app's agent the root transferred it to) as one user-role text, `tools/jobs/resume.py::job_notice` (the Deep Agents notice below), whoever started it: its call already has a result (the root's "pending", or a sub-agent's job id), and a second result for the call itself made ADK's rearranger send the call, that result and nothing between, so the root answered without the turns since. A native ADK YAML app's job is told the same way (it used to answer its pending call as a `FunctionResponse`, and needed `record.call_id`); a call still open (a starter that returned nothing) is answered first (`_answer_left_open`). A sub-agent's long-running tools are not wrapped (`_build_agent` wraps the root's only): ADK pauses the whole invocation on a pending long-running call, inside a delegation too, so a sub-agent's starter returns the job id as an ordinary result. ADK's `recent_messages` leaves the notice out by its header, since ADK keeps no mark on a message. The CLI delivers only the jobs that wait for the current conversation, by one rule (`cli/waiting_jobs.py`) for the deliveries, the status bar's `↻N` and the line startup says: a finished job flagged `resume_on_complete` whose delivery is still `PENDING` (`JobRecord.awaiting_resume`: not one being delivered), that is this conversation's, or has none, or whose conversation is gone, `can_resume` saying so and no other installed backend's store keeping it (`waiting_jobs.opens_anywhere`, `BaseCLIApp._kept_elsewhere`) (those two told it is unavailable): another conversation's waits until it is opened, `/resume` (`resume_session`) telling them when `job_auto_resume` is on, startup only naming them (`_name_its_waiting_jobs`: outside the input handler Ctrl+C cannot stop a turn); the status bar's `↻N` counts them whatever the setting (`↻N: /jobs resume` when it is off; its `can_resume` answers kept 30 s, forgotten after `/sessions --delete`, a conversation `/new` drops on the memory store, or a new conversation on another backend). On Deep Agents a finished job's result cannot be the pending call's second result (the call already has its `pending` one, and Anthropic and OpenAI take one result per call), so `resume_with_job_result` runs a turn whose input is one `HumanMessage`: `tools/jobs/resume.py::JOB_NOTICE_HEADER`, the ask (`job_notice_ask`: for the root's own job `JOB_NOTICE_ASK`, tell the user what it means: without it a model may say nothing; for a sub-agent's, `JOB_NOTICE_ASK_FOR`, the same ask naming the sub-agent), then `job_result_payload(record, result)` as JSON, a line each (`job_notice`), marked `response_metadata={"agentic_cli": {"kind": "job_result", "job_id": ...}}` (`workflow/deepagents/sessions.py::job_notification`). No provider adapter sends that field; `recent_messages`, and so fact extraction, leaves the message out; the checkpoint keeps it for the model. The root agent receives every job, a sub-agent's too (its run ended when its `task` returned), and the notice names the sub-agent whose call started it (`JobRecord.started_by`, its instance, from the active run at submit; `job_notice_ask`: "A background job researcher-2 started has finished…", the root's own `JOB_NOTICE_ASK`). `can_resume` needs the record's session and user and the conversation's thread, not a call id. diff --git a/README.md b/README.md index 3dd2813c..bc8a4828 100644 --- a/README.md +++ b/README.md @@ -283,6 +283,16 @@ before `super().__init__()`, as `self.verbose` is above. A command registered later (`app.command_registry.register(...)`) completes and is listed by `/help` too. +The session's six dialog methods (`show_dialog`, `yes_no_dialog`, +`message_dialog`, `choice_dialog`, `dropdown_dialog`, `checklist_dialog`) +take one lock, wrapped as the session is assigned, so one dialog opens at a +time: a command's dialog and a question of a run in a sub-agent's view wait +for each other, where thinking-prompt raises on a second, and a task may open +one inside its own (a dialog that waits on one it opened from another task +waits for ever). An app keeps that by assigning a session of its own through +`self.session`, not as a class attribute with a value, which replaces the +property and leaves its dialogs unwrapped. + The session draws in `get_theme(name)` for the user's `ui_theme` (see [Theme and dialog placement](#theme-and-dialog-placement)): `dark` unless they chose another, which is thinking-prompt's dark theme in agentic-cli's colors. @@ -1436,7 +1446,9 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", manager's entry points (provisional, on the open conversation, any of its sub-agents): `run_instance(id, message)` (a turn of its own, counted toward no turn's runs; stopping the stream is your stop of the run), - `stop_instance(id)`, `close_instance(id)`, `steer_instance(id, message)`, + `interrupt_instance(id)` (that run ends `interrupted`, as at a process + exit, not your stop), `stop_instance(id)`, `close_instance(id)`, + `steer_instance(id, message)`, `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). @@ -1447,12 +1459,16 @@ reviewer = AgentConfig(name="reviewer", prompt="Check what was said.", 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 + run (it is then `stopped`; your next line continues it); `/exit` while it + works interrupts it, as quitting the app does, and leaves it `idle`, its + parent free to continue 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). + The run's questions and a command's dialogs open one at a time, each + waiting for the other ([Customizing the CLI](#customizing-the-cli)). - **What the agent graph refuses.** `inherit_context` is for sub-agents only, and only for the main agent's own sub-agents that have none of their own. A coordinator cannot have a tool of its own named `task` (nor, with diff --git a/src/agentic_cli/cli/agent_view.py b/src/agentic_cli/cli/agent_view.py index 063240aa..a4f86fd6 100644 --- a/src/agentic_cli/cli/agent_view.py +++ b/src/agentic_cli/cli/agent_view.py @@ -17,8 +17,10 @@ input handler: thinking-prompt takes no line while a handler runs, so the 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. +``stopped``). The app's exit interrupts a run still working +(``AgentView.interrupt``), as a process exit interrupts any run: no stop of +the user's, so the instance stays ``idle``. A closed instance's view is +read-only: no prompt, and a line typed there is refused. ``/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 @@ -280,6 +282,29 @@ def stop(self) -> bool: run.cancel() return bool(working) + def interrupt(self) -> bool: + """Interrupt the run in view, as a process exit does: no stop of the user's. + + The manager ends it as a turn's cancel (``interrupt_instance``): the + run ``interrupted``, the instance ``idle``, so its parent may continue + it. A line waiting to run is cancelled before it starts. Whether one + was working; ``settled`` waits for it. + """ + working = [run for run in self._runs if not run.done()] + if not working: + return False + try: + self.app.workflow.interrupt_instance( + self.instance, + session_id=self.conversation.session_id, + user_id=self.conversation.user_id, + ) + except (RuntimeError, AttributeError): + pass # no workflow runs: no run of it works + for run in working: + run.cancel() + return True + async def settled(self) -> None: """Wait until no run the user started here works (none is stopped).""" while self._runs: diff --git a/src/agentic_cli/cli/app.py b/src/agentic_cli/cli/app.py index bf31b71e..08045c34 100644 --- a/src/agentic_cli/cli/app.py +++ b/src/agentic_cli/cli/app.py @@ -2348,7 +2348,7 @@ async def handle_input(text: str) -> None: # Ctrl+C stops the run in a sub-agent's view, which works outside # 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. + # and the run goes on, until /exit interrupts it or it ends. if not bind_ctrl_c(self.session, lambda: self._agent_view): logger.info("agent_view_ctrl_c_not_bound") @@ -2365,12 +2365,14 @@ 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). + # A view's run still working is interrupted, as a process + # exit interrupts any run: only Ctrl+C in a view is the + # user's stop, so the sub-agent stays idle and its parent + # may continue it. It ends before the workflow goes (whose + # cleanup waits for that turn), so its turn records it. view = self._agent_view if view is not None: - view.stop() + view.interrupt() await view.settled() # Propose memories from the session (if enabled) while the workflow diff --git a/src/agentic_cli/workflow/adk/interrupted_calls_plugin.py b/src/agentic_cli/workflow/adk/interrupted_calls_plugin.py index aa26f366..4256127b 100644 --- a/src/agentic_cli/workflow/adk/interrupted_calls_plugin.py +++ b/src/agentic_cli/workflow/adk/interrupted_calls_plugin.py @@ -8,9 +8,9 @@ This plugin rewrites them as ``workflow/interrupts.py`` says: a call that finished keeps its result (ADK stores parallel calls' results together, after the last, so the finished one would be lost), a call at its -permission prompt was not run (in a sub-agent run its parent or a limit -stopped, the seal says which: ``stop_cause``), a call whose job was -submitted runs on, and any other was interrupted by the user; the +permission prompt was not run, a call whose job was submitted runs on, and +any other was interrupted, by the user or, in a sub-agent run its parent or +a limit stopped, by that (the seal says which: ``stop_cause``); the content-less event becomes the main agent's reply ``MARKER``. ADK's seals pair a result with a call by id alone, so a call whose id @@ -125,8 +125,8 @@ class InterruptedCallsPlugin(BasePlugin): sends. stop_cause: Asked once for each seal it writes: what stopped the run whose runner wrote it (``Delegations.stop_cause``), told to a - call that waited at its prompt; None, or None answered, for the - user's stop. + call that waited at its prompt or was running; None, or None + answered, for the user's stop. """ def __init__( @@ -304,7 +304,8 @@ def _from_record( the state it changed goes into ``actions``, stored with the answer as with its result. Any other is answered as ``OpenCalls.answer`` says: ``by_user`` whether the user stopped its turn (a stopped turn's call, by - default); ``cause`` what stopped the run, for a call at its prompt. + default); ``cause`` what stopped the run, for a call at its prompt or + running. """ answer = open_calls.answer(call_id, by_user=by_user, run=run, cause=cause) if not isinstance(answer, _Finished): diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index 34f3331c..6eb6c857 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -781,8 +781,9 @@ def _chain( ) -> list: """A plugin chain in the order ``_plugin_chain`` gives, from its ``head`` on. - ``stop_cause`` is what a seal tells a call at its prompt stopped the - run (``InterruptedCallsPlugin``): a sub-agent chain's. + ``stop_cause`` is what a seal tells a call at its prompt, or + running, stopped the run (``InterruptedCallsPlugin``): a sub-agent + chain's. """ from agentic_cli.workflow.adk.foreign_reasoning_plugin import ForeignReasoningPlugin diff --git a/src/agentic_cli/workflow/agents/control.py b/src/agentic_cli/workflow/agents/control.py index 1acccd9a..1bd2f046 100644 --- a/src/agentic_cli/workflow/agents/control.py +++ b/src/agentic_cli/workflow/agents/control.py @@ -32,9 +32,9 @@ stays unstored until its backend says the run's transcript holds it (``stored``); ``Delegations`` gives the unstored ones (``unstored``) to the instance's next run, so a message is never lost. -- ``stop_cause`` is what a call the run left at its permission prompt is - told stopped the run: its parent, its time limit or its token limit - (None for the user's stop). +- ``stop_cause`` is what a call the run left at its permission prompt, or + running, is told stopped the run: its parent, its time limit or its token + limit (None for the user's stop). All of it runs on the event loop; nothing here blocks. """ @@ -281,7 +281,10 @@ def unstored(self) -> list[str]: @property def stop_cause(self) -> str | None: - """What stopped the run, for a call it left at its prompt; None while it works or for the user's stop.""" + """What stopped the run, for a call it left at its prompt or running. + + None while it works, or for the user's stop. + """ if self.cancelled is None: return None by, error = self.cancelled diff --git a/src/agentic_cli/workflow/agents/delegate.py b/src/agentic_cli/workflow/agents/delegate.py index 676548ce..8cff2595 100644 --- a/src/agentic_cli/workflow/agents/delegate.py +++ b/src/agentic_cli/workflow/agents/delegate.py @@ -940,7 +940,8 @@ def _emit_instance( self._emit(WorkflowEvent.agent_instance(last.ref, status, reason=reason)) def stop_cause(self, run: RunRef | None, *, conversation: SessionRef | None = None) -> str | None: - """What stopped ``run``, for a call it left at its prompt (``interrupts.not_run``). + """What stopped ``run``, for a call it left at its prompt or running + (``interrupts.not_run``, ``interrupts.interrupted_by``). Its own control's cancel (``RunControl.stop_cause``: its parent, its time limit, its token limit), else ``its parent`` when a run above diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index 68b918ee..6ba87c61 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -99,6 +99,7 @@ set_active_turn, turn_has_ended, ) +from agentic_cli.workflow.tool_output import cap_tool_result, tool_output_dir from agentic_cli.workflow.service_registry import ( get_service, set_service_registry, @@ -145,6 +146,16 @@ RECORDS_RELEASE_WAIT = 10.0 +class _UserRun: + """A run the user started (``run_instance``), while its turn lasts: its + task once it starts, and whether it is interrupted (``interrupt_instance``), + which makes a stop of its stream a turn's cancel, not the user's stop.""" + + def __init__(self) -> None: + self.work: asyncio.Task[Delegated] | None = None + self.interrupted = False + + def _module_of(klass: type) -> str: module = getattr(klass, "__module__", None) return module if isinstance(module, str) else "" @@ -861,9 +872,18 @@ async def _deleting(self, conversation: SessionRef) -> AsyncGenerator[None, None # or on the one its ``session_id`` and ``user_id`` name, as ``process`` # takes them, on any of its instances, through ``Delegations``. + @property + def _user_runs(self) -> dict[tuple[SessionRef, str], _UserRun]: + """The runs the user started that are working, by conversation and instance.""" + held = self.__dict__.get("_user_runs_held") + if held is None: + held = self.__dict__["_user_runs_held"] = {} + return held + @property def _instance_results(self) -> dict[tuple[SessionRef, str], dict[str, Any]]: - """The latest envelope of each instance the user ran, by conversation and instance.""" + """The latest envelope of each instance the user ran, by conversation and + instance, as the cap left it (``_user_ran``).""" held = self.__dict__.get("_instance_results_held") if held is None: held = self.__dict__["_instance_results_held"] = {} @@ -887,12 +907,15 @@ async def run_instance( conversation's outside-content mark; a mark it brought marks the conversation here. A stopped instance runs (only the user may); one that is unknown, closed or running, or a blank message, is one - ``ERROR`` event and nothing runs. The run's full envelope is kept for - ``instance_result``. + ``ERROR`` event and nothing runs. The run's envelope is kept for + ``instance_result``, through the tool result cap. Stopping the stream (Ctrl+C cancels the consumer, or it closes the generator) is the user's stop of the run: it ends ``cancelled`` by - the user and the instance is ``stopped``, inside the turn. + the user and the instance is ``stopped``, inside the turn. A run + ``interrupt_instance`` interrupts ends as a turn's cancel ends its + runs instead: ``interrupted``, the instance ``idle``, the stream + raising ``asyncio.CancelledError``. Yields: The run's ``WorkflowEvent``s. @@ -907,9 +930,14 @@ async def run_instance( state=await self._conversation_state(ref), ) live = live_events.LiveEvents() + key = (ref, instance) + held = self._user_runs[key] = _UserRun() def stop_it() -> None: - # Its consumer stopped (Ctrl+C): the user's stop of the run alone. + # Its consumer stopped (Ctrl+C): the user's stop of the run + # alone, unless the run is interrupted (a turn's cancel). + if held.interrupted: + return record = self.agent_runs.instance(ref, instance) if record is not None and record.status == INSTANCE_RUNNING and record.runs: self._delegations.cancel( @@ -917,15 +945,20 @@ def stop_it() -> None: ) async def source() -> AsyncGenerator[WorkflowEvent, None]: + if held.interrupted: # before its run started: none starts + raise asyncio.CancelledError # The run's own task: a stop cancels the run, not its caller, # so it ends cancelled by the user, not interrupted. - work = asyncio.create_task( + work = held.work = asyncio.create_task( self._delegations.follow_up(request), name=f"user run of {instance}" ) try: delegated = await asyncio.shield(work) except asyncio.CancelledError: - stop_it() # a run that started after the consumer's stop looked + if held.interrupted: + work.cancel() # the run's caller is cancelled: it ends interrupted + else: + stop_it() # a run that started after the consumer's stop looked await asyncio.wait([work]) if not work.cancelled() and work.exception() is None: self._user_ran(ref, instance, work.result()) @@ -935,21 +968,78 @@ async def source() -> AsyncGenerator[WorkflowEvent, None]: return self._user_ran(ref, instance, delegated) - with live_events.reporting(live): - async with contextlib.aclosing( - live_events.merged(source(), live, on_stop=stop_it) - ) as items: - async for item in items: - event = self._apply_event_hook(item) - if event is not None: - yield event + try: + with live_events.reporting(live): + async with contextlib.aclosing( + live_events.merged(source(), live, on_stop=stop_it) + ) as items: + async for item in items: + event = self._apply_event_hook(item) + if event is not None: + yield event + finally: + if self._user_runs.get(key) is held: + del self._user_runs[key] + + def interrupt_instance( + self, instance: str, *, session_id: str | None = None, user_id: str | None = None + ) -> bool: + """Interrupt the run of ``instance`` the user started, as a turn's cancel (provisional). + + What a process exit does to a run: not the user's stop. The run of + that ``run_instance`` ends ``interrupted`` and its instance stays + ``idle``, so its parent may continue it; its stream then raises + ``asyncio.CancelledError``, and its turn records the run and writes + the records as it ends (a stop of that stream from now on is no + stop of the user's either). Only ``run_instance``'s run: a run of + the root's turn ends with that turn. + + Returns: + Whether such a run was working (or about to start); False, + doing nothing, otherwise. + """ + held = self._user_runs.get((self.session_ref(session_id, user_id), instance)) + if held is None or held.interrupted or (held.work is not None and held.work.done()): + return False + held.interrupted = True + if held.work is not None: + held.work.cancel() + return True def _user_ran(self, ref: SessionRef, instance: str, delegated: Delegated) -> None: - """Take what a run the user started left: its mark on the conversation, its envelope.""" + """Take what a run the user started left: its mark on the conversation, its envelope. + + The envelope is kept as the root reads it (``view_notice``): through + the tool result cap, as every envelope a model reads is (a ``task`` + result's too), so one over ``tool_result_max_chars`` is cut as a + dict, its note under ``truncated`` naming its full output, saved + once, as the run ends, in the tool-output folder under the + instance's name. + """ for value in delegated.state.values(): if isinstance(value, str) and value: self._outside_marks.mark(ref, value) - self._instance_results[(ref, instance)] = dict(delegated.result) + self._instance_results[(ref, instance)] = self._capped(instance, dict(delegated.result)) + + def _capped(self, instance: str, result: dict[str, Any]) -> dict[str, Any]: + """``result`` through the tool result cap, under ``instance``'s name; uncut if the cap fails.""" + try: + capped = cap_tool_result( + result, + tool_name=instance, + max_chars=self._settings.tool_result_max_chars, + folder=tool_output_dir(self._settings.app_name), + ) + except Exception as error: # noqa: BLE001 - the cap never raises by design + # A bug in the cap must not lose the envelope: it goes uncut, as + # a tool result does when the backends' cap fails. + logger.warning( + "tool_result_cap_failed", tool=instance, + error_type=type(error).__name__, error=str(error), + ) + logger.debug("tool_result_cap_failed", tool=instance, exc_info=error) + return result + return capped if isinstance(capped, dict) else result def instance_result( self, instance: str, *, session_id: str | None = None, user_id: str | None = None @@ -957,8 +1047,10 @@ def instance_result( """The envelope of the latest run of ``instance`` that the user started (provisional). Kept in memory for the conversation (the records keep only the head - of a result); None when no run of the user's ended there, or after - the conversation was deleted. + of a result), as the tool result cap left it: one over + ``tool_result_max_chars`` is cut, its note under ``truncated`` naming + its full output. None when no run of the user's ended there, or + after the conversation was deleted. """ return self._instance_results.get((self.session_ref(session_id, user_id), instance)) diff --git a/src/agentic_cli/workflow/deepagents/manager.py b/src/agentic_cli/workflow/deepagents/manager.py index bdb7f5ac..11bb6caf 100644 --- a/src/agentic_cli/workflow/deepagents/manager.py +++ b/src/agentic_cli/workflow/deepagents/manager.py @@ -882,8 +882,9 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: live_events.report(event) except asyncio.CancelledError: # Its instance's next run answers the calls this one left open - # as the user's (as ADK seals them). The run's own cancel has - # stopped it; any other (its turn's) goes on. + # with what stopped it, the user or its cause (as ADK seals + # them). The run's own cancel has stopped it; any other (its + # turn's) goes on. self._open_calls.cancelled( conversation, instance=run.ref.instance, cause=self._delegations.stop_cause(run.ref, conversation=conversation), @@ -1038,10 +1039,9 @@ async def _stored_instances(self, conversation: "SessionRef") -> dict[str, int]: """The highest instance number of each type ``conversation``'s checkpointer keeps. The base's hook (``Delegations`` asks it once per conversation per - turn): read from the conversation's stored records when they name - instances, else from the instance threads - (``CheckpointSessions.stored_instances``), so a manager after a - restart numbers past what another ran there. + turn): read from the conversation's stored records and, as their + floor, its instance threads (``CheckpointSessions.stored_instances``), + so a manager after a restart numbers past what another ran there. """ if self._sessions is None: return {} diff --git a/src/agentic_cli/workflow/deepagents/middleware.py b/src/agentic_cli/workflow/deepagents/middleware.py index 2202955d..6adbe7f3 100644 --- a/src/agentic_cli/workflow/deepagents/middleware.py +++ b/src/agentic_cli/workflow/deepagents/middleware.py @@ -472,7 +472,8 @@ class InterruptedCallsMiddleware(AgentMiddleware): new input arrives, so that result is kept here as it passes (outermost, after the gate, the cap and the error handling). A call that waited at its permission prompt was not run; one whose job was submitted runs on; - any other was interrupted, by the user when this manager saw the cancel. + any other was interrupted, by the user when this manager saw the cancel + (in a sub-agent run its parent or a limit stopped, by that). On the main agent, a turn the user stopped before any reply leaves ``MARKER`` as its reply, so the next turn answers only the new message. Each call is recorded and answered as the run's that made it @@ -480,8 +481,8 @@ class InterruptedCallsMiddleware(AgentMiddleware): the task it runs in, ``agents/delegate.py``), so a sub-agent's call never answers its parent's delegation of the same id. A sub-agent instance's next run answers, on its own thread, what an earlier run of it left - open, from the instance's record, as the user's when that run was - stopped (as ADK seals a stopped run's). + open, from the instance's record, with what stopped that run when it + was stopped (as ADK seals a stopped run's). Everything pairs a result with its call by id, the provider adapters too. A provider that numbers its call ids per response (``call_0`` in diff --git a/src/agentic_cli/workflow/deepagents/sessions.py b/src/agentic_cli/workflow/deepagents/sessions.py index 9cdb7983..879864b1 100644 --- a/src/agentic_cli/workflow/deepagents/sessions.py +++ b/src/agentic_cli/workflow/deepagents/sessions.py @@ -39,9 +39,10 @@ and row, so a delete cut short leaves the conversation, by which the rest is found again. The instances a conversation keeps, which number a new manager's next ones (``stored_instances``), are the records' ids and -counters and the threads', read cheaply (each thread's first checkpoint -holds no message), so an instance whose start write was lost is numbered -past too. +counters and the threads', read from each thread's first checkpoint only +(it holds the first run's input, which the saver decodes: the brief, and an +inheriting instance's copy of its parent's conversation), so an instance +whose start write was lost is numbered past too. A finished job reports to the conversation in a ``HumanMessage`` of its own (``job_notification``), marked in its ``response_metadata``, which no @@ -327,10 +328,14 @@ async def instances(self, ref: SessionRef) -> list[str]: """The sub-agent instances whose transcript thread ``ref``'s conversation keeps, sorted. Read from the instance runs' first input checkpoints, by their - metadata (``source`` ``input``, ``step`` -1): one per thread, which - holds no message yet, never a checkpoint that holds a transcript (the - saver unpickles every checkpoint it returns, and its filter is a - metadata equality). A thread whose id does not name this conversation + metadata (``source`` ``input``, ``step`` -1): one per thread, never + a later one, which would hold the transcript (the saver decodes every + checkpoint it returns, and its filter is a metadata equality). The + one read holds its run's input, in its ``__start__`` channel and its + pending writes, and the saver decodes it on the event loop: the + brief, and an inheriting instance's copy of its parent's + conversation, so the read grows with the instances and with those + conversations. A thread whose id does not name this conversation and an instance is left out, whatever its metadata says. """ wanted = { diff --git a/src/agentic_cli/workflow/interrupts.py b/src/agentic_cli/workflow/interrupts.py index 728fc0be..159cfcd8 100644 --- a/src/agentic_cli/workflow/interrupts.py +++ b/src/agentic_cli/workflow/interrupts.py @@ -8,7 +8,10 @@ - a call that finished before the cancel keeps its real result, and the state it changed (``save_tasks``' tasks, a delegation's plan); -- a running call, or a delegation, is answered ``INTERRUPTED_BY_USER``; +- a running call, or a delegation, is answered ``INTERRUPTED_BY_USER``, + or, in a sub-agent run its parent or a limit stopped, ``Interrupted: + stopped the run before this call finished; ...`` + (``interrupted_by``); - a call waiting at its permission prompt (both gates mark it) or at a question it asked (``BaseWorkflowManager.request_user_input``, by the active tool call) is ``NOT_RUN``, or, in a sub-agent run its parent or a @@ -69,6 +72,11 @@ "Interrupted by the user before it finished; it may have partly run. " "Check before running it again." ) +#: A call that was running when its run was stopped by something else. +INTERRUPTED_BY = ( + "Interrupted: {cause} stopped the run before this call finished; it may " + "have partly run. Check before running it again." +) #: A call left open by something else: a crash, or a cancel from before this rule. INTERRUPTED = ( "Interrupted before it finished (its turn or the app stopped); it may have " @@ -93,6 +101,12 @@ def not_run(cause: str | None) -> str: return NOT_RUN if cause is None else NOT_RUN_BY.format(cause=cause) +def interrupted_by(cause: str | None) -> str: + """What a call running when its run was stopped is told: ``INTERRUPTED_BY_USER`` + for the user's stop, else ``INTERRUPTED_BY`` naming ``cause``, as ``not_run`` does.""" + return INTERRUPTED_BY_USER if cause is None else INTERRUPTED_BY.format(cause=cause) + + #: The longest call id ``fresh_call_id`` makes: OpenAI's Chat Completions #: takes none longer. _CALL_ID_MAX = 40 @@ -162,7 +176,11 @@ def job_for_call(call_id: str | None, *, started_by: str | None = None) -> Any | def unrecorded( - call_id: str | None, *, by_user: bool, started_by: str | None = None + call_id: str | None, + *, + by_user: bool, + started_by: str | None = None, + cause: str | None = None, ) -> dict[str, Any]: """The answer for an open call no record holds: its job's state, else why it has none. @@ -170,12 +188,14 @@ def unrecorded( the job by the instance of the call's run (``started_by``); ADK's ``left_open`` answers the root's own calls through it (``started_by`` None), and a sub-agent's call with no job, its run being numbered no - more. + more. A stopped run's call (``by_user``) says what stopped it + (``interrupted_by(cause)``: None for the user); one no stop answers is + ``INTERRUPTED``. """ record = job_for_call(call_id, started_by=started_by) if record is not None: return job_started(record) - return interrupted(INTERRUPTED_BY_USER if by_user else INTERRUPTED) + return interrupted(interrupted_by(cause) if by_user else INTERRUPTED) class _Active(enum.Enum): @@ -302,8 +322,9 @@ def answer( A job answers the call only when that run's instance submitted it (``job_for_call``). cause: What stopped the run, for a call at its prompt - (``not_run``); None: the one recorded with the instance's - stop (``cancelled(cause=)``), else the user's. + (``not_run``) or one that was running (``interrupted_by``, + when ``by_user``); None: the one recorded with the + instance's stop (``cancelled(cause=)``), else the user's. """ if call_id: key = get_active_turn() @@ -311,12 +332,12 @@ def answer( finished = self._finished.get(key, {}) if mark in finished: return finished[mark] + if cause is None and mark[0] is not None: + cause = self._causes.get((key, mark[0])) if mark in self._asking.get(key, ()): - if cause is None and mark[0] is not None: - cause = self._causes.get((key, mark[0])) return interrupted(not_run(cause)) # Its job, if it submitted one: the job of the run it was given. - return unrecorded(call_id, by_user=by_user, started_by=_instance(run)) + return unrecorded(call_id, by_user=by_user, started_by=_instance(run), cause=cause) def cancelled( self, key: Any, *, instance: str | None = None, cause: str | None = None @@ -325,9 +346,9 @@ def cancelled( a run of that instance of it. ``cause`` is what stopped that run when it was not the user (its - parent, a limit: ``not_run``), kept for the call it left at its - prompt, which the instance's next run answers; None (a stop by the - user) forgets an earlier one. + parent, a limit: ``not_run``, ``interrupted_by``), kept for the + calls it left at its prompt or running, which the instance's next + run answers; None (a stop by the user) forgets an earlier one. """ if instance is None: self._cancelled.add(key) diff --git a/tests/cli/test_agent_view.py b/tests/cli/test_agent_view.py index e41a105b..f78668ff 100644 --- a/tests/cli/test_agent_view.py +++ b/tests/cli/test_agent_view.py @@ -19,6 +19,7 @@ from __future__ import annotations import asyncio +import json from types import MethodType, SimpleNamespace import pytest @@ -48,12 +49,14 @@ RUN_CANCELLED, RUN_COMPLETED, RUN_INPUT_REQUIRED, + RUN_INTERRUPTED, ) 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, + FOLLOWING, HELD, SESSION, USER, @@ -65,8 +68,10 @@ contract_hold, contract_start_job, delegate, + envelope_read, follow_team, make_crew, + message, parent_team, project, says, @@ -394,6 +399,32 @@ async def test_after_a_run_of_yours_the_main_agent_is_told_once(self, make_crew) await typed(app, "/agent researcher-1", "/back") assert crew.requests("coordinator") == 3 + async def test_a_result_over_the_cap_is_told_cut_with_its_note(self, make_crew): + """The envelope the notice carries passes the tool result cap, as a + ``task`` result does: cut to ``tool_result_max_chars``, with the note + that names its full output, saved for ``read_file``.""" + crew, app = await in_a_view( + make_crew, coordinator=[says("Noted.")], researcher=[says("Y is 7. " * 1_000)], + ) + crew.manager.settings.tool_result_max_chars = 2_000 + + await typed(app, "Now find Y.", "/back") + + notice = crew.last_message("coordinator") + frame = view_notice("researcher-1", {})[: -len("{}")] + assert notice.startswith(frame), notice[:200] + sent = notice[len(frame):] + assert len(sent) <= 2_000, len(sent) + read = json.loads(sent) + assert (read["run"], read["status"], read["success"]) == ( + "researcher-1#2", RUN_COMPLETED, True, + ) + assert read["result"].startswith("Y is 7.") and "characters cut]" in read["result"] + assert read["truncated"].startswith("Cut: ") and "tool-output/researcher-1-" in ( + read["truncated"] + ) + assert crew.manager.instance_result("researcher-1", session_id=SESSION) == read + async def test_without_a_run_of_yours_nothing_is_told(self, make_crew): crew, app = await in_a_view(make_crew) @@ -562,11 +593,14 @@ def test_a_fake_session_gets_none(self): 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).""" + async def test_a_run_still_working_at_exit_is_interrupted(self, make_crew, monkeypatch): + """``/exit`` while the run in view works: the process exit interrupts + the run, as it would any run (only Ctrl+C in a view is the user's + stop), before the workflow goes (whose cleanup waits for it). The run + ends ``interrupted`` and the sub-agent stays ``idle``, so after a + restart its parent continues it.""" crew = make_crew( - follow_team(), + follow_team(), store="sqlite", coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], researcher=[says("X is 42."), calls(use("contract_block", "r1"))], ) @@ -607,9 +641,21 @@ async def then_exit() -> None: 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", + "researcher-1#2", RUN_INTERRUPTED, None, + ) + assert crew.instances() == [("researcher-1", INSTANCE_IDLE)] + + restarted = make_crew( + follow_team(), store="sqlite", subagents=FOLLOWING, + coordinator=[calls(message("researcher-1", "Go on.", "c2")), says("Done.")], + researcher=[says("Went on.")], + ) + await asyncio.wait_for(restarted.turn("Go on."), 20) + + read = envelope_read(restarted.results_read("coordinator")["c2"]) + assert (read["run"], read["status"], read["result"]) == ( + "researcher-1#3", RUN_COMPLETED, "Went on.", ) - assert crew.instances() == [("researcher-1", INSTANCE_STOPPED)] class TestCtrlCNotBound: diff --git a/tests/workflow/deepagents/test_sessions.py b/tests/workflow/deepagents/test_sessions.py index 58964c1b..bbde30e2 100644 --- a/tests/workflow/deepagents/test_sessions.py +++ b/tests/workflow/deepagents/test_sessions.py @@ -279,13 +279,15 @@ async def test_none_is_none(self, saver, store): assert await CheckpointSessions(saver, store).stored_instances(ref()) == {} - async def test_the_threads_are_the_floor_under_the_records_and_read_cheaply( + async def test_the_threads_are_the_floor_under_the_records_read_from_their_first_input( self, saver, store, monkeypatch ): """The records' counters and ids number past what they hold, and the threads past what the records never named (a start write that was - lost): each thread's first checkpoint says so, which holds no - messages, so no transcript is unpickled on the event loop.""" + lost): each thread's first checkpoint says so. That checkpoint holds + the run's first input, its brief (in the ``__start__`` channel and in + its pending writes), which the saver decodes, and no message of the + transcript after it: no later checkpoint is read.""" await say(saver, ref()) await instance_ran(saver, ref(), "researcher-1", "One.", "Two.") await instance_ran(saver, ref(), "researcher-6", "Lost.", "Lost again.") # unnamed @@ -296,12 +298,19 @@ async def test_the_threads_are_the_floor_under_the_records_and_read_cheaply( {"instance": "researcher-1"}, {"instance": "writer-2"}, {"instance": "notes"}, ], }) - decoded: list[int] = [] + decoded: list[tuple[int, list[str], list[str]]] = [] alist = saver.alist async def listing(*args, **kwargs): async for item in alist(*args, **kwargs): - decoded.append(len(item.checkpoint["channel_values"].get("messages", ()))) + values = item.checkpoint["channel_values"] + start = values.get("__start__") or {} + decoded.append(( + len(values.get("messages", ())), + [message.content for message in start.get("messages", ())], + [message.content for _, channel, written in item.pending_writes + if channel == "messages" for message in written], + )) yield item monkeypatch.setattr(saver, "alist", listing) @@ -309,10 +318,14 @@ async def listing(*args, **kwargs): counts = await sessions.stored_instances(ref()) assert counts == {"researcher": 6, "writer": 2} - assert decoded == [0, 0] # one empty first checkpoint a thread, none of the later ones + first_inputs = [ + (0, ["Then One."], ["Then One."]), (0, ["Then Lost."], ["Then Lost."]), + ] + # Each thread's first input, twice over; nothing a later run wrote. + assert sorted(decoded) == sorted(first_inputs) decoded.clear() assert await sessions.instances(ref()) == ["researcher-1", "researcher-6"] - assert decoded == [0, 0] + assert sorted(decoded) == sorted(first_inputs) async def test_records_that_name_no_instance_read_the_threads(self, saver, store): await instance_ran(saver, ref(), "researcher-4") diff --git a/tests/workflow/test_interrupts.py b/tests/workflow/test_interrupts.py index a8286134..64192490 100644 --- a/tests/workflow/test_interrupts.py +++ b/tests/workflow/test_interrupts.py @@ -28,6 +28,7 @@ OpenCalls, fresh_call_id, interrupted, + interrupted_by, job_for_call, job_started, not_run, @@ -475,6 +476,79 @@ def test_a_stop_by_the_user_leaves_no_cause(self): assert calls.answer("r1", by_user=True) == interrupted(NOT_RUN) +class TestARunningCallSaysWhy: + """A call that was running when its run was stopped is told what stopped + the run, as a call at its prompt is: the user (``INTERRUPTED_BY_USER``, as + before), or its parent, its time limit or its token limit + (``interrupted_by``). A call no stop answers (a crash's) is ``INTERRUPTED``.""" + + def test_the_texts(self): + assert interrupted_by(None) == INTERRUPTED_BY_USER + assert interrupted_by("its parent") == ( + "Interrupted: its parent stopped the run before this call finished; " + "it may have partly run. Check before running it again." + ) + assert interrupted_by("its time limit") == ( + "Interrupted: its time limit stopped the run before this call finished; " + "it may have partly run. Check before running it again." + ) + assert interrupted_by("its token limit") == ( + "Interrupted: its token limit stopped the run before this call finished; " + "it may have partly run. Check before running it again." + ) + + def test_the_cause_given_is_the_answer(self): + """ADK's seal names the cause as the run stops.""" + calls = OpenCalls() + with turn_of(ref("a")): + with run_as(RESEARCHER): + calls.finished("r1", "the lookup") + + assert calls.answer("r2", by_user=True, cause="its parent") == interrupted( + interrupted_by("its parent") + ) + assert calls.answer("r1", by_user=True, cause="its parent") == "the lookup" + + def test_a_stopped_instances_cause_is_kept_for_its_next_run(self): + """Deep Agents answers at the instance's next run: the cause recorded + with the instance's stop words its running calls too.""" + calls = OpenCalls() + calls.cancelled(ref("a"), instance="researcher-1", cause="its token limit") + calls.clear(ref("a")) + + with turn_of(ref("a")): + with run_as(SECOND): + assert calls.take_cancel(ref("a"), instance="researcher-1") is True + assert calls.answer("r2", by_user=True) == interrupted( + interrupted_by("its token limit") + ) + with run_as(OTHER): # another instance: no cause of its own + assert calls.answer("r2", by_user=True) == interrupted(INTERRUPTED_BY_USER) + + def test_a_stop_by_the_user_or_none_seen_says_so(self): + calls = OpenCalls() + calls.cancelled(ref("a"), instance="researcher-1", cause="its parent") + calls.cancelled(ref("a"), instance="researcher-1") # stopped again, by the user + + with turn_of(ref("a")): + with run_as(RESEARCHER): + assert calls.answer("r2", by_user=True) == interrupted(INTERRUPTED_BY_USER) + # No stop this process saw (a crash): the cause given says nothing. + assert calls.answer("r2", by_user=False, cause="its parent") == interrupted( + INTERRUPTED + ) + + def test_unrecorded_names_the_cause(self): + with turn_of(ref("a")): + assert unrecorded("r2", by_user=True, cause="its time limit") == interrupted( + interrupted_by("its time limit") + ) + assert unrecorded("r2", by_user=True) == interrupted(INTERRUPTED_BY_USER) + assert unrecorded("r2", by_user=False, cause="its time limit") == interrupted( + INTERRUPTED + ) + + class TestADeletedConversation: def test_forget_drops_its_calls_a_failed_turns_and_its_stops_and_no_others(self): calls = OpenCalls() diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index 2d95262c..9825b857 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -102,6 +102,7 @@ INTERRUPTED_BY_USER, NOT_RUN, interrupted, + interrupted_by, ) from agentic_cli.workflow.outside_content import OUTSIDE_CONTENT_KEY from agentic_cli.workflow.permissions import EXEMPT, Capability, PermissionEngine @@ -4474,19 +4475,27 @@ async def test_after_ctrl_c(self, make_crew): ("researcher-1#1", RUN_INTERRUPTED), ("researcher-1#2", RUN_COMPLETED), ] - async def test_after_its_parent_stopped_it_and_the_turn_ended(self, make_crew): + @pytest.mark.parametrize(("by", "error", "cause"), [ + ("parent", "no longer needed", "its parent"), + ("limit", TIME_LIMIT_ERROR, "its time limit"), + ]) + async def test_after_its_parent_or_a_limit_stopped_it_and_the_turn_ended( + self, make_crew, by, error, cause + ): + """The call that was running says what stopped the run, not the user.""" crew = self.stopping(make_crew, between=[says("Stopped it.")]) turn = crew.start() await asyncio.wait_for(BLOCKING["started"].wait(), 10) await until(lambda: crew.recorded("r1", "researcher-1#1")) - assert crew.cancel("researcher-1#1", by="parent", error="no longer needed") is True + assert crew.cancel("researcher-1#1", by=by, error=error) is True await asyncio.wait_for(turn, 10) await crew.turn("Go on.") answers = self.answered_once(crew, 1) assert json.loads(answers["r1"]) == {"success": True, "value": 42} - assert INTERRUPTED_BY_USER in answers["r2"] + assert json.loads(answers["r2"]) == interrupted(interrupted_by(cause)) + assert INTERRUPTED_BY_USER not in answers["r2"] assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Went on." async def test_after_a_crash_in_a_new_process(self, make_crew, monkeypatch): @@ -5660,6 +5669,42 @@ async def view() -> None: assert [call for call, _ in crew.call_results("researcher", -1)] == ["r1"] assert crew.instances() == [("researcher-1", INSTANCE_IDLE)] + async def test_an_interrupt_ends_its_run_as_a_turns_cancel_and_the_instance_idle( + self, make_crew + ): + """``interrupt_instance`` (a process exit): no stop of the user's.""" + crew = make_crew( + follow_team(), + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done."), + calls(follow("researcher-1", "Go on.", "c2")), says("Done.")], + researcher=[says("X is 42."), calls(use("contract_block", "r1")), says("Went on.")], + ) + await crew.turn() + assert crew.manager.interrupt_instance("researcher-1") is False # none works + + async def view() -> None: + async for _ in crew.manager.run_instance("researcher-1", "Wait here."): + pass + + viewing = asyncio.create_task(view()) + await asyncio.wait_for(BLOCKING["started"].wait(), 10) + assert crew.manager.interrupt_instance("researcher-1") is True + done, _ = await asyncio.wait({viewing}, timeout=10) + if not done: + await Crew.stop(viewing) + assert done, "the interrupted run did not end" + assert viewing.cancelled() + + second = crew.records()[-1] + assert (second.ref.run, second.status, second.cancelled_by) == ( + "researcher-1#2", RUN_INTERRUPTED, None, + ) + assert crew.instances() == [("researcher-1", INSTANCE_IDLE)] + assert crew.manager.interrupt_instance("researcher-1") is False + # Its parent continues it. + await crew.turn("Go on.") + assert envelope_read(crew.results_read("coordinator")["c2"])["result"] == "Went on." + async def test_one_that_cannot_run_is_one_error_and_nothing_runs(self, make_crew): crew = make_crew( follow_team(continuable=False),