The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): /new and /branch switch to sessions the gateway created
Tekniume6407704c472
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex 3a5a0e0928f..3b92563a340 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -1097,7 +1097,7 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):from gateway.slash_commands_branch_thread import parse_branch_args_, branch_name = parse_branch_args(_command_arg(cmd_original))now = datetime.now()- new_session_id = mint_session_id(now)+ new_session_id = self._new_session_id(now, branch_of=self.session_id) # the gateway's branch childbranch_title = branch_name or self._session_db.get_next_title_in_lineage(self._session_db.get_session_title(self.session_id) or "branch")parent_session_id = self.session_iddiff --git a/hermes_cli/cli_init_mixin.py b/hermes_cli/cli_init_mixin.pyindex ffa9377479d..440dcfd85ce 100644--- a/hermes_cli/cli_init_mixin.py+++ b/hermes_cli/cli_init_mixin.py@@ -375,6 +375,24 @@ class CLIInitMixin:self.session_id = sidgetattr(self, "_write_terminal_breadcrumb", lambda: None)()+ def _new_session_id(self, now, *, branch_of=None, title=None):+ """The id main mints for /new (``new_session_id``) and /branch (``mint_session_id``). On a gateway+ store it is a session the gateway created: /new is a fresh ``session.create`` on the profile's+ default model (an explicit -m was for the previous session only), /branch the child of+ ``session.mutate branch``. Off the gateway (tests) it is main's local mint."""+ from hermes_cli.gateway_session_store import GatewaySessionStore+ store = getattr(self, "_session_db", None)+ if not isinstance(store, GatewaySessionStore):+ from hermes_state_ids import new_session_id+ return new_session_id(now)+ if branch_of:+ return store.branch(branch_of, title)+ sid = store.create({"toolsets": getattr(self, "enabled_toolsets", None),+ "pass_session_id": getattr(self, "pass_session_id", False) or None,+ "ignore_rules": getattr(self, "ignore_rules", False) or None})+ self.session_id = sid+ return sid+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_session_mixin.py b/hermes_cli/cli_session_mixin.pyindex d17d73f6519..ac27e2ecaeb 100644--- a/hermes_cli/cli_session_mixin.py+++ b/hermes_cli/cli_session_mixin.py@@ -14,7 +14,6 @@ import sysfrom agent.i18n import tfrom hermes_constants import get_hermes_home-from hermes_state_ids import new_session_idfrom pathlib import Pathfrom rich.console import Consolefrom rich.markup import escape as _escape@@ -518,7 +517,7 @@ class CLISessionMixin:self._discard_session_if_empty(old_session_id)self.session_start = datetime.now()- self.session_id = new_session_id(self.session_start)+ self.session_id = self._new_session_id(self.session_start) # the gateway's new session# getattr: tests drive new_session unbound against a SimpleNamespace stand-in.getattr(self, "_write_terminal_breadcrumb", lambda: None)()self.conversation_history = []diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.pyindex a7c54f69d43..b71da3c5080 100644--- a/hermes_cli/gateway_agent.py+++ b/hermes_cli/gateway_agent.py@@ -177,6 +177,37 @@ class GatewayAgent:returnself._show_reasoning_sent = wanted+ # -- session identity ----------------------------------------------------------------------+ @property+ def session_id(self):+ return self._session_id++ @session_id.setter+ def session_id(self, value):+ """Main repoints ``agent.session_id`` on /new, /resume and /branch: attach this viewer to that+ gateway session (idempotent) and read its state from then on."""+ previous = getattr(self, "_session_id", None)+ self._session_id = value+ if previous is None or value == previous or not value:+ return+ store = self._session_db+ if store is not None and hasattr(store, "attach"):+ try:+ store.attach(value)+ except GatewayClientError as exc:+ logger.debug("session.resume %s failed: %s", value, exc)+ else:+ try:+ self.connection.call("session.resume", session_id=value)+ except GatewayClientError as exc:+ logger.debug("session.resume %s failed: %s", value, exc)+ state = self._state()+ if self.apply_session_usage not in state.usage_listeners:+ state.usage_listeners.append(self.apply_session_usage)+ self._apply_info(state.info)+ if state.usage:+ self.apply_session_usage(state.usage)+# -- snapshot-backed reads ---------------------------------------------------------------def _state(self):return self.connection.state(self.session_id)diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.pyindex f0a014ff41d..955334bbc43 100644--- a/hermes_cli/gateway_session_store.py+++ b/hermes_cli/gateway_session_store.py@@ -131,15 +131,33 @@ class GatewaySessionStore:if str(exc) in {"not_found", "permission_denied"}:return Noneraise+ return self.create(launch)++ def create(self, launch=None):+ """``session.create`` with the launch policy; adopts and returns the new session id."""+ from agent.session_source import session_source_forparams = _creation_policy(launch or {})params["cwd"] = os.path.realpath(os.getenv("TERMINAL_CWD") or os.getcwd())- # Main's label for this row (a finite `-q`/`-Q` run is ``oneshot``, which `hermes -c` and- # `--resume latest` count as CLI history; `--source` wins), the rule run_agent applies.- from agent.session_source import session_source_for+ # Main's row label: ``cli``, ``oneshot`` for a finite -q/-Q run, or an explicit --source.params["source"] = session_source_for("cli")snapshot = self.call("session.create", request_id=uuid.uuid4().hex, **params)return self._adopt(snapshot)+ def branch(self, session_id, title=None):+ """``session.mutate branch``: the gateway forks the whole active transcript into a child it+ attaches this viewer to; returns the child id (main's /branch then switches to it)."""+ snapshot = self.call("session.resume", session_id=session_id)+ payload = {"title": title} if title else {}+ receipt = self.call("session.mutate", session_id=session_id, request_id=uuid.uuid4().hex,+ expected_revision=snapshot["revision"],+ expected_generation=snapshot["execution_generation"],+ operation="branch", payload=payload) or {}+ child = receipt.get("branched_session_id")+ if not child:+ raise GatewayClientError("branch_failed")+ self._adopt(self.attach(child))+ return child+def _revision(self, session_id):return self.call("session.resume", session_id=session_id)["revision"]diff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.pyindex 9a1ab38ee16..3a062f7ebcb 100644--- a/tests/hermes_cli/test_gateway_agent.py+++ b/tests/hermes_cli/test_gateway_agent.py@@ -446,3 +446,15 @@ def test_gateway_clarify_batch_request_opens_mains_batch_panel(make_agent):agent.run_conversation("ask")assert [q["qid"] for q in shown[0]] == ["q0", "q1"] and shown[0][1]["multi_select"] is Trueassert replies == [("srq-clr", {"answers": {"q0": "red", "q1": '["s", "l"]'}, "outcome": "submitted"})]+++def test_agent_follows_mains_session_id_switch(make_agent):+ """/new, /resume and /branch point ``agent.session_id`` at another session: the agent attaches to it+ (``session.resume``) and reads that session's state."""+ agent, client = make_agent([])+ agent.connection.state("local-other").info = {"model": "other-model"}+ agent.session_id = "local-other"+ assert agent.session_id == "local-other"+ assert ("session.resume", {"session_id": "local-other"}) in client.calls+ agent.connection.state("local-other").apply_usage({"api_calls": 3, "input_tokens": 9})+ assert agent.session_api_calls == 3diff --git a/tests/hermes_cli/test_gateway_session_store.py b/tests/hermes_cli/test_gateway_session_store.pyindex cc54522ccbb..cf637b0cca7 100644--- a/tests/hermes_cli/test_gateway_session_store.py+++ b/tests/hermes_cli/test_gateway_session_store.py@@ -255,3 +255,47 @@ def test_rewind_refuses_when_the_warm_view_diverged(store):with pytest.raises(RuntimeError):db.rewind_user_turn("local-old", -1, warm_history=[{"role": "user", "content": "other"}])assert len([c for c in client.calls if c[0] == "session.mutate"]) == before+++def test_new_session_id_is_a_fresh_gateway_session(store, monkeypatch):+ """/new: the id main mints is the gateway's new session (created with the profile's default model:+ an explicit -m was for the previous session only)."""+ from hermes_cli.cli_init_mixin import CLIInitMixin+ monkeypatch.delenv("HERMES_SESSION_SOURCE", raising=False)+ db, client = store+ host = types.SimpleNamespace(session_id="local-old", _resumed=True, _session_db=db, model="m-explicit",+ _explicit_model_override=True, requested_provider=None, enabled_toolsets=["file"],+ _gateway_session_open=True)+ host._ensure_gateway_session = lambda: CLIInitMixin._ensure_gateway_session(host)+ db.open_session(cli("local-old", resumed=True))+ sid = CLIInitMixin._new_session_id(host, None)+ assert sid == "local-new" and host.session_id == "local-new"+ method, params = [c for c in client.calls if c[0] == "session.create"][-1]+ assert "model" not in params and params["toolsets"] == ["file"]+++def test_branch_session_id_is_the_gateway_branch_child(store):+ from hermes_cli.cli_init_mixin import CLIInitMixin+ db, client = store+ base = client.rpc++ async def rpc(method, *, _timeout=None, **params):+ if method == "session.mutate" and params["operation"] == "branch":+ client.calls.append((method, params))+ client.known.add("local-child")+ return {"branched_session_id": "local-child", "copied_messages": 2}+ return await base(method, _timeout=_timeout, **params)+ client.rpc = rpc+ db.open_session(cli("local-old", resumed=True))+ host = types.SimpleNamespace(session_id="local-old", _session_db=db)+ assert CLIInitMixin._new_session_id(host, None, branch_of="local-old", title="fork") == "local-child"+ mutate = [p for m, p in client.calls if m == "session.mutate"][-1]+ assert mutate["payload"] == {"title": "fork"} and "expected_generation" in mutate+ assert "local-child" in db.snapshots+++def test_new_session_id_off_the_gateway_is_mains_mint():+ from hermes_cli.cli_init_mixin import CLIInitMixin+ host = types.SimpleNamespace(_session_db=None)+ from datetime import datetime+ assert CLIInitMixin._new_session_id(host, datetime(2026, 10, 12, 1, 2, 3)).startswith("20261012_010203_")