Skip to content

The agent that grows with you

fix(cli): route /model, /refine, /review and /moa through the gateway session

unsupportedpastelse5e00c3f356e
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.py
index fb8877b37d1..de9a01c669e 100644
--- a/hermes_cli/cli_commands_mixin.py
+++ b/hermes_cli/cli_commands_mixin.py
@@ -752,9 +752,9 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):
if not 1 <= idx <= len(snaps):
return print(f" {_t('snapshot.invalid_number', max=len(snaps))}")
snap_id = snaps[idx - 1]["id"]
- # Close our SessionDB first so the restore doesn't contend with this process's live connection.
+ # Close our own SessionDB first (restore contention); an open gateway session's store must stay.
local_session_db = getattr(self, "_session_db", None)
- if local_session_db is not None:
+ if local_session_db is not None and not getattr(self, "_gateway_session_open", False):
with suppress(Exception):
local_session_db.close()
self._session_db = None
diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.py
index 90d398846f2..011afe4ae5a 100644
--- a/hermes_cli/gateway_agent.py
+++ b/hermes_cli/gateway_agent.py
@@ -161,6 +161,9 @@ class GatewayAgent:
self.reasoning_config = reasoning_config
else:
self._reasoning_config = reasoning_config
+ # Main's /moa rebuilds its agent on the MoA virtual provider for one turn (the session's info
+ # below then overwrites ``model``): that preset rides the turn's submit as its model_override.
+ self._moa_preset = model if provider == "moa" else None
self._apply_info(self._state().info)
self.reasoning_callback = reasoning_callback
self.service_tier = service_tier
@@ -213,6 +216,33 @@ class GatewayAgent:
except (GatewayClientError, KeyError, TypeError) as exc:
logger.debug("session.mutate reasoning failed: %s", exc)
+ def switch_model(self, new_model, new_provider="", api_key="", base_url="", api_mode="", capabilities=None):
+ """Main's in-place swap (``/model``, ``/model --once`` and its restore, /new's reset to the config
+ default, /resume) as ``session.mutate model``: the gateway resolves the target with the same
+ switch pipeline and commits it to the session's policy, so the next turn runs on it; keys and
+ endpoints stay gateway-side. Main's caller already confirmed a guarded target
+ (``_confirm_expensive_model_switch``), so the owner's ``confirmation_required`` is answered once
+ with its token. A refusal raises: main's callers roll their own fields back."""
+ if new_model == self.model and (not new_provider or new_provider == self.provider):
+ return
+ from hermes_cli.gateway_mutations import model_refusal_text
+ payload = {"model": new_model, **({"provider": new_provider} if new_provider else {})}
+ snapshot = self.connection.call("session.resume", session_id=self.session_id)
+ fence = dict(session_id=self.session_id, operation="model", expected_revision=snapshot["revision"],
+ expected_generation=snapshot["execution_generation"])
+ result = self.connection.call("session.mutate", request_id=uuid.uuid4().hex, payload=payload, **fence) or {}
+ if result.get("status") == "confirmation_required":
+ # The refusal wrote nothing: the same fence is re-sent with the owner's token.
+ result = self.connection.call("session.mutate", request_id=uuid.uuid4().hex,
+ payload={**payload, "confirm": result["confirm"]}, **fence) or {}
+ if result.get("status") == "confirmation_required":
+ raise GatewayClientError(model_refusal_text(result, confirmed=True))
+ state = self._state()
+ state.adopt_snapshot(self.connection.call("session.resume", session_id=self.session_id))
+ # A rebuilt stand-in reads the session's info: it must show the committed model.
+ state.info.update(model=result.get("model") or new_model, **({"provider": new_provider} if new_provider else {}))
+ self._apply_info(state.info)
+
# -- session identity ----------------------------------------------------------------------
@property
def session_id(self):
@@ -488,6 +518,9 @@ class GatewayAgent:
if self.clarify_callback is not None:
# Main's batch panel answers the clarify tool's whole question set (one ``clarify`` request).
params["clarify_batch"] = True
+ if self._moa_preset and (self._state().info or {}).get("provider") != "moa":
+ # /moa one-shot: this admission alone runs the preset; the session's route is untouched.
+ params["model_override"] = {"model": self._moa_preset, "provider": "moa"}
return params
def _stage_content_parts(self, parts):
diff --git a/hermes_cli/gateway_setting_commands.py b/hermes_cli/gateway_setting_commands.py
index 5dd36fb1308..6e3d32fcf33 100644
--- a/hermes_cli/gateway_setting_commands.py
+++ b/hermes_cli/gateway_setting_commands.py
@@ -5,6 +5,8 @@ agent or config. Rewired, the session's agent lives in the gateway, so the gatew
decides and applies the change (gateway/session_setting_commands.py; RULING §1: one behaviour per
command, every surface) and the CLI prints its reply. Client-side state the CLI itself enforces
(``/busy``: what Enter does while a turn runs) is mirrored locally after the owner accepts it.
+``/refine`` and ``/review`` take the same route: their background reviewer must run beside the
+session's agent in the gateway (as on messaging), where its result is delivered back to the session.
"""
from __future__ import annotations
@@ -17,7 +19,8 @@ def _mirror_busy(cli, arg):
cli.busy_input_mode = arg.lower()
-GATEWAY_SETTINGS = {"personality": None, "busy": _mirror_busy, "approvals": None, "footer": None, "fast": None}
+GATEWAY_SETTINGS = {"personality": None, "busy": _mirror_busy, "approvals": None, "footer": None, "fast": None,
+ "refine": None, "review": None}
def run(cli, canonical, cmd):
diff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.py
index aad541bdd5f..56cadd80a42 100644
--- a/tests/hermes_cli/test_gateway_agent.py
+++ b/tests/hermes_cli/test_gateway_agent.py
@@ -29,9 +29,12 @@ class FakeClient:
self.result = result if result is not None else {}
self.usage = usage or {}
self.on_interrupt = None
+ self.mutate_replies = []
async def rpc(self, method, *, _timeout=None, **params):
self.calls.append((method, params))
+ if method == "session.mutate" and self.mutate_replies:
+ return self.mutate_replies.pop(0)
if method == "prompt.submit":
asyncio.get_running_loop().call_soon(lambda: asyncio.ensure_future(self._play()))
return {"admission_id": "adm-1", "status": "queued", "execution_generation": 7}
@@ -707,3 +710,57 @@ def test_a_transport_loss_at_submit_is_still_gateway_connection():
result = submit_against(GatewayClientError(DISCONNECTED))
assert result["failed"] is True and result["error"] == DISCONNECTED
assert result["failure_reason"] == "gateway_connection" and result["failure_retryable"] is False
+
+
+def test_model_switch_is_the_session_model_mutation_and_a_rebuilt_agent_shows_it(make_agent):
+ """/model, /model --once and /new's reset to the config default call main's
+ ``agent.switch_model`` (#134889 M1). The gateway commits the target as a generation-fenced
+ ``session.mutate model`` (no key or endpoint leaves the CLI), and the agent main rebuilds for the
+ next turn reads the committed model from the session, not the old one."""
+ agent, client = make_agent([], model="old-model", provider="openrouter")
+ agent.switch_model(new_model="new-model", new_provider="anthropic", api_key="sk-local",
+ base_url="https://example.invalid", api_mode="anthropic_messages", capabilities=None)
+ mutations = [p for m, p in client.calls if m == "session.mutate"]
+ assert len(mutations) == 1
+ assert mutations[0]["operation"] == "model"
+ assert mutations[0]["payload"] == {"model": "new-model", "provider": "anthropic"}
+ assert (mutations[0]["expected_revision"], mutations[0]["expected_generation"]) == (1, 7)
+ assert (agent.model, agent.provider) == ("new-model", "anthropic")
+ rebuilt = GatewayAgent(connection=agent.connection, session_id=SID, model="old-model", provider="openrouter")
+ assert (rebuilt.model, rebuilt.provider) == ("new-model", "anthropic")
+
+
+def test_a_guarded_model_target_is_confirmed_once_with_the_owners_token(make_agent):
+ """Main asked before calling switch_model (``_confirm_expensive_model_switch``); the owner's own
+ guard refusal is answered with its token once. A second refusal (the session moved) raises, so
+ main rolls its fields back and the agent keeps the old model."""
+ refusal = {"status": "confirmation_required", "confirm": "tok-1", "confirm_message": "Expensive model"}
+ agent, client = make_agent([], model="old-model")
+ client.mutate_replies = [refusal, {"status": "committed", "model": "pricey-model"}]
+ agent.switch_model(new_model="pricey-model", new_provider="openrouter")
+ sent = [p["payload"] for m, p in client.calls if m == "session.mutate"]
+ assert sent == [{"model": "pricey-model", "provider": "openrouter"},
+ {"model": "pricey-model", "provider": "openrouter", "confirm": "tok-1"}]
+ assert agent.model == "pricey-model"
+ other, other_client = make_agent([], model="old-model")
+ other_client.mutate_replies = [refusal, dict(refusal, confirm="tok-2")]
+ with pytest.raises(GatewayClientError, match="Model not switched"):
+ other.switch_model(new_model="pricey-model", new_provider="openrouter")
+ assert other.model == "old-model"
+
+
+def test_moa_one_shot_preset_rides_this_turns_submit_as_its_model_override(make_agent):
+ """``/moa <prompt>`` (#134889 CLI-18): main rebuilds its agent on the MoA virtual provider for
+ one turn, but the session's info names the session's own model. The preset must reach the turn
+ as its admission's ``model_override``; a regular rebuild sends none."""
+ done = [frame("message.complete", {"text": "ok", "outcome": "completed"})]
+ agent, client = make_agent(done)
+ agent.connection.state(SID).info.update(model="claude-sonnet", provider="anthropic")
+ moa = GatewayAgent(connection=agent.connection, session_id=SID, model="default", provider="moa")
+ moa.run_conversation("compare these designs")
+ submit = dict(client.calls)["prompt.submit"]
+ assert submit["model_override"] == {"model": "default", "provider": "moa"}
+ client.calls.clear()
+ regular = GatewayAgent(connection=agent.connection, session_id=SID, model="claude-sonnet", provider="anthropic")
+ regular.run_conversation("next")
+ assert "model_override" not in dict(client.calls)["prompt.submit"]
diff --git a/tests/hermes_cli/test_gateway_setting_commands.py b/tests/hermes_cli/test_gateway_setting_commands.py
index 70d88435a4d..f4732a979f8 100644
--- a/tests/hermes_cli/test_gateway_setting_commands.py
+++ b/tests/hermes_cli/test_gateway_setting_commands.py
@@ -24,3 +24,21 @@ def test_busy_runs_on_the_gateway_and_mirrors_the_mode(monkeypatch, capsys):
assert conn.calls == [("slash.exec", {"session_id": "local-s", "command": "busy queue"})]
assert cli.busy_input_mode == "queue"
assert gateway_setting_commands.run(cli, "history", "/history") is False # a local read stays local
+
+
+def test_refine_and_review_run_on_the_gateway_sessions_agent(monkeypatch, capsys):
+ """/refine and /review (#134889 M3, M4/CLI-6): the CLI's agent is a gateway stand-in, so the
+ gateway's handler runs the reviewer beside the session's agent (as messaging does) and the CLI
+ prints its reply; no reviewer runs in the CLI process."""
+ conn = _Conn()
+ monkeypatch.setattr("hermes_cli.gateway_side.connection_for", lambda cli: conn)
+
+ def local_review(*_a, **_k):
+ raise AssertionError("the reviewer must not run in the CLI process")
+ monkeypatch.setattr("agent.review_engine.start_review", local_review)
+ cli = SimpleNamespace(session_id="local-s")
+ assert gateway_setting_commands.run(cli, "refine", "/refine naming") is True
+ assert gateway_setting_commands.run(cli, "review", "/review the diff") is True
+ assert conn.calls == [("slash.exec", {"session_id": "local-s", "command": "refine naming"}),
+ ("slash.exec", {"session_id": "local-s", "command": "review the diff"})]
+ assert "Busy input mode: queue" in capsys.readouterr().out # the owner's reply is printed
diff --git a/tests/hermes_cli/test_snapshot_restore_gateway_session.py b/tests/hermes_cli/test_snapshot_restore_gateway_session.py
new file mode 100644
index 00000000000..7cf9ac05639
--- /dev/null
+++ b/tests/hermes_cli/test_snapshot_restore_gateway_session.py
@@ -0,0 +1,28 @@
+"""/snapshot restore in a gateway-backed classic CLI keeps the CLI on its gateway session.
+
+Regression for #134889 N7: after a /snapshot restore, /context raised
+``'GatewayAgent' object has no attribute 'load_soul_identity'``.
+"""
+from types import SimpleNamespace
+
+from hermes_cli.cli_commands_mixin import CLICommandsMixin
+from hermes_cli.gateway_session_store import GatewaySessionStore
+from hermes_cli.gateway_side import connection_for
+
+
+class _Conn:
+ final = False
+ closed = False
+
+
+def test_a_snapshot_restore_leaves_the_cli_on_its_gateway_session(monkeypatch):
+ """Main closed its own SessionDB before restoring. Rewired, ``_session_db`` is the gateway session
+ store: dropping it left every later command off the gateway, and /context then ran main's local
+ breakdown on the gateway stand-in agent."""
+ monkeypatch.setattr("hermes_cli.backup.restore_quick_snapshot", lambda snap_id: False)
+ monkeypatch.setattr("hermes_cli.backup.list_quick_snapshots", lambda limit=None: [{"id": "snap-1"}])
+ conn = _Conn()
+ cli = SimpleNamespace(_session_db=GatewaySessionStore(conn), _gateway_session_open=True)
+ assert connection_for(cli) is conn
+ CLICommandsMixin._snapshot_restore(cli, ["/snapshot", "restore", "snap-1"])
+ assert connection_for(cli) is conn