The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): carry classic CLI launch flags into the gateway session
unsupportedpastels7b50d36ac394
diff --git a/hermes_cli/cli_init_mixin.py b/hermes_cli/cli_init_mixin.pyindex 7dd41eabf26..d2d7492eb89 100644--- a/hermes_cli/cli_init_mixin.py+++ b/hermes_cli/cli_init_mixin.py@@ -20,6 +20,41 @@ from utils import base_url_host_matches, base_url_hostname, is_truthy_value# Log-record parity with the origin module.logger = logging.getLogger("cli")+# The launch flags that pick the model route: ``/new`` starts on the profile's default route.+_ROUTE_FLAGS = ("model", "provider", "api_key", "base_url")+++def _gateway_launch(cli):+ """This run's explicit launch flags as gateway ``session.create`` policy (main handed them to AIAgent)."""+ explicit_model = getattr(cli, "_explicit_model_override", False)+ provider = getattr(cli, "requested_provider", None)+ return {"model": cli.model if explicit_model else None,+ "provider": provider if explicit_model and provider not in {None, "", "auto"} else None,+ "api_key": getattr(cli, "_explicit_api_key", None),+ "base_url": getattr(cli, "_explicit_base_url", None),+ # Only a picked list (-t or the coding posture); the gateway resolves the profile default (#138670).+ "toolsets": getattr(cli, "enabled_toolsets", None) if getattr(cli, "_explicit_toolsets", False) else None,+ "reasoning": getattr(cli, "_explicit_reasoning", None),+ "max_turns": getattr(cli, "_explicit_max_turns", None),+ "checkpoints": getattr(cli, "_explicit_checkpoints", False) or None,+ "pass_session_id": getattr(cli, "pass_session_id", False) or None,+ "ignore_rules": getattr(cli, "ignore_rules", False) or None,+ "run_budget": getattr(cli, "_explicit_run_budget", None),+ "verbose": getattr(cli, "verbose", False) or None,+ "skills": _explicit_launch_skills(cli)}+++def _explicit_launch_skills(cli):+ """The `-s/--skills` names, which the gateway renders into the session once at creation (the CLI's+ own prompt never reaches it). ``skills.auto_load`` names are left out: the gateway's agent loads those."""+ requested = getattr(cli, "_preload_skills_requested", None) or []+ if not requested:+ return None+ from agent.skill_commands import resolve_auto_load_skills+ from cli import CLI_CONFIG+ auto = set() if getattr(cli, "ignore_rules", False) else set(resolve_auto_load_skills(CLI_CONFIG))+ return [name for name in requested if name not in auto] or None+class CLIInitMixin:"""HermesCLI constructor phases: display options, model/provider routing, turn limits, toolsets, checkpoints, prompt/reasoning, runtime state, session store and UI state."""@@ -370,20 +405,7 @@ class CLIInitMixin:store = getattr(self, "_session_db", None)if getattr(self, "_gateway_session_open", False) or not isinstance(store, GatewaySessionStore):return- launch = {"model": self.model if getattr(self, "_explicit_model_override", False) else None,- "provider": (self.requested_provider if getattr(self, "_explicit_model_override", False)- and self.requested_provider not in {None, "", "auto"} else None),- "api_key": getattr(self, "_explicit_api_key", None),- "base_url": getattr(self, "_explicit_base_url", None),- "toolsets": self.enabled_toolsets if getattr(self, "_explicit_toolsets", False) else None,- # Main handed these to AIAgent; the gateway's agent gets them as creation policy.- "reasoning": getattr(self, "_explicit_reasoning", None),- "max_turns": getattr(self, "_explicit_max_turns", None),- "checkpoints": getattr(self, "_explicit_checkpoints", False) or None,- "pass_session_id": getattr(self, "pass_session_id", False) or None,- "ignore_rules": getattr(self, "ignore_rules", False) or None,- "run_budget": getattr(self, "_explicit_run_budget", None),- "verbose": getattr(self, "verbose", False) or None}+ launch = _gateway_launch(self)# A resumed row this gateway has not imported yet (a legacy / in-process session) is imported# under the active-session registry lock, which refuses while ANY live lease holds the id —# including this process's own, claimed before the first turn. Hand the slot over around the@@ -404,7 +426,8 @@ class CLIInitMixin:def _new_session_id(self, now, *, branch_of=None, title=None):"""The id main mints for /new (``new_session_id``) and /branch (``mint_session_id``). On a gatewaystore it is a session the gateway created: /new is a fresh ``session.create`` on the profile's- default model (an explicit -m was for the previous session only), /branch the child of+ default model (an explicit -m was for the previous session only) with the run's other launch+ flags, /branch the child of``session.mutate branch``. Before this CLI opened its gateway session (or off the gateway) it ismain's local mint, which ``_ensure_gateway_session`` replaces on first use, as at startup."""from hermes_cli.gateway_session_store import GatewaySessionStore@@ -413,11 +436,17 @@ class CLIInitMixin:from hermes_state_ids import new_session_idreturn new_session_id(now)if branch_of:- return store.branch(branch_of, title)- toolsets = getattr(self, "enabled_toolsets", None) if getattr(self, "_explicit_toolsets", False) else None- sid = store.create({"toolsets": toolsets,- "pass_session_id": getattr(self, "pass_session_id", False) or None,- "ignore_rules": getattr(self, "ignore_rules", False) or None}, record_cwd=False)+ child = store.branch(branch_of, title)+ # Main's with_session_yolo: a live /yolo carries onto the branch. The gateway's child starts+ # without the parent's toggle, so set it there too (/branch moves the CLI's own flag over).+ from tools.approval import is_session_yolo_enabled+ if is_session_yolo_enabled(branch_of):+ from tools.approval_yolo import toggle_session_yolo+ toggle_session_yolo(child, True, persist=lambda on: store.set_session_yolo(child, on))+ return child+ # The run's other launch flags hold for every session it opens, as main's one AIAgent did across /new.+ launch = {key: value for key, value in _gateway_launch(self).items() if key not in _ROUTE_FLAGS}+ sid = store.create(launch, record_cwd=False)self.session_id = sidreturn siddiff --git a/hermes_cli/cli_tui_runtime_mixin.py b/hermes_cli/cli_tui_runtime_mixin.pyindex 2ac9d30fc54..f73a7c95400 100644--- a/hermes_cli/cli_tui_runtime_mixin.py+++ b/hermes_cli/cli_tui_runtime_mixin.py@@ -266,7 +266,13 @@ class CLITuiRuntimeMixin:if _term_lines > 2:print("\n" * (_term_lines - 1), end="", flush=True)- self._ensure_gateway_session() # the banner shows the gateway session's id and inventory+ from hermes_cli.gateway_client import GatewayClientError+ try:+ self._ensure_gateway_session() # the banner shows the gateway session's id and inventory+ except GatewayClientError as exc:+ # A refused open (a changed launch flag on --resume) is a startup error, not a traceback.+ print(f"Error: {exc}", file=sys.stderr)+ raise SystemExit(2) from Noneself.show_banner()self._show_security_advisories()self._show_startup_browser_notice()diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.pyindex 7990eaf32d3..a5756bdc8b0 100644--- a/hermes_cli/gateway_session_store.py+++ b/hermes_cli/gateway_session_store.py@@ -129,11 +129,13 @@ class GatewaySessionStore:gateway does not know is left as is: main's own "Session not found" path reports it."""if getattr(cli, "_resumed", False):try:- return self._adopt(self.attach(cli.session_id))+ snapshot = self.attach(cli.session_id)except GatewayClientError as exc:if str(exc) in {"not_found", "permission_denied"}:return Noneraise+ _check_resume_launch(launch or {}, snapshot)+ return self._adopt(snapshot)return self.create(launch)def create(self, launch=None, title=None, *, record_cwd=True):@@ -392,14 +394,36 @@ def _creation_policy(launch):fields["toolsets"] = ",".join(str(item) for item in fields["toolsets"])policy = _requested_policy(argparse.Namespace(**fields, source=None))policy.pop("source", None)- if launch.get("run_budget") is not None: # main's `--run-budget` (the thin client refuses it)+ policy.update(_classic_only_policy(launch))+ policy.update(env_launch_flags())+ return policy+++def _classic_only_policy(launch):+ """Main's `--run-budget` and `-v`, which the thin client refuses."""+ policy = {}+ if launch.get("run_budget") is not None:policy["run_budget"] = float(launch["run_budget"])- if launch.get("verbose"): # main's `-v` (the thin client refuses it)+ if launch.get("verbose"):policy["verbose"] = True- policy.update(env_launch_flags())return policy+# Flags a resume may only repeat. Not ``toolsets``: the classic CLI always sends its resolved selection, so+# an unset ``-t`` cannot be told from an explicit one here.+_RESUME_CHECKED = tuple(key for key in _LAUNCH_POLICY if key != "toolsets")+++def _check_resume_launch(launch, snapshot):+ """Explicit launch flags on ``--resume`` / ``-c`` against the session's frozen route, as the thin+ client 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+ check_resume_policy(argparse.Namespace(**{key: launch.get(key) for key in _RESUME_CHECKED}), 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)++def session_store():return GatewaySessionStore()diff --git a/tests/hermes_cli/test_gateway_session_store.py b/tests/hermes_cli/test_gateway_session_store.pyindex 3e76c8083d6..807fe17d3b3 100644--- a/tests/hermes_cli/test_gateway_session_store.py+++ b/tests/hermes_cli/test_gateway_session_store.py@@ -488,3 +488,89 @@ def test_resume_hands_the_cli_lease_over_while_the_gateway_imports_the_row(storeclient.rpc = rpcCLIInitMixin._ensure_gateway_session(h)assert events == ["release", ("session.resume", True), ("claim", "local-old")], events+++# Regressions for #134889 (classic CLI launch flags reaching the gateway-owned session).++def test_skills_flag_reaches_session_create_without_auto_load_names(store, monkeypatch):+ """CLI-1: `-s/--skills` rides ``session.create`` (the gateway renders it into the session once); the+ CLI's own system prompt never reaches the gateway. ``skills.auto_load`` names the gateway loads itself."""+ from hermes_cli.cli_init_mixin import CLIInitMixin+ monkeypatch.setattr("agent.skill_commands.resolve_auto_load_skills", lambda config=None: ["pinned"])+ db, client = store+ host = types.SimpleNamespace(model="m1", requested_provider="auto", enabled_toolsets=["file"],+ session_id="20261012_000000_abcdef", _resumed=False, _session_db=db,+ _preload_skills_requested=["pinned", "arxiv"])+ CLIInitMixin._ensure_gateway_session(host)+ assert [p for m, p in client.calls if m == "session.create"][-1]["skills"] == ["arxiv"]+++def _frozen_launch(client, launch_request):+ base = client.rpc++ async def rpc(method, *, _timeout=None, **params):+ result = await base(method, _timeout=_timeout, **params)+ if method == "session.resume":+ result["info"]["launch_request"] = dict(launch_request)+ return result+ client.rpc = rpc+++def test_explicit_flags_on_resume_are_checked_against_the_frozen_route(store):+ """CLI-2: `--resume` / `-c` with `-m`, `--max-turns`, `--checkpoints`, ... is refused when it would+ change the frozen route (as the thin client refuses it), never silently ignored; repeating it is fine."""+ db, client = store+ _frozen_launch(client, {"model": "m-frozen", "model_requested": "m-alias", "max_turns": 5, "run_budget": 60.0})+ for launch in ({"max_turns": 1}, {"model": "m-other"}, {"checkpoints": True}, {"run_budget": 30},+ {"verbose": True}, {"skills": ["arxiv"]}):+ with pytest.raises(GatewayClientError, match="Resume retains gateway session policy"):+ GatewaySessionStore(db.connection).open_session(cli("local-old", resumed=True), launch)+ for launch in ({}, {"max_turns": 5, "model": "m-alias", "run_budget": 60, "toolsets": ["web"]}):+ assert GatewaySessionStore(db.connection).open_session(cli("local-old", resumed=True), launch) == "local-old"+++def test_new_session_keeps_the_runs_launch_policy(store, monkeypatch):+ """CLI-3: `/new` keeps `--max-turns`, `--checkpoints`, `--run-budget`, `-v` and `-s` (main kept one+ AIAgent across /new); only the explicit model route is left to the profile default."""+ from hermes_cli.cli_init_mixin import CLIInitMixin+ monkeypatch.setattr("agent.skill_commands.resolve_auto_load_skills", lambda config=None: [])+ db, client = store+ db.open_session(cli("local-old", resumed=True))+ host = types.SimpleNamespace(session_id="local-old", _session_db=db, _gateway_session_open=True,+ model="m-explicit", _explicit_model_override=True, requested_provider="openrouter",+ enabled_toolsets=["file"], _explicit_max_turns=3, _explicit_checkpoints=True,+ _explicit_run_budget=60, verbose=True, _preload_skills_requested=["arxiv"])+ CLIInitMixin._new_session_id(host, None)+ params = [p for m, p in client.calls if m == "session.create"][-1]+ assert (params["max_turns"], params["checkpoints"], params["run_budget"], params["verbose"],+ params["skills"], params["toolsets"]) == (3, True, 60.0, True, ["arxiv"], ["file"]), params+ assert "model" not in params and "provider" not in params+++def test_branch_carries_a_live_yolo_onto_the_gateway_child(store):+ """CLI-20: the gateway's branch child starts without the parent's `/yolo` toggle while the CLI moves+ its own flag over (status bar YOLO); the CLI sets the child's bypass on the gateway too."""+ from hermes_cli.cli_init_mixin import CLIInitMixin+ from tools import approval+ db, client = store+ base = client.rpc++ async def rpc(method, *, _timeout=None, **params):+ if method == "session.mutate" and params["operation"] == "branch":+ client.calls.append((method, params))+ child = f"local-child-{len(client.calls)}"+ client.known.add(child)+ return {"branched_session_id": child, "copied_messages": 0}+ return await base(method, _timeout=_timeout, **params)+ client.rpc = rpc+ db.open_session(cli("local-old", resumed=True))+ host = types.SimpleNamespace(session_id="local-old", _session_db=db, _gateway_session_open=True)+ plain = CLIInitMixin._new_session_id(host, None, branch_of="local-old")+ assert not [p for m, p in client.calls if m == "config.set"]+ approval.enable_session_yolo("local-old")+ try:+ child = CLIInitMixin._new_session_id(host, None, branch_of="local-old")+ finally:+ for key in ("local-old", plain, "local-child"):+ approval.disable_session_yolo(key)+ assert [p for m, p in client.calls if m == "config.set"] == [{"session_id": child, "key": "yolo", "value": "1"}]