The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): refuse a typed --api-key the resumed session does not take
Tekniumaaf76760f4fc
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex 2119c21dadc..1941f4f9fc8 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -113,18 +113,24 @@ 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):+def _gateway_owned_id(session_db, session_id, refused=None):"""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."""+ 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_MISMATCHfrom 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: # health: allow BLE001 -- a refused attach leaves main's own resume path to report it- return 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 Nonedef _user_display_text(content) -> str:diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex a2c6b48eb2b..1c9597a1f7e 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) # the receipt owner- if target_id == self.session_id:- return _cp(f" {_t('resume.already_on')}")+ 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 Noneold_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 6119553d1db..bb9559a57c3 100644--- a/hermes_cli/cli_init_mixin.py+++ b/hermes_cli/cli_init_mixin.py@@ -220,6 +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'sself._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_chat.py b/hermes_cli/gateway_chat.pyindex 4e780c2fb8e..f06c7bec78c 100644--- a/hermes_cli/gateway_chat.py+++ b/hermes_cli/gateway_chat.py@@ -9,7 +9,7 @@ from pathlib import Pathimport sysimport uuid-from hermes_cli.gateway_client import GatewayClientError, connect_gateway+from hermes_cli.gateway_client import RESUME_KEY_MISMATCH, GatewayClientError, connect_gateway# These options change execution or require frontend facilities not yet exposed by# the authority. Reject them, rather than mutate process-wide gateway settings.@@ -133,8 +133,7 @@ async def _resume(client, args, **params):return await client.rpc("session.resume", **params, **({"api_key": key} if key else {}))except GatewayClientError as exc:if key and str(exc) == "admission_conflict":- raise GatewayClientError("--api-key on resume must be the key this session was launched with "- "(a session launched without --api-key keeps its profile credentials).") from None+ raise GatewayClientError(RESUME_KEY_MISMATCH) from Noneraise@@ -267,7 +266,7 @@ def resume_policy_error(keys):def exit_on_resume_refusal(exc):"""A refused resume is a usage error on every classic path (interactive startup's copy): ``Error:``, exit 2."""- if isinstance(exc, GatewayClientError) and str(exc).startswith(_RESUME_POLICY_MISMATCH):+ if isinstance(exc, GatewayClientError) and str(exc).startswith((_RESUME_POLICY_MISMATCH, RESUME_KEY_MISMATCH)):print(f"Error: {exc}", file=sys.stderr)raise SystemExit(2) from Nonediff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.pyindex ba9f0a74444..45e459da7aa 100644--- a/hermes_cli/gateway_client.py+++ b/hermes_cli/gateway_client.py@@ -16,6 +16,9 @@ GATEWAY_WS_TICKET_PREFIX = "hermes-gateway-ticket."# Per-request answer budget. Owner verbs are admissions/reads that answer promptly; the one that# legitimately runs long passes its own budget (``rpc(..., _timeout=...)``).DEFAULT_RPC_TIMEOUT = 30+# A typed ``--api-key`` on a resume that the owner does not bind (``rebind_launch_key``): every CLI says this.+RESUME_KEY_MISMATCH = ("--api-key on resume must be the key this session was launched with "+ "(a session launched without --api-key keeps its profile credentials).")# Canonical ``/compress`` answers only after the summary call(s) and the commit: a long session's# summary routinely takes more than 30 s (``auxiliary.compression.timeout`` defaults to 120 s per# request, ``compression.context_total_ceiling_seconds`` to 600 s). Same budget as Desktop'sdiff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.pyindex 7166ea49904..761702f514d 100644--- a/hermes_cli/gateway_connection.py+++ b/hermes_cli/gateway_connection.py@@ -16,7 +16,7 @@ import queueimport threadingimport time-from hermes_cli.gateway_client import DEFAULT_RPC_TIMEOUT, GatewayClientError, GatewayRPCError+from hermes_cli.gateway_client import DEFAULT_RPC_TIMEOUT, RESUME_KEY_MISMATCH, GatewayClientError, GatewayRPCErrorlogger = logging.getLogger(__name__)@@ -144,6 +144,9 @@ 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.+ self.launch_api_key_typed = False@classmethoddef shared(cls):@@ -266,16 +269,20 @@ class GatewayConnection:logger.debug("session.resume %s after reconnect: %s", session_id, exc)state.subscription_id = None- def resume(self, call, session_id):+ def resume(self, call, session_id, *, typed=False):"""``session.resume`` through ``call`` (the store's attach; :meth:`_resubscribe`), re-supplying:attr:`launch_api_key`. Only a refusal in ``_KEY_NOT_TAKEN`` resumes plain (a keyed startup alias on- a Desktop/TUI session); any other is raised, not hidden by a keyless attach whose first turn fails."""+ a Desktop/TUI session); any other is raised, not hidden by a keyless attach whose first turn fails.+ ``typed`` (a typed ``--api-key`` the user resumes with) never resumes plain: ``admission_conflict``+ is the thin client's refusal. A reconnect passes False: nothing was typed there."""key = self.launch_api_keyif key:try:return call("session.resume", session_id=session_id, api_key=key)except GatewayRPCError as exc:- if str(exc) not in _KEY_NOT_TAKEN:+ if typed and str(exc) == "admission_conflict":+ raise GatewayClientError(RESUME_KEY_MISMATCH) from None+ if typed or str(exc) not in _KEY_NOT_TAKEN:raiselogger.debug("session.resume %s: launch key not taken (%s); resuming without it", session_id, exc)return call("session.resume", session_id=session_id)diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.pyindex 980ac622011..69302bf0501 100644--- a/hermes_cli/gateway_session_store.py+++ b/hermes_cli/gateway_session_store.py@@ -127,14 +127,15 @@ class GatewaySessionStore:not take the key (a keyed startup alias resuming a Desktop/TUI session) attaches as is."""if session_id in self.snapshots:return self.snapshots[session_id]- snapshot = self.connection.resume(self.call, session_id)+ snapshot = self.connection.resume(self.call, session_id, typed=self.connection.launch_api_key_typed)self._adopt(snapshot)return snapshotdef open_session(self, cli, launch=None):"""Create (or resume) the gateway session for this CLI and adopt its id. A resume target thegateway does not know is left as is: main's own "Session not found" path reports it."""- self.connection.launch_api_key = (launch or {}).get("api_key") or None+ key = self.connection.launch_api_key = (launch or {}).get("api_key") or None+ 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)diff --git a/tests/hermes_cli/test_gateway_resume_launch_key.py b/tests/hermes_cli/test_gateway_resume_launch_key.pyindex 5c3bb641350..58f587fead3 100644--- a/tests/hermes_cli/test_gateway_resume_launch_key.py+++ b/tests/hermes_cli/test_gateway_resume_launch_key.py@@ -201,3 +201,95 @@ async def test_a_read_only_viewer_still_gets_the_plain_attach(tmp_path, monkeypaowners.key_of(owners.keyed)finally:await owners.close(conn)+++def _typed(session_id, key):+ """``hermes --resume <id> --api-key <key>``: the key the user typed (``HermesCLI._typed_api_key``)."""+ return SimpleNamespace(_resumed=True, session_id=session_id, _typed_api_key=key)+++async def test_resume_with_a_different_explicit_key_is_refused_not_dropped(tmp_path, monkeypatch):+ """Review probe (#141481, CLI-34): a typed ``--api-key`` the session was not launched with is refused with+ the thin client's words, never attached plain on the session's own key. Same owner life: K1 still held."""+ from hermes_cli.gateway_client import RESUME_KEY_MISMATCH+ owners = await _Owners().start(tmp_path, monkeypatch)+ conn = GatewayConnection(connect=owners.dial)+ try:+ store = GatewaySessionStore(conn)+ wrong = {**LAUNCH, 'api_key': 'A-DIFFERENT-KEY'}+ with pytest.raises(GatewayClientError) as refused:+ await asyncio.to_thread(store.open_session, _typed(owners.keyed, 'A-DIFFERENT-KEY'), wrong)+ assert str(refused.value) == RESUME_KEY_MISMATCH+ assert owners.keyed not in store.snapshots # nothing attached+ # A typed key on a session launched without one: the same refusal (the thin client's too).+ with pytest.raises(GatewayClientError, match='must be the key this session was launched with'):+ await asyncio.to_thread(store.open_session, _typed(owners.plain, RAW), LAUNCH)+ # The right typed key still resumes (after a restart: test_resume_after_a_restart_resupplies_the_launch_key).+ assert await asyncio.to_thread(store.open_session, _typed(owners.keyed, RAW), LAUNCH) == owners.keyed+ finally:+ assert owners.key_of(owners.keyed) == RAW # the session runs on K1 regardless+ await owners.close(conn)+++async def test_a_keyed_alias_still_opens_a_keyless_session(tmp_path, monkeypatch, caplog):+ """The key came from a keyed startup alias (nothing typed): ``-c`` / ``--resume`` of a session launched+ without a key keeps the plain-resume fallback, and a reconnect resubscribes it plain too."""+ caplog.set_level(logging.DEBUG, logger='hermes_cli.gateway_connection')+ owners = await _Owners().start(tmp_path, monkeypatch)+ conn = GatewayConnection(connect=owners.dial)+ try:+ store = GatewaySessionStore(conn)+ alias = SimpleNamespace(_resumed=True, session_id=owners.plain, _typed_api_key=None)+ launch = {**LAUNCH, 'base_url': None} # a changed --base-url on resume is refused on its own+ assert await asyncio.to_thread(store.open_session, alias, launch) == owners.plain+ assert conn.launch_api_key == RAW and not conn.launch_api_key_typed+ assert any('admission_conflict' in line for line in _plain_retries(caplog))+ before = conn.states[owners.plain].subscription_id+ await owners.hang_up(conn)+ await owners.boot('restarted')+ await asyncio.to_thread(conn.start, 10)+ assert conn.states[owners.plain].subscription_id not in (None, before)+ finally:+ await owners.close(conn)+++async def test_a_typed_key_reconnect_keeps_the_fallback(tmp_path, monkeypatch):+ """A reconnect types nothing: a typed-key CLI that also viewed a keyless session resubscribes it plain."""+ owners = 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)+ assert conn.launch_api_key_typed+ await asyncio.to_thread(conn.resume, store.call, owners.plain) # e.g. a session.resume a view made plain+ conn.state(owners.plain).subscription_id = 'viewed'+ await owners.hang_up(conn)+ await owners.boot('restarted')+ await asyncio.to_thread(conn.start, 10)+ assert owners.key_of(owners.keyed) == RAW+ assert conn.states[owners.plain].subscription_id not in (None, 'viewed')+ finally:+ await owners.close(conn)+++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+ owners = 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)+ printed = []+ 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'+ finally:+ await owners.close(conn)diff --git a/tests/hermes_cli/test_resume_compressed_gateway_id.py b/tests/hermes_cli/test_resume_compressed_gateway_id.pyindex aff545772a7..dec270813d8 100644--- a/tests/hermes_cli/test_resume_compressed_gateway_id.py+++ b/tests/hermes_cli/test_resume_compressed_gateway_id.py@@ -63,7 +63,7 @@ def _gateway_store(loop, authority, tmp_path):from hermes_cli.gateway_session_store import GatewaySessionStorefrom hermes_state import SessionDBstates = {}- connection = types.SimpleNamespace(final=False, launch_api_key=None,+ connection = types.SimpleNamespace(final=False, launch_api_key=None, launch_api_key_typed=False,state=lambda sid: states.setdefault(sid, SessionState(sid)))connection.resume = types.MethodType(GatewayConnection.resume, connection) # the store's attach helpergateway = AuthorityConnection(authority, object(), {