The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(cli): HermesCLI's agent and session store are the gateway's (the two seams)
Teknium9748e38caa1b
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex f9a74812d7f..c4203a86095 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -626,7 +626,7 @@ class CLIAgentSetupMixin:"""Build the agent on first use; when resuming, restore history from SQLite.Returns True on success."""from cli import ChatConsole, _cprint, _prepare_deferred_agent_startup, logger- from run_agent import AIAgent+ from hermes_cli.gateway_agent import GatewayAgent as AIAgent # the gateway runs the turnif self.agent is not None:return True@@ -640,12 +640,18 @@ class CLIAgentSetupMixin:from hermes_cli.mcp_startup import ensure_mcp_discovery_before_agent_buildensure_mcp_discovery_before_agent_build(logger=logger, single_query=getattr(self, "_single_query_mode", False))+ from hermes_cli.cli_chat_error_copy import agent_init_failure_messageif self._session_db is None:try:- from hermes_state_registry import acquire- self._session_db = acquire()+ from hermes_cli.gateway_session_store import session_store+ self._session_db = session_store()except Exception as e:logger.warning("SQLite session store not available — session will NOT be indexed: %s", e)+ try:+ self._ensure_gateway_session()+ except Exception as e:+ ChatConsole().print(f"[bold red]{_escape(agent_init_failure_message(e))}[/]")+ return Falseif (self._resumed and self._session_db and not self.conversation_historyand not self._load_resumed_history_late()):@@ -716,6 +722,7 @@ class CLIAgentSetupMixin:# patch_stdout's StdoutProxy (#2262), holding lines while a response box streams so a# subagent/background completion notice never splits the reply mid-paragraph.self.agent._print_fn = self._agent_status_print+ self.agent._finite = single_query_mode # -q/-Q: a finite gateway admission (headless clarify)# Hydrate credits notices at session OPEN (parity with the TUI) so a depletion# warning shows before the first message. Idempotent + fail-open in the helper.try:diff --git a/hermes_cli/cli_info_mixin.py b/hermes_cli/cli_info_mixin.pyindex 58c71869008..068a4faba57 100644--- a/hermes_cli/cli_info_mixin.py+++ b/hermes_cli/cli_info_mixin.py@@ -128,7 +128,17 @@ class CLIInfoMixin:enabled_toolsets=self.enabled_toolsets, session_id=self.session_id,context_length=ctx_len, provider=self.provider, context_pinned=ctx_pinned)- if snapshot is not None:+ gateway_inventory = getattr(self._session_db, "banner_inventory", lambda: None)()+ if gateway_inventory is not None:+ # The gateway session's snapshot (the TUI banner's data): the CLI enumerates nothing.+ self._defer_tool_warnings = True+ build_welcome_banner(+ tools=gateway_inventory["tools"], get_toolset_for_tool=gateway_inventory["get_toolset_for_tool"],+ availability=gateway_inventory["availability"],+ skills_by_category=gateway_inventory["skills_by_category"],+ **{**banner_kw, "cwd": gateway_inventory["cwd"] or cwd,+ "context_length": gateway_inventory["context_length"] or ctx_len})+ elif snapshot is not None:self._defer_tool_warnings = Truetoolset_map = snapshot["toolset_map"]build_welcome_banner(diff --git a/hermes_cli/cli_init_mixin.py b/hermes_cli/cli_init_mixin.pyindex 254f2e864aa..dd7915cadf0 100644--- a/hermes_cli/cli_init_mixin.py+++ b/hermes_cli/cli_init_mixin.py@@ -329,8 +329,8 @@ class CLIInitMixin:# path a moment later from the REPL thread, and a second writer repeats the full# open (the /proc-wide deleted-WAL scan, ~4k readlinks) while the render thread# holds the GIL — that repeat was the post-banner freeze before the first prompt.- from hermes_state_registry import acquire- self._session_db = acquire()+ from hermes_cli.gateway_session_store import session_store+ self._session_db = session_store() # the gateway is the single writerexcept Exception as e:# Without a store the transcript is NOT persisted while the chat looks healthy,# so surface it prominently rather than only logging.@@ -356,6 +356,26 @@ class CLIInitMixin:_run_state_db_auto_maintenance(self._session_db)_run_checkpoint_auto_maintenance()+ def _ensure_gateway_session(self):+ """Create (or resume) this CLI's gateway session and adopt the id it returns, before the banner+ and the first turn. Idempotent; a store without the gateway facade (tests) is left alone."""+ store = self._session_db+ if getattr(self, "_gateway_session_open", False) or not hasattr(store, "open_session"):+ return+ launch = {"model": self.model if getattr(self, "_explicit_model_override", False) else None,+ "provider": (self.requested_provider if getattr(self, "_explicit_model_override", False)+ and self.requested_provider not in {None, "", "auto"} else None),+ "api_key": getattr(self, "_explicit_api_key", None),+ "base_url": getattr(self, "_explicit_base_url", None),+ "toolsets": self.enabled_toolsets,+ "pass_session_id": getattr(self, "pass_session_id", False) or None,+ "ignore_rules": getattr(self, "ignore_rules", False) or None}+ sid = store.open_session(self, launch)+ self._gateway_session_open = True+ if sid and sid != self.session_id:+ self.session_id = sid+ getattr(self, "_write_terminal_breadcrumb", lambda: None)()+def _init_ui_state(self):"""Per-run mutable UI state; must exist before any chat() call since -q never goes through run()."""from cli import CLI_CONFIG, _status_bar_visible_from_display_configdiff --git a/hermes_cli/cli_tui_runtime_mixin.py b/hermes_cli/cli_tui_runtime_mixin.pyindex c470445a7c4..e2186b49ce8 100644--- a/hermes_cli/cli_tui_runtime_mixin.py+++ b/hermes_cli/cli_tui_runtime_mixin.py@@ -240,6 +240,7 @@ class CLITuiRuntimeMixin:if _term_lines > 2:print("\n" * (_term_lines - 1), end="", flush=True)+ self._ensure_gateway_session() # the banner shows the gateway session's id and inventoryself.show_banner()self._show_security_advisories()self._show_browser_backend_notice()diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.pynew file mode 100644index 00000000000..15ef74155e8--- /dev/null+++ b/hermes_cli/gateway_session_store.py@@ -0,0 +1,229 @@+"""``HermesCLI._session_db`` backed by the shared gateway session (CALLMAP §3.5).++Main's classic CLI holds a ``SessionDB`` writer. Rewired, the gateway is the single writer:++- reads (resume lookup, recap history, titles, the /resume picker, safety checks) go to a+ read-only ``state.db`` reader in this process, which the maintainer allows;+- every write is a gateway verb (``session.create`` / ``session.resume`` / ``session.mutate`` /+ ``session.detach``) or a documented no-op where the gateway already owns the work+ (transcript flushes, token accounting, maintenance);+- anything not yet on the gateway raises ``GatewayClientError`` (a ``ValueError``), so main's+ existing ``except`` paths print it instead of writing locally.++The session id is the gateway's: :meth:`open_session` creates or resumes the session before the+banner and adopts the id it returns.+"""+from __future__ import annotations++import argparse+import logging+import os+import uuid++from hermes_cli.gateway_client import GatewayClientError+from hermes_cli.gateway_connection import GatewayConnection++logger = logging.getLogger(__name__)++# Read-only SessionDB methods main's CLI calls (served by the WAL reader).+_READS = frozenset({+ "get_session", "get_session_title", "get_session_by_title", "resolve_resume_session_id",+ "get_messages_as_conversation", "get_resume_conversations", "assert_resume_safe",+ "is_kanban_owned_session", "list_sessions_rich", "search_sessions", "get_next_title_in_lineage",+ "get_handoff_state", "get_meta", "get_compression_tip", "resolve_session_by_title", "get_messages",+ "session_count", "sanitize_title", "session_yolo_enabled",+})+# Writes the gateway already performs itself (persistence, accounting, maintenance).+_GATEWAY_OWNED = frozenset({+ "create_session", "reopen_session", "append_messages_batch", "flush_token_counts",+ "update_session_model", "patch_session_model_config", "maybe_auto_archive",+ "maybe_auto_prune_and_vacuum", "set_meta", "update_token_counts", "close",+})+_COUNTED_REPAIRS = frozenset({"prune_empty_ghost_sessions", "finalize_orphaned_compression_sessions"})+# Launch options main's ``cli.main`` takes that are creation policy on the gateway session.+_LAUNCH_POLICY = ("model", "provider", "toolsets", "reasoning", "api_key", "base_url", "max_turns",+ "ignore_rules", "checkpoints", "pass_session_id", "skills")+++def _noop(*_a, **_k):+ return None+++def _zero(*_a, **_k):+ return 0+++class GatewaySessionStore:+ """Truthy while the gateway connection is usable (main's ``if self._session_db:`` guards)."""++ def __init__(self, connection=None):+ self.connection = connection or GatewayConnection.shared()+ self.snapshots: dict[str, dict] = {}+ self.current: dict | None = None+ self._reader = None+ self._reader_failed = False++ def __bool__(self):+ return not self.connection.closed++ # -- reads -----------------------------------------------------------------------------+ def _db(self):+ if self._reader is None and not self._reader_failed:+ try:+ from hermes_constants import get_hermes_home+ from hermes_state import SessionDB+ self._reader = SessionDB(db_path=get_hermes_home() / "state.db", read_only=True)+ except Exception as exc: # no state.db yet (the gateway creates it): reads find nothing+ logger.debug("read-only state.db unavailable: %s", exc)+ self._reader_failed = True+ return self._reader++ def __getattr__(self, name):+ if name.startswith("__"):+ raise AttributeError(name)+ if name in _READS:+ if name in {"sanitize_title", "session_yolo_enabled"}:+ from hermes_state import SessionDB+ return getattr(SessionDB, name)+ db = self._db()+ if db is None:+ return _noop+ return getattr(db, name)+ if name in _GATEWAY_OWNED:+ return _noop+ if name in _COUNTED_REPAIRS:+ return _zero++ def refused(*_a, **_k):+ raise GatewayClientError(f"{name} is not on the gateway session yet; nothing was written")+ return refused++ # -- session lifecycle -----------------------------------------------------------------+ def call(self, method, **params):+ return self.connection.call(method, **params)++ def _adopt(self, snapshot):+ sid = snapshot["stored_session_id"]+ self.snapshots[sid] = snapshot+ self.current = snapshot+ self.connection.state(sid).adopt_snapshot(snapshot)+ return sid++ def attach(self, session_id):+ """``session.resume`` once per session id this viewer uses (idempotent)."""+ if session_id in self.snapshots:+ return self.snapshots[session_id]+ snapshot = self.call("session.resume", session_id=session_id)+ self._adopt(snapshot)+ return snapshot++ def open_session(self, cli, launch=None):+ """Create (or resume) the gateway session for this CLI and adopt its id. A resume target the+ gateway does not know is left as is: main's own "Session not found" path reports it."""+ if getattr(cli, "_resumed", False):+ try:+ return self._adopt(self.attach(cli.session_id))+ except GatewayClientError as exc:+ if str(exc) in {"not_found", "permission_denied"}:+ return None+ raise+ params = _creation_policy(launch or {})+ params["cwd"] = os.path.realpath(os.getenv("TERMINAL_CWD") or os.getcwd())+ params["source"] = os.environ.get("HERMES_SESSION_SOURCE") or "cli"+ snapshot = self.call("session.create", request_id=uuid.uuid4().hex, **params)+ return self._adopt(snapshot)++ def _revision(self, session_id):+ return self.call("session.resume", session_id=session_id)["revision"]++ def _mutate(self, session_id, operation, payload):+ return self.call("session.mutate", session_id=session_id, request_id=uuid.uuid4().hex,+ expected_revision=self._revision(session_id), operation=operation, payload=payload)++ def set_session_title(self, session_id, title):+ self._mutate(session_id, "rename", {"title": title})+ if session_id in self.snapshots:+ self.connection.state(session_id).title = title+ return True++ def delete_session(self, session_id, sessions_dir=None):+ self.snapshots.pop(session_id, None)+ self._mutate(session_id, "delete", {})+ return True++ def end_session(self, session_id, reason=None):+ """Detach this viewer; the gateway ends an idle session itself."""+ snapshot = self.snapshots.pop(session_id, None)+ subscription = (snapshot or {}).get("subscription_id")+ if subscription and not self.connection.closed:+ try:+ self.call("session.detach", session_id=session_id, subscription_id=subscription)+ except GatewayClientError as exc:+ logger.debug("session.detach failed: %s", exc)++ def delete_session_if_empty(self, session_id, sessions_dir=None):+ """Main's quit-immediately prune, as a gateway delete: only a row with no messages, no title+ and no children (checked on the read-only reader; the gateway deletes the lineage)."""+ db = self._db()+ if db is None:+ return False+ try:+ with db._read_ctx() as conn:+ empty = conn.execute(+ "SELECT 1 FROM sessions WHERE id = ? AND title IS NULL"+ " AND NOT EXISTS (SELECT 1 FROM messages WHERE messages.session_id = sessions.id)"+ " AND NOT EXISTS (SELECT 1 FROM sessions child WHERE child.parent_session_id = sessions.id)",+ (session_id,)).fetchone()+ except Exception as exc:+ logger.debug("empty-session probe failed: %s", exc)+ return False+ if not empty:+ return False+ try:+ return self.delete_session(session_id)+ except GatewayClientError as exc:+ logger.debug("empty session prune refused: %s", exc)+ return False++ # -- banner --------------------------------------------------------------------------+ def banner_inventory(self):+ """The current session snapshot's banner fields (``gateway/session_local_inventory``), as+ ``build_welcome_banner`` kwargs; None until a session is open."""+ info = (self.current or {}).get("info") or {}+ if "tools" not in info:+ return None+ grouped = info.get("tools") or {}+ toolset_of = {name: toolset for toolset, names in grouped.items() for name in names or []}+ availability = info.get("tool_availability") or {+ "available_toolsets": [], "unavailable_toolsets": [], "lazy_tools": [], "disabled_tools": []}+ for item in availability.get("unavailable_toolsets", []):+ for name in item.get("tools", []):+ toolset_of.setdefault(name, item.get("id", item.get("name", "")))+ return {+ "tools": [{"type": "function", "function": {"name": name}} for names in grouped.values()+ for name in names or []],+ "get_toolset_for_tool": toolset_of.get,+ "availability": availability,+ "skills_by_category": info.get("skills") or {},+ "mcp_status": list(info.get("mcp_servers") or []),+ "enabled_toolsets": info.get("enabled_toolsets"),+ "context_length": info.get("context_length"),+ "cwd": info.get("cwd"),+ }+++def _creation_policy(launch):+ """The explicit launch flags as ``session.create`` policy (the thin client's own mapping);+ unset flags leave the gateway to resolve the profile default, as main's CLI did."""+ from hermes_cli.gateway_chat import _requested_policy, env_launch_flags+ fields = {key: launch.get(key) for key in _LAUNCH_POLICY}+ if isinstance(fields.get("toolsets"), (list, tuple)):+ fields["toolsets"] = ",".join(str(item) for item in fields["toolsets"])+ policy = _requested_policy(argparse.Namespace(**fields, source=None))+ policy.pop("source", None)+ policy.update(env_launch_flags())+ return policy+++def session_store():+ return GatewaySessionStore()diff --git a/tests/hermes_cli/test_gateway_session_store.py b/tests/hermes_cli/test_gateway_session_store.pynew file mode 100644index 00000000000..d906dcaba8d--- /dev/null+++ b/tests/hermes_cli/test_gateway_session_store.py@@ -0,0 +1,118 @@+"""GatewaySessionStore: main's ``_session_db`` facade over gateway verbs (scripted gateway, no live one)."""+import asyncio+import types+from contextlib import asynccontextmanager++import pytest++from hermes_cli.gateway_client import GatewayClientError+from hermes_cli.gateway_connection import GatewayConnection+from hermes_cli.gateway_session_store import GatewaySessionStore++INFO = {"model": "fake-model", "cwd": "/w", "context_length": 128000, "enabled_toolsets": ["file"],+ "tools": {"file": ["read_file", "write_file"]}, "skills": {"devops": ["sdlc-review"]},+ "mcp_servers": [], "tool_availability": {"available_toolsets": ["file"], "unavailable_toolsets": [],+ "lazy_tools": [], "disabled_tools": []}}+++def snapshot(sid, revision=3):+ return {"session_id": sid, "stored_session_id": sid, "messages": [], "revision": revision,+ "execution_generation": 0, "subscription_id": "sub-" + sid, "info": dict(INFO)}+++class FakeClient:+ def __init__(self, known=("local-old",)):+ self.events = asyncio.Queue()+ self.calls = []+ self.known = set(known)++ async def rpc(self, method, *, _timeout=None, **params):+ self.calls.append((method, params))+ if method == "session.create":+ self.known.add("local-new")+ return snapshot("local-new")+ if method == "session.resume":+ if params["session_id"] not in self.known:+ raise GatewayClientError("not_found")+ return snapshot(params["session_id"])+ return {"status": "ok", "detached": True}+++def store():+ client = FakeClient()++ @asynccontextmanager+ async def connect():+ yield client+ conn = GatewayConnection(connect=connect)+ conn.start(5)+ yield GatewaySessionStore(conn), client+ conn.close()+++def cli(session_id="20261012_000000_abcdef", resumed=False):+ return types.SimpleNamespace(session_id=session_id, _resumed=resumed)+++def test_new_session_is_created_on_the_gateway_and_its_id_adopted(store, monkeypatch):+ monkeypatch.delenv("HERMES_SESSION_SOURCE", raising=False)+ db, client = store+ sid = db.open_session(cli(), {"model": "m1", "toolsets": ["file", "web"], "provider": None})+ assert sid == "local-new"+ method, params = client.calls[0]+ assert method == "session.create"+ assert params["model"] == "m1" and params["toolsets"] == ["file", "web"] and params["source"] == "cli"+ assert "provider" not in params and params["cwd"]+ assert db.connection.state("local-new").info["model"] == "fake-model"+++def test_resume_attaches_and_unknown_target_is_left_to_mains_not_found_path(store):+ db, client = store+ assert db.open_session(cli("local-old", resumed=True)) == "local-old"+ assert client.calls[-1][0] == "session.resume"+ assert db.open_session(cli("missing", resumed=True)) is None+++def test_title_rename_delete_and_detach_are_gateway_verbs(store):+ db, client = store+ db.open_session(cli("local-old", resumed=True))+ db.set_session_title("local-old", "Some Title")+ mutate = [p for m, p in client.calls if m == "session.mutate"][-1]+ assert mutate["operation"] == "rename" and mutate["payload"] == {"title": "Some Title"}+ assert mutate["expected_revision"] == 3+ assert db.connection.state("local-old").title == "Some Title"+ db.end_session("local-old", "cli_close")+ assert client.calls[-1] == ("session.detach", {"session_id": "local-old", "subscription_id": "sub-local-old"})+ db.delete_session("local-old")+ assert [p for m, p in client.calls if m == "session.mutate"][-1]["operation"] == "delete"+++def test_gateway_owned_writes_are_noops_and_unknown_writes_refuse(store):+ db, client = store+ before = len(client.calls)+ db.create_session("x", source="cli")+ db.reopen_session("x")+ db.append_messages_batch("x", [])+ assert db.prune_empty_ghost_sessions() == 0+ assert len(client.calls) == before+ with pytest.raises(ValueError):+ db.rewind_user_turn("x", 1)+++def test_banner_inventory_comes_from_the_session_snapshot(store):+ db, _ = store+ assert db.banner_inventory() is None+ db.open_session(cli("local-old", resumed=True))+ inv = db.banner_inventory()+ assert [t["function"]["name"] for t in inv["tools"]] == ["read_file", "write_file"]+ assert inv["get_toolset_for_tool"]("read_file") == "file"+ assert inv["skills_by_category"] == {"devops": ["sdlc-review"]}+ assert inv["context_length"] == 128000 and inv["cwd"] == "/w"+++def test_store_is_falsy_once_the_gateway_connection_closed(store):+ db, _ = store+ assert db+ db.connection.close()+ assert not db