Skip to content

The agent that grows with you

fix: never drop --api-key/--base-url/--reasoning on --tui; resume can re-supply a launch key

Tekniumaed0e3bca53c
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index a23cc260897..70989460ca4 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4772,6 +4772,7 @@ export interface CanonicalResumeParams {
workspace?: string | null
source?: string | null
editor?: Record<string, unknown> | null
+ api_key?: string | null
defer_history?: boolean
omit_messages?: boolean
cols?: number | null
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index bb2faa8061b..19da558594d 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -9410,6 +9410,18 @@
"default": null,
"title": "Editor"
},
+ "api_key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Api Key"
+ },
"defer_history": {
"default": false,
"title": "Defer History",
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 0a11d2e7926..90723f9add0 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -367,6 +367,11 @@ class AuthorityConnection:
self.authority.authorize(self.actor, ref, 'session:control')
from gateway.session_local_mcp import resume_editor_mcp
resume_editor_mcp(self.authority, ref, params['editor'])
+ if 'api_key' in params:
+ # A launch-only key re-supplied after a restart (`--resume <id> --api-key`).
+ self.authority.authorize(self.actor, ref, 'session:control')
+ from gateway.session_policy import rebind_launch_key
+ rebind_launch_key(self.authority, ref, params['api_key'])
# Read-only mount (#85303): an ended row stays ended until the first admitted turn
# reopens it (``reopen_local_session`` in the drain), so opening a finished chat
# never re-lights DB-derived liveness with no new activity.
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index 3cfdf26ecc2..7b9530c85ff 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -330,10 +330,52 @@ def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=No
configs[config_ref] = dict(config_secrets)
if api_key is not None:
keys[ref] = api_key
- return replace(policy, credential_ref=ref if api_key is not None else None,
+ # The durable ref carries the key's fingerprint (the digest config_secret_ref already
+ # persists for config keys) so a restarted owner can verify a re-supplied key
+ # (rebind_launch_key); the key itself is never durable.
+ from agent.credential_persistence import fingerprint_secret_value
+ return replace(policy, credential_ref=f'{ref}#{fingerprint_secret_value(api_key)}' if api_key is not None else None,
config_secret_ref=config_ref if config_secrets else None)
+def _key_slot(credential_ref):
+ """The in-memory slot of a durable credential ref (``<instance>:<epoch>:<sid>[#<fingerprint>]``)."""
+ return credential_ref.split('#', 1)[0]
+
+
+def rebind_launch_key(authority, session, api_key):
+ """``session.resume`` re-supplying a launch-only key after an owner restart revoked it
+ (call after authorizing *session*, a SessionRef).
+
+ Only a session launched with a key can take one, and only that same key (its durable
+ fingerprint); anything else is an override of the frozen route and is refused. Like the
+ original, the key lives in this authority's memory only."""
+ import hmac
+ from agent.credential_persistence import fingerprint_secret_value
+ from gateway.config import Platform
+ if not isinstance(api_key, str) or not api_key.strip():
+ raise RuntimeStoreError('invalid_params')
+ source = authority.sessions[session.session_id].source
+ if source is None or source.platform != Platform.LOCAL:
+ raise RuntimeStoreError('admission_conflict')
+ from hermes_state_local import local_receipt
+ ref = restore_policy(local_receipt(authority.db, session.session_id)['policy']).credential_ref
+ if ref is None:
+ raise RuntimeStoreError('admission_conflict')
+ keys = getattr(authority, '_local_launch_keys', None)
+ if keys is None:
+ keys = authority._local_launch_keys = {}
+ held = keys.get(_key_slot(ref))
+ if held is not None:
+ if not hmac.compare_digest(held, api_key):
+ raise RuntimeStoreError('admission_conflict')
+ return
+ _, _, fingerprint = ref.partition('#')
+ if not fingerprint or not hmac.compare_digest(fingerprint, fingerprint_secret_value(api_key) or ''):
+ raise RuntimeStoreError('admission_conflict')
+ keys[_key_slot(ref)] = api_key
+
+
def release_launch_secrets(authority, session_ids):
"""Drop retired sessions' launch keys, frozen config secrets and editor MCP servers.
@@ -346,7 +388,8 @@ def release_launch_secrets(authority, session_ids):
return
prefix = f'{authority.instance_id}:{authority.epoch}:'
keys = getattr(authority, '_local_launch_keys', None) or {}
- for ref in [ref for ref in keys if ref.startswith(prefix) and ref[len(prefix):] in retired]:
+ # A key re-supplied after a restart sits in the slot of the epoch that minted it.
+ for ref in [ref for ref in keys if ref.split(':', 2)[-1] in retired]:
del keys[ref]
configs = getattr(authority, '_local_config_secrets', None) or {}
for ref in list(configs):
@@ -364,7 +407,7 @@ def release_launch_secrets(authority, session_ids):
def launch_key(authority, policy):
if policy.credential_ref is None:
return None
- value = getattr(authority, '_local_launch_keys', {}).get(policy.credential_ref)
+ value = getattr(authority, '_local_launch_keys', {}).get(_key_slot(policy.credential_ref))
if value is None:
raise RuntimeStoreError('launch_credentials_unavailable')
return value
diff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.py
index c087dbb0f34..c23bbe7009d 100644
--- a/hermes_cli/gateway_chat.py
+++ b/hermes_cli/gateway_chat.py
@@ -106,6 +106,20 @@ def _workspace_key(cwd):
os.chdir(previous)
+async def _resume(client, args, **params):
+ """``session.resume``; ``--api-key`` re-supplies a launch-only key an owner restart revoked.
+ The owner binds it only to a session launched with that same key (never durable); anything
+ else is a route override and refused like every other creation flag on resume."""
+ key = getattr(args, "api_key", None)
+ try:
+ 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
+
+
async def _resume_latest(client, args):
"""Bare ``-c``: this terminal's breadcrumb session when the owner still has it, else (and for
``--resume latest``) the owner's most recent CLI session, this workspace first."""
@@ -113,13 +127,13 @@ async def _resume_latest(client, args):
crumb = (read_breadcrumb() or {}).get("session_id") if getattr(args, "continue_last", None) is True else None
if isinstance(crumb, str) and crumb:
try:
- return await client.rpc("session.resume", session_id=crumb)
+ return await _resume(client, args, session_id=crumb)
except GatewayClientError as exc:
if str(exc) not in {"not_found", "permission_denied"}:
raise
workspace = await asyncio.to_thread(_workspace_key, _caller_cwd(args))
try:
- return await client.rpc("session.resume", latest="cli", **({"workspace": workspace} if workspace else {}))
+ return await _resume(client, args, latest="cli", **({"workspace": workspace} if workspace else {}))
except GatewayClientError as exc:
if str(exc) != "not_found":
raise
@@ -149,12 +163,12 @@ async def run_gateway_chat(args, emitter=None):
name = getattr(args, "resume", None) or title
try:
# Exact id first, then title (latest lineage continuation), as the classic CLI did.
- snapshot = await client.rpc("session.resume", session_id=name)
+ snapshot = await _resume(client, args, session_id=name)
except GatewayClientError as exc:
if str(exc) != "not_found":
raise
try:
- snapshot = await client.rpc("session.resume", title=name)
+ snapshot = await _resume(client, args, title=name)
except GatewayClientError as exc:
if str(exc) != "not_found":
raise
@@ -195,6 +209,7 @@ async def run_gateway_chat(args, emitter=None):
emitter.bind_session(snapshot["stored_session_id"])
view = GatewayChatView(client, snapshot, quiet=quiet, emitter=emitter,
usage_file=getattr(args, "usage_file", None))
+ view.launch_api_key = getattr(args, "api_key", None) # /new keeps this launch's key
view.unattended = isinstance(oneshot_prompt, str)
view.resume_footer = oneshot and not quiet
if (getattr(args, "resume", None) or title or latest) and not quiet:
diff --git a/hermes_cli/gateway_chat_commands.py b/hermes_cli/gateway_chat_commands.py
index 407ed8fa3ee..dabe3e5a5f3 100644
--- a/hermes_cli/gateway_chat_commands.py
+++ b/hermes_cli/gateway_chat_commands.py
@@ -113,6 +113,9 @@ async def _new(view, rest):
if key in accepted and key not in {"request_id", "title"}}
if info.get("cwd") and "cwd" in accepted:
request["cwd"] = info["cwd"]
+ # The frozen request never holds the launch key; the one this terminal supplied rides along.
+ if getattr(view, "launch_api_key", None) and "api_key" in accepted:
+ request["api_key"] = view.launch_api_key
snapshot = await view.client.rpc("session.create", request_id=uuid.uuid4().hex, **request)
await view.adopt(snapshot)
print(t("cli.session.new_session"))
diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.py
index d8a2b2daac1..a944037e916 100644
--- a/hermes_cli/gateway_chat_view.py
+++ b/hermes_cli/gateway_chat_view.py
@@ -48,6 +48,7 @@ class GatewayChatView:
self.finite = False
self.unattended = False # `-z`: the classic one-shot auto-approves; `-q` stays single-query
self.resume_footer = False # `chat -q` without -Q: main's "Resume this session with:" block
+ self.launch_api_key = None # `--api-key` of this terminal's launch; never durable (/new reuses it)
self.finite_admission = None
self._finite_events = []
self.streams = {}
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 072d75a1a45..c9bbbe1df2d 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -905,6 +905,7 @@ from hermes_cli.main_web_build import ( # frozen updater surface: update_cmd*.p
from hermes_cli.main_tui_launch import (
_launch_tui,
_pin_kanban_board_env,
+ _refuse_unforwarded_tui_flags,
_resolve_use_tui,
_sync_bundled_skills_quietly,
)
@@ -1709,6 +1710,7 @@ def cmd_chat(args):
if stream_json_requested(args) or _bypass_chat_launch(args) or not _resolve_use_tui(args):
from hermes_cli.gateway_chat_startup import launch_gateway_chat
sys.exit(launch_gateway_chat(args))
+ _refuse_unforwarded_tui_flags(args)
_apply_safe_mode(args)
_apply_user_config_bypass(args)
_guard_noninteractive_user_config(args)
diff --git a/hermes_cli/main_tui_launch.py b/hermes_cli/main_tui_launch.py
index 84cfdc77e5a..657b1a70b6e 100644
--- a/hermes_cli/main_tui_launch.py
+++ b/hermes_cli/main_tui_launch.py
@@ -365,6 +365,22 @@ def _require_bypass_model(env: dict, model: Optional[str], resume_session_id: Op
raise SystemExit(1)
+# Launch flags the Ink client cannot carry into session.create yet. Refused (exit 2, as classic
+# chat refuses unsupported flags), never dropped: a dropped --api-key/--base-url would silently
+# run the session on the profile's own endpoint and credentials.
+_TUI_UNFORWARDED = {"api_key": "--api-key", "base_url": "--base-url", "reasoning": "--reasoning"}
+
+
+def _refuse_unforwarded_tui_flags(args) -> None:
+ flags = [flag for name, flag in _TUI_UNFORWARDED.items() if getattr(args, name, None)]
+ if flags:
+ print(f"Error: Unsupported --tui options: {', '.join(flags)}. No session was started.\n"
+ f" Use classic chat for this launch: hermes chat --cli {' '.join(flags)} ...\n"
+ " Or set model.base_url / agent.reasoning_effort in config.yaml (/reasoning in the TUI).",
+ file=sys.stderr)
+ raise SystemExit(2)
+
+
def _launch_tui(
resume_session_id: Optional[str] = None, tui_dev: bool = False, native_mode: Optional[bool] = None,
model: Optional[str] = None,
diff --git a/tests/gateway/test_launch_key_resume_rebind.py b/tests/gateway/test_launch_key_resume_rebind.py
new file mode 100644
index 00000000000..4d1ddc166da
--- /dev/null
+++ b/tests/gateway/test_launch_key_resume_rebind.py
@@ -0,0 +1,58 @@
+"""A launch-only key revoked by an owner restart can be re-supplied on session.resume, and only
+the key the session was launched with (its durable fingerprint); never persisted."""
+from types import SimpleNamespace
+
+import pytest
+
+
+async def test_resume_rebinds_only_the_launch_key_after_restart(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_controls import AuthorityConnection
+ from gateway.session_local import create_local_session
+ from gateway.session_policy import launch_key, policy_for_source
+ from hermes_state_runtime import RuntimeStoreError
+ monkeypatch.setattr(run, '_load_gateway_config', lambda *a, **k: {'platform_toolsets': {'cli': []}})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+
+ def runner():
+ owner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,
+ _cached_agent_for=lambda route: None, _evict_cached_agent=lambda route: None)
+ owner._adapter_for_source = lambda source: owner.adapters.get(source.platform)
+ return owner
+
+ raw = 'UNIQUE-LAUNCH-ONLY-KEY'
+ first = await initialize_session_authority(runner(), profile_id=str(tmp_path), instance_id='first')
+ actor = AuthorityConnection(first, object(), {'user_id': 'owner'}).actor
+ keyed = create_local_session(first, actor, {'request_id': 'keyed', 'cwd': str(tmp_path), 'model': 'm',
+ 'toolsets': [], 'base_url': 'http://127.0.0.1:9/v1', 'api_key': raw})
+ plain = create_local_session(first, actor, {'request_id': 'plain', 'cwd': str(tmp_path), 'model': 'm',
+ 'toolsets': []})
+ with store._db._read_ctx() as conn:
+ assert not [row for row in conn.execute('SELECT value FROM state_meta') if raw in row[0]]
+ cold = await initialize_session_authority(runner(), profile_id=str(tmp_path), instance_id='restarted')
+ connection = AuthorityConnection(cold, object(), {'user_id': 'owner'})
+
+ async def resume(ref, **extra):
+ reply = await connection.dispatch({'id': 1, 'method': 'session.resume',
+ 'params': {'session_id': ref.session_id, **extra}})
+ return reply.get('error', {}).get('message') or 'ok'
+
+ def key_of(ref):
+ return launch_key(cold, policy_for_source(cold.runner, cold.sessions[ref.session_id].source))
+
+ try:
+ assert await resume(keyed) == 'ok'
+ with pytest.raises(RuntimeStoreError, match='launch_credentials_unavailable'):
+ key_of(keyed)
+ assert await resume(keyed, api_key='a-different-key') == 'admission_conflict'
+ assert await resume(plain, api_key=raw) == 'admission_conflict' # no launch key to re-supply
+ assert await resume(keyed, api_key=raw) == 'ok'
+ assert key_of(keyed) == raw and key_of(plain) is None
+ assert await resume(keyed, api_key='a-different-key') == 'admission_conflict'
+ finally:
+ await connection.close()
+ store._db.close()
diff --git a/tests/hermes_cli/test_gateway_chat.py b/tests/hermes_cli/test_gateway_chat.py
index 5b901912c82..bf9a2064387 100644
--- a/tests/hermes_cli/test_gateway_chat.py
+++ b/tests/hermes_cli/test_gateway_chat.py
@@ -234,3 +234,45 @@ async def test_documented_env_opt_ins_ride_the_classic_create_and_bypass_needs_a
monkeypatch.delenv(name)
assert gateway_chat.launch_from_args(argparse.Namespace(query="q")) == 1
assert "--model" in capsys.readouterr().err
+
+
+async def test_launch_key_flags_are_never_silently_dropped(monkeypatch, tmp_path, capsys):
+ """N23: `--tui` cannot carry --api-key/--base-url/--reasoning into Ink's create yet, so it
+ refuses them (exit 2) instead of running on the profile's endpoint; classic chat re-supplies
+ the launch key on resume (an owner restart revoked it) and `/new` keeps it."""
+ from contextlib import asynccontextmanager
+ from hermes_cli import gateway_chat, gateway_chat_commands, main as main_mod
+ from hermes_cli.gateway_chat_view import GatewayChatView
+ monkeypatch.setattr(main_mod, "_launch_tui", lambda *_a, **_k: pytest.fail("TUI launched without the flags"))
+ for flag in ("api_key", "base_url", "reasoning"):
+ with pytest.raises(SystemExit) as refused:
+ main_mod.cmd_chat(argparse.Namespace(tui=True, **{flag: "x"}))
+ assert refused.value.code == 2 and "--" + flag.replace("_", "-") in capsys.readouterr().err
+ calls = []
+
+ class Peer:
+ async def rpc(self, method, **params):
+ calls.append((method, params))
+ if method == "runtime.describe":
+ return {"session_create": {"sources": ["cli"], "parameters": ["cwd", "model", "api_key", "source"]}}
+ if method == "session.info":
+ return {"launch_request": {"source": "cli", "model": "m"}, "cwd": str(tmp_path)}
+ return {"stored_session_id": "stored", "execution_generation": 0,
+ "info": {"launch_request": {"source": "cli", "model": "m"}}}
+
+ @asynccontextmanager
+ async def connected():
+ yield Peer()
+
+ async def rendered(self, query, *, oneshot):
+ await gateway_chat_commands._new(self, "")
+ return 0
+
+ monkeypatch.setattr(gateway_chat, "connect_gateway", connected)
+ monkeypatch.setattr(GatewayChatView, "run", rendered)
+ args = argparse.Namespace(resume="stored", api_key="launch-key", query="q", quiet=True)
+ assert await gateway_chat.run_gateway_chat(args) == 0
+ sent = {method: params for method, params in calls}
+ assert sent["session.resume"] == {"session_id": "stored", "api_key": "launch-key"}
+ assert sent["session.create"]["api_key"] == "launch-key"
diff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.py
index 11f90762d8d..374f73d04b4 100644
--- a/tui_gateway/contracts/canonical_sessions.py
+++ b/tui_gateway/contracts/canonical_sessions.py
@@ -48,6 +48,8 @@ class CanonicalResumeParams(ProfileParams):
workspace: str | None = None
source: str | None = None
editor: dict[str, JsonValue] | None = None
+ # Re-supplies a launch-only key a restart revoked; never durable, must match the launch's.
+ api_key: str | None = None
defer_history: bool = False
omit_messages: bool = False
cols: int | None = None