The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): classify the /resume target with one session.resume
kshitijk4poor065ea31ad355
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex f1b552c2306..15c5702a885 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -118,13 +118,25 @@ def _gateway_owned_id(session_db, session_id):``stored_session_id``. A canonical local compression segment holds the transcript, but its creationreceipt lives on the conversation's logical owner, which every turn and mutation must name (as Inkand ``session.resume`` do). Unchanged off the gateway store or when the resume is refused."""+ return _gateway_open(session_db, session_id)[0]+++def _gateway_open(session_db, session_id):+ """``(owner_id, refusal)`` from one ``session.resume`` of *session_id* on this viewer: the attach+ subscribes it and names its receipt owner (:func:`_gateway_owned_id`). ``refusal`` is the reason+ code when the owner answered that this viewer may not open it (``RESUME_GONE``), else ``None``:+ off the gateway store, a transient refusal, or no answer, the caller proceeds on its local reads."""+ from hermes_cli.gateway_client import GatewayRPCError+ from hermes_cli.gateway_connection import RESUME_GONEfrom hermes_cli.gateway_session_store import GatewaySessionStoreif not isinstance(session_db, GatewaySessionStore):- return session_id+ return session_id, Nonetry:- return session_db.attach(session_id).get("stored_session_id") or session_id- except Exception: # health: allow BLE001 -- a refused attach leaves main's own resume path to report it- return session_id+ return session_db.attach(session_id).get("stored_session_id") or session_id, None+ except GatewayRPCError as exc:+ return session_id, (str(exc) if str(exc) in RESUME_GONE else None)+ except Exception: # health: allow BLE001 -- no answer: the turn reports the lost connection itself+ return session_id, Nonedef _user_display_text(content) -> str:diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex 24037bd63f7..dce85369e58 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -31,12 +31,12 @@ from hermes_state_ids import new_session_id as mint_session_idfrom agent.i18n import tfrom agent.message_metadata import message_identityfrom agent.turn_context import extract_api_content_sidecar-from hermes_cli.cli_agent_setup_mixin import _gateway_owned_id, _retire_agent+from hermes_cli.cli_agent_setup_mixin import _gateway_open, _retire_agentfrom hermes_cli.cli_commands_session_tools import (CLICommandsSessionToolsMixin, _TTYBuf, _accent, _accent_line, _command_arg, _cp, _dim,_dim_line, _gt, _lines, _pr, _probe, _rollback_kept, _save, _say_block, _shlex_args, _t, _tn)from hermes_cli.cli_session_switch import (- _end_current_session, _open_switched_session, _sync_agent_to_session)+ _end_current_session, _sync_agent_to_session)from hermes_cli.browser_connect import (DEFAULT_BROWSER_CDP_URL, discover_local_cdp_url, find_free_debug_port, is_browser_debug_ready,launch_chrome_debug, local_port_in_use, manual_chrome_debug_command)@@ -177,7 +177,7 @@ def _cron_api(**kwargs) -> dict:return json.loads(cronjob_tool(**kwargs))-# Session-switch plumbing (end, open, repoint) lives in ``hermes_cli/cli_session_switch.py``.+# Session-switch plumbing (end, repoint) lives in ``hermes_cli/cli_session_switch.py``.def _without_session_meta(messages) -> list:@@ -881,11 +881,11 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):from hermes_cli.kanban_resume_guard import kanban_resume_refusalif (kanban_refusal := kanban_resume_refusal(self._session_db, target_id)):return _cp(f" {kanban_refusal}")- read_id, target_id = target_id, _gateway_owned_id(self._session_db, target_id) # the receipt owner- # Subscribe the target on this viewer before anything changes: the write side is the- # gateway's and /resume can land before any agent exists (also covers already-on after a- # refused launch attach). The agent setter's later attach is free: attach caches per id.- if (refusal := _open_switched_session(self, target_id)):+ # One session.resume, before anything changes: it subscribes the target and names its receipt+ # owner; a target the gateway refuses this viewer stops the switch, so the current session is+ # neither ended nor swapped for one whose next prompt would be refused.+ read_id, (target_id, refusal) = target_id, _gateway_open(self._session_db, target_id)+ if refusal:return _cp(f" {_gt('resume.switch_failed')} {target_id} ({refusal})")if target_id == self.session_id:return _cp(f" {_t('resume.already_on')}")diff --git a/hermes_cli/cli_session_switch.py b/hermes_cli/cli_session_switch.pyindex 75d688738f8..609ca5dfb17 100644--- a/hermes_cli/cli_session_switch.py+++ b/hermes_cli/cli_session_switch.py@@ -1,15 +1,12 @@"""Session-switch plumbing shared by /resume, /sessions and /branch.The switch itself lives in ``cli_commands_mixin``; the handoff it needs sits here: end the row-being left, open the row being entered on this viewer, then repoint an already-built agent.+being left, then repoint an already-built agent."""from __future__ import annotationsfrom contextlib import suppress-from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError-from hermes_cli.gateway_connection import RESUME_GONE-def _end_current_session(cli, reason: str) -> None:"""Flush un-persisted messages, then end the current session row with ``reason``.@@ -22,35 +19,6 @@ def _end_current_session(cli, reason: str) -> None:cli._session_db.end_session(cli.session_id, reason)-def _open_switched_session(cli, session_id: str) -> str | None:- """Subscribe ``session_id`` on this viewer's connection before a switch commits.-- Reads at the switch are local by design, the write side is a gateway verb: the gateway- refuses ``prompt.submit`` for a session its connection never resumed- (``gateway/session_controls.py``: ``submit`` -> ``permission_denied``). Startup resume and- the agent's ``session_id`` setter reach the store's ``attach``; a switch typed before the- first turn reaches neither, because ``_sync_agent_to_session`` only repoints an agent that- already exists, so the first prompt after the switch was refused instead of answering.-- Returns ``None`` when the switch may proceed, else the refusal reason for the caller to- report. Printing stays with the caller: its copy and its seams are the handler's.- """- store = getattr(cli, "_session_db", None)- attach = getattr(store, "attach", None)- if not callable(attach):- return None- try:- attach(session_id)- except GatewayRPCError as exc:- # The owner answered: only an ownership refusal stops the switch.- reason = str(exc)- return reason if reason in RESUME_GONE else None- except GatewayClientError:- # No answer (unavailable, disconnected, timeout). The switch's reads are local, so it- # proceeds as before; the turn reports the lost connection itself.- return None--def _sync_agent_to_session(cli, session_id: str, *, parent_session_id: str, reason: str) -> None:"""Point an already-built agent at ``session_id`` after a /resume or /branch switch: resetper-session state, re-anchor the DB flush index, and notify memory providers withdiff --git a/tests/hermes_cli/test_cli_resume_command.py b/tests/hermes_cli/test_cli_resume_command.pyindex 1cd6aa997ca..8de05839dfc 100644--- a/tests/hermes_cli/test_cli_resume_command.py+++ b/tests/hermes_cli/test_cli_resume_command.py@@ -1,6 +1,8 @@import osfrom unittest.mock import MagicMock, patch+import pytest+from cli import HermesCLI@@ -241,46 +243,62 @@ class TestResumeFlushesBeforeEndSession:cli_obj._session_db.end_session.assert_called_once()-class TestResumeSubscribesTheTarget:- """The gateway refuses ``prompt.submit`` for a session this connection never resumed, so a- /resume typed before the first turn (no agent, so no setter attach) must subscribe the target- itself, and a refusal of that subscription must keep the current session."""+class TestResumeOpensTheTargetOnTheGateway:+ """/resume on the gateway session store: one ``session.resume`` of the target classifies it before+ anything changes. A real store, so the switch takes its gateway path (a ``MagicMock`` store is not+ a ``GatewaySessionStore`` and skips it); the gateway double admits or refuses ``session.resume``."""- def _resume(self, attach_error=None):+ def _switch(self, refusal=None):+ from hermes_cli.gateway_client import GatewayRPCError+ from hermes_cli.gateway_connection import GatewayConnection+ from hermes_cli.gateway_session_store import GatewaySessionStore++ calls = []++ def gateway(method, **params):+ calls.append((method, params))+ if method == "session.resume" and params["session_id"] == "target" and refusal:+ raise GatewayRPCError(refusal)+ if method == "session.resume":+ sid = params["session_id"]+ return {"stored_session_id": sid, "subscription_id": f"sub-{sid}", "info": {}}+ return {}++ conn = GatewayConnection()+ conn.start = lambda *_a, **_k: None+ store = GatewaySessionStore(conn)+ store.call = gateway+ store._reader = MagicMock()+ store._reader.get_session.return_value = {"id": "target", "title": "T"}+ store._reader.resolve_resume_session_id.return_value = "target"+ store._reader.get_resume_conversations.return_value = ([], [])+ store.attach("current_session")+ calls.clear()cli_obj = _make_cli()- cli_obj._session_db.get_session.return_value = {"id": "target", "title": "T"}- cli_obj._session_db.get_resume_conversations.return_value = ([], [])- cli_obj._session_db.resolve_resume_session_id.return_value = "target"- cli_obj._session_db.attach.side_effect = attach_error+ cli_obj._session_db = storewith (patch("hermes_cli.main._resolve_session_by_name_or_id", return_value="target"),patch("cli._cprint") as mock_cprint,):cli_obj._handle_resume_command("/resume target")- return cli_obj, " ".join(str(call) for call in mock_cprint.call_args_list)+ printed = " ".join(str(call) for call in mock_cprint.call_args_list)+ return cli_obj, conn, calls, printed- def test_resume_before_the_first_turn_subscribes_the_target(self):- cli_obj, _ = self._resume()+ def test_an_openable_target_is_subscribed_and_the_old_session_detached(self):+ cli_obj, conn, calls, _ = self._switch()assert cli_obj.session_id == "target"- cli_obj._session_db.attach.assert_called_once_with("target")+ assert conn.states["target"].subscription_id == "sub-target"+ assert [method for method, _ in calls] == ["session.resume", "session.detach"]+ assert conn.states["current_session"].subscription_id is None- def test_a_refused_subscription_keeps_the_current_session(self):+ @pytest.mark.parametrize("refusal", ["not_found", "permission_denied", "profile_mismatch"])+ def test_a_refused_target_keeps_the_current_session(self, refusal):from agent.i18n import t- from hermes_cli.gateway_client import GatewayRPCError-- cli_obj, printed = self._resume(GatewayRPCError("permission_denied"))-- assert cli_obj.session_id == "current_session"- cli_obj._session_db.end_session.assert_not_called()- assert t("gateway.resume.switch_failed") in printed- assert "permission_denied" in printed-- def test_an_unknown_target_keeps_the_current_session(self):- from hermes_cli.gateway_client import GatewayRPCError- cli_obj, printed = self._resume(GatewayRPCError("not_found"))+ cli_obj, conn, calls, printed = self._switch(refusal)assert cli_obj.session_id == "current_session"- cli_obj._session_db.end_session.assert_not_called()- assert "not_found" in printed+ assert conn.states["current_session"].subscription_id == "sub-current_session"+ assert calls == [("session.resume", {"session_id": "target"})] # asked once, nothing detached+ assert t("gateway.resume.switch_failed") in printed and refusal in printed