The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): hold a typed --api-key only to the startup resume
David Dudok de Wit9a4f899d413b
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex 1941f4f9fc8..2119c21dadc 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -113,24 +113,18 @@ def _compression_descendant(session_db, session_id):return resolved_id if resolved_id and resolved_id != session_id else None-def _gateway_owned_id(session_db, session_id, refused=None):+def _gateway_owned_id(session_db, session_id):"""The id the gateway answers for physical row *session_id*: ``session.resume``'s``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 Ink- and ``session.resume`` do). Unchanged off the gateway store or when the resume is refused, except a- typed ``--api-key`` the session does not take, when ``refused`` (``/resume``) prints it and None is- returned (nothing switches)."""- from hermes_cli.gateway_client import RESUME_KEY_MISMATCH+ and ``session.resume`` do). Unchanged off the gateway store or when the resume is refused."""from hermes_cli.gateway_session_store import GatewaySessionStoreif not isinstance(session_db, GatewaySessionStore):return session_idtry:return session_db.attach(session_id).get("stored_session_id") or session_id- except Exception as exc: # health: allow BLE001 -- a refused attach leaves main's own resume path to report it- if refused is None or str(exc) != RESUME_KEY_MISMATCH:- return session_id- refused(f" {exc}")- return None+ except Exception: # health: allow BLE001 -- a refused attach leaves main's own resume path to report it+ return session_iddef _user_display_text(content) -> str:diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex 1c9597a1f7e..a2c6b48eb2b 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -975,9 +975,9 @@ 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, _cp) # the receipt owner- if target_id is None or target_id == self.session_id: # None: a typed --api-key it refused (printed)- return _cp(f" {_t('resume.already_on')}") if target_id else None+ read_id, target_id = target_id, _gateway_owned_id(self._session_db, target_id) # the receipt owner+ if target_id == self.session_id:+ return _cp(f" {_t('resume.already_on')}")old_session_id = self.session_id_end_current_session(self, "resumed_other")self.session_id, self._resumed, self._pending_title = target_id, True, Nonediff --git a/hermes_cli/cli_init_mixin.py b/hermes_cli/cli_init_mixin.pyindex bb9559a57c3..b2f5431bfc4 100644--- a/hermes_cli/cli_init_mixin.py+++ b/hermes_cli/cli_init_mixin.py@@ -220,7 +220,7 @@ class CLIInitMixin:# --api-key wins; otherwise a URL-bearing startup alias carries its own credential.# See #28660.self._explicit_api_key = api_key or _startup_api_key_override or None- self._typed_api_key = api_key or None # the store refuses a resume this key cannot bind, keeps an alias's+ self._typed_api_key = api_key or None # a startup resume it cannot bind is refused; an alias's falls backself._explicit_base_url = base_url or _startup_base_url_override or None# Resolved lazily at use-time via _ensure_runtime_credentials().diff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.pyindex 2613969ad54..17ad8093180 100644--- a/hermes_cli/gateway_connection.py+++ b/hermes_cli/gateway_connection.py@@ -157,8 +157,8 @@ class GatewayConnection:# This CLI's launch-only key (``--api-key`` or a keyed startup alias), set by the session store:# an owner restart revokes it, so every resume re-supplies it (the owner's ``rebind_launch_key``).self.launch_api_key = None- # True when that key is the typed ``--api-key`` (not a keyed startup alias's): a resume the owner- # will not bind it to is refused as the thin client refuses it, never attached plain.+ # True when that key is the typed ``--api-key`` (not a keyed startup alias's): a startup resume the+ # owner will not bind it to is refused as the thin client refuses it, never attached plain.self.launch_api_key_typed = False@classmethoddiff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.pyindex 69302bf0501..fb31667a63f 100644--- a/hermes_cli/gateway_session_store.py+++ b/hermes_cli/gateway_session_store.py@@ -121,13 +121,15 @@ class GatewaySessionStore:self.connection.state(sid).adopt_snapshot(snapshot)return sid- def attach(self, session_id):+ def attach(self, session_id, *, typed=False):"""``session.resume`` once per session id this viewer uses (idempotent), carrying this CLI's launchkey as the thin client does (``GatewayConnection.resume``, the reconnect's too). A session that does- not take the key (a keyed startup alias resuming a Desktop/TUI session) attaches as is."""+ not take the key (a keyed startup alias resuming a Desktop/TUI session) attaches as is. ``typed``+ (only :meth:`open_session`'s startup resume, where the user typed ``--api-key`` for that session)+ refuses it instead, as the thin client does."""if session_id in self.snapshots:return self.snapshots[session_id]- snapshot = self.connection.resume(self.call, session_id, typed=self.connection.launch_api_key_typed)+ snapshot = self.connection.resume(self.call, session_id, typed=typed)self._adopt(snapshot)return snapshot@@ -138,7 +140,7 @@ class GatewaySessionStore:self.connection.launch_api_key_typed = key is not None and key == getattr(cli, "_typed_api_key", None)if getattr(cli, "_resumed", False):try:- snapshot = self.attach(cli.session_id)+ snapshot = self.attach(cli.session_id, typed=self.connection.launch_api_key_typed)except GatewayClientError as exc:if str(exc) in {"not_found", "permission_denied"}:return Nonediff --git a/tests/hermes_cli/test_gateway_resume_launch_key.py b/tests/hermes_cli/test_gateway_resume_launch_key.pyindex 58f587fead3..f21c29ebfee 100644--- a/tests/hermes_cli/test_gateway_resume_launch_key.py+++ b/tests/hermes_cli/test_gateway_resume_launch_key.py@@ -276,20 +276,56 @@ async def test_a_typed_key_reconnect_keeps_the_fallback(tmp_path, monkeypatch):@pytest.mark.asyncio-async def test_slash_resume_with_a_typed_key_is_refused_and_does_not_switch(tmp_path, monkeypatch):- """``/resume <keyless session>`` in a ``--api-key`` CLI: the refusal is printed and nothing switches- (``_gateway_owned_id`` returns None); a refused attach of any other kind keeps main's path."""- from hermes_cli.cli_agent_setup_mixin import _gateway_owned_id- from hermes_cli.gateway_client import RESUME_KEY_MISMATCH+async def test_slash_resume_in_a_typed_key_cli_switches_to_a_keyless_session_on_its_own_route(+ tmp_path, monkeypatch):+ """Review (#141481, CLI-34): only the startup resume holds a typed ``--api-key``. ``/resume <keyless+ session>`` in a ``--api-key`` CLI switches to it as on main, and the owner does not bind the key to it:+ the session keeps its own frozen route."""+ from unittest.mock import patch+ from cli import HermesCLI+ from hermes_state import SessionDBowners = await _Owners().start(tmp_path, monkeypatch)conn = GatewayConnection(connect=owners.dial)try:store = GatewaySessionStore(conn)- await asyncio.to_thread(store.open_session, _typed(owners.keyed, RAW), LAUNCH)+ store._reader = SessionDB(db_path=owners.store._db.db_path, read_only=True) # the CLI's state.db reads+ cli = HermesCLI.__new__(HermesCLI)+ cli._session_db, cli._resumed, cli.session_id, cli._typed_api_key = store, True, owners.keyed, RAW+ cli.agent, cli.conversation_history, cli._pending_resume_sessions = None, [], None+ cli._restore_session_cwd = cli._restore_session_yolo = cli._restore_session_model = lambda *a, **k: None+ await asyncio.to_thread(store.open_session, cli, LAUNCH) # hermes --resume <keyed> --api-key Kprinted = []- assert await asyncio.to_thread(_gateway_owned_id, store, owners.plain, printed.append) is None- assert printed == [f' {RESUME_KEY_MISMATCH}']- assert await asyncio.to_thread(_gateway_owned_id, store, owners.plain) == owners.plain # no printer: as main- assert await asyncio.to_thread(_gateway_owned_id, store, 'missing-id', printed.append) == 'missing-id'+ with patch('hermes_cli.main._resolve_session_by_name_or_id', return_value=None), \+ patch('cli._cprint', printed.append):+ await asyncio.to_thread(cli._handle_resume_command, f'/resume {owners.plain}')+ assert cli.session_id == owners.plain, printed+ assert store.current['stored_session_id'] == owners.plain+ assert owners.key_of(owners.plain) is None # not rebound to K+ finally:+ await owners.close(conn)+++async def test_branch_after_new_in_a_typed_key_cli_switches_to_the_child(tmp_path, monkeypatch):+ """Review probe (#141481, CLI-34): ``/new`` in a ``--api-key`` CLI opens a session on the profile's default+ route, without the key, and ``/branch`` of it attaches the child the owner just made with the plain+ fallback. Held to the typed key, the attach raised the ``--api-key`` mismatch after the owner had+ committed the child: the CLI stayed on the parent, and each retry made another child."""+ from datetime import datetime+ from gateway import run+ from hermes_cli.cli_init_mixin import CLIInitMixin+ owners = await _Owners().start(tmp_path, monkeypatch)+ monkeypatch.setattr(run, '_load_gateway_config', lambda *a, **k: {'platform_toolsets': {'cli': []}, 'model': 'm'})+ conn = GatewayConnection(connect=owners.dial)+ try:+ store = GatewaySessionStore(conn)+ cli = _typed(owners.keyed, RAW)+ cli._session_db, cli._gateway_session_open = store, True+ await asyncio.to_thread(store.open_session, cli, LAUNCH)+ fresh = await asyncio.to_thread(CLIInitMixin._new_session_id, cli, datetime.now()) # /new+ assert owners.key_of(fresh) is None+ owners.store._db.append_message(fresh, role='user', content='hello')+ child = await asyncio.to_thread(CLIInitMixin._new_session_id, cli, datetime.now(), branch_of=fresh) # /branch+ assert child != fresh and store.current['stored_session_id'] == childfinally:await owners.close(conn)