Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -945,8 +945,9 @@ the start of the entry's title.
`<conversation 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; 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 `<conversation 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",
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (<app_name>--agents: the sub-agent runs' app, which no conversation list reads), child_session_id (<conversation id>/<instance>, the conversation id's % and / percent-encoded, so its first / always ends the conversation and no two conversations share an id; child_of reads one back; a ValueError past ADK's 128 characters; the instance's follow-up runs continue it), delete_children (a conversation's child sessions, events and all: those its records name, 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 (<app_name>--agents: the sub-agent runs' app, which no conversation list reads), child_session_id (<conversation id>/<instance>, the conversation id's % and / percent-encoded, so its first / always ends the conversation and no two conversations share an id; child_of reads one back; a ValueError past ADK's 128 characters; the instance's follow-up runs continue it), delete_children (a conversation's child sessions, events and all: those its records name, 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: <text>"; no field sent as null; OpenRouter's cache writes, which ADK's usage mapping drops, kept on the usage as cache_creation_input_tokens)
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
9 changes: 7 additions & 2 deletions src/agentic_cli/workflow/adk/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 21 additions & 13 deletions src/agentic_cli/workflow/adk/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,11 @@
conversation, not with the square of it: ``RECORDS_KEY`` holds the header
(version, time, counters) and ``RECORDS_KEY.instance.<n>`` and
``RECORDS_KEY.run.<n>`` 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
Expand Down Expand Up @@ -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": <int>, "writes":
#: <int>}``, the rewrites so far and the writes appended since the last.
Expand Down Expand Up @@ -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.

Expand All @@ -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

Expand All @@ -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(
Expand Down
14 changes: 14 additions & 0 deletions src/agentic_cli/workflow/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
23 changes: 23 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from unittest.mock import patch

import pytest
from pydantic import ValidationError

from agentic_cli.config import (
BaseSettings,
Expand All @@ -18,6 +19,7 @@
set_settings,
validate_settings,
)
from agentic_cli.settings_persistence import PROJECT_SETTABLE_KEYS
from agentic_cli.workflow.config import AgentConfig


Expand All @@ -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):
Expand Down
Loading
Loading