diff --git a/CHANGELOG.md b/CHANGELOG.md index a8af5a0c..05ef2d6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -930,26 +930,36 @@ the start of the entry's title. backends, and survive a restart.** A conversation's instances, its runs (each with its brief, its envelope's fields, its tokens by model, its own plan and tasks) and its id counters are written to the conversation's - store at each run event that changes them (one write at a time per + store at each run's start and end and each change of an instance's status + (not at a working status, `queued`, `running` or `input_required`, which a + restart reads as `interrupted` all the same; one write at a time per conversation, the records as they are when it starts; a turn returns once its records are written; a write that fails is warned of once per - conversation, `subagent_records_not_saved`, and fails neither the run nor - the turn): on ADK in a session of the child app named as the conversation - (`--agents`, id ``, its `%` and `/` - percent-encoded, as in its instances' ids; the state split by key so a + conversation, `subagent_records_not_saved`, and fails no turn, nor any run + that makes its transcript (a first run, or a follow-up whose transcript is + gone) and whose start it was: a transcript is made only once the records + name its instance, so that run fails with `The conversation's + sub-agent records could not be stored, so this run was not started.`, code + `RECORDS_NOT_STORED`, and nothing of it is made): on ADK in a session of + the child app named as the conversation (`--agents`, id + ``, its `%` and `/` percent-encoded, as in its instances' ids; the state split by key so a write holds what changed: the header under `agentic_cli.agents`, - `adk/sessions.py::RECORDS_KEY`, and a key for each instance and run), on Deep Agents in - the store beside the checkpointer (namespace `("agentic_cli", "agents", + `adk/sessions.py::RECORDS_KEY`, and a key for each instance and run; its + events stay bounded: after 100 appended writes, + `adk/sessions.py::RECORDS_REWRITE_AFTER`, the next one writes the records + whole into a second session, id `/`, one generation on, + and deletes the first, the two alternating, a read taking the newer), on + Deep Agents in the store beside the checkpointer (namespace `("agentic_cli", "agents", , )`, key the session id); the memory store keeps them for the process. They load with the conversation (`load_session`, a turn's start, `/agents`; the manager's `load_agents(ref)`, provisional): a run found 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, 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 + continues it, new instances are numbered past them (the records' counters + and ids, which name every transcript the conversation keeps; for records + that do not read, the transcripts the store finds: ADK's listing of the + user's child sessions, Deep Agents' instance threads, read from each + thread's first checkpoint; and a first run whose transcript 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 @@ -958,7 +968,8 @@ the start of the entry's title. `AgentRuns(on_change=)` tells each change; a backend keeps them through `BaseWorkflowManager._load_agent_records` and `_save_agent_records` (the base keeps none: its records stay in memory). Deleting the conversation - deletes them, after its transcripts and before the conversation. + deletes them, after the transcripts they name (for records that do not + read, those the store finds) and before the conversation. - **Sub-agent instances, continued with follow-up runs, on both backends.** A delegation starts an instance (`researcher-2`) that outlives its run: `idle` once the run ends, it takes follow-ups, each its next run @@ -1539,7 +1550,15 @@ the start of the entry's title. `{workspace}/sessions/checkpoints.db`, next to ADK's `sessions.db` and, as it is, owner-only (`sqlite_uri` may point ADK and Deep Agents at one file: their tables do not collide), Postgres at `postgres_uri`, or - memory. Every session hook takes `user_id`. `list_sessions` gives each + memory. Each agent's messages are Deep Agents' delta channel + (`AgentCliState` subclasses `deepagents.DeepAgentState`): a checkpoint + stores the messages its step added, a full copy every 50 updates, so a + conversation's checkpoints grow with its length, not its square (40 + turns of 1,000-character prompts and answers: about 0.3 MB, where whole + copies took 8 MB), and the session hooks, a reader's too, read messages + through a graph of that state over the checkpointer, which puts them + together; a conversation stored with whole copies reads and continues + as before. Every session hook takes `user_id`. `list_sessions` gives each conversation's row (`SessionInfo`, below) from its newest checkpoint, `delete_session` also removes the sub-agents' checkpoints and returns False for an unknown id, and `recent_messages` is the user's and the @@ -2093,17 +2112,19 @@ the start of the entry's title. `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`: 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 + name, which name every transcript, since a first run's is made only once + its start is stored; a listing's only for records that do not read; Deep + Agents deletes the instances' threads the same way). 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 + conversation per turn, under a lock of the conversation's own: the + instances its records name, none without records, and the store's own + look, ADK's listing or Deep Agents' threads, only for records that do not + read; `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 diff --git a/CLAUDE.md b/CLAUDE.md index 5554cf96..fa360c04 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,7 +51,7 @@ agentic-cli/ │ │ ├── waiting_jobs.py # Which finished jobs wait to be told in the open conversation: one rule (JobRecord.awaiting_resume, then its own, no conversation's, or a gone conversation's: can_resume, then the other installed backends' readers, opens_anywhere: one another backend keeps is not gone, its job waits for it) for the deliveries, ↻N and the startup line │ │ └── usage_tracker.py # Token usage / status bar: ctx = the main agent's last prompt over its context_trigger (a call with a purpose, a sub-agent's, a summary's or a side call's, never moves it); the token segment the open conversation's total, every call of its turns; format_usage: /status's rows by agent and /agents 's tokens by model │ ├── workflow/ -│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none), and _agent_tool_names, what a task call's tools may name (the agent's own tools by the names its model sees, KEPT_TOOLS left out; the base's: its configured tools; ADK and Deep Agents add MCP and skill tools; ADK raises delegate.ToolsUnlistedError for a toolset it could not list, which Delegations answers TOOLS_UNLISTED_ERROR); _run_models: a run's maps of each agent's model and numbers, its type's its model choice's when it runs on one, a general_purpose run's its spawner's (based_on; _general_model: the spawner's resolved model named general_purpose); the sub-agent records beside each conversation: the store hooks _load_agent_records/_save_agent_records (the base: none, records in memory only), load_agents (once per conversation per manager, before the store is open nothing; load_session reads them again, after this manager's own writes, warning of a store that cannot be read; each turn's start, where one that cannot be read stops the turn; another version, or records that do not read, ignored with one warning, subagent_records_ignored, and never written over: the conversation is not written until load_session reads them; a run found working written back interrupted), agent_runs' on_change -> RecordsWriter (agents/records.py) for a loaded conversation, _agent_records_written (a turn's end; ADK, before a first run's child session), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), start_instance (a turn: Delegations.start_by_user, the user's new instance, parent root, depth 1, started_by user, counted toward no turn's runs; a type the user may not start or a blank objective one ERROR; a conversation not yet stored stored right before the run starts (after the reads that can fail), _keep_conversation: ADK's session with one state-only event, Deep Agents' index row, titled from the objective with no turns; an inheriting type's copy of the conversation from _inherited_history, the backend's hook: ADK's session's root-visible events, Deep Agents' root messages, summary applied; its first event the run's start), both streamed by _users_run (the run in a task of its own; _UsersRunEvents notes the run as its start is reported and until_started awaits that one future, so a stop before the consumer read it, or before the run started, stops it by the user as it starts, before its hook is entered), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', each config's model_choices as its model would be, with its model_settings, into _choice_models by (agent, choice), choice_models, then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built, and _compute_choice_budgets (each model choice's, context_budget(agent, model=choice)): each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) +│ │ ├── base_manager.py # BaseWorkflowManager (abstract; subagents=: its SubAgentPolicy, subagent_policy, read-only, kept for its life; _delegations: its Delegations (agents/delegate.py), made on first use over agent_runs, the policy, the agents' configs, the usage ledgers, _run_agent, the backend's hook that runs one sub-agent run, and _stored_instances, the one that says how many instances of each type a conversation's store keeps (the base: none), and _agent_tool_names, what a task call's tools may name (the agent's own tools by the names its model sees, KEPT_TOOLS left out; the base's: its configured tools; ADK and Deep Agents add MCP and skill tools; ADK raises delegate.ToolsUnlistedError for a toolset it could not list, which Delegations answers TOOLS_UNLISTED_ERROR); _run_models: a run's maps of each agent's model and numbers, its type's its model choice's when it runs on one, a general_purpose run's its spawner's (based_on; _general_model: the spawner's resolved model named general_purpose); 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), _agent_start_stored (a run's start in the records before it makes its transcript, a first run or a follow-up whose transcript is gone, on both backends: the records name every transcript; RunFailed with RECORDS_NOT_STORED when the store did not take it), a release that detaches the store first waits for the writes under way (RECORDS_RELEASE_WAIT, before its synchronous part, so a cancel there stops only the wait; what the store does not answer is abandoned, RecordsWriter.abandon), _deleting(ref) around a backend's delete (the conversation's writes discarded first; after it agent_runs.forget, OpenCalls.forget, UsageLedgers.forget, Delegations.forget, the load mark dropped and the instances' instance_result); the user's control of the open conversation's sub-agents, each on session_ref(session_id, user_id): run_instance (a turn, Delegations.follow_up started_by user, counted toward no turn's runs, from _conversation_state, a mark the run brought marking the conversation; a refusal one ERROR; Ctrl+C the user's stop: the run in a task of its own, cancelled by the user and waited for), start_instance (a turn: Delegations.start_by_user, the user's new instance, parent root, depth 1, started_by user, counted toward no turn's runs; a type the user may not start or a blank objective one ERROR; a conversation not yet stored stored right before the run starts (after the reads that can fail), _keep_conversation: ADK's session with one state-only event, Deep Agents' index row, titled from the objective with no turns; an inheriting type's copy of the conversation from _inherited_history, the backend's hook: ADK's session's root-visible events, Deep Agents' root messages, summary applied; its first event the run's start), both streamed by _users_run (the run in a task of its own; _UsersRunEvents notes the run as its start is reported and until_started awaits that one future, so a stop before the consumer read it, or before the run started, stops it by the user as it starts, before its hook is entered), interrupt_instance (that run ended as a turn's cancel, interrupted, its instance idle: a process exit; a stop of its stream then no stop of the user's), instance_result, stop_instance/close_instance (Delegations.stop_by_user/close_by_user, load_agents first, written before returning), steer_instance, tell_root (the backend's _deliver_notice; view_notice); request_user_input: a sub-agent run waits on the user with its working slot lent (agents/delegate.py::waiting_on_user), and can_request_user_input says whether anyone could answer now (no callback, or its turn ended: nothing is lent); _load_models: load the catalog, then resolve every model (the configs', each config's model_choices as its model would be, with its model_settings, into _choice_models by (agent, choice), choice_models, then _resolve_extra_models: a backend's agents built without configs, leniently), once, no retry (the background refresh started after a successful init checks the models the settings name); _compute_budgets right after it, before any service is built, and _compute_choice_budgets (each model choice's, context_budget(agent, model=choice)): each agent's context numbers, ContextBudgetError for a window too small to work in, for a backend that says _manages_context (ADK, whoever built its agents, and Deep Agents; LangGraph has none); the lifecycle: cleanup, reinitialize and the one release, _release_resources: the base's state reset, the backend's hooks _detach_backend/_detach_store (skipped while _keeping keeps the store), the services detached and their closes started on a worker thread, then every closer and the services waited for last (shielded), in one shielded task; the turn: _turn, every turn's entry (log context, _turn_admission, _workflow_context; the sub-agent runs it leaves open, a cancel's or a failure's, recorded interrupted as it ends: agent_runs, workflow/agents/runs.py), and the templates over the backend's hooks: resume_with_job_result (the job's result read on a worker thread, job_notice → _deliver_job_notice), can_resume (_record_resumable, _conversation_exists), compact (→ _compact_turn), supports_job_resume/supports_compact derived from them; services (services.py's ServiceSet behind the forwards: _services, _build_services(_into), _get_service_tool_map, _close_services, _keeping) and the hand-over: lend_services → initialize_services(services=loan) → give_services (no turn while a manager holds services it does not own); service detection, tool assembly; context_budget/root_agent_name; the usage ledgers (usage: the open conversation's, usage_of; _turn counts each turn in its conversation's and gives a run a cancel leaves open what it used) and side calls (_report_side_call: generate_simple's usage, its purpose from usage.side_call, summarize's tool, on_session_end's memory_extraction outside any turn, recorded in its conversation's ledger and, in a turn, reported through its live events, never to a turn that has ended: turn_has_ended); summarize and fact extraction: a prompt over the default model's room, at the resolved max_tokens, cut in the middle, never under MIN_PROMPT_ROOM, _fit_prompt; the memory index behind the forwards _memory_index_now/_memory_index_cached/_memory_index_cap/_forget_memory_index and _index_snapshots (memory_index.py's MemoryIndex; the release clears it); the roster (agents/roster.py's Rosters, _rosters: _roster_wanted(root), a root with message_agent, _roster_now; _forget_memory_index drops it too, and the release and a delete)) │ │ ├── factory.py # create_workflow_manager_from_settings (_BACKENDS: orchestrator → "module:Class" + extra, imported when chosen; orchestrator=: another backend than the settings'; session_store=: the store a manager is built for, BaseWorkflowManager.session_store, the settings' by default; subagents=: the SubAgentPolicy the manager gets, checked before a backend is imported); orchestrator_of; check_backend (an unknown name, a missing extra) │ │ ├── session_readers.py # SessionReader: a backend's stored conversations read without its manager (list/info/exists/delete/aclose, rows naming the backend; delete deletes what the manager's does, ADK's sub-agent transcripts and records with the conversation), opened from the settings and a store (open_session_reader: the backend's own session code, adk/sessions.py::open_sessions and deepagents/sessions.py::open_sessions, imported on a worker thread; no agents, models or services; a sqlite store not made yet reads empty and is not made, Deep Agents not even imported for it; a database without its backend's tables, looked at read-only, reads empty, nothing written to it: no table, no journal mode); none for the memory store or LangGraph; ImportError (the install hint) for a missing extra; reader_backends │ │ ├── service_registry.py # get_service/require_service + ContextVar registry; the registry keys and KNOWN_SERVICE_KEYS, read from services.py's table @@ -84,7 +84,7 @@ agentic-cli/ │ │ │ ├── capabilities.py # Capability, EXEMPT │ │ │ ├── matchers.py # PathMatcher, URLMatcher, ShellMatcher, StringGlobMatcher │ │ │ └── rules.py, store.py, prompt.py (build_request(run=): a sub-agent's prompt opens with its run; is_permission_request: by its perm- id) -│ │ ├── agents/ # Sub-agents: runs.py: the RUN_* statuses (a working run's: RUN_QUEUED, RUN_RUNNING, RUN_INPUT_REQUIRED, RUN_WORKING_STATUSES; a record says running from its start), INSTANCE_RUNNING/IDLE/STOPPED/CLOSED and INSTANCE_STATUSES, InstanceRecord (an instance: parent, depth, title, status, runs, continuable, and the tools and model its first run's start gave it, and a general_purpose one's based_on, read as None from records without them), RunRecord (input: a follow-up's message as written, "" for a first run), AgentRuns (a manager's runs and instances by conversation: run_for names - and its first run #1 per (conversation, parent run, call id), a new one once it ended, and a start with no call (the user's) a new one each time; next_run: an instance's next run; instances/instance, kept from the events: a start makes or reopens the instance running, an end sets its status from instance_status, AGENT_INSTANCE a change without a run; number_from: past the instances a conversation's store keeps, a count never lowered; observe records AGENT_RUN under the turn it is reported in; interrupt_open; a record's usage: what the run used, by model, from its end event or the ledger; its plan and tasks: the run's own last, from its end event; RECORDS_VERSION, export (a conversation's records as JSON-safe data: v, saved, numbered, instances, runs) and restore (replaces them; a run found working ends interrupted, INTERRUPTED_ERROR, at the later of its start and saved, its instance idle, closed for a type that is not continuable; each run's end order stored (end), any time or field that does not read ValueError; counters never below an instance kept; ValueError for another version or records that do not read, nothing changed), stored_instance_ids (the instances stored records name; None for none), AgentRuns(on_change=): told each change, never by restore), run_title, result_head, run_instance and run_number (the one reader of a run id: researcher-2#1's instance and number), run_label (how a dialog names a run: researcher-2 (researcher, run 1)), SUBAGENT_ERROR_PREFIX (ADK's old words for a failed delegation, kept for callers), show_as_delegation(result, envelope) (a delegation's TOOL_RESULT shown alike on both backends: the result's first line, or Failed: ; metadata["result"] the envelope); a record's brief, started_by, mode and cancelled_by; delegate.py: Delegations (delegate(DelegationRequest) → Delegated and follow_up(FollowUpRequest) → Delegated: the one place a run starts and ends, on both backends (a follow-up is the instance's next run through the same hook, AgentRun.follow_up: refused as an error result, no run, for an unknown or not-yours instance (NOT_YOURS_ERROR, YOURS, NO_SUB_AGENTS), a closed one (CLOSED_ERROR), one the user stopped when an agent sends it (STOPPED_ERROR), a running one (RUNNING_ERROR), one whose type the app no longer has (TYPE_GONE_ERROR) and a blank message (NO_MESSAGE_ERROR); an agent's counts toward max_runs_per_turn, the user's (started_by USER) does not; a run's end carries the status it leaves its instance in: stopped for the user's cancel, closed for a type that is not continuable or the oldest idle one past max_open, else idle; close(conversation, instance, reason=): an idle or stopped instance and its descendants, AGENT_INSTANCE closed; open_calls=: the manager's OpenCalls, whose stop recorded for an instance is taken when the instance is left closed (its end, close, max_open, or a turn that stops a one-shot run), so its calls are freed; max_open ranks by AgentRuns.end_order, the order ends were recorded in, never the clock): the brief read against what the calling run may start (offered(agent, depth): its own sub-agents, then, while may_spawn, the types agents may start at run time, an inheriting one for the root alone, general_purpose last made for the caller's type (config_for(agent_type, based_on=), general_purpose: one per spawner type); task_offer: task's TaskOffer for that run, None for nothing; types: every agent type by name, read-only, what a skill's start checks against), its tools and model against the type's own (read_choices, tool_names= asked only for a call naming tools), then start(StartRequest, its tools= and model= carried to AgentRun.tools/.model and RunControl.tools, and general_purpose's based_on= to AgentRun.based_on, and said by its start: every run of the instance keeps them, a follow-up one whose type lost them refused, CHOICE_GONE_ERROR) (also start_by_user's, /agent new's: a type startable_by_user, spawnable for "user", else user_start_refused's USER_START_ERROR, NO_USER_TYPES_ERROR or NO_OBJECTIVE_ERROR as the error result; no caller or call, started_by USER, counted False, titled run_title(objective)), the one entry for a first run (counted unless the user's, started_by as given; who may start the type is the asker's to check), the run named (a turn's first run past the instances its conversation's store keeps: stored=, asked once per conversation per turn, again after a failed or stopped ask), its AGENT_RUN start and end observed and reported, the backend's hook (RunHook: AgentRun → RunAnswer) run in a task of its own with the run active and no tool call, the end by the answer (completed, partial for a cut or the step limit, refused, failed for an error or a raise, with one recoverable ERROR failed: , or RunFailed's own words, its result the text the run wrote before it failed (RunFailed(text=); a failed model call the hook's RunAnswer.error, failure_reason, with error_code its type, the warning's code), cancelled by its control with what the hook had), interrupted on its turn's cancel, which wins; the envelope as the result; each run under its RunControl, the type's limits over the policy's, kept while it works: control(run), cancel(run_id, by=, error=), the run alone; a call past max_runs_per_turn the error result RUNS_PER_TURN_ERROR, no run; the stored instances asked under a lock per conversation; forget(conversation): a deleted one's slots, unread messages, waiting closes and asks; each run in a working slot of its conversation's SlotPool, slots(conversation): policy.max_active slots, made on first use and kept, the root taking none: taken right before its hook and its time limit, queued then running while it waits for one, given back at its end, straight back to a caller that waits on it alone; a caller that delegates lends its slot while it waits for its children), DelegationRequest, StartRequest, FollowUpRequest, AgentRun (control, follow_up), RunAnswer, RunFailed, started_by, waiting_on_user (a sub-agent run waiting on the user: input_required, its slot lent, queued while its take-back waits for a slot, then running; nested waits once; request_user_input and the permission engine); records.py: RecordsWriter (each conversation's records written to its store as they change: changed, one write at a time per conversation taking the records as it starts, so changes made meanwhile go together in the next; flush, flush_all, discard (a delete's: what waits dropped, the write under way waited for); a failed write warned once per conversation, subagent_records_not_saved, never raised); slots.py: SlotPool (acquire(priority): a free slot, else a future in a heap by priority, RETURNING before NEW, then arrival; release; lent(slot, on_wait=): the slot lent while its run waits, nested lends once, taken back at RETURNING after (on_wait called when that has to wait), at most one take-back waiting for a slot and none once it is held (a wait that starts while one is queued takes it over, and one handed the slot withdraws any queued since), nothing taken back after a cancel, so a tool's caught timeout around a question leaves its run working without a slot, input_required until its next question is answered (running again, still without a slot) or its end; hand_back(slot, to): a child's slot to its parent waiting on it alone; free, waiting; a cancelled waiter leaves the heap, one handed a slot as it is cancelled hands it on; not asyncio.Semaphore), Slot (held, lent), RETURNING, NEW; control.py: RunControl (one run's: tools, the type's own tools it may use, and keeps(name): one of them or of KEPT_TOOLS, the state and delegation tools, what both backends filter by; cancel(by=, error=) its task, the first cancel winning, own_cancel for the hook that takes it and returns, finish: the hook's work ended, no cancel after it (ADK's state read loses no answer), timing: the time limit while the hook runs; model_call/at_step_limit/final_call: the step limit, STEP_LIMIT_NOTE on the last allowed call; used: the token limit, against its own calls and side_tokens (its side calls and summaries, from the ledger), an answer past it that makes calls the run's last, cancelled by it, one that makes none its result (calls=); model_call once final stays final; a cancel leaves a task its turn is cancelling alone; steer/take_steering), STEP_LIMIT_NOTE; outcome.py: a sub-agent's refused or cut answer (outcome_of, the refusal notice as Deep Agents 0.7.34 words it, cut_off, cut_off_warning, OPENAI_REFUSAL_PREFIX: how ADK's OpenAI adapters word a refusal); policy.py: SubAgentPolicy (max_active, max_runs_per_turn, limits, max_open, follow_ups, spawn_sources: of SPAWN_SOURCES, kept as a frozenset, max_spawn_depth, general_purpose: the built-in type, a ValueError without a source) and AgentLimits (max_model_calls, timeout, max_tokens; over: a type's limits over the policy's, field by field, None taking the base's), DEFAULT_LIMITS (100 model calls), frozen and checked as they are made (a ValueError naming the field), as_policy (the one reading of a subagents= argument: a TypeError for anything but a policy or None); brief.py: BRIEF_FIELDS, Brief, BriefError, read_brief (a task call's agent type and brief, against the types its caller may start: the error texts), read_choices (its tools, some of the type's own, and its model, one of its model_choices: TOOLS_ERROR, NO_TOOLS_ERROR, MODEL_ERROR, NO_MODEL_CHOICES_ERROR), task_message (a run's first message, a section per filled field; an inheriting type's ends with INHERITED_CONTEXT_NOTE), task_parameters and task_description (task's schema and description, the same for both backends: tools always, TOOLS_DESCRIPTION, model when a type offered has choices, MODEL_DESCRIPTION, and a type's line its "model choices: , "; limit_sentences: the limits it states, "At most sub-agents work at once; more calls in one response wait for a free slot. At most runs per turn.", then DEPTH_SENTENCE, "Sub-agents cannot start sub-agents.", when no run the call starts may start one; warn=False for a description made per run), TaskOffer and task_offer (both, for the types one run may start); envelope.py: envelope (a delegation run's result: success only for completed, a one-line error, cancelled_by for a cancelled run), read_envelope (a dict or its JSON text, else None; never raises), view_notice (`VIEW_NOTICE`: what the root is told once the user worked with an instance), the limit and interrupted error texts; `Delegations.message` (an idle instance's follow-up; a running one's run steered, or with `interrupt` cancelled by its parent and followed up; one run per instance, so of two messages to one idle instance in one answer the first runs and the second is steered into it), `stop` (a running instance's run cancelled by its parent, the instance idle; `close` closes it and its descendants, a running one's at its run's end), `check`, `steer(conversation, run, message)`, `stop_by_user`/`close_by_user` (`STOPPED_BY_USER_ERROR`, `CLOSED_BY_USER`: a running run cancelled by the user and waited for), `stop_cause(run)` and `cancel(..., conversation=)`; a message steered to a run that its transcript does not hold when it ends (`RunControl.unstored`) is kept for the instance's next run; a run whose parent's run its control stopped ends `cancelled` by its parent (`its parent's run was stopped`); a run that did not complete fully names its open tasks in its envelope (`envelope(open_tasks=)`, `open_task_descriptions`) and a cancelled run keeps its plan and tasks; `SubAgentPolicy.follow_ups`; brief.py: `follow_up_description`/`follow_up_parameters` (the parent's tools' texts); follow_ups.py: `call_follow_up_tool` (a message_agent, stop_agent or check_agents call as the run in progress); spawn.py: spawnable (the types a source may start at run time: the policy's spawn_sources and the type's spawnable_by, then GENERAL_PURPOSE with the policy's general_purpose), may_spawn (depth below max_spawn_depth), can_have_children (who is built with task, and with follow_ups the parent's tools and the roster: sub-agents, or a type agents may start while the root or runs below it may; the general-purpose type never), depth_sentence_applies, AGENT_SOURCE/SKILL_SOURCE/USER_SOURCE, general_purpose_config (the built-in type made for a spawner type: its tools, MCP servers, skills and model, GENERAL_PURPOSE_PROMPT, GENERAL_PURPOSE_DESCRIPTION), general_purpose_spawners (the types one is built for), root_type; no backend imports; roster.py: roster_text (the main agent's open sub-agents, newest first, one line each, ROSTER_OPEN/ROSTER_HEADER/ROSTER_CLOSE, at most ROSTER_MAX characters in whole lines, "" for none open), Rosters (a snapshot per conversation, as MemoryIndex: now, forget, clear; the root's own instances, parent root) +│ │ ├── agents/ # Sub-agents: runs.py: the RUN_* statuses (a working run's: RUN_QUEUED, RUN_RUNNING, RUN_INPUT_REQUIRED, RUN_WORKING_STATUSES; a record says running from its start), INSTANCE_RUNNING/IDLE/STOPPED/CLOSED and INSTANCE_STATUSES, InstanceRecord (an instance: parent, depth, title, status, runs, continuable, and the tools and model its first run's start gave it, and a general_purpose one's based_on, read as None from records without them), RunRecord (input: a follow-up's message as written, "" for a first run), AgentRuns (a manager's runs and instances by conversation: run_for names - and its first run #1 per (conversation, parent run, call id), a new one once it ended, and a start with no call (the user's) a new one each time; next_run: an instance's next run; instances/instance, kept from the events: a start makes or reopens the instance running, an end sets its status from instance_status, AGENT_INSTANCE a change without a run; number_from: past the instances a conversation's store keeps, a count never lowered; observe records AGENT_RUN under the turn it is reported in; interrupt_open; a record's usage: what the run used, by model, from its end event or the ledger; its plan and tasks: the run's own last, from its end event; RECORDS_VERSION, export (a conversation's records as JSON-safe data: v, saved, numbered, instances, runs) and restore (replaces them; a run found working ends interrupted, INTERRUPTED_ERROR, at the later of its start and saved, its instance idle, closed for a type that is not continuable; each run's end order stored (end), any time or field that does not read ValueError; counters never below an instance kept; ValueError for another version or records that do not read, nothing changed), stored_instance_ids (the instances stored records name; None for none), AgentRuns(on_change=): told a run's start and end, an instance's status change and interrupt_open, never a working status (a restart reads it as interrupted) nor restore), run_title, result_head, run_instance and run_number (the one reader of a run id: researcher-2#1's instance and number), run_label (how a dialog names a run: researcher-2 (researcher, run 1)), SUBAGENT_ERROR_PREFIX (ADK's old words for a failed delegation, kept for callers), show_as_delegation(result, envelope) (a delegation's TOOL_RESULT shown alike on both backends: the result's first line, or Failed: ; metadata["result"] the envelope); a record's brief, started_by, mode and cancelled_by; delegate.py: Delegations (delegate(DelegationRequest) → Delegated and follow_up(FollowUpRequest) → Delegated: the one place a run starts and ends, on both backends (a follow-up is the instance's next run through the same hook, AgentRun.follow_up: refused as an error result, no run, for an unknown or not-yours instance (NOT_YOURS_ERROR, YOURS, NO_SUB_AGENTS), a closed one (CLOSED_ERROR), one the user stopped when an agent sends it (STOPPED_ERROR), a running one (RUNNING_ERROR), one whose type the app no longer has (TYPE_GONE_ERROR) and a blank message (NO_MESSAGE_ERROR); an agent's counts toward max_runs_per_turn, the user's (started_by USER) does not; a run's end carries the status it leaves its instance in: stopped for the user's cancel, closed for a type that is not continuable or the oldest idle one past max_open, else idle; close(conversation, instance, reason=): an idle or stopped instance and its descendants, AGENT_INSTANCE closed; open_calls=: the manager's OpenCalls, whose stop recorded for an instance is taken when the instance is left closed (its end, close, max_open, or a turn that stops a one-shot run), so its calls are freed; max_open ranks by AgentRuns.end_order, the order ends were recorded in, never the clock): the brief read against what the calling run may start (offered(agent, depth): its own sub-agents, then, while may_spawn, the types agents may start at run time, an inheriting one for the root alone, general_purpose last made for the caller's type (config_for(agent_type, based_on=), general_purpose: one per spawner type); task_offer: task's TaskOffer for that run, None for nothing; types: every agent type by name, read-only, what a skill's start checks against), its tools and model against the type's own (read_choices, tool_names= asked only for a call naming tools), then start(StartRequest, its tools= and model= carried to AgentRun.tools/.model and RunControl.tools, and general_purpose's based_on= to AgentRun.based_on, and said by its start: every run of the instance keeps them, a follow-up one whose type lost them refused, CHOICE_GONE_ERROR) (also start_by_user's, /agent new's: a type startable_by_user, spawnable for "user", else user_start_refused's USER_START_ERROR, NO_USER_TYPES_ERROR or NO_OBJECTIVE_ERROR as the error result; no caller or call, started_by USER, counted False, titled run_title(objective)), the one entry for a first run (counted unless the user's, started_by as given; who may start the type is the asker's to check), the run named (a turn's first run past the instances its conversation's store keeps: stored=, asked once per conversation per turn, again after a failed or stopped ask), its AGENT_RUN start and end observed and reported, the backend's hook (RunHook: AgentRun → RunAnswer) run in a task of its own with the run active and no tool call, the end by the answer (completed, partial for a cut or the step limit, refused, failed for an error or a raise, with one recoverable ERROR failed: , or RunFailed's own words, its result the text the run wrote before it failed (RunFailed(text=); a failed model call the hook's RunAnswer.error, failure_reason, with error_code its type, the warning's code), cancelled by its control with what the hook had), interrupted on its turn's cancel, which wins; the envelope as the result; each run under its RunControl, the type's limits over the policy's, kept while it works: control(run), cancel(run_id, by=, error=), the run alone; a call past max_runs_per_turn the error result RUNS_PER_TURN_ERROR, no run; the stored instances asked under a lock per conversation; forget(conversation): a deleted one's slots, unread messages, waiting closes and asks; each run in a working slot of its conversation's SlotPool, slots(conversation): policy.max_active slots, made on first use and kept, the root taking none: taken right before its hook and its time limit, queued then running while it waits for one, given back at its end, straight back to a caller that waits on it alone; a caller that delegates lends its slot while it waits for its children), DelegationRequest, StartRequest, FollowUpRequest, AgentRun (control, follow_up), RunAnswer, RunFailed, started_by, waiting_on_user (a sub-agent run waiting on the user: input_required, its slot lent, queued while its take-back waits for a slot, then running; nested waits once; request_user_input and the permission engine); records.py: RecordsWriter (each conversation's records written to its store as they change: changed, one write at a time per conversation taking the records as it starts, so changes made meanwhile go together in the next; flush, flush_all, discard (a delete's: what waits dropped, the write under way waited for); a failed write warned once per conversation, subagent_records_not_saved, never raised; RECORDS_NOT_STORED and RECORDS_NOT_STORED_CODE: the failure of a run that makes its transcript whose start could not be stored); slots.py: SlotPool (acquire(priority): a free slot, else a future in a heap by priority, RETURNING before NEW, then arrival; release; lent(slot, on_wait=): the slot lent while its run waits, nested lends once, taken back at RETURNING after (on_wait called when that has to wait), at most one take-back waiting for a slot and none once it is held (a wait that starts while one is queued takes it over, and one handed the slot withdraws any queued since), nothing taken back after a cancel, so a tool's caught timeout around a question leaves its run working without a slot, input_required until its next question is answered (running again, still without a slot) or its end; hand_back(slot, to): a child's slot to its parent waiting on it alone; free, waiting; a cancelled waiter leaves the heap, one handed a slot as it is cancelled hands it on; not asyncio.Semaphore), Slot (held, lent), RETURNING, NEW; control.py: RunControl (one run's: tools, the type's own tools it may use, and keeps(name): one of them or of KEPT_TOOLS, the state and delegation tools, what both backends filter by; cancel(by=, error=) its task, the first cancel winning, own_cancel for the hook that takes it and returns, finish: the hook's work ended, no cancel after it (ADK's state read loses no answer), timing: the time limit while the hook runs; model_call/at_step_limit/final_call: the step limit, STEP_LIMIT_NOTE on the last allowed call; used: the token limit, against its own calls and side_tokens (its side calls and summaries, from the ledger), an answer past it that makes calls the run's last, cancelled by it, one that makes none its result (calls=); model_call once final stays final; a cancel leaves a task its turn is cancelling alone; steer/take_steering), STEP_LIMIT_NOTE; outcome.py: a sub-agent's refused or cut answer (outcome_of, the refusal notice as Deep Agents 0.7.34 words it, cut_off, cut_off_warning, OPENAI_REFUSAL_PREFIX: how ADK's OpenAI adapters word a refusal); policy.py: SubAgentPolicy (max_active, max_runs_per_turn, limits, max_open, follow_ups, spawn_sources: of SPAWN_SOURCES, kept as a frozenset, max_spawn_depth, general_purpose: the built-in type, a ValueError without a source) and AgentLimits (max_model_calls, timeout, max_tokens; over: a type's limits over the policy's, field by field, None taking the base's), DEFAULT_LIMITS (100 model calls), frozen and checked as they are made (a ValueError naming the field), as_policy (the one reading of a subagents= argument: a TypeError for anything but a policy or None); brief.py: BRIEF_FIELDS, Brief, BriefError, read_brief (a task call's agent type and brief, against the types its caller may start: the error texts), read_choices (its tools, some of the type's own, and its model, one of its model_choices: TOOLS_ERROR, NO_TOOLS_ERROR, MODEL_ERROR, NO_MODEL_CHOICES_ERROR), task_message (a run's first message, a section per filled field; an inheriting type's ends with INHERITED_CONTEXT_NOTE), task_parameters and task_description (task's schema and description, the same for both backends: tools always, TOOLS_DESCRIPTION, model when a type offered has choices, MODEL_DESCRIPTION, and a type's line its "model choices: , "; limit_sentences: the limits it states, "At most sub-agents work at once; more calls in one response wait for a free slot. At most runs per turn.", then DEPTH_SENTENCE, "Sub-agents cannot start sub-agents.", when no run the call starts may start one; warn=False for a description made per run), TaskOffer and task_offer (both, for the types one run may start); envelope.py: envelope (a delegation run's result: success only for completed, a one-line error, cancelled_by for a cancelled run), read_envelope (a dict or its JSON text, else None; never raises), view_notice (`VIEW_NOTICE`: what the root is told once the user worked with an instance), the limit and interrupted error texts; `Delegations.message` (an idle instance's follow-up; a running one's run steered, or with `interrupt` cancelled by its parent and followed up; one run per instance, so of two messages to one idle instance in one answer the first runs and the second is steered into it), `stop` (a running instance's run cancelled by its parent, the instance idle; `close` closes it and its descendants, a running one's at its run's end), `check`, `steer(conversation, run, message)`, `stop_by_user`/`close_by_user` (`STOPPED_BY_USER_ERROR`, `CLOSED_BY_USER`: a running run cancelled by the user and waited for), `stop_cause(run)` and `cancel(..., conversation=)`; a message steered to a run that its transcript does not hold when it ends (`RunControl.unstored`) is kept for the instance's next run; a run whose parent's run its control stopped ends `cancelled` by its parent (`its parent's run was stopped`); a run that did not complete fully names its open tasks in its envelope (`envelope(open_tasks=)`, `open_task_descriptions`) and a cancelled run keeps its plan and tasks; `SubAgentPolicy.follow_ups`; brief.py: `follow_up_description`/`follow_up_parameters` (the parent's tools' texts); follow_ups.py: `call_follow_up_tool` (a message_agent, stop_agent or check_agents call as the run in progress); spawn.py: spawnable (the types a source may start at run time: the policy's spawn_sources and the type's spawnable_by, then GENERAL_PURPOSE with the policy's general_purpose), may_spawn (depth below max_spawn_depth), can_have_children (who is built with task, and with follow_ups the parent's tools and the roster: sub-agents, or a type agents may start while the root or runs below it may; the general-purpose type never), depth_sentence_applies, AGENT_SOURCE/SKILL_SOURCE/USER_SOURCE, general_purpose_config (the built-in type made for a spawner type: its tools, MCP servers, skills and model, GENERAL_PURPOSE_PROMPT, GENERAL_PURPOSE_DESCRIPTION), general_purpose_spawners (the types one is built for), root_type; no backend imports; roster.py: roster_text (the main agent's open sub-agents, newest first, one line each, ROSTER_OPEN/ROSTER_HEADER/ROSTER_CLOSE, at most ROSTER_MAX characters in whole lines, "" for none open), Rosters (a snapshot per conversation, as MemoryIndex: now, forget, clear; the root's own instances, parent root) │ │ ├── adk/ # ADK orchestrator │ │ │ ├── manager.py # GoogleADKWorkflowManager (the agents built from configs or, adk_config_path, by ADK from a native YAML (library-only: no BaseCLIApp starts one; loaded once per manager at the first _validate_agent_graph (_native_root: the settings' keys exported first; a retry, a model switch and a start after cleanup build on the same tree, whose toolsets the closed runner left reusable), its agents' models resolved leniently in _resolve_extra_models, the base's hook, its registered tools' services detected; configs passed with it ignored, adk_native_configs_ignored): the only difference; _do_initialize builds the app from the tree alone, _build_app → ADKBuild, through the hooks _plugin_chain (the whole chain, top to bottom, its head _init_plugins), _compaction_config (None for a root without a budget), _context_cache_config, _agent_model_refs; the event processor built from the build; a config-built agent's prompt as an instruction provider, sent as written: no `{name}` state injection; _compact_turn: ADK's compaction once, in the base's compact turn; supports_compact False once built for a root without a budget (_no_compact_support says why); the job resume hooks: _conversation_exists (the session read without its events, num_recent_events=0), _deliver_job_notice (the notice, for every app); _run_config: the agents' synchronous tools run in ADK's tool thread pool, 8 workers; _run_and_stream: a run that fails yields the turn's one ERROR, last, none after an ERROR already yielded, and keeps the record of its calls that returned for the next turn (OpenCalls.failed; _answer_left_open forgets it once its answers are stored); the agents: _create_agents builds each config's agent on its own (_agents, by name; no ADK sub_agents), a delegating one with a TaskTool (its own tool named task: AgentGraphError); a runner per sub-agent type (_agent_runners: NoAfterTurnCompactionRunner on App(name=child_app(app_name), root_agent=the type's agent, plugins=_agent_plugin_chain(agent), the app's context cache, no compaction) over the session service, closed with the main runner by _detach_backend, rebuilt by every initialization); a runner per (type, model choice) too (_variant_runners over _variant_agents: the type's agent built on the choice, _build_agent(model=), its chain _agent_plugin_chain(agent, model=, budget=), every plugin reading the choice's model, kind and numbers under the type's name), closed and rebuilt alike; _general_agents/_general_runners: the built-in general_purpose type's agent and runner per spawner type (Delegations.general_purpose, no delegation tools), picked by run.based_on; _agent_tool_names: the built agent's tools by name, an MCP toolset's listed when first asked and kept for the build; _run_agent, the base's hook: the runner of run.model's choice or the type's, its processor on _run_models' maps, the raw log told the choice (_chosen_model); the instance's child session (_child_session: a first run makes it from run.state and an inheriting instance's copied events, once; never one the store keeps, whose instance numbering goes past: ADK's create_session refuses it, and the run fails; a follow-up takes the stored session, answers the calls an earlier run left open there (left_open_by) and passes the caller's mark when it holds none; one the store lost is made as a first run's), _stored_instances (the base's hook: the highest instance number of each type the conversation's child sessions keep), the type's runner on the task message (a follow-up's own message) with an abort signal set before it is closed, a run-mode ADKEventProcessor, the raw log's records reported as they come (_report_raw_log); a model's failure raised as the provider's (_plugin_cause), an overflow RunFailed, a reply that is no answer RunAnswer(error=), the shared keys it changed read back) │ │ │ ├── build.py # ADKBuild (root, reply_agents, plugins, compaction, cache, models); load_native_root (from_config at validation; what ADK cannot load, wrapped as AgentGraphError naming the file, ADK's error the cause; a root that is not an LlmAgent, a name used twice in the tree and a task-mode agent refused, AgentGraphError naming it; ensure_direct_anthropic); what the run reads of any tree: reply_agents (the root and the chat-mode agents it can transfer to), own_after_tool_agents (left out by the cap) @@ -95,7 +95,7 @@ agentic-cli/ │ │ │ ├── overflow_plugin.py # OverflowPlugin (OVERFLOW_PLUGIN_FAILED: ADK's wrapper of its errors, which the manager unwraps): a provider's overflow summarized (the root; the retry: the memory index and roster that open the request, the summary and the turns it kept) or trimmed (a sub-agent's keeping its task message and its instance's brief), retried once (the retry timed around its own request: call_clock.mark_latency), then CONTEXT_OVERFLOW: overflow_message for an agent that replies (reply_agents), subagent_overflow_message for a sub-agent's run (root None on its runner), which fails it; a sub-agent's trimmed retry keeps its task message (keep_task) │ │ │ ├── memory_index_plugin.py # MemoryIndexPlugin: the conversation's memory index first in the root's requests (before the overflow handler and the fit guard, which keep and fold it) │ │ │ ├── roster_plugin.py # RosterPlugin: the conversation's roster of the root's open sub-agents first in the root's requests, before MemoryIndexPlugin (which puts the index ahead of it), for a root with message_agent -│ │ │ ├── sessions.py # A conversation's row in its session state (agentic_cli.title, agentic_cli.turns), saved with each user turn (run_async(state_delta=)); typed_prompts, NOTICE_METADATA and is_notice (a notice to the root's run, left out of both typed_prompts and recent_messages); ServiceSessions: the session hooks over a session service (the manager's and its reader's); make_session_service, session_db_url; open_sessions (a reader's store: empty without ADK's sessions table, looked at read-only); CHILD_APP_SUFFIX, child_app (--agents: the sub-agent runs' app, which no conversation list reads), child_session_id (/, the conversation id's % and / percent-encoded, so its first / always ends the conversation and no two conversations share an id; child_of reads one back; a ValueError past ADK's 128 characters; the instance's follow-up runs continue it), delete_children (a conversation's child sessions, events and all: those its records name and every one a listing finds), stored_instances (the highest instance number of each type a conversation's child sessions keep: by the instances its records name, else a listing); BRIEF_KEY (agentic_cli.brief): set by an instance's first run with its message, marking it as the instance's brief; RECORDS_KEY (agentic_cli.agents): a conversation's sub-agent records, in the child app's session named as the conversation, encoded (records_session_id, a ValueError past ADK's 128 characters; load_records, save_records: the header under RECORDS_KEY and a key for each instance and run, made at the first write, then one event per write whose state delta holds only the keys that changed; delete_records); ServiceSessions.delete: the transcripts, then the records, then the conversation, whatever its look found +│ │ │ ├── sessions.py # A conversation's row in its session state (agentic_cli.title, agentic_cli.turns), saved with each user turn (run_async(state_delta=)); typed_prompts, NOTICE_METADATA and is_notice (a notice to the root's run, left out of both typed_prompts and recent_messages); ServiceSessions: the session hooks over a session service (the manager's and its reader's); make_session_service, session_db_url; open_sessions (a reader's store: empty without ADK's sessions table, looked at read-only); CHILD_APP_SUFFIX, child_app (--agents: the sub-agent runs' app, which no conversation list reads), child_session_id (/, the conversation id's % and / percent-encoded, so its first / always ends the conversation and no two conversations share an id; child_of reads one back; a ValueError past ADK's 128 characters; the instance's follow-up runs continue it), delete_children (a conversation's child sessions, events and all: those its records name, which name every one, none without records; a listing only for records that do not read), stored_instances (the highest instance number of each type a conversation's child sessions keep: by the instances its records name, none without records, a listing only for records that do not read); BRIEF_KEY (agentic_cli.brief): set by an instance's first run with its message, marking it as the instance's brief; RECORDS_KEY (agentic_cli.agents): a conversation's sub-agent records, in the child app's session named as the conversation, encoded (records_session_id, a ValueError past ADK's 128 characters; load_records, save_records: the header under RECORDS_KEY and a key for each instance and run, made at the first write, then one event per write whose state delta holds only the keys that changed; past RECORDS_REWRITE_AFTER (100) writes the next one rewrites the records whole into the other of two sessions, records_session_ids: the id and the id plus /, alternating by _GENERATION_KEY, a read taking the higher generation, a conversation whose second id exceeds MAX_KEY appending to its one; neither names an instance, child_of; delete_records deletes both); ServiceSessions.delete: the transcripts, then the records, then the conversation, whatever its look found │ │ │ ├── event_processor.py # ADKEventProcessor (each call's LLM_USAGE normalized by its model's provider kind, kinds (an agent without one: an unknown kind's), with its latency (call_clock's mark), and recorded in the conversation's ledger before on_event, a run's end with what it used; reply_agents: the agents whose text is the reply; another's, a sub-agent's, marked as activity; a reply that is no answer, NO_ANSWER_CODES, → the turn's ERROR; a failed result, an MCP isError one too, → a failed TOOL_RESULT naming its error, as on Deep Agents; TASK_PROGRESS after a tool call that changed the task list, its state delta's tasks, as on Deep Agents: start_turn forgets the list reported; every event names its run, the agent's own at depth 0, TOOL_CALL and TOOL_RESULT their tool_call_id; a task call's TOOL_RESULT shown as on Deep Agents, from its envelope: show_as_delegation; run=: a processor for one sub-agent run, on its child session, every event that run's, a sub-agent's text activity, no TASK_PROGRESS (a run's list is its own: only the root's is reported), its last answer with text, its outcome mark and its failure kept (answer, outcome, failure: an overflow, a reply that is no answer but an empty one) for _run_agent) │ │ │ ├── model_factory.py # build_adk_model: ResolvedModel → ADK model, config, planner │ │ │ ├── openai_compatible.py # OpenAICompatibleLlm (the configured providers: openrouter and openai_compatible kinds; reasoning text; OpenRouter's reasoning_details kept on the thought part (thought_signature, with the model that wrote them) and sent back on that turn's assistant message to that model only; a Chat Completions refusal, streamed or not, as the text ADK's Responses adapter makes of one, "OpenAI refusal: "; no field sent as null; OpenRouter's cache writes, which ADK's usage mapping drops, kept on the usage as cache_creation_input_tokens) @@ -119,10 +119,10 @@ 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 what a run at the agent's first depth is offered, task_offer: the root's fixed, a sub-agent's rewritten per call by RunControlMiddleware; bound to the task declaration; a call by a run offered nothing answered unknown_tool_result, as ADK answers a tool it did not declare): 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); start_skill_run (a load_skill of a skill that names an agent type: SkillAgents.start, answered as task is, one Command) │ │ │ ├── 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: 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) +│ │ │ ├── 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 (messages read through _messages_at: a one-node graph of AgentCliState over the saver, compiled at the first read, which puts a checkpoint's messages together from their deltas, for a reader without a manager too; instances: the scan of 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), only for records that do not read; stored_instances and delete: the stored records' ids and counters and the instances they name, none without records, the scan for records that do not read; 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) +│ │ │ └── state.py # AgentCliState (a DeepAgentState: messages are its delta channel, the new messages per checkpoint and a full copy every 50 updates): plan, tasks (last write wins), outside_content (first write wins) │ │ └── langgraph/ # LangGraph orchestrator (deprecated, removed in 0.8.0) │ │ ├── manager.py # LangGraphWorkflowManager │ │ ├── graph_builder.py # LangGraphBuilder (graph; one chat model per agent via langchain_models) @@ -271,7 +271,7 @@ Workflow: - **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, 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). +- **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, which name every transcript, since a first run's is made only once its start is stored; every child id whose decoded conversation it is, `child_of`, only for records that do not read). 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 the conversation's records, the threads only for records that do not read (`_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 its records name (the scan's for records that do not read) before the conversation's records and its thread (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 at a run's start and end and an instance's status change (`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 and the instances they name (the store's own look only for records that do not read, and the store refusing a first run onto a transcript); 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. - **Resource ownership**: one release, `BaseWorkflowManager._release_resources` (cleanup, reinitialize and a failed initialization's rollback run it): it resets the base's state (`_initialized`, budgets, index snapshots, the catalog detached), takes the backend's closers from `_detach_backend()` (ADK: the runner, which closes the agents' MCP toolsets; Deep Agents: the agents' MCP sessions, handed over to a fresh `MCPSessions`) and `_detach_store()` (ADK: the session service; Deep Agents: the checkpointer, the session index and their connections), detaches the services through `_cleanup_managers` (the release's services hook: a backend's override runs; outside a release, as in LangGraph's cleanup, it closes them in place) and starts closing them on a worker thread (their closers block: `docker rm -f`, a kernel shutdown, the jobs directory's lock; on the loop they froze the app), then runs the closers (backend, store, catalog, then the services' close waited for last under a shield of its own: a hanging service close holds none of the rest, and a shutdown's cancel cancels no close not yet started) in one task awaited under a shield, each isolated (`_aclose_owned` for a duck-typed `aclose()`/`close()`): a cancel stops only the wait. The hooks are synchronous: one that returns an awaitable is closed and fails the release with a `TypeError`, after the rest is released. An override of `_release_resources` reads `self._keeping_store` to know whether a switch keeps the store. `cleanup()` is idempotent; `WorkflowController.close()` is the single shutdown path (cancel init → shut executor → clean manager). `reinitialize(preserve_sessions=True)` (a model switch) runs inside `_keeping(True)` (`_carrying_services` is its other name): the store is not detached and the services are carried, since session grants, sandbox kernels, jobs, knowledge bases and the conversations belong to the conversation, not the model, so neither the release nor a failed attempt's rollback closes them (a retry continues the conversation); the backend's own resources (ADK's runner, Deep Agents' MCP sessions) close and reopen. `_release_resources(keep_session_service=/keep_checkpointer=)` keeps the store, with a `DeprecationWarning`, until 0.8.0. LangGraph keeps its own `cleanup`/`reinitialize`. A run's services can move to a manager of either backend: `loan = old.lend_services()` (the table's services `old` owns, but itself), `await new.initialize_services(services=loan)` (borrowed, published, only what is missing built; no release of `new` closes them, so a failed, cancelled or abandoned start leaves `old` owning and using them), `await old.give_services(loan)` (between turns: inside one of `old`'s it raises `RuntimeError`; under `old`'s lifecycle and turn locks and `new`'s lifecycle lock: `new` owns them, each row's `rebind` moves the permission engine's `workflow`/`per_call` and the knowledge base's summarizer to it, and `old`'s release drops them unclosed). A manager holding services it does not own runs no turn (`_turn_admission` raises `RuntimeError`): the engine's per-call check reads its owner's outside-content marks, so `new` runs none before the give and `old` none after it until its release. The CLI's `WorkflowController.switch_backend` (a conversation opened or started on another backend) hands the run's services over so: lend, start, give, publish at once, release the old one. diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index 9aa06a23..393673d6 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -1947,10 +1947,12 @@ async def _child_session( the store lost is made as a first run's, the follow-up's message alone. - A session is made only once the conversation's records name its - instance (the run's start written: ``_agent_records_written``), so - the records name every transcript the conversation keeps, which is - how its delete and its numbering find them (``adk/sessions.py``). + A session is made, by a first run or a follow-up whose session is + gone, only once the conversation's records name its instance (the + run's start written: ``_agent_start_stored``, which fails the run + when the store did not take the write), so the records name every + transcript the conversation keeps, which is how its delete and its + numbering find them (``adk/sessions.py``). Returns: The shared state the run starts from, and the state delta its @@ -1971,7 +1973,7 @@ async def _child_session( return start, {OUTSIDE_CONTENT_KEY: mark} return start, None if run.conversation is not None: - await self._agent_records_written(run.conversation) + await self._agent_start_stored(run.conversation) session = await service.create_session( app_name=app, user_id=user_id, session_id=session_id, state=dict(run.state) ) diff --git a/src/agentic_cli/workflow/adk/sessions.py b/src/agentic_cli/workflow/adk/sessions.py index cf61b73a..d4be98fe 100644 --- a/src/agentic_cli/workflow/adk/sessions.py +++ b/src/agentic_cli/workflow/adk/sessions.py @@ -48,12 +48,18 @@ a write's event holds what changed and the records grow in step with the conversation, not with the square of it: ``RECORDS_KEY`` holds the header (version, time, counters) and ``RECORDS_KEY.instance.`` and -``RECORDS_KEY.run.`` the n-th instance and run. No two conversations' +``RECORDS_KEY.run.`` the n-th instance and run. Its events would still +grow without bound, so past ``RECORDS_REWRITE_AFTER`` writes the next one +rewrites the records whole into a second session (``records_session_ids``: +the conversation's id and that plus ``/``, alternating, ``_GENERATION_KEY`` +telling the newer, which a read takes), then deletes the first. No two conversations' records or transcripts share an id. Numbering past the stored instances -finds a conversation's children by the instances its records name, a -listing of the user's child sessions only for a conversation without -readable records; a delete removes both, so a transcript the records never -named (a start write that was lost) goes too. ``ServiceSessions.delete`` +finds a conversation's children by the instances its records name: a first +run's session is made only once its start is in the records, so they name +every one, and a conversation without records has none. A listing of the +user's child sessions is only for records that do not read (another +version's), which this manager writes none of its runs to; a delete follows +the same rule. ``ServiceSessions.delete`` deletes the transcripts first, then the records, then the conversation, so a delete cut short leaves the conversation, by which the rest is found again. """ @@ -102,6 +108,13 @@ _INSTANCE_KEY = f"{RECORDS_KEY}.instance." _RUN_KEY = f"{RECORDS_KEY}.run." +#: How many writes are appended to one records session before the next write +#: rewrites the records whole into the other one (``save_records``). +RECORDS_REWRITE_AFTER = 100 +#: The state key of a records session's generation: ``{"n": , "writes": +#: }``, the rewrites so far and the writes appended since the last. +_GENERATION_KEY = f"{RECORDS_KEY}.generation" + #: What a child session's app name adds to the conversation's app name. CHILD_APP_SUFFIX = "--agents" #: The longest app name or session id ADK stores (``sessions/schemas/shared.py``). @@ -134,9 +147,27 @@ def records_session_id(conversation: str) -> str: return session_id +def records_session_ids(conversation: str) -> tuple[str, str | None]: + """The two child-app sessions that alternate as ``conversation``'s records session. + + ``(records_session_id(conversation), that + "/")``: the records are + rewritten whole into the other one past ``RECORDS_REWRITE_AFTER`` writes + (``save_records``). The second is None when its id would be longer than + ADK stores (``MAX_KEY``): that conversation keeps appending to its one. + Neither names an instance (``child_of``). + + Raises: + ValueError: The first id is longer than ADK stores, as ``records_session_id``. + """ + first = records_session_id(conversation) + second = f"{first}/" + return first, second if len(second) <= MAX_KEY else None + + def child_of(session_id: str) -> tuple[str, str] | None: """The conversation and the instance a child app's session id names - (``child_session_id``, decoded); None for a records session or an id that names none.""" + (``child_session_id``, decoded); None for a records session (either of its + two, ``records_session_ids``) or an id that names none.""" encoded, slash, instance = session_id.partition("/") if not slash or not instance or "/" in instance: return None @@ -164,11 +195,18 @@ def child_session_id(conversation: str, instance: str) -> str: async def _named_children( service: "BaseSessionService", app_name: str, user_id: str, conversation: str ) -> list[str] | None: - """The ids of the child sessions ``conversation``'s stored records name; None - without readable records (one look at its records session).""" - named = stored_instance_ids( - await load_records(service, SessionRef(app_name, user_id, conversation)) - ) + """The ids of the child sessions ``conversation``'s stored records name (one + look at its records session). + + A first run's session is made only once its start is in the records, so + they name every one: none when the conversation has no records. None + only for records that do not read (another version's), which only a + listing can answer for. + """ + stored = await load_records(service, SessionRef(app_name, user_id, conversation)) + if stored is None: + return [] + named = stored_instance_ids(stored) if named is None: return None prefix = f"{_encoded(conversation)}/" @@ -198,10 +236,9 @@ async def _children( ) -> list[str]: """The ids of ``conversation``'s child sessions, ``user_id``'s, to number past. - Each is ``child_session_id(conversation, )``. A conversation - with records has the instances they name; one without, those a listing - finds. A transcript the records never named is no loss here: a first run - onto an existing session is refused. + Each is ``child_session_id(conversation, )``: the instances the + conversation's records name, none without records, and a listing's only + for records that do not read. """ named = await _named_children(service, app_name, user_id, conversation) if named is not None: @@ -209,26 +246,64 @@ async def _children( return await _listed_children(service, app_name, user_id, conversation) -async def load_records(service: "BaseSessionService", ref: SessionRef) -> Any | None: - """``ref``'s records, put back together from its records session; None for none. +async def _current_records( + service: "BaseSessionService", ref: SessionRef +) -> tuple["Session", str, str | None] | None: + """The records session of ``ref`` with the higher generation (``_GENERATION_KEY``), + with the two ids (``records_session_ids``); None for none, or when no id fits. - The header under ``RECORDS_KEY`` with ``instances`` and ``runs`` from the - keys that hold each (in order). Read without the session's events - (``num_recent_events=0``). + Read without events (``num_recent_events=0``). Both sessions exist only + when a rewrite was cut short before it deleted the older one: the newer + holds the whole records, and a session without the key is generation 0. """ from google.adk.sessions.base_session_service import GetSessionConfig try: - session_id = records_session_id(ref.session_id) + first, second = records_session_ids(ref.session_id) except ValueError: return None # its records could never be stored: none are - session = await service.get_session( - app_name=child_app(ref.app_name), user_id=ref.user_id, session_id=session_id, - config=GetSessionConfig(num_recent_events=0), - ) - if session is None: + best: Session | None = None + best_generation = -1 + for session_id in (first, second): + if session_id is None: + continue + session = await service.get_session( + app_name=child_app(ref.app_name), user_id=ref.user_id, session_id=session_id, + config=GetSessionConfig(num_recent_events=0), + ) + if session is None: + continue + generation = _generation(session.state or {}) + if generation["n"] > best_generation: + best, best_generation = session, generation["n"] + return None if best is None else (best, first, second) + + +def _generation(state: Mapping[str, Any]) -> dict[str, int]: + """``state``'s generation: its rewrites so far (``n``) and the writes + appended since (``writes``).""" + held = state.get(_GENERATION_KEY) + if not isinstance(held, Mapping): + return {"n": 0, "writes": 0} + n, writes = held.get("n"), held.get("writes") + return { + "n": n if type(n) is int else 0, + "writes": writes if type(writes) is int else 0, + } + + +async def load_records(service: "BaseSessionService", ref: SessionRef) -> Any | None: + """``ref``'s records, put back together from its records session; None for none. + + The header under ``RECORDS_KEY`` with ``instances`` and ``runs`` from the + keys that hold each (in order). Read without the session's events + (``num_recent_events=0``), from the newer of the two sessions the records + alternate between (``records_session_ids``). + """ + found = await _current_records(service, ref) + if found is None: return None - state = session.state or {} + state = found[0].state or {} header = state.get(RECORDS_KEY) if not isinstance(header, Mapping): return None @@ -265,23 +340,27 @@ async def save_records( holds only the keys that differ from what the session holds (the header, the instances and runs that changed or came, a key the records no longer hold set to None), so a write costs what changed (``append_event``: ADK - keeps a session's state only through its events). + keeps a session's state only through its events). Its events would grow + without bound, so once ``RECORDS_REWRITE_AFTER`` writes were appended the + next one rewrites the records whole into the other of the two sessions + (``records_session_ids``), one generation on (``_GENERATION_KEY``), and + deletes the first: the older session is deleted before the new one is + made (one a cut-short rewrite left), and the new one before the old, so + a crash between leaves both and a read takes the newer. """ from google.adk.events import Event, EventActions - from google.adk.sessions.base_session_service import GetSessionConfig app = child_app(ref.app_name) - session_id = records_session_id(ref.session_id) + first, second = records_session_ids(ref.session_id) flat = _flat(data) - session = await service.get_session( - app_name=app, user_id=ref.user_id, session_id=session_id, - config=GetSessionConfig(num_recent_events=0), - ) - if session is None: + found = await _current_records(service, ref) + if found is None: await service.create_session( - app_name=app, user_id=ref.user_id, session_id=session_id, state=flat, + app_name=app, user_id=ref.user_id, session_id=first, + state={**flat, _GENERATION_KEY: {"n": 0, "writes": 0}}, ) return + session = found[0] held = session.state or {} delta: dict[str, Any] = {key: value for key, value in flat.items() if held.get(key) != value} for key, value in held.items(): @@ -289,20 +368,36 @@ async def save_records( delta[key] = None if not delta: return + generation = _generation(held) + if generation["writes"] >= RECORDS_REWRITE_AFTER and second is not None: + other = second if session.id == first else first + await service.delete_session(app_name=app, user_id=ref.user_id, session_id=other) + await service.create_session( + app_name=app, user_id=ref.user_id, session_id=other, + state={**flat, _GENERATION_KEY: {"n": generation["n"] + 1, "writes": 0}}, + ) + await service.delete_session(app_name=app, user_id=ref.user_id, session_id=session.id) + return + delta[_GENERATION_KEY] = {"n": generation["n"], "writes": generation["writes"] + 1} await service.append_event(session, Event( author=RECORDS_AUTHOR, actions=EventActions(state_delta=delta), )) async def delete_records(service: "BaseSessionService", ref: SessionRef) -> None: - """Delete ``ref``'s records session, its events with it; none is nothing to do.""" + """Delete ``ref``'s records sessions (both: ``records_session_ids``). + + Their events go with them; none is nothing to do. + """ try: - session_id = records_session_id(ref.session_id) + ids = records_session_ids(ref.session_id) except ValueError: return # its records could never be stored: none are - await service.delete_session( - app_name=child_app(ref.app_name), user_id=ref.user_id, session_id=session_id, - ) + for session_id in ids: + if session_id is not None: + await service.delete_session( + app_name=child_app(ref.app_name), user_id=ref.user_id, session_id=session_id, + ) async def delete_children( @@ -312,10 +407,10 @@ async def delete_children( Every session of ``app_name``'s child app (``child_app``) that is ``user_id``'s and ``conversation``'s (``child_session_id``): those its - records name and those a listing finds (a transcript the records never - named, its start write lost, goes too); their events go with them (ADK's - session store deletes a session's events with it). What a conversation's - delete leaves of it otherwise. + records name, which name every one (none without records), and, for + records that do not read, those a listing finds; their events go with + them (ADK's session store deletes a session's events with it). What a + conversation's delete leaves of it otherwise. Args: service: The session service the conversation is in. @@ -326,10 +421,11 @@ async def delete_children( Returns: How many it deleted: the instances' transcripts, not the records. """ - children = sorted({ - *(await _named_children(service, app_name, user_id, conversation) or ()), - *await _listed_children(service, app_name, user_id, conversation), - }) + named = await _named_children(service, app_name, user_id, conversation) + children = sorted( + named if named is not None + else await _listed_children(service, app_name, user_id, conversation) + ) for session_id in children: await service.delete_session( app_name=child_app(app_name), user_id=user_id, session_id=session_id diff --git a/src/agentic_cli/workflow/agents/records.py b/src/agentic_cli/workflow/agents/records.py index 2c81eaf6..5ea40f1e 100644 --- a/src/agentic_cli/workflow/agents/records.py +++ b/src/agentic_cli/workflow/agents/records.py @@ -6,10 +6,14 @@ one at a time per conversation, each taking the records as they are when it starts (``export``), so changes made while one is under way are written together by the next (the latest wins), and a burst of run events costs one -write or two. A write never fails a run or a turn: a failure is warned of -once per conversation and logged at debug after that. ``flush`` waits until -a conversation's records are written (a turn's end, a delete); its own -cancel leaves the write to finish. +write or two. A write fails no run or turn but a run that makes its +transcript (a first run, or a follow-up whose transcript is gone) and whose +start it was (``RECORDS_NOT_STORED``): that transcript is made only once the +run's start is in the records, so the records name every transcript. A +failure is warned of once per conversation and logged at debug after that. +``flush`` waits until a conversation's records are written (a turn's end, a +delete, the start of a run that makes its transcript); its own cancel leaves +the write to finish. """ from __future__ import annotations @@ -24,6 +28,14 @@ logger = Loggers.workflow() +#: The failure of a run that makes its transcript (a first run, or a follow-up +#: whose transcript is gone) when its start could not be stored: its +#: transcript is not made, so the records never lack one. +RECORDS_NOT_STORED = ( + "The conversation's sub-agent records could not be stored, so this run was not started." +) +RECORDS_NOT_STORED_CODE = "RECORDS_NOT_STORED" + #: The longest error text a failed write's log line carries. _MAX_LOGGED_ERROR = 500 diff --git a/src/agentic_cli/workflow/agents/runs.py b/src/agentic_cli/workflow/agents/runs.py index 5863d648..9d5ed1cb 100644 --- a/src/agentic_cli/workflow/agents/runs.py +++ b/src/agentic_cli/workflow/agents/runs.py @@ -23,7 +23,9 @@ The registry is in memory; a conversation's records are kept beside it in its store as well (``BaseWorkflowManager``'s store hooks): ``on_change`` is -told each time a conversation's records change, ``export`` gives them as +told each time a conversation's records change at a run's start or end or +an instance's status change (not at a working status: a restart reads any as +``interrupted``, so the stored one is never used), ``export`` gives them as JSON-safe data (every instance, every run's record, the id counters, ``RECORDS_VERSION``) and ``restore`` reads that back when the conversation is loaded again (after a restart, or by another manager); a run found still @@ -268,8 +270,10 @@ class AgentRuns: Args: on_change: Told the conversation each time its records change (a - run's event that changes them, ``interrupt_open``), never by - ``restore``: what a store's writes follow. None: nobody is told. + run's start or end, an instance's status change, ``interrupt_open``; + not a run's working status, which a restart reads as + ``interrupted`` whatever was stored), never by ``restore``: what + a store's writes follow. None: nobody is told. """ def __init__(self, *, on_change: Callable[[SessionRef | None], None] | None = None) -> None: @@ -371,7 +375,8 @@ def observe(self, event: WorkflowEvent) -> None: A start makes the run's record (its call, title, brief, input, who started it and its mode), ``running``, and makes its instance or reopens it (``running``); a working status (``queued``, - ``running``, ``input_required``) becomes a working record's status; + ``running``, ``input_required``) becomes a working record's status + (``on_change`` is not told: a restart reads it as ``interrupted``); an end gives it its status, time, result, error, whether it is partial, what it used, who cancelled it and its own last plan and tasks, and sets its instance's status from the end's @@ -424,7 +429,6 @@ def observe(self, event: WorkflowEvent) -> None: and working.status != status ): working.status = status - self._changed(conversation) return if status not in RUN_END_STATUSES: return diff --git a/src/agentic_cli/workflow/base_manager.py b/src/agentic_cli/workflow/base_manager.py index 0c9fb74d..be8242e2 100644 --- a/src/agentic_cli/workflow/base_manager.py +++ b/src/agentic_cli/workflow/base_manager.py @@ -61,10 +61,15 @@ Delegations, FollowUpRequest, RunAnswer, + RunFailed, waiting_on_user, ) from agentic_cli.workflow.agents.policy import SubAgentPolicy, as_policy -from agentic_cli.workflow.agents.records import RecordsWriter +from agentic_cli.workflow.agents.records import ( + RECORDS_NOT_STORED, + RECORDS_NOT_STORED_CODE, + RecordsWriter, +) from agentic_cli.workflow.agents.roster import Rosters from agentic_cli.workflow.agents.runs import ( INSTANCE_CLOSED, @@ -740,9 +745,11 @@ async def _stored_instances(self, conversation: SessionRef) -> Mapping[str, int] # # A conversation's records (``agent_runs``: its instances, its runs with # their briefs, envelopes and usage, its id counters) are kept in its - # store through the backend's hooks: written at each run event that - # changes them (``RecordsWriter``: one write at a time per conversation, - # the latest records each time), all written before a turn returns, + # store through the backend's hooks: written at a run's start and end and + # at an instance's status change (``RecordsWriter``: one write at a time + # per conversation, the latest records each time), all written before a + # turn returns, a run's start before it makes its transcript + # (``_agent_start_stored``: the records name every transcript), # loaded once per conversation (``load_agents``: ``load_session`` and each # turn's start), and deleted with the conversation by the backend's # session code, after the transcripts and before the conversation @@ -764,7 +771,8 @@ async def _save_agent_records( Replaces what the store kept. Called one at a time per conversation (``RecordsWriter``); a failure is warned of once per conversation and - fails nothing. The base keeps none. + fails no run or turn but a run that makes its transcript and whose + start it was (``_agent_start_stored``). The base keeps none. """ return None @@ -886,6 +894,30 @@ async def _agent_records_written(self, conversation: SessionRef) -> None: if writer is not None: await writer.flush(conversation) + async def _agent_start_stored(self, conversation: SessionRef) -> None: + """Wait until a run's start is in ``conversation``'s stored records. + + A run that makes its transcript (a first run, or a follow-up whose + transcript is gone) calls it first, and makes the transcript only + after it returns, so the records name every transcript the + conversation keeps, which is what its numbering and its delete read. + A conversation whose stored records do not read returns at once: this + manager writes none of its runs, and the store's own look covers it + (``_agents_unwritten``). + + Raises: + RunFailed: The latest write of the conversation's records failed, + or its records were never loaded (``RECORDS_NOT_STORED``). + """ + if conversation in self._agents_unwritten: + return + await self._agent_records_written(conversation) + writer = self.__dict__.get("_records_writer") + if conversation not in self._agents_loaded or ( + writer is not None and writer.unsaved(conversation) + ): + raise RunFailed(RECORDS_NOT_STORED, code=RECORDS_NOT_STORED_CODE) + @contextlib.asynccontextmanager async def _deleting(self, conversation: SessionRef) -> AsyncGenerator[None, None]: """The block deletes ``conversation`` from the store; this manager then forgets it. diff --git a/src/agentic_cli/workflow/deepagents/manager.py b/src/agentic_cli/workflow/deepagents/manager.py index 85aaf006..cb9d3fac 100644 --- a/src/agentic_cli/workflow/deepagents/manager.py +++ b/src/agentic_cli/workflow/deepagents/manager.py @@ -970,6 +970,9 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: RunFailed: Its request no longer fits its model's window, still after its summary (``subagent_overflow_message``), with the last text it wrote. + RunFailed: A run that makes its thread (a first run, or a + follow-up whose thread is gone) whose start the store did + not take (``RECORDS_NOT_STORED``): its thread is not made. RunFailed: A first run whose instance's thread the store already keeps: a stored transcript is never another run's. RuntimeError: The run has no conversation (its thread needs one). @@ -992,21 +995,27 @@ async def _run_agent(self, run: AgentRun) -> RunAnswer: HumanMessage(content=run.message, id=task_id) if run.follow_up else brief_message(run.message, id=task_id) ) - if not run.follow_up and self._checkpointer is not None: - # A first run never continues a thread the store already keeps - # (as ADK refuses to make an existing session): whatever numbered - # it, a stored transcript is never another run's. + kept = None + if self._checkpointer is not None: kept = await self._checkpointer.aget_tuple( {"configurable": { "thread_id": instance_thread_id(conversation, run.ref.instance), "checkpoint_ns": "", }} ) - if kept is not None: - raise RunFailed( - f"The thread of sub-agent {run.ref.instance} already exists.", - code="THREAD_EXISTS", - ) + if not run.follow_up and kept is not None: + # A first run never continues a thread the store already keeps + # (as ADK refuses to make an existing session): whatever numbered + # it, a stored transcript is never another run's. + raise RunFailed( + f"The thread of sub-agent {run.ref.instance} already exists.", + code="THREAD_EXISTS", + ) + if kept is None: + # A run that makes its thread (a first run, or a follow-up whose + # thread is gone) does so only once its start is in the records, + # which then name every thread the conversation keeps. + await self._agent_start_stored(conversation) if run.follow_up: inputs: dict[str, Any] = { **{k: v for k, v in run.state.items() if k in SHARED_KEYS and v}, @@ -1208,8 +1217,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 and, as their - floor, its instance threads (``CheckpointSessions.stored_instances``), + turn): read from the conversation's stored records (their ids and + counters, none without records) and, only for records that do not + read, its instance threads (``CheckpointSessions.stored_instances``), so a manager after a restart numbers past what another ran there. """ if self._sessions is None: diff --git a/src/agentic_cli/workflow/deepagents/sessions.py b/src/agentic_cli/workflow/deepagents/sessions.py index b231f440..0a0a1b14 100644 --- a/src/agentic_cli/workflow/deepagents/sessions.py +++ b/src/agentic_cli/workflow/deepagents/sessions.py @@ -37,12 +37,14 @@ that changes them, never a row of the index. ``delete`` deletes the instances' threads first, then the records, then the conversation's thread 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 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. +found again. A first run's thread is made only once its start is in the +records, so the records name every instance a conversation keeps: they are +what number a new manager's next ones (``stored_instances``: their ids and +counters, none without records) and what ``delete`` removes. The threads are +looked at only for records that do not read (another version's: this manager +writes none of its runs), by 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). A finished job reports to the conversation in a ``HumanMessage`` of its own (``job_notification``), marked in its ``response_metadata``, which no @@ -233,10 +235,14 @@ def is_notice(message: BaseMessage) -> bool: class CheckpointSessions: """The session hooks, answered from a checkpointer and the index beside it. - Reads go to the saver and the store, not to a compiled graph, so they - work whenever the checkpointer is open, also while the agents are being - rebuilt. Listing and ``info`` read the index; ``exists`` and ``recent`` - read the conversation itself, from its latest root checkpoint. + Reads go to the saver and the store, not to the agents' compiled graphs, + so they work whenever the checkpointer is open, also while the agents are + being rebuilt, and without a manager. A checkpoint's ``messages`` is a + delta channel (``AgentCliState``): its raw values hold what its step + added, so messages are read through a one-node graph of the agents' state + compiled over the saver (``_messages_at``), which puts them together from + the thread's writes. Listing and ``info`` read the index; ``exists`` and + ``recent`` read the conversation itself, from its latest root checkpoint. Args: saver: The checkpointer the root agent writes to. @@ -252,6 +258,39 @@ def __init__( self._saver = saver self._store = store self._backfill = backfill + # The graph messages are read through (``_reader``), made at its first use. + self._reading: Any = None + + def _reader(self) -> Any: + """The graph the messages are read through, compiled at its first use. + + One node and the agents' state (``AgentCliState``), over the saver: + its ``aget_state`` puts a checkpoint's messages together from their + deltas, as the agents' own graphs do. Deep Agents is imported here, + not with this module (``open_sessions`` imports it for a store that + holds nothing yet). Compiled once, over the saver held at that first + read. + """ + if self._reading is None: + from langgraph.graph import START, StateGraph + + from agentic_cli.workflow.deepagents.state import AgentCliState + + graph = StateGraph(AgentCliState) + graph.add_node("read", _read_nothing) + graph.add_edge(START, "read") + self._reading = graph.compile(checkpointer=self._saver) + return self._reading + + async def _messages_at(self, item: "CheckpointTuple | None") -> list[BaseMessage]: + """The messages of the checkpoint ``item`` names, put together. + + Through ``_reader``; none for None. + """ + if item is None: + return [] + snapshot = await self._reader().aget_state(item.config) + return list(snapshot.values.get("messages") or ()) async def exists(self, ref: SessionRef) -> bool: """Whether ``ref``'s root thread holds at least one message, or the index holds its row. @@ -259,7 +298,7 @@ async def exists(self, ref: SessionRef) -> bool: A row without a message is a conversation whose only work is a run the user started (``keep``). """ - if _messages(await self._root(ref)): + if await self._messages_at(await self._root(ref)): return True item = await self._store.aget(_rows_of(ref.app_name, ref.user_id), ref.session_id) return item is not None and _from_value(ref.session_id, item.value) is not None @@ -292,7 +331,8 @@ async def info(self, ref: SessionRef) -> SessionInfo | None: if row is not None: return row checkpoint = await self._root(ref) - return _row(ref.session_id, checkpoint) if _messages(checkpoint) else None + messages = await self._messages_at(checkpoint) + return _row(ref.session_id, checkpoint, messages) if messages else None async def record(self, ref: SessionRef, adding: Sequence[BaseMessage] = ()) -> None: """Write ``ref``'s row from its latest root checkpoint. Never raises. @@ -315,13 +355,14 @@ async def record(self, ref: SessionRef, adding: Sequence[BaseMessage] = ()) -> N namespace = _rows_of(ref.app_name, ref.user_id) try: item = await self._root(ref) + stored = await self._messages_at(item) held = await self._store.aget(namespace, ref.session_id) kept = held.value if held is not None and _is_kept(held.value) else None if adding: - messages = [*_messages(item), *adding] + messages = [*stored, *adding] row = _row_of(ref.session_id, messages, datetime.now(timezone.utc)) - elif _messages(item): - row = _row(ref.session_id, item) + elif stored: + row = _row(ref.session_id, item, stored) elif kept is not None: return else: @@ -363,10 +404,13 @@ async def list( 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, never - a later one, which would hold the transcript (the saver decodes every - checkpoint it returns, and its filter is a metadata equality). The + The store's own look, for a conversation whose stored records do not + read (``stored_instances``, ``delete``): the records name every + instance otherwise. Read from the instance runs' first input + checkpoints, by their 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 @@ -398,19 +442,24 @@ async def stored_instances(self, ref: SessionRef) -> dict[str, int]: Read from the instances' ids (``-``, ``AgentRuns``' instance ids), as ``adk/sessions.py::stored_instances`` reads ADK's: what another manager ran there, which this one numbers past. An - instance that names no such number is left out. The threads are the - floor (``instances``: a thread a start write never named is numbered - past too), and the stored records' ids and counters count with them: - the counters never fall below an instance kept. + instance that names no such number is left out. The stored records' + ids and counters count (a first run's thread is made only once its + start is in them, so they name every instance: none without + records), and the counters never fall below an instance kept. The + threads are looked at only for records that do not read + (``instances``). """ counts: dict[str, int] = {} records = await self.agent_records(ref) - named = stored_instance_ids(records) or [] - for instance in sorted({*named, *await self.instances(ref)}): + if records is None: + return counts + readable = stored_instance_ids(records) + named = await self.instances(ref) if readable is None else readable + for instance in sorted(named): agent, _, number = instance.rpartition("-") if agent and number.isascii() and number.isdigit(): counts[agent] = max(counts.get(agent, 0), int(number)) - numbered = records.get("numbered") if named else None + numbered = records.get("numbered") if readable else None if isinstance(numbered, Mapping): for agent, count in numbered.items(): if isinstance(agent, str) and type(count) is int and count > counts.get(agent, 0): @@ -423,11 +472,19 @@ async def delete(self, ref: SessionRef) -> bool: False if there was no conversation (its instances' threads and its records are deleted whatever else is found: they go first, so a delete cut short leaves the conversation, by which the rest is found again). - The instances are found from their threads, not the records, so a - thread the records never named goes too. The thread goes with any + The instances are the ones its records name, which name every one + (a first run's thread is made only once its start is in them): none + without records. Records that do not read (another version's) leave + the store's own look, ``instances``. The thread goes with any sub-agent checkpoints an older version stored in it. """ - for instance in await self.instances(ref): + records = await self.agent_records(ref) + if records is None: + kept: list[str] = [] + else: + named = stored_instance_ids(records) + kept = await self.instances(ref) if named is None else named + for instance in kept: await self._saver.adelete_thread(instance_thread_id(ref, instance)) await self.delete_agent_records(ref) namespace = _rows_of(ref.app_name, ref.user_id) @@ -448,7 +505,7 @@ async def recent(self, ref: SessionRef, limit: int) -> list[dict]: are left out. """ out: list[dict] = [] - for message in _messages(await self._root(ref)): + for message in await self._messages_at(await self._root(ref)): if isinstance(message, HumanMessage): if is_notice(message): continue @@ -585,11 +642,12 @@ async def _scan(self, app_name: str, user_id: str) -> dict[str, SessionInfo]: seen = latest.get(ref.session_id) if seen is None or _updated(item) > _updated(seen): latest[ref.session_id] = item - return { - session_id: _row(session_id, item) - for session_id, item in latest.items() - if _messages(item) - } + rows: dict[str, SessionInfo] = {} + for session_id, item in latest.items(): + messages = await self._messages_at(item) + if messages: + rows[session_id] = _row(session_id, item, messages) + return rows #: What closes a store a reader opened. @@ -734,19 +792,20 @@ def _from_value(session_id: str, value: Any) -> SessionInfo | None: return None -def _messages(item: "CheckpointTuple | None") -> list[BaseMessage]: - if item is None: - return [] - return list(item.checkpoint["channel_values"].get("messages") or ()) +def _read_nothing(state: Any) -> dict[str, Any]: + """The reader graph's node: never run (the graph is only read).""" + return {} def _updated(item: "CheckpointTuple") -> datetime: return datetime.fromisoformat(item.checkpoint["ts"]) -def _row(session_id: str, item: "CheckpointTuple") -> SessionInfo: - """A conversation's row from its latest root checkpoint.""" - return _row_of(session_id, _messages(item), _updated(item)) +def _row( + session_id: str, item: "CheckpointTuple", messages: Sequence[BaseMessage] +) -> SessionInfo: + """A conversation's row from its latest root checkpoint and its messages.""" + return _row_of(session_id, messages, _updated(item)) def _row_of( diff --git a/src/agentic_cli/workflow/deepagents/state.py b/src/agentic_cli/workflow/deepagents/state.py index 2b8e73ba..3896ed52 100644 --- a/src/agentic_cli/workflow/deepagents/state.py +++ b/src/agentic_cli/workflow/deepagents/state.py @@ -2,7 +2,7 @@ from typing import Annotated, NotRequired -from langchain.agents import AgentState +from deepagents import DeepAgentState def _last(old: object, new: object) -> object: @@ -15,10 +15,14 @@ def _first(old: object, new: object) -> object: return old or new -class AgentCliState(AgentState): - """LangChain's agent state, plus the plan and task state tools' keys. +class AgentCliState(DeepAgentState): + """Deep Agents' agent state, plus the plan and task state tools' keys. - ``messages`` keeps LangChain's ``add_messages``. ``plan`` and ``tasks`` + ``messages`` is Deep Agents' delta channel: each checkpoint stores the + messages its step added (a full copy every 50 updates), and LangGraph + puts the list together from the thread's writes as it reads a + checkpoint, so a conversation's checkpoints grow with its length, not + its square (``CheckpointSessions`` reads them so too). ``plan`` and ``tasks`` are written by ``save_plan`` and ``save_tasks`` (the LangGraph-library state tools). A sub-agent has its own, starting empty, and none flows back to the coordinator; one agent's parallel ``save_tasks`` calls in diff --git a/tests/workflow/adk/test_child_sessions.py b/tests/workflow/adk/test_child_sessions.py index 0c0b2b8a..8140b491 100644 --- a/tests/workflow/adk/test_child_sessions.py +++ b/tests/workflow/adk/test_child_sessions.py @@ -52,7 +52,14 @@ from agentic_cli.workflow.adk import sessions as adk_sessions # noqa: E402 from agentic_cli.workflow.adk.manager import GoogleADKWorkflowManager # noqa: E402 from agentic_cli.workflow.adk.fit_guard_plugin import brief_of # noqa: E402 -from agentic_cli.workflow.adk.sessions import BRIEF_KEY, RECORDS_KEY, child_app # noqa: E402 +from agentic_cli.workflow.adk.sessions import ( # noqa: E402 + _GENERATION_KEY, + BRIEF_KEY, + MAX_KEY, + RECORDS_KEY, + RECORDS_REWRITE_AFTER, + child_app, +) from agentic_cli.workflow.agents import SubAgentPolicy # noqa: E402 from agentic_cli.workflow.agents.runs import RECORDS_VERSION # noqa: E402 from agentic_cli.workflow.permissions import EXEMPT # noqa: E402 @@ -130,11 +137,15 @@ async def test_it_deletes_the_conversations_children_alone(self, service): (APP, "u", "s"), # the conversation itself ]: await service.create_session(app_name=app_name, user_id=user_id, session_id=session_id) + # Records that do not read: the store's own listing is what finds them. + await adk_sessions.save_records(service, SessionRef(APP, "u", "s"), {"v": 0}) deleted = await adk_sessions.delete_children(service, APP, "u", "s") assert deleted == 3 - assert await stored_ids(service, child_app(APP)) == ["s%2Fx/researcher-1", "t/researcher-1"] + assert await stored_ids(service, child_app(APP)) == [ + "s", "s%2Fx/researcher-1", "t/researcher-1", # "s": the records + ] assert await stored_ids(service, child_app(APP), "v") == ["s/researcher-1"] assert await stored_ids(service, APP) == ["s"] @@ -157,6 +168,7 @@ def events() -> int: author="researcher", content=types.Content(role="model", parts=[types.Part(text="X is 42.")]), )) + await adk_sessions.save_records(service, SessionRef(APP, "u", "s"), {"v": 0}) before = events() await adk_sessions.delete_children(service, APP, "u", "s") @@ -246,6 +258,158 @@ async def test_a_shorter_write_forgets_what_it_no_longer_holds(self, service): assert [i["instance"] for i in loaded["instances"]] == ["writer-1"] + async def test_its_events_stay_bounded(self, service): + """Past ``RECORDS_REWRITE_AFTER`` appended writes the records are + written whole into the other of two sessions and the first is + deleted, so a conversation's records never hold more events than + that.""" + conversation = SessionRef(APP, "u", "s") + data = records_naming("researcher-1") + data["runs"].append({"run": "researcher-1#1", "status": "running"}) + for number in range(3 * RECORDS_REWRITE_AFTER): + data = json.loads(json.dumps(data)) # the service keeps what it is given + data["runs"][0]["status"] = f"running-{number}" + await adk_sessions.save_records(service, conversation, data) + + events = 0 + for session_id in ("s", "s/"): + session = await service.get_session( + app_name=child_app(APP), user_id="u", session_id=session_id + ) + events += len(session.events) if session is not None else 0 + + assert events <= RECORDS_REWRITE_AFTER + loaded = await adk_sessions.load_records(service, conversation) + assert loaded["runs"] == data["runs"] + + async def test_a_rewrite_holds_the_whole_records_and_the_next_generation(self, service): + conversation = SessionRef(APP, "u", "s") + data = records_naming("researcher-1", "researcher-2") + data["runs"] = [{"run": "researcher-1#1", "status": "x"}, {"run": "researcher-2#1"}] + for number in range(RECORDS_REWRITE_AFTER + 1): + data = json.loads(json.dumps(data)) + data["runs"][0]["status"] = f"x{number}" + await adk_sessions.save_records(service, conversation, data) + data = json.loads(json.dumps(data)) + data["runs"][0]["status"] = "rewritten" + with no_blocking_calls(): # the save that rewrites + await adk_sessions.save_records(service, conversation, data) + + assert await stored_ids(service, child_app(APP)) == ["s/"] + session = await service.get_session( + app_name=child_app(APP), user_id="u", session_id="s/" + ) + assert session.state[_GENERATION_KEY] == {"n": 1, "writes": 0} + assert session.state[f"{RECORDS_KEY}.run.000000"] == data["runs"][0] + assert session.state[f"{RECORDS_KEY}.run.000001"] == data["runs"][1] + assert [k for k in session.state if k.startswith(f"{RECORDS_KEY}.instance.")] == [ + f"{RECORDS_KEY}.instance.000000", f"{RECORDS_KEY}.instance.000001", + ] + assert await adk_sessions.load_records(service, conversation) == data + + async def test_a_crash_between_the_rewrite_and_the_delete_keeps_the_newer( + self, service, monkeypatch + ): + conversation = SessionRef(APP, "u", "s") + data = records_naming("researcher-1") + data["runs"] = [{"run": "researcher-1#1", "status": "x"}] + + async def save(label: str) -> dict: + changed = json.loads(json.dumps(data)) + changed["runs"][0]["status"] = label + await adk_sessions.save_records(service, conversation, changed) + return changed + + for number in range(RECORDS_REWRITE_AFTER + 1): + await save(f"x{number}") + real = service.delete_session + + async def crashing(**names): + if names["session_id"] == "s": + raise OSError("killed") + await real(**names) + + monkeypatch.setattr(service, "delete_session", crashing) + with pytest.raises(OSError): + await save("rewritten") + monkeypatch.undo() + + assert await stored_ids(service, child_app(APP)) == ["s", "s/"] + assert (await adk_sessions.load_records(service, conversation))["runs"][0]["status"] == ( + "rewritten" + ) + newer = await save("after") + assert await stored_ids(service, child_app(APP)) == ["s", "s/"] + session = await service.get_session( + app_name=child_app(APP), user_id="u", session_id="s/" + ) + assert session.state[_GENERATION_KEY] == {"n": 1, "writes": 1} # appended there + assert await adk_sessions.load_records(service, conversation) == newer + for number in range(RECORDS_REWRITE_AFTER): + await save(f"y{number}") + # The rewrite after it deleted the stale one first: one session is left. + assert len(await stored_ids(service, child_app(APP))) == 1 + await adk_sessions.delete_records(service, conversation) + assert await stored_ids(service, child_app(APP)) == [] + + async def test_a_delete_after_a_crash_removes_both(self, service, monkeypatch): + """A rewrite cut short leaves both records sessions: the + conversation's delete removes both, and the transcripts they name.""" + conversation = SessionRef(APP, "u", "s") + await service.create_session(app_name=APP, user_id="u", session_id="s") + await service.create_session( + app_name=child_app(APP), user_id="u", session_id="s/researcher-1" + ) + data = records_naming("researcher-1") + data["runs"] = [{"run": "researcher-1#1", "status": "x"}] + for number in range(RECORDS_REWRITE_AFTER + 1): + data = json.loads(json.dumps(data)) + data["runs"][0]["status"] = f"x{number}" + await adk_sessions.save_records(service, conversation, data) + real = service.delete_session + + async def crashing(**names): + if names["session_id"] == "s": + raise OSError("killed") + await real(**names) + + monkeypatch.setattr(service, "delete_session", crashing) + data = json.loads(json.dumps(data)) + data["runs"][0]["status"] = "rewritten" + with pytest.raises(OSError): + await adk_sessions.save_records(service, conversation, data) + monkeypatch.undo() + assert await stored_ids(service, child_app(APP)) == ["s", "s/", "s/researcher-1"] + + assert await adk_sessions.ServiceSessions(service).delete(conversation) is True + + assert await stored_ids(service, child_app(APP)) == [] + assert await stored_ids(service, APP) == [] + + async def test_a_conversation_whose_second_id_is_too_long_keeps_appending(self, service): + conversation = "c" * MAX_KEY + ref = SessionRef(APP, "u", conversation) + assert adk_sessions.records_session_ids(conversation) == (conversation, None) + data = records_naming("researcher-1") + data["runs"] = [{"run": "researcher-1#1", "status": "x"}] + for number in range(RECORDS_REWRITE_AFTER + 2): + data = json.loads(json.dumps(data)) + data["runs"][0]["status"] = f"x{number}" + await adk_sessions.save_records(service, ref, data) + + assert await stored_ids(service, child_app(APP)) == [conversation] + assert await adk_sessions.load_records(service, ref) == data + + async def test_neither_records_session_names_an_instance(self, service): + assert adk_sessions.child_of("s") is None and adk_sessions.child_of("s/") is None + assert adk_sessions.records_session_ids("s") == ("s", "s/") + for session_id in ("s", "s/"): + await service.create_session( + app_name=child_app(APP), user_id="u", session_id=session_id + ) + + assert await adk_sessions._listed_children(service, APP, "u", "s") == [] + async def test_a_records_id_too_long_for_adk_is_refused_and_a_delete_goes_on(self, service): conversation = "/" * 50 # a storable id that encodes to 150 characters with pytest.raises(ValueError): @@ -379,21 +543,52 @@ async def listing(**names): assert await adk_sessions.delete_children(service, APP, "u", "s") == 2 assert await stored_ids(service, child_app(APP)) == ["s"] - async def test_a_delete_also_removes_what_the_records_never_named(self, service): - """A start write can be lost: the records miss a transcript that exists, - which numbering leaves to the store's refusal and a delete must not.""" + async def test_a_delete_removes_what_the_records_name_and_lists_nothing( + self, service, monkeypatch + ): + """A first run's transcript is made only once the records name it, so + the records name every transcript: a session they do not name is + another's, and nothing is listed to look for one.""" conversation = SessionRef(APP, "u", "s") for session_id in ("s/researcher-1", "s/researcher-2", "t/researcher-1"): await service.create_session( app_name=child_app(APP), user_id="u", session_id=session_id ) await adk_sessions.save_records(service, conversation, records_naming("researcher-1")) + listed: list[str] = [] + real = service.list_sessions + + async def listing(**names): + listed.append(names["app_name"]) + return await real(**names) + + monkeypatch.setattr(service, "list_sessions", listing) counts = await adk_sessions.stored_instances(service, APP, "u", "s") deleted = await adk_sessions.delete_children(service, APP, "u", "s") - assert (counts, deleted) == ({"researcher": 1}, 2) - assert await stored_ids(service, child_app(APP)) == ["s", "t/researcher-1"] + assert (counts, deleted, listed) == ({"researcher": 1}, 1, []) + monkeypatch.undo() + assert await stored_ids(service, child_app(APP)) == ["s", "s/researcher-2", "t/researcher-1"] + + async def test_a_conversation_without_records_lists_nothing(self, service, monkeypatch): + """No records means no transcript was ever made for it.""" + await service.create_session( + app_name=child_app(APP), user_id="u", session_id="t/researcher-1" + ) + listed: list[str] = [] + real = service.list_sessions + + async def listing(**names): + listed.append(names["app_name"]) + return await real(**names) + + monkeypatch.setattr(service, "list_sessions", listing) + + counts = await adk_sessions.stored_instances(service, APP, "u", "s") + deleted = await adk_sessions.delete_children(service, APP, "u", "s") + + assert (counts, deleted, listed) == ({}, 0, []) async def test_records_of_another_version_are_no_list(self, service): await service.create_session( @@ -441,8 +636,13 @@ async def deleting(**names): service.delete_session = deleting assert await adk_sessions.ServiceSessions(service).delete(conversation) is True + # The records are two sessions (``s``, ``s/``): neither is a transcript. assert deleted == [ - (child_app(APP), "s/researcher-1"), (child_app(APP), "s"), (APP, "s"), + (child_app(APP), "s/researcher-1"), (child_app(APP), "s"), (child_app(APP), "s/"), + (APP, "s"), + ] + assert [d for d in deleted if d[0] == child_app(APP) and d[1].partition("/")[2]] == [ + (child_app(APP), "s/researcher-1"), ] async def test_a_conversation_already_gone_leaves_none_behind(self, project, monkeypatch): @@ -534,6 +734,8 @@ async def test_the_highest_stored_number_of_each_type(self, service): await service.create_session( app_name=child_app(APP), user_id="u", session_id=session_id ) + # Records that do not read: the listing's filtering is what counts them. + await adk_sessions.save_records(service, SessionRef(APP, "u", "s"), {"v": 0}) counts = await adk_sessions.stored_instances(service, APP, "u", "s") diff --git a/tests/workflow/deepagents/fakes.py b/tests/workflow/deepagents/fakes.py index 1dba0ee1..689cbb32 100644 --- a/tests/workflow/deepagents/fakes.py +++ b/tests/workflow/deepagents/fakes.py @@ -199,3 +199,21 @@ async def hook(run: Any) -> RunAnswer: types={config.name: config for config in configs}, hook=hook, ) return lambda: made + + +async def stored_messages(saver: Any, config: dict) -> list[BaseMessage]: + """The messages of the checkpoint ``config`` names, put together from their deltas. + + ``config`` is a run config (its thread's newest checkpoint) or a + ``CheckpointTuple``'s ``.config``. Read as ``CheckpointSessions`` reads + them: a one-node graph of the agents' state over ``saver``. + """ + from langgraph.graph import START, StateGraph + + from agentic_cli.workflow.deepagents.state import AgentCliState + + graph = StateGraph(AgentCliState) + graph.add_node("read", lambda state: {}) + graph.add_edge(START, "read") + snapshot = await graph.compile(checkpointer=saver).aget_state(config) + return list(snapshot.values.get("messages") or ()) diff --git a/tests/workflow/deepagents/test_brief.py b/tests/workflow/deepagents/test_brief.py index fa6ed1c6..0c625035 100644 --- a/tests/workflow/deepagents/test_brief.py +++ b/tests/workflow/deepagents/test_brief.py @@ -27,7 +27,7 @@ is_brief, ) from agentic_cli.workflow.summary_prompt import SUMMARY_PREFIX -from tests.workflow.deepagents.fakes import ScriptedChat, ai, task +from tests.workflow.deepagents.fakes import ScriptedChat, ai, stored_messages, task from tests.workflow.deepagents.test_context import USER_TURN, context, resolved from tests.workflow.deepagents.test_manager import _manager, ctx, hermetic, scripted, turn # noqa: F401 @@ -97,10 +97,10 @@ async def test_an_instances_first_message_is_its_brief_and_a_follow_up_is_not( await turn(manager, "Again.") thread = instance_thread_id(manager.session_ref("s", "u"), "helper-1") saved = await manager._checkpointer.aget_tuple({"configurable": {"thread_id": thread}}) + messages = await stored_messages(manager._checkpointer, saved.config) finally: await manager.cleanup() - messages = saved.checkpoint["channel_values"]["messages"] humans = [m for m in messages if isinstance(m, HumanMessage)] assert [is_brief(m) for m in humans] == [True, False] assert humans[0].text.startswith("# Task: Find X.") and humans[1].text == "Now Y." diff --git a/tests/workflow/deepagents/test_job_resume.py b/tests/workflow/deepagents/test_job_resume.py index c4f5ae68..a1294b22 100644 --- a/tests/workflow/deepagents/test_job_resume.py +++ b/tests/workflow/deepagents/test_job_resume.py @@ -62,7 +62,7 @@ ) from tests.conftest import MockContext # noqa: E402 from tests.workflow.adk.fakes import FakeAPI, anthropic_message, openai_response # noqa: E402 -from tests.workflow.deepagents.fakes import ScriptedModels, ai, task # noqa: E402 +from tests.workflow.deepagents.fakes import ScriptedModels, ai, stored_messages, task # noqa: E402 from tests.workflow.langchain_fakes import gemini_reply, route, route_google # noqa: E402 # What the tools below wait on, set by the test that runs them. @@ -789,7 +789,7 @@ async def test_the_notification_is_left_out_and_kept_for_the_model( saved = await manager._checkpointer.aget_tuple({"configurable": { "thread_id": thread_id(manager.session_ref("s", "u")), "checkpoint_ns": "", }}) - assert [m.text for m in saved.checkpoint["channel_values"]["messages"]] == [ + assert [m.text for m in await stored_messages(manager._checkpointer, saved.config)] == [ "Start it.", "Started.", _notice_text(_record(), "ok"), "It finished." ] diff --git a/tests/workflow/deepagents/test_session_index.py b/tests/workflow/deepagents/test_session_index.py index 7b140bae..14b1c9ea 100644 --- a/tests/workflow/deepagents/test_session_index.py +++ b/tests/workflow/deepagents/test_session_index.py @@ -46,7 +46,13 @@ from agentic_cli.workflow.sessions import SessionInfo, SessionRef # noqa: E402 from tests.conftest import MockContext # noqa: E402 from tests.workflow.compacting import compact_now # noqa: E402 -from tests.workflow.deepagents.fakes import ScriptedChat, ScriptedModels, ai, task # noqa: E402 +from tests.workflow.deepagents.fakes import ( # noqa: E402 + ScriptedChat, + ScriptedModels, + ai, + stored_messages, + task, +) from tests.workflow.deepagents.test_compact import THREE, answers, solo # noqa: E402 from tests.workflow.deepagents.test_context import ( # noqa: E402,F401 GatedChat, @@ -82,10 +88,20 @@ async def unread(manager, call): sessions = manager._sessions counting = CountingSaver(sessions._saver) sessions._saver = counting + # The messages are read through a graph over the saver the sessions were + # made with, which the wrapper never sees: count those reads too. + messages_at = sessions._messages_at + + async def counted(item): + counting.reads.append("messages") + return await messages_at(item) + + sessions._messages_at = counted try: value = await call() finally: sessions._saver = counting.saver + del sessions._messages_at assert counting.reads == [], f"it read checkpoints: {counting.reads}" return value @@ -101,7 +117,7 @@ async def truth(manager, session: str = "s", user: str = "u") -> SessionInfo: item = await manager._checkpointer.aget_tuple( {"configurable": {"thread_id": thread_id(ref), "checkpoint_ns": ""}} ) - return _row(session, item) + return _row(session, item, await stored_messages(manager._checkpointer, item.config)) async def say(saver, session: SessionRef, text: str) -> None: @@ -563,12 +579,14 @@ async def their_turn_ends() -> None: ours._saver = TurnDuringScan(saver, their_turn_ends) rows = {row.session_id: row for row in await ours.list("app", "u")} - truth_of = { - ref.session_id: _row(ref.session_id, await saver.aget_tuple( + truth_of = {} + for ref in (stale, raced): + item = await saver.aget_tuple( {"configurable": {"thread_id": thread_id(ref), "checkpoint_ns": ""}} - )) - for ref in (stale, raced) - } + ) + truth_of[ref.session_id] = _row( + ref.session_id, item, await stored_messages(saver, item.config) + ) assert rows == truth_of assert (rows["stale"].turns, rows["raced"].turns) == (2, 2) finally: diff --git a/tests/workflow/deepagents/test_sessions.py b/tests/workflow/deepagents/test_sessions.py index 47963e1a..833d3009 100644 --- a/tests/workflow/deepagents/test_sessions.py +++ b/tests/workflow/deepagents/test_sessions.py @@ -33,7 +33,10 @@ from __future__ import annotations +import asyncio +import contextlib import sqlite3 +import threading from types import SimpleNamespace import pytest @@ -42,9 +45,17 @@ from langchain_core.messages import AIMessage, HumanMessage # noqa: E402 -from agentic_cli.workflow.checkpointers import open_checkpointer, open_store # noqa: E402 +from agentic_cli.tools.registry import register_tool # noqa: E402 +from agentic_cli.workflow.checkpointers import ( # noqa: E402 + deepagents_sqlite_location, + open_checkpointer, + open_store, +) +from agentic_cli.workflow.permissions import EXEMPT # noqa: E402 +from agentic_cli.workflow.session_readers import open_session_reader # noqa: E402 from agentic_cli.workflow.config import AgentConfig # noqa: E402 from agentic_cli.workflow.deepagents import manager as manager_module # noqa: E402 +from agentic_cli.workflow.deepagents import sessions as sessions_module # noqa: E402 from agentic_cli.workflow.deepagents.agent_builder import build_agent_tree # noqa: E402 from agentic_cli.workflow.deepagents.manager import DeepAgentsWorkflowManager # noqa: E402 from agentic_cli.tools.jobs import JobState # noqa: E402 @@ -61,7 +72,13 @@ from agentic_cli.workflow.sessions import SessionInfo, SessionRef # noqa: E402 from tests.conftest import MockContext # noqa: E402 from tests.loop_guard import no_blocking_calls # noqa: E402 -from tests.workflow.deepagents.fakes import ScriptedChat, ScriptedModels, ai, task # noqa: E402 +from tests.workflow.deepagents.fakes import ( # noqa: E402 + ScriptedChat, + ScriptedModels, + ai, + stored_messages, + task, +) AWKWARD = SessionRef("app", "ü/ser:1", 'a "quoted"/id') SOLO = AgentConfig(name="solo", prompt="p") @@ -261,6 +278,8 @@ async def test_the_highest_stored_number_of_each_type(self, saver, store): await instance_ran(saver, ref(session="s2"), "researcher-7") # another conversation's await instance_ran(saver, ref(user="bob"), "writer-9") # another user's sessions = CheckpointSessions(saver, store) + # Records that do not read: the scan's filtering is what counts them. + await sessions.save_agent_records(ref(), {"v": 99}) assert await sessions.instances(ref()) == [ "notes", "researcher-1", "researcher-3", "writer-2", @@ -279,60 +298,71 @@ 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_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. 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.""" + async def test_readable_records_are_read_alone(self, saver, store, monkeypatch): + """A first run's thread is made only once the records name it, so the + records' ids and counters are every instance the conversation keeps: + no thread is scanned.""" await say(saver, ref()) - await instance_ran(saver, ref(), "researcher-1", "One.", "Two.") - await instance_ran(saver, ref(), "researcher-6", "Lost.", "Lost again.") # unnamed + for instance in ("researcher-1", "researcher-2", "researcher-3"): + await instance_ran(saver, ref(), instance) sessions = CheckpointSessions(saver, store) - await sessions.save_agent_records(ref(), { - **records_of(), "numbered": {"researcher": 5, "writer": 2}, - "instances": [ - {"instance": "researcher-1"}, {"instance": "writer-2"}, {"instance": "notes"}, - ], - }) - decoded: list[tuple[int, list[str], list[str]]] = [] + await sessions.save_agent_records( + ref(), records_naming("researcher-1", researcher=2) + ) + scans: list[dict] = [] alist = saver.alist - async def listing(*args, **kwargs): - async for item in alist(*args, **kwargs): - 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 + def listing(config, *, filter=None, **kwargs): + if filter and "thread_kind" in filter: + scans.append(filter) + return alist(config, filter=filter, **kwargs) monkeypatch.setattr(saver, "alist", listing) - counts = await sessions.stored_instances(ref()) + with no_blocking_calls(): + counts = await sessions.stored_instances(ref()) - assert counts == {"researcher": 6, "writer": 2} - 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 sorted(decoded) == sorted(first_inputs) + assert counts == {"researcher": 2} + assert scans == [] - async def test_records_that_name_no_instance_read_the_threads(self, saver, store): + async def test_records_that_name_no_instance_count_none(self, saver, store, monkeypatch): await instance_ran(saver, ref(), "researcher-4") sessions = CheckpointSessions(saver, store) await sessions.save_agent_records(ref(), records_of("researcher-4#1")) + scans: list[dict] = [] + alist = saver.alist - assert await sessions.stored_instances(ref()) == {"researcher": 4} + def listing(config, *, filter=None, **kwargs): + if filter and "thread_kind" in filter: + scans.append(filter) + return alist(config, filter=filter, **kwargs) + + monkeypatch.setattr(saver, "alist", listing) + + assert await sessions.stored_instances(ref()) == {} + assert scans == [] + + async def test_a_conversation_without_records_scans_nothing(self, saver, store, monkeypatch): + """No records means no instance thread was ever made for it: a thread + named like one of its instances is left.""" + await say(saver, ref()) + await instance_ran(saver, ref(), "researcher-4") + sessions = CheckpointSessions(saver, store) + scans: list[dict] = [] + alist = saver.alist + + def listing(config, *, filter=None, **kwargs): + if filter and "thread_kind" in filter: + scans.append(filter) + return alist(config, filter=filter, **kwargs) + + monkeypatch.setattr(saver, "alist", listing) + + assert await sessions.stored_instances(ref()) == {} + assert await sessions.delete(ref()) is True + assert scans == [] + monkeypatch.undo() + assert await sessions.instances(ref()) == ["researcher-4"] async def test_records_of_another_version_read_the_threads(self, saver, store): await instance_ran(saver, ref(), "researcher-4") @@ -563,6 +593,15 @@ async def test_none_for_a_conversation_that_is_not_stored(self, saver, store): assert await sessions.info(ref(user="bob")) is None +def records_naming(*instances: str, **numbered: int) -> dict: + """Stored records that name ``instances`` (each with its first run) and number past ``numbered``.""" + return { + "v": 1, "saved": "2026-11-19T10:00:00", "numbered": numbered, + "instances": [{"instance": instance} for instance in instances], + "runs": [{"run": f"{instance}#1"} for instance in instances], + } + + class TestDelete: async def test_it_removes_the_thread_with_its_sub_agents(self, saver, store): await delegate(saver, ref()) @@ -579,6 +618,7 @@ async def test_it_deletes_its_instances_threads_and_no_others(self, saver, store await instance_ran(saver, ref(), "researcher-1", "One.", "Two.") await instance_ran(saver, ref(session="s2"), "researcher-1") sessions = CheckpointSessions(saver, store) + await sessions.save_agent_records(ref(), records_naming("researcher-1")) with no_blocking_calls(): assert await sessions.delete(ref()) is True @@ -595,7 +635,7 @@ async def test_its_records_go_after_its_instances_and_before_it( await say(saver, ref()) await instance_ran(saver, ref(), "researcher-1") sessions = CheckpointSessions(saver, store) - await sessions.save_agent_records(ref(), records_of("researcher-1#1")) + await sessions.save_agent_records(ref(), records_naming("researcher-1")) await sessions.save_agent_records(ref(session="s2"), records_of("writer-1#1")) done: list[str] = [] delete_thread, delete_item = type(saver).adelete_thread, type(store).adelete @@ -619,12 +659,26 @@ async def deleting_item(self, namespace, key) -> None: async def test_a_conversation_already_gone_leaves_no_instance_behind(self, saver, store): await instance_ran(saver, ref(), "researcher-1") sessions = CheckpointSessions(saver, store) - await sessions.save_agent_records(ref(), records_of("researcher-1#1")) + await sessions.save_agent_records(ref(), records_naming("researcher-1")) assert await sessions.delete(ref()) is False assert await threads(saver) == [] assert await sessions.agent_records(ref()) is None + async def test_a_delete_with_records_of_another_version_scans(self, saver, store): + """Only the store can say what a conversation keeps when this manager + wrote none of its records: its instances' threads are found by the scan.""" + await say(saver, ref()) + await instance_ran(saver, ref(), "researcher-1") + await instance_ran(saver, ref(session="s2"), "researcher-1") + sessions = CheckpointSessions(saver, store) + await sessions.save_agent_records(ref(), {"v": 99}) + + assert await sessions.delete(ref()) is True + + assert await sessions.instances(ref()) == [] + assert await sessions.instances(ref(session="s2")) == ["researcher-1"] + async def test_an_unknown_session_is_not_deleted(self, saver, store): await say(saver, ref()) sessions = CheckpointSessions(saver, store) @@ -911,3 +965,256 @@ async def test_a_conversation_never_kept_is_titled_and_dropped_as_before(self, s await sessions.record(ref()) # no message stored: its row goes assert await sessions.list("app", "alice") == [] + + +# --- messages stored as deltas ----------------------------------------------------------- + +#: What the blocking tool waits for: set when it starts, and to let it end. +HELD: dict[str, threading.Event] = {} + + +@register_tool(capabilities=EXEMPT, description="Waits until released (a session-test tool).") +def sessions_test_hold() -> dict: + """Waits until the test releases it.""" + HELD["started"].set() + HELD["go"].wait(10) + return {"success": True} + + +def texts(messages) -> list[str]: + return [message.text for message in messages if message.text] + + +class TestMessagesStoredAsDeltas: + """Each agent's ``messages`` is Deep Agents' delta channel + (``AgentCliState(DeepAgentState)``): a checkpoint holds the messages its + step added, a full copy every 50 updates, so a conversation's checkpoints + grow with its length, not its square. The session hooks read the + messages put together (``CheckpointSessions._messages_at``), with or + without a manager.""" + + @staticmethod + async def turns(manager, count: int, size: int = 0, *, user: str = "u") -> None: + for n in range(count): + await converse(manager, f"Q{n}." + "q" * size, user=user, session="s") + + @pytest.fixture + def sqlite_settings(self, hermetic): + with MockContext(google_api_key="test-key", session_store="sqlite") as context: + yield context.settings + + @staticmethod + def made(monkeypatch, settings, answers, configs=(SOLO,)) -> DeepAgentsWorkflowManager: + """A manager whose one agent answers ``answers`` (texts, or scripted answers).""" + script = [ai(a) if isinstance(a, str) else a for a in answers] + monkeypatch.setattr(manager_module, "build_chat_model", ScriptedModels(solo=script)) + return DeepAgentsWorkflowManager( + agent_configs=list(configs), settings=settings, model="gemini-2.5-flash", + ) + + async def test_a_checkpoint_holds_the_new_messages_not_all_of_them( + self, sqlite_settings, monkeypatch + ): + manager = self.made(monkeypatch, sqlite_settings, ["A0.", "A1.", "A2."]) + try: + await self.turns(manager, 3) + ref = manager.session_ref("s", "u") + item = await manager._checkpointer.aget_tuple(run_config(ref)) + values = item.checkpoint["channel_values"] + read = await stored_messages(manager._checkpointer, item.config) + finally: + await manager.cleanup() + + assert not isinstance(values.get("messages"), list) or len(values["messages"]) < 6 + assert texts(read) == ["Q0.", "A0.", "Q1.", "A1.", "Q2.", "A2."] + + async def test_a_long_conversation_stores_each_message_about_once( + self, sqlite_settings, monkeypatch + ): + """40 turns of a 1,000-character prompt and answer: about 80 KB of + messages. Stored whole at each checkpoint they cost over 8 MB.""" + manager = self.made( + monkeypatch, sqlite_settings, [f"A{n}." + "a" * 1_000 for n in range(40)] + ) + try: + await self.turns(manager, 40, size=1_000) + ref = manager.session_ref("s", "u") + finally: + await manager.cleanup() + + with contextlib.closing(sqlite3.connect(deepagents_sqlite_location(sqlite_settings))) as db: + stored = sum( + db.execute( + f"select coalesce(sum(length({column})), 0) from {table}" + " where thread_id = ? and checkpoint_ns = ''", + (thread_id(ref),), + ).fetchone()[0] + for table, column in (("checkpoints", "checkpoint"), ("writes", "value")) + ) + assert stored < 1_000_000 + + async def test_the_hooks_read_a_conversation_stored_as_deltas( + self, sqlite_settings, monkeypatch + ): + manager = self.made(monkeypatch, sqlite_settings, ["A0.", "A1.", "A2."]) + user = sqlite_settings.default_user # the reader's + try: + await self.turns(manager, 3, user=user) + ref = manager.session_ref("s", user) + with no_blocking_calls(): + exists = await manager.session_exists("s", user_id=user) + info = await manager.session_info("s", user_id=user) + recent = await manager.recent_messages("s", limit=10, user_id=user) + await manager._sessions.record(ref) + row = await manager._sessions.info(ref) + finally: + await manager.cleanup() + reader = await open_session_reader("deepagents", sqlite_settings, store="sqlite") + try: + with no_blocking_calls(): + read = (await reader.exists("s"), await reader.info("s")) + finally: + await reader.aclose() + + assert (exists, info.turns, info.title) == (True, 3, "Q0.") + assert [m["content"] for m in recent] == ["Q0.", "A0.", "Q1.", "A1.", "Q2.", "A2."] + assert (row.title, row.turns) == ("Q0.", 3) + assert (read[0], read[1].title, read[1].turns) == (True, "Q0.", 3) + + async def test_a_cancelled_turn_reads_whole(self, sqlite_settings, monkeypatch): + HELD["started"], HELD["go"] = threading.Event(), threading.Event() + hold = AgentConfig(name="solo", prompt="p", tools=[sessions_test_hold]) + manager = self.made(monkeypatch, sqlite_settings, [ + "A0.", ai("Holding.", calls=[("sessions_test_hold", {})]), + ], configs=(hold,)) + try: + await self.turns(manager, 1) + turn = asyncio.ensure_future(converse(manager, "Hold.", user="u", session="s")) + await asyncio.to_thread(HELD["started"].wait, 10) + turn.cancel() + with contextlib.suppress(asyncio.CancelledError): + await turn + HELD["go"].set() + ref = manager.session_ref("s", "u") + truth = (await manager._root.aget_state(run_config(ref))).values["messages"] + recent = await manager.recent_messages("s", limit=10, user_id="u") + info = await manager.session_info("s", user_id="u") + finally: + HELD["go"].set() + await manager.cleanup() + + assert texts(truth)[:3] == ["Q0.", "A0.", "Hold."] + assert [m["content"] for m in recent] == [ + m.text for m in truth if m.type in ("human", "ai") and m.text + ] + assert (info.title, info.turns) == ("Q0.", 2) + + async def test_the_backfill_reads_a_conversation_stored_as_deltas( + self, sqlite_settings, monkeypatch + ): + manager = self.made(monkeypatch, sqlite_settings, ["A0.", "A1."]) + try: + await self.turns(manager, 2) + ref = manager.session_ref("s", "u") + store = manager._sessions._store + await store.adelete(sessions_module._rows_of(ref.app_name, "u"), "s") + await store.adelete( + sessions_module._marks_of(ref.app_name, "u"), sessions_module._MARK_KEY + ) + assert await manager._sessions._rows(ref.app_name, "u") == {} + with no_blocking_calls(): + listed = await manager.list_sessions(user_id="u") + written = await manager._sessions._rows(ref.app_name, "u") + finally: + await manager.cleanup() + + assert [(r.session_id, r.title, r.turns) for r in listed] == [("s", "Q0.", 2)] + assert [(r.title, r.turns) for r in written.values()] == [("Q0.", 2)] + + async def test_a_reader_reads_a_conversation_stored_as_deltas_without_a_row( + self, sqlite_settings, monkeypatch + ): + """No manager runs: the reader's ``info`` and its listing (the + backfill) put the messages together themselves.""" + manager = self.made(monkeypatch, sqlite_settings, ["A0.", "A1.", "A2."]) + user = sqlite_settings.default_user + try: + await self.turns(manager, 3, user=user) + ref = manager.session_ref("s", user) + store = manager._sessions._store + await store.adelete(sessions_module._rows_of(ref.app_name, user), "s") + await store.adelete( + sessions_module._marks_of(ref.app_name, user), sessions_module._MARK_KEY + ) + finally: + await manager.cleanup() + reader = await open_session_reader("deepagents", sqlite_settings, store="sqlite") + try: + with no_blocking_calls(): + info = await reader.info("s") + listed = await reader.list() + finally: + await reader.aclose() + + assert (info.title, info.turns) == ("Q0.", 3) + assert [(r.session_id, r.title, r.turns) for r in listed] == [("s", "Q0.", 3)] + + async def test_a_cancelled_turn_then_a_new_one_reads_whole( + self, sqlite_settings, monkeypatch + ): + HELD["started"], HELD["go"] = threading.Event(), threading.Event() + hold = AgentConfig(name="solo", prompt="p", tools=[sessions_test_hold]) + manager = self.made(monkeypatch, sqlite_settings, [ + "A0.", ai("Holding.", calls=[("sessions_test_hold", {})]), "A2.", + ], configs=(hold,)) + try: + await self.turns(manager, 1) + turn = asyncio.ensure_future(converse(manager, "Hold.", user="u", session="s")) + await asyncio.to_thread(HELD["started"].wait, 10) + turn.cancel() + with contextlib.suppress(asyncio.CancelledError): + await turn + HELD["go"].set() + await converse(manager, "Next.", user="u", session="s") + recent = await manager.recent_messages("s", limit=20, user_id="u") + info = await manager.session_info("s", user_id="u") + finally: + HELD["go"].set() + await manager.cleanup() + + contents = [m["content"] for m in recent] + assert contents == ["Q0.", "A0.", "Hold.", "Holding.", "Next.", "A2."] + assert info.turns == 3 + + async def test_a_conversation_stored_with_plain_messages_reads_and_goes_on( + self, sqlite_settings, monkeypatch + ): + """What an older version stored: the whole list in each checkpoint.""" + manager = self.made(monkeypatch, sqlite_settings, ["A1."]) + try: + await manager.initialize_services() + ref = manager.session_ref("s", "u") + await plain_thread(manager._checkpointer, ref, "Q0.", "A0.") + await converse(manager, "Q1.", user="u", session="s") + recent = await manager.recent_messages("s", limit=10, user_id="u") + finally: + await manager.cleanup() + + assert [m["content"] for m in recent] == ["Q0.", "A0.", "Q1.", "A1."] + + +async def plain_thread(saver, session: SessionRef, *texts: str) -> None: + """A root checkpoint holding ``texts`` (a user's, then an answer, in turn) + whole in its values, as a version without the delta channel stored it.""" + from langgraph.checkpoint.base import empty_checkpoint + + checkpoint = empty_checkpoint() + checkpoint["channel_values"] = {"messages": [ + (HumanMessage if n % 2 == 0 else AIMessage)(text, id=f"m{n}") + for n, text in enumerate(texts) + ]} + checkpoint["channel_versions"] = {"messages": "1"} + config = {"configurable": {"thread_id": thread_id(session), "checkpoint_ns": ""}} + metadata = {"app_name": session.app_name, "user_id": session.user_id, + "session_id": session.session_id, "source": "loop", "step": 1} + await saver.aput(config, checkpoint, metadata, {"messages": "1"}) diff --git a/tests/workflow/test_adk_model_errors.py b/tests/workflow/test_adk_model_errors.py index 90a4cb39..c520e440 100644 --- a/tests/workflow/test_adk_model_errors.py +++ b/tests/workflow/test_adk_model_errors.py @@ -260,8 +260,9 @@ def coordinator(request) -> dict: async def locked(**kwargs): config = kwargs.get("config") - # The run's child session (``s/researcher-1``), not the conversation's records (``s``). - if kwargs["app_name"].endswith("--agents") and "/" in kwargs["session_id"] \ + # The run's child session (``s/researcher-1``), not the conversation's + # records (``s``, ``s/``). + if kwargs["app_name"].endswith("--agents") and kwargs["session_id"].partition("/")[2] \ and config is not None \ and config.num_recent_events == 0: raise RuntimeError("database is locked") diff --git a/tests/workflow/test_agent_records.py b/tests/workflow/test_agent_records.py index 7fa9e420..f2b204b1 100644 --- a/tests/workflow/test_agent_records.py +++ b/tests/workflow/test_agent_records.py @@ -28,11 +28,15 @@ RUN_INTERRUPTED, RUN_RUNNING, ) -from agentic_cli.workflow.agents.delegate import AgentRun, DelegationRequest, RunAnswer +from agentic_cli.workflow.agents.delegate import AgentRun, DelegationRequest, RunAnswer, RunFailed from agentic_cli.workflow.agents.envelope import INTERRUPTED_ERROR from agentic_cli.workflow import base_manager as base_manager_module from agentic_cli.workflow.agents import records as records_module -from agentic_cli.workflow.agents.records import RecordsWriter +from agentic_cli.workflow.agents.records import ( + RECORDS_NOT_STORED, + RECORDS_NOT_STORED_CODE, + RecordsWriter, +) from agentic_cli.workflow.agents.runs import RECORDS_VERSION from agentic_cli.workflow.base_manager import BaseWorkflowManager from agentic_cli.workflow.config import AgentConfig @@ -947,3 +951,57 @@ async def deleting() -> None: manager.save_gate.set() assert ref in manager._agents_loaded + + +class TestAStartStored: + """A first run's transcript is made only once its start is in the + records (``_agent_start_stored``), so the records name every transcript + the conversation keeps: a store that failed that write fails the run, + and so does a conversation whose records were never loaded. A + conversation whose stored records do not read is never written, so its + runs start without waiting.""" + + async def test_a_written_start_returns(self, kept): + manager = kept({}) + ref = manager.session_ref("s", "u") + await turn(manager) + manager._agent_records_changed(ref) + + with no_blocking_calls(): + await manager._agent_start_stored(ref) + + assert not manager._agent_records.unsaved(ref) + + async def test_a_failed_write_fails_the_run(self, kept): + manager = kept({}) + ref = manager.session_ref("s", "u") + await turn(manager) + manager.save_fails = OSError("disk full") + manager._agent_records_changed(ref) # the run's start, which the store fails + + with pytest.raises(RunFailed) as raised: + await manager._agent_start_stored(ref) + + assert raised.value.code == RECORDS_NOT_STORED_CODE == "RECORDS_NOT_STORED" + assert str(raised.value) == RECORDS_NOT_STORED + + async def test_a_conversation_never_loaded_fails_the_run(self, kept): + manager = kept({}) + await manager.initialize_services() + + with pytest.raises(RunFailed) as raised: + await manager._agent_start_stored(manager.session_ref("s", "u")) + + assert raised.value.code == RECORDS_NOT_STORED_CODE + + async def test_unreadable_records_do_not_wait(self, kept): + manager = kept({}) + ref = manager.session_ref("s", "u") + await turn(manager) + manager._agents_unwritten.add(ref) + manager.save_gate = asyncio.Event() # a write that never ends + manager._agent_records.changed(ref) + try: + await asyncio.wait_for(manager._agent_start_stored(ref), 1) + finally: + manager.save_gate.set() diff --git a/tests/workflow/test_agent_runs.py b/tests/workflow/test_agent_runs.py index 39ef60f8..e975f387 100644 --- a/tests/workflow/test_agent_runs.py +++ b/tests/workflow/test_agent_runs.py @@ -1080,16 +1080,28 @@ def test_a_change_and_no_change(self): ref = started(runs, ONE, "c1", "researcher") assert told == [ONE] - for status, changes in [(RUN_RUNNING, False), (RUN_QUEUED, True), (RUN_QUEUED, False)]: - in_turn(ONE, lambda: runs.observe(WorkflowEvent.agent_run(ref, status, call_id="c1"))) - assert len(told) == 1 + changes - told[:] = [ONE] ended(runs, ONE, ref) assert told == [ONE, ONE] for _ in range(2): in_turn(ONE, lambda: runs.observe(WorkflowEvent.agent_instance(ref, INSTANCE_CLOSED))) assert told == [ONE, ONE, ONE] + def test_a_working_status_changes_the_record_and_tells_no_change(self): + """A restart reads any working status as ``interrupted``, so the + stored one is never used: a run's start and end are written, not + its working statuses.""" + told: list[SessionRef | None] = [] + runs = AgentRuns(on_change=told.append) + + ref = started(runs, ONE, "c1", "researcher") + for status in (RUN_QUEUED, RUN_RUNNING, RUN_INPUT_REQUIRED, RUN_RUNNING): + in_turn(ONE, lambda: runs.observe(WorkflowEvent.agent_run(ref, status, call_id="c1"))) + assert runs.records(ONE)[0].status == status + ended(runs, ONE, ref) + + assert [record.status for record in runs.records(ONE)] == [RUN_COMPLETED] + assert len(told) == 2 # the start and the end + def test_interrupt_open_tells_when_it_ends_one(self): told: list[SessionRef | None] = [] runs = AgentRuns(on_change=told.append) diff --git a/tests/workflow/test_session_store.py b/tests/workflow/test_session_store.py index f387d186..0403c18f 100644 --- a/tests/workflow/test_session_store.py +++ b/tests/workflow/test_session_store.py @@ -261,9 +261,10 @@ async def recording(**kwargs): assert await mgr.delete_session("sess-x") is True assert await mgr.delete_session("missing") is False - # A delete looks at the conversation, then its sub-agent records, neither with events. + # A delete looks at the conversation, then its sub-agent records (the two + # sessions they alternate between), neither with events. assert [getattr(config, "num_recent_events", None) for config in asked] == [ - 1, 1, 0, 0, 0, 0, + 1, 1, 0, 0, 0, 0, 0, 0, ] async def test_exists_list_recent_delete(self, tmp_path: Path): diff --git a/tests/workflow/test_subagents_contract.py b/tests/workflow/test_subagents_contract.py index dee98508..ee4a0dca 100644 --- a/tests/workflow/test_subagents_contract.py +++ b/tests/workflow/test_subagents_contract.py @@ -62,6 +62,7 @@ from agentic_cli.tools.registry import register_tool from agentic_cli.workflow import live_events from agentic_cli.workflow.agents import records as agent_records +from agentic_cli.workflow.agents.records import RECORDS_NOT_STORED from agentic_cli.workflow.agents import ( INSTANCE_CLOSED, INSTANCE_IDLE, @@ -2975,7 +2976,7 @@ async def transcripts(crew: Crew) -> list[str]: prefix = f"{conversation.session_id}/" return sorted( session.id.removeprefix(prefix) for session in listed.sessions - if session.id.startswith(prefix) + if session.id.startswith(prefix) and session.id != prefix # ``s/``: records ) found: set[str] = set() own = [conversation.app_name, conversation.user_id, conversation.session_id] @@ -3174,8 +3175,9 @@ async def test_on_adk_a_run_whose_work_ended_keeps_it_while_its_state_is_read( async def slow_state_read(**kwargs: Any) -> Any: config = kwargs.get("config") - # The run's child session (``s/researcher-1``), not the conversation's records (``s``). - if kwargs["app_name"].endswith("--agents") and "/" in kwargs["session_id"] \ + # The run's child session (``s/researcher-1``), not the conversation's + # records (``s``, ``s/``). + if kwargs["app_name"].endswith("--agents") and kwargs["session_id"].partition("/")[2] \ and config is not None \ and config.num_recent_events == 0: stopped = None @@ -5341,9 +5343,12 @@ async def test_a_run_the_process_was_killed_in_reads_interrupted_and_goes_on( ("researcher-2#1", RUN_COMPLETED), ] - async def test_a_failing_write_is_warned_of_once_and_the_runs_complete( + async def test_a_failing_write_is_warned_of_once_and_a_follow_up_completes( self, make_crew, monkeypatch ): + """A follow-up's instance is named in the records already: a store + that fails its writes fails it not (a first run it does: + ``TestARunWhoseStartIsNotStored``).""" crew = make_crew( follow_team(), coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done."), @@ -5362,9 +5367,10 @@ def __getattr__(self, level: str): {"event": event, "log_level": level, **fields} ) + events = await crew.turn() monkeypatch.setattr(crew.manager, "_save_agent_records", fails) monkeypatch.setattr(agent_records, "logger", Recorder()) - events = [*await crew.turn(), *await crew.turn("Go on.")] + events += await crew.turn("Go on.") read = crew.results_read("coordinator") assert [envelope_read(read[call])["status"] for call in ("c1", "c2")] == [ @@ -5379,48 +5385,114 @@ def __getattr__(self, level: str): assert [e for e in events if e.type is EventType.ERROR] == [] -class TestATranscriptTheRecordsNeverNamed: - """A run's start write can be lost (the store failed, the process was - killed first) while its transcript exists. The records then miss an - instance: a new instance never continues it, and a delete still removes - it.""" +async def store_fails(conversation: SessionRef, data: Any) -> None: + """A store that fails every records write.""" + raise OSError("disk full") - @staticmethod - async def lost_start_write(make_crew, monkeypatch): - first = make_crew( + +class TestARunWhoseStartIsNotStored: + """A first run's transcript is made only once its start is in the + records, so the records name every transcript the conversation keeps + (what its numbering and its delete read). A store that fails that write + fails the run, and nothing of it is made: the turn goes on.""" + + async def test_it_fails_and_makes_no_transcript(self, make_crew, monkeypatch): + crew = make_crew( follow_team(), store="sqlite", coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done."), calls(delegate("researcher", "Find Y.", "c2")), says("Done.")], researcher=[says("X is 42."), says("Y is 7.")], ) + await crew.turn("Find X.") + monkeypatch.setattr(crew.manager, "_save_agent_records", store_fails) + + events = await crew.turn("Find Y.") + + second = next(r for r in crew.records() if r.ref.instance == "researcher-2") + assert (second.status, second.error) == (RUN_FAILED, RECORDS_NOT_STORED) + assert envelope_read(crew.results_read("coordinator")["c2"])["error"] == RECORDS_NOT_STORED + assert await transcripts(crew) == ["researcher-1"] + assert "Find Y." not in "".join(crew.bodies("researcher")) + assert [e.content for e in events if e.type is EventType.TEXT][-1] == "Done." + + async def test_parallel_first_runs_each_fail_and_give_their_slots_back( + self, make_crew, monkeypatch + ): + crew = make_crew( + follow_team(), store="sqlite", subagents=SubAgentPolicy(max_active=1), + coordinator=[calls(delegate("researcher", "Find X.", "c1"), + delegate("researcher", "Find Y.", "c2")), says("Done.")], + researcher=[says("X is 42."), says("Y is 7.")], + ) + monkeypatch.setattr(crew.manager, "_save_agent_records", store_fails) + + events = await crew.turn("Find X and Y.") + + assert [(r.ref.instance, r.status, r.error) for r in crew.records()] == [ + ("researcher-1", RUN_FAILED, RECORDS_NOT_STORED), + ("researcher-2", RUN_FAILED, RECORDS_NOT_STORED), + ] + read = crew.results_read("coordinator") + assert [envelope_read(read[c])["error"] for c in ("c1", "c2")] == [RECORDS_NOT_STORED] * 2 + assert await transcripts(crew) == [] + assert crew.requests("researcher") == 0 + assert [e.content for e in events if e.type is EventType.TEXT][-1] == "Done." + assert (crew.slots().free, crew.slots().waiting) == (1, 0) + + async def test_a_follow_up_still_runs(self, make_crew, monkeypatch): + """Its instance is named in the records already.""" + crew = make_crew( + follow_team(), store="sqlite", + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done."), + calls(follow("researcher-1", "Go on.", "c3")), says("Done.")], + researcher=[says("X is 42."), says("Went on.")], + ) + await crew.turn("Find X.") + monkeypatch.setattr(crew.manager, "_save_agent_records", store_fails) + + await crew.turn("Go on.") + + read = envelope_read(crew.results_read("coordinator")["c3"]) + assert (read["status"], read["result"]) == (RUN_COMPLETED, "Went on.") + assert await transcripts(crew) == ["researcher-1"] + + async def test_records_of_another_version_still_start_runs(self, make_crew): + """This manager writes none of that conversation's records, so its + runs wait for none.""" + first = make_crew( + follow_team(), store="sqlite", + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done.")], + researcher=[says("X is 42.")], + ) await first.turn("Find X.") - monkeypatch.setattr(first.manager, "_save_agent_records", written_no_more) - await first.turn("Find Y.") - assert await transcripts(first) == ["researcher-1", "researcher-2"] + await first.manager._save_agent_records(first.conversation, {"v": 0}) await first.manager.cleanup() - - async def test_a_new_instance_never_continues_it(self, make_crew, monkeypatch): - await self.lost_start_write(make_crew, monkeypatch) second = make_crew( follow_team(), store="sqlite", - coordinator=[calls(delegate("researcher", "Find Z.", "c3")), says("Done.")], - researcher=[says("Z is 3.")], + coordinator=[calls(delegate("researcher", "Find Y.", "c2")), says("Done.")], + researcher=[says("Y is 7.")], ) - await second.turn("Find Z.") + await second.turn("Find Y.") - assert "researcher-2" not in [ - r.ref.instance for r in second.records() if r.status == RUN_COMPLETED - ] - assert "Find Y." not in "".join(second.bodies("researcher")) - assert "researcher-2" in await transcripts(second) # as it was + (record,) = second.records() + assert (record.ref.instance, record.status) == ("researcher-2", RUN_COMPLETED) + assert await transcripts(second) == ["researcher-1", "researcher-2"] async def test_a_first_run_onto_a_stored_transcript_fails_rather_than_continue_it( - self, make_crew, monkeypatch + self, make_crew ): """Whatever numbered it: here a store that could tell nothing of what it keeps.""" - await self.lost_start_write(make_crew, monkeypatch) + first = make_crew( + follow_team(), store="sqlite", + coordinator=[calls(delegate("researcher", "Find X.", "c1")), + calls(delegate("researcher", "Find Y.", "c2")), says("Done.")], + researcher=[says("X is 42."), says("Y is 7.")], + ) + await first.turn("Find X and Y.") + assert await transcripts(first) == ["researcher-1", "researcher-2"] + await first.manager.cleanup() second = make_crew( follow_team(), store="sqlite", coordinator=[calls(delegate("researcher", "Find Z.", "c3")), says("Done.")], @@ -5442,17 +5514,95 @@ async def reads_none(conversation: SessionRef) -> None: assert "Find X." not in "".join(second.bodies("researcher")) assert await transcripts(second) == ["researcher-1", "researcher-2"] - async def test_a_delete_removes_it_too(self, make_crew, monkeypatch): - await self.lost_start_write(make_crew, monkeypatch) + +class TestAFollowUpThatMakesItsTranscript: + """An instance whose first run failed ``RECORDS_NOT_STORED`` is left + ``idle`` and can be followed up. A follow-up that makes its transcript + (it has none: the first run made none) waits for its start to be stored + as a first run does, so the records name every transcript.""" + + @staticmethod + def crew_of(make_crew, monkeypatch): + crew = make_crew( + follow_team(), store="sqlite", + coordinator=[calls(delegate("researcher", "Find X.", "c1")), + calls(follow("researcher-1", "Try again.", "c2")), says("Done.")], + researcher=[says("X is 42.")], + ) + monkeypatch.setattr(crew.manager, "_save_agent_records", store_fails) + return crew + + async def test_it_fails_while_the_store_still_fails_and_leaves_no_transcript( + self, make_crew, monkeypatch + ): + crew = self.crew_of(make_crew, monkeypatch) + + await crew.turn("Find X.") + + read = crew.results_read("coordinator") + assert envelope_read(read["c1"])["error"] == RECORDS_NOT_STORED + assert envelope_read(read["c2"])["error"] == RECORDS_NOT_STORED + assert await transcripts(crew) == [] + monkeypatch.undo() + assert await crew.manager.delete_session(SESSION, user_id=USER) is True + assert await transcripts(crew) == [] + + async def test_it_completes_once_the_store_recovers_and_the_delete_removes_it( + self, make_crew, monkeypatch + ): + crew = make_crew( + follow_team(), store="sqlite", + coordinator=[calls(delegate("researcher", "Find X.", "c1")), says("Done."), + calls(follow("researcher-1", "Try again.", "c2")), says("Done.")], + researcher=[says("X is 42.")], + ) + monkeypatch.setattr(crew.manager, "_save_agent_records", store_fails) + await crew.turn("Find X.") + monkeypatch.undo() + + await crew.turn("Try again.") + + read = envelope_read(crew.results_read("coordinator")["c2"]) + assert (read["status"], read["result"]) == (RUN_COMPLETED, "X is 42.") + stored = await crew.manager._load_agent_records(crew.conversation) + assert "researcher-1" in [i["instance"] for i in stored["instances"]] + assert await transcripts(crew) == ["researcher-1"] + assert await crew.manager.delete_session(SESSION, user_id=USER) is True + assert await transcripts(crew) == [] + + +class TestRecordsThatDoNotRead: + """A conversation whose stored records are another version's: this + manager writes none of its runs, so only the store can say what it + keeps. Its runs are numbered past the transcripts the store keeps, and a + delete removes every one of them.""" + + async def test_numbering_and_a_delete_still_find_their_transcripts(self, make_crew): + first = make_crew( + follow_team(), store="sqlite", + coordinator=[calls(delegate("researcher", "Find X.", "c1"), + delegate("researcher", "Find Y.", "c2")), says("Done.")], + researcher=[says("X is 42."), says("Y is 7.")], + ) + await first.turn("Find X and Y.") + await first.manager._save_agent_records(first.conversation, {"v": 0}) + await first.manager.cleanup() second = make_crew( - follow_team(), store="sqlite", coordinator=[says("Hi.")], researcher=[], + follow_team(), store="sqlite", + coordinator=[calls(delegate("researcher", "Find Z.", "c3")), says("Done.")], + researcher=[says("Z is 3.")], ) - await second.turn("Hi.") - assert await second.manager.delete_session(SESSION, user_id=USER) is True + with no_blocking_calls(): + await second.turn("Find Z.") + (record,) = second.records() + made = await transcripts(second) + deleted = await second.manager.delete_session(SESSION, user_id=USER) + assert (record.ref.instance, record.status) == ("researcher-3", RUN_COMPLETED) + assert made == ["researcher-1", "researcher-2", "researcher-3"] + assert deleted is True assert await transcripts(second) == [] - assert await second.manager._load_agent_records(second.conversation) is None class TestADeletedConversation: