diff --git a/CHANGELOG.md b/CHANGELOG.md index 05ef2d6d..008371d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -945,8 +945,9 @@ the start of the entry's title. ``, 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; its - events stay bounded: after 100 appended writes, - `adk/sessions.py::RECORDS_REWRITE_AFTER`, the next one writes the records + events stay bounded: after `adk_subagent_records_rewrite_after` appended + writes (a setting: 100 by default, at least 1, read at each write, so a + change applies at the next), 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", diff --git a/CLAUDE.md b/CLAUDE.md index fa360c04..895dd290 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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, 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 +│ │ │ ├── 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 adk_subagent_records_rewrite_after writes (a setting read at each write: RECORDS_REWRITE_AFTER, 100, by default) 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) diff --git a/README.md b/README.md index 327cf3b9..c9d39cb2 100644 --- a/README.md +++ b/README.md @@ -602,6 +602,7 @@ configured is reported (`settings_secrets_dir_ignored`). | `thinking_effort` | `AGENTIC_THINKING_EFFORT` | "medium" | Thinking level: none, low, medium, high | | `prompt_caching_enabled` | `AGENTIC_PROMPT_CACHING_ENABLED` | true | Prompt caching: Claude, and Gemini on ADK | | `orchestrator` | `AGENTIC_ORCHESTRATOR` | "adk" | The backend new conversations run on: `adk`, `deepagents`, or `langgraph` (deprecated); a conversation keeps its own | +| `adk_subagent_records_rewrite_after` | `AGENTIC_ADK_SUBAGENT_RECORDS_REWRITE_AFTER` | 100 | ADK: a conversation's sub-agent records session takes this many appended writes, then the next copies the records whole into a fresh session and deletes the old one with its events (at least 1) | | `session_store` | `AGENTIC_SESSION_STORE` | "sqlite" | Where conversations are kept: `sqlite`, `postgres`, or `memory` (nothing on disk: one conversation at a time, none to resume) | | `context_summarize_at` | `AGENTIC_CONTEXT_SUMMARIZE_AT` | 0.85 | Summarize the earlier conversation at this fraction of the model's input budget (0.5 to 0.95) | | `context_max_tokens` | `AGENTIC_CONTEXT_MAX_TOKENS` | 200000 | Or once a prompt reaches this many tokens, if that comes first (0: no ceiling; otherwise at least 16000) | diff --git a/src/agentic_cli/workflow/adk/manager.py b/src/agentic_cli/workflow/adk/manager.py index 393673d6..c58db7a0 100644 --- a/src/agentic_cli/workflow/adk/manager.py +++ b/src/agentic_cli/workflow/adk/manager.py @@ -2016,12 +2016,17 @@ async def _save_agent_records( records session, made at the first write (``adk/sessions.py::save_records``). A session of its own, never the conversation's: ADK takes no second - writer on a session while a turn runs on it. + writer on a session while a turn runs on it. Rewritten past + ``adk_subagent_records_rewrite_after`` appended writes, read at each + write, so a change applies at the next. Raises: RuntimeError: The session store is not open. """ - await save_records(self._open_store(), conversation, data) + await save_records( + self._open_store(), conversation, data, + rewrite_after=self._settings.adk_subagent_records_rewrite_after, + ) def _open_store(self) -> Any: service = self._session_service diff --git a/src/agentic_cli/workflow/adk/sessions.py b/src/agentic_cli/workflow/adk/sessions.py index d4be98fe..2153cdb1 100644 --- a/src/agentic_cli/workflow/adk/sessions.py +++ b/src/agentic_cli/workflow/adk/sessions.py @@ -49,10 +49,11 @@ 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. 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' +grow without bound, so past ``RECORDS_REWRITE_AFTER`` writes (the settings' +``adk_subagent_records_rewrite_after``) 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 first run's session is made only once its start is in the records, so they name @@ -109,7 +110,8 @@ _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``). +#: rewrites the records whole into the other one (``save_records``), unless +#: the settings say otherwise (``adk_subagent_records_rewrite_after``). 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. @@ -331,7 +333,11 @@ def _flat(data: Mapping[str, Any]) -> dict[str, Any]: async def save_records( - service: "BaseSessionService", ref: SessionRef, data: Mapping[str, Any] + service: "BaseSessionService", + ref: SessionRef, + data: Mapping[str, Any], + *, + rewrite_after: int = RECORDS_REWRITE_AFTER, ) -> None: """Keep ``data`` as ``ref``'s sub-agent records, replacing what its records session held. @@ -341,12 +347,14 @@ async def save_records( 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). 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. + without bound, so once ``rewrite_after`` writes were appended (the + manager's ``adk_subagent_records_rewrite_after``, ``RECORDS_REWRITE_AFTER`` + by default) 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 @@ -369,7 +377,7 @@ async def save_records( if not delta: return generation = _generation(held) - if generation["writes"] >= RECORDS_REWRITE_AFTER and second is not None: + if generation["writes"] >= 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( diff --git a/src/agentic_cli/workflow/settings.py b/src/agentic_cli/workflow/settings.py index 82bd9b09..fd6c8081 100644 --- a/src/agentic_cli/workflow/settings.py +++ b/src/agentic_cli/workflow/settings.py @@ -779,6 +779,20 @@ def _validate_sandbox_network(cls, v: str) -> str: description="LangGraph only: store type for long-term memory (memory or postgres)", json_schema_extra={"ui_order": 148}, ) + # ADK keeps a conversation's sub-agent records in a session of their own; + # past this many appended writes the next one rewrites it + # (workflow/adk/sessions.py::save_records). Read at each write. + adk_subagent_records_rewrite_after: int = Field( + default=100, + ge=1, + title="Sub-agent Records Rewrite", + description=( + "ADK only: once this many writes were appended to a conversation's " + "sub-agent records session, the next one copies the records whole into " + "a fresh session and deletes the old one with its events (at least 1)" + ), + json_schema_extra={"ui_order": 149}, + ) def session_db_url(self, store: str | None = None) -> str | None: """Async SQLAlchemy URL for the session store, or None when ephemeral. diff --git a/tests/test_config.py b/tests/test_config.py index 0159f84e..17ada66e 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -6,6 +6,7 @@ from unittest.mock import patch import pytest +from pydantic import ValidationError from agentic_cli.config import ( BaseSettings, @@ -18,6 +19,7 @@ set_settings, validate_settings, ) +from agentic_cli.settings_persistence import PROJECT_SETTABLE_KEYS from agentic_cli.workflow.config import AgentConfig @@ -37,6 +39,27 @@ def test_default_values(self, temp_workspace: Path): assert settings.embedding_model == "all-MiniLM-L6-v2" assert settings.python_executor_timeout == 30 + def test_the_adk_sub_agent_records_rewrite(self, temp_workspace: Path): + """How many writes ADK's sub-agent records session takes before the next + rewrites it: 100 by default, at least 1.""" + with patch.dict(os.environ, {}, clear=True): + settings = BaseSettings(workspace_dir=temp_workspace) + assert settings.adk_subagent_records_rewrite_after == 100 + one = BaseSettings( + workspace_dir=temp_workspace, adk_subagent_records_rewrite_after=1 + ) + assert one.adk_subagent_records_rewrite_after == 1 + env = {"AGENTIC_ADK_SUBAGENT_RECORDS_REWRITE_AFTER": "500"} + with patch.dict(os.environ, env): + from_env = BaseSettings(workspace_dir=temp_workspace) + assert from_env.adk_subagent_records_rewrite_after == 500 + with pytest.raises(ValidationError): + BaseSettings( + workspace_dir=temp_workspace, adk_subagent_records_rewrite_after=0 + ) + # An app's or the user's to set, never a project file's. + assert "adk_subagent_records_rewrite_after" not in PROJECT_SETTABLE_KEYS + def test_workspace_path_expansion(self): """Test that ~ is expanded in workspace_dir.""" with patch.dict(os.environ, {}, clear=True): diff --git a/tests/workflow/adk/test_child_sessions.py b/tests/workflow/adk/test_child_sessions.py index 8140b491..beec3efb 100644 --- a/tests/workflow/adk/test_child_sessions.py +++ b/tests/workflow/adk/test_child_sessions.py @@ -282,6 +282,22 @@ async def test_its_events_stay_bounded(self, service): loaded = await adk_sessions.load_records(service, conversation) assert loaded["runs"] == data["runs"] + async def test_a_lower_bound_rewrites_sooner(self, service): + """``rewrite_after`` is the bound a write keeps (the manager passes its + ``adk_subagent_records_rewrite_after``).""" + conversation = SessionRef(APP, "u", "s") + data = records_naming("researcher-1") + data["runs"].append({"run": "researcher-1#1", "status": "running"}) + for number in range(5): # a create, three appends, then the rewrite + 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, rewrite_after=3 + ) + + assert await stored_ids(service, child_app(APP)) == ["s/"] + assert await adk_sessions.load_records(service, conversation) == data + 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") @@ -452,6 +468,35 @@ async def test_a_turns_runs_are_in_its_records_session(self, store, project, mon ("researcher-1#1", "completed"), ] + async def test_each_write_keeps_the_settings_bound(self, project, monkeypatch): + """``adk_subagent_records_rewrite_after`` is read at each write: a + change applies at the next one.""" + route(monkeypatch, anthropic, "AsyncAnthropic", FakeAPI(two_delegations())) + manager = manager_on("memory") + try: + await say(manager, "Find X.") # the store is open + conversation = manager.session_ref("t", "u") + children = child_app(conversation.app_name) + data = records_naming("researcher-1") + for number in range(4): # a create and three appends + # A copy each time: the service keeps what it is given. + data = json.loads(json.dumps(data)) + data["numbered"] = {"researcher": number} + await manager._save_agent_records(conversation, data) + before = await stored_ids(manager._session_service, children) + manager._settings.adk_subagent_records_rewrite_after = 3 + data = json.loads(json.dumps(data)) + data["numbered"] = {"researcher": 4} + await manager._save_agent_records(conversation, data) + after = await stored_ids(manager._session_service, children) + loaded = await manager._load_agent_records(conversation) + finally: + await manager.cleanup() + + assert ("t" in before, "t/" in before) == (True, False) # 100: no rewrite yet + assert ("t" in after, "t/" in after) == (False, True) + assert loaded == data + async def test_a_first_runs_start_is_written_before_its_transcript_is_made( self, project, monkeypatch ):