The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): name the clashing flag on a refused resume; env opt-ins never refuse
unsupportedpastels33b53db7c031
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex 138fee83e3f..30cb28683fe 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -634,6 +634,8 @@ class CLIAgentSetupMixin:try:self._ensure_gateway_session()except Exception as e: # health: allow BLE001 -- any session.create/resume failure is main's agent-init failure copy, never a traceback+ from hermes_cli.gateway_chat import exit_on_resume_refusal+ exit_on_resume_refusal(e) # -q: a changed flag on --resume is interactive startup's `Error:` + exit 2ChatConsole().print(f"[bold red]{_escape(agent_init_failure_message(e))}[/]")return Falseif (diff --git a/hermes_cli/cli_init_mixin.py b/hermes_cli/cli_init_mixin.pyindex 0c4bcc8fcbf..e4bb3f607dd 100644--- a/hermes_cli/cli_init_mixin.py+++ b/hermes_cli/cli_init_mixin.py@@ -290,6 +290,8 @@ class CLIInitMixin:self.pass_session_id = pass_session_id# --ignore-rules: AIAgent skips context files (AGENTS.md/SOUL.md/...) and memory.self.ignore_rules = ignore_rules or is_truthy_value(os.environ.get("HERMES_IGNORE_RULES"))+ # The env opt-in is creation policy only: a resume checks just a typed --ignore-rules (the thin client's rule).+ self._explicit_ignore_rules = bool(ignore_rules)def _init_prompt_and_reasoning(self, reasoning):"""Ephemeral system prompt/prefill, reasoning + service tier, OpenRouter routing knobs, fallback chain."""diff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.pyindex 0333d868020..1c8c724db6c 100644--- a/hermes_cli/gateway_chat.py+++ b/hermes_cli/gateway_chat.py@@ -221,6 +221,30 @@ async def run_gateway_chat(args, emitter=None):_RESUME_POLICY_MISMATCH = "Resume retains gateway session policy; creation overrides are unsupported on resume."+# A refused resume flag as the user typed it, and the slash command that changes it on the resumed session.+_RESUME_FLAG_HINTS = {"model": ("-m/--model", "/model"), "provider": ("--provider", "/model"),+ "base_url": ("--base-url", "/model"), "reasoning": ("--reasoning", "/reasoning"),+ "yolo": ("--yolo", "/yolo"), "toolsets": ("-t/--toolsets", None),+ "skills": ("-s/--skills", None), "verbose": ("-v/--verbose", None), "cwd": ("--in", None)}+++def resume_policy_error(keys):+ """The resume refusal naming each flag that differs from the session's frozen launch, and the way forward."""+ hints = [_RESUME_FLAG_HINTS.get(key, ("--" + key.replace("_", "-"), None)) for key in keys]+ flags = ", ".join(dict.fromkeys(flag for flag, _ in hints))+ switch = " or ".join(dict.fromkeys(command for _, command in hints if command))+ one = len(hints) == 1+ them = "it" if one else "them"+ after = f" and use {switch} after resuming to switch" if switch else f", or start a new session to use {them}"+ return GatewayClientError(f"{_RESUME_POLICY_MISMATCH} {flags} {'differs' if one else 'differ'} from this "+ f"session's launch: resume without {them}{after}.")+++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):+ print(f"Error: {exc}", file=sys.stderr)+ raise SystemExit(2) from Nonedef _launch_flags(args):@@ -266,11 +290,10 @@ def check_resume_policy(args, snapshot):from hermes_constants import get_hermes_homeflags = {key: requested[key] for key in ("model", "provider", "base_url", "api_key") if key in requested}requested["model"] = resolve_launch_route(flags, load_user_config_effective(get_hermes_home() / "config.yaml"))["model"]- for key, value in requested.items():- if key == "api_key":- continue # never durable; a repeated key is not a policy change- if frozen.get(key) != value:- raise GatewayClientError(_RESUME_POLICY_MISMATCH)+ # api_key is never durable; a repeated key is not a policy change.+ differs = [key for key, value in requested.items() if key != "api_key" and frozen.get(key) != value]+ if differs:+ raise resume_policy_error(differs)def _register_terminal_process() -> None:diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.pyindex ae769f3cc76..622fe2cbe8b 100644--- a/hermes_cli/gateway_session_store.py+++ b/hermes_cli/gateway_session_store.py@@ -134,8 +134,10 @@ class GatewaySessionStore:if str(exc) in {"not_found", "permission_denied"}:return Noneraise- # The CLI always sends its resolved toolsets; only an explicit -t is checked.- _check_resume_launch({**(launch or {}), "toolsets": getattr(cli, "_typed_toolsets", None)}, snapshot)+ # The CLI sends a coding-posture toolset pick and an env-folded ignore_rules too; only a typed+ # -t / --ignore-rules is checked.+ _check_resume_launch({**(launch or {}), "toolsets": getattr(cli, "_typed_toolsets", None),+ "ignore_rules": getattr(cli, "_explicit_ignore_rules", None) or None}, snapshot)return self._adopt(snapshot)return self.create(launch)@@ -417,14 +419,15 @@ _RESUME_CHECKED = _LAUNCH_POLICYdef _check_resume_launch(launch, snapshot):"""Explicit launch flags on ``--resume`` / ``-c`` against the session's frozen route, as the thinclient checks them: the same flags again are fine, a different value is refused, never dropped."""- from hermes_cli.gateway_chat import _RESUME_POLICY_MISMATCH, check_resume_policy+ from hermes_cli.gateway_chat import check_resume_policy, resume_policy_errorfields = {key: launch.get(key) for key in _RESUME_CHECKED}if isinstance(fields.get("toolsets"), (list, tuple)):fields["toolsets"] = ",".join(str(item) for item in fields["toolsets"])check_resume_policy(argparse.Namespace(**fields), snapshot)frozen = ((snapshot.get("info") or {}).get("launch_request") or {})- if any(frozen.get(key) != value for key, value in _classic_only_policy(launch).items()):- raise GatewayClientError(_RESUME_POLICY_MISMATCH)+ differs = [key for key, value in _classic_only_policy(launch).items() if frozen.get(key) != value]+ if differs:+ raise resume_policy_error(differs)def session_store():diff --git a/tests/hermes_cli/test_gateway_session_store.py b/tests/hermes_cli/test_gateway_session_store.pyindex 3f5c65ea01e..c8f49371e5d 100644--- a/tests/hermes_cli/test_gateway_session_store.py+++ b/tests/hermes_cli/test_gateway_session_store.py@@ -648,3 +648,47 @@ def test_branch_never_shows_yolo_the_gateway_refused(store):finally:for key in ("local-old", "local-child"):approval.disable_session_yolo(key)+++def test_exported_ignore_rules_never_refuses_a_bare_resume(store, monkeypatch):+ """CLI-2: an exported HERMES_IGNORE_RULES is creation policy only, so a bare `hermes -c` continues a+ session created without it (Desktop, Ink, before the export); a typed --ignore-rules is still refused,+ as the thin client refuses it."""+ from hermes_cli.cli_init_mixin import CLIInitMixin, _gateway_launch+ monkeypatch.setenv("HERMES_IGNORE_RULES", "1")+ db, client = store+ _frozen_launch(client, {"model": "m-frozen"})++ def host(typed):+ h = cli("local-old", resumed=True)+ CLIInitMixin._init_checkpoints_and_rules(h, False, False, typed)+ return h++ bare = host(False)+ assert bare.ignore_rules and _gateway_launch(bare)["ignore_rules"] is True # a new session still gets it+ assert GatewaySessionStore(db.connection).open_session(bare, _gateway_launch(bare)) == "local-old"+ typed = host(True)+ with pytest.raises(GatewayClientError, match="Resume retains gateway session policy"):+ GatewaySessionStore(db.connection).open_session(typed, _gateway_launch(typed))+++def test_resume_refusal_names_the_clashing_flag_and_the_way_forward(store):+ """CLI-2: the refusal (one text for both clients) names the flag that differs from the frozen launch+ and how to go on: resume without it, then the slash command that switches it live."""+ import argparse+ from hermes_cli.gateway_chat import check_resume_policy+ db, client = store+ _frozen_launch(client, {"model": "m-frozen", "max_turns": 5})+ host = cli("local-old", resumed=True)+ with pytest.raises(GatewayClientError, match="Resume retains gateway session policy") as refused:+ GatewaySessionStore(db.connection).open_session(host, {"model": "m-other"})+ assert "-m/--model differs" in str(refused.value) and "use /model after resuming" in str(refused.value)+ with pytest.raises(GatewayClientError, match="--max-turns differs") as refused:+ GatewaySessionStore(db.connection).open_session(host, {"max_turns": 1})+ assert "start a new session" in str(refused.value)+ with pytest.raises(GatewayClientError, match="--run-budget differs"):+ GatewaySessionStore(db.connection).open_session(host, {"run_budget": 30})+ # The thin client raises the same text.+ with pytest.raises(GatewayClientError, match="--provider differs .* use /model after resuming"):+ check_resume_policy(argparse.Namespace(provider="anthropic"),+ {"info": {"launch_request": {"provider": "openrouter"}}})diff --git a/tests/hermes_cli/test_resume_quiet_stderr.py b/tests/hermes_cli/test_resume_quiet_stderr.pyindex ea59a55fc55..6bfeb447145 100644--- a/tests/hermes_cli/test_resume_quiet_stderr.py+++ b/tests/hermes_cli/test_resume_quiet_stderr.py@@ -13,6 +13,8 @@ Interactive mode (tool_progress_mode == "full") still uses ChatConsole.from datetime import datetimefrom unittest.mock import MagicMock+import pytest+from cli import HermesCLIfrom agent.i18n import t@@ -114,3 +116,27 @@ class TestResumeQuietStderr:assert "has no messages" not in captured.outassert "has no messages" in captured.errassert "Starting fresh" in captured.err++ def test_resume_policy_refusal_is_a_usage_error_not_an_agent_init_failure(self, capsys):+ """`--resume X --max-turns 1 -q ...` printed the agent-init failure copy ("couldn't start the model+ connection ... hermes doctor") and exited 1; it is interactive startup's `Error:` line on stderr+ with exit 2. Any other failed open keeps the agent-init copy."""+ from hermes_cli.gateway_chat import _RESUME_POLICY_MISMATCH+ from hermes_cli.gateway_client import GatewayClientError+ cli = _make_cli(quiet=True, db=MagicMock())+ refusal = f"{_RESUME_POLICY_MISMATCH} --max-turns differs from this session's launch."++ def refuse():+ raise GatewayClientError(refusal)+ cli._ensure_gateway_session = refuse+ with pytest.raises(SystemExit) as exited:+ cli._init_agent()+ captured = capsys.readouterr()+ assert exited.value.code == 2+ assert captured.err.strip() == f"Error: {refusal}"+ assert "couldn't start" not in captured.out + captured.err++ def unreachable():+ raise GatewayClientError("gateway unavailable")+ cli._ensure_gateway_session = unreachable+ assert cli._init_agent() is False