Skip to content

The agent that grows with you

fix(cli): keep a one-turn model switch on the rebuilt agent

David Dudok de Witcd2d28f2a9fb
diff --git a/gateway/session_cli_turn.py b/gateway/session_cli_turn.py
index 8e210e60e67..490c1f9f7bf 100644
--- a/gateway/session_cli_turn.py
+++ b/gateway/session_cli_turn.py
@@ -100,13 +100,24 @@ def one_turn_runtime(override, model, runtime_kwargs, config):
if not result.success:
raise RuntimeError(result.error_message or f"model {override['model']!r} could not be resolved")
runtime = dict(runtime_kwargs)
- if result.target_provider != runtime_kwargs.get('provider'):
- # The previous provider's pool and ACP command belong to that provider only.
- runtime.update(credential_pool=None, command=None, args=[])
- runtime.update(provider=result.target_provider, requested_provider=result.target_provider,
- api_key=result.api_key, base_url=result.base_url, api_mode=result.api_mode or None,
- request_overrides=dict(result.request_overrides or {}),
- capabilities=dict(result.runtime_capabilities or {}))
+ current_provider = runtime_kwargs.get('provider') or ''
+ same_provider = (result.target_provider or '').strip().lower() == current_provider.strip().lower()
+ if same_provider:
+ # The explicit provider on a one-turn override re-resolves the provider's default endpoint
+ # and key. The session already has both, so keep them. The wire follows the target, as a
+ # session /model writes it: Copilot, Nous Portal and OpenCode pick it per model.
+ from hermes_cli.models import normalize_opencode_base_url, opencode_provider_family
+ api_mode = result.api_mode or runtime.get('api_mode')
+ runtime['api_mode'] = api_mode or None
+ if runtime.get('base_url') and opencode_provider_family(result.target_provider):
+ runtime['base_url'] = normalize_opencode_base_url(result.target_provider, api_mode, runtime['base_url'])
+ else:
+ # A different provider does not keep this session's pool, endpoint, or key.
+ runtime.update(credential_pool=None, command=None, args=[],
+ api_key=result.api_key, base_url=result.base_url, api_mode=result.api_mode or None,
+ request_overrides=dict(result.request_overrides or {}),
+ capabilities=dict(result.runtime_capabilities or {}))
+ runtime.update(provider=result.target_provider, requested_provider=result.target_provider)
return result.new_model, runtime
diff --git a/gateway/session_local_inventory.py b/gateway/session_local_inventory.py
index 7b32f0a8814..9e983a574e7 100644
--- a/gateway/session_local_inventory.py
+++ b/gateway/session_local_inventory.py
@@ -223,13 +223,42 @@ def agent_inventory(agent) -> dict:
def publish_settled_info(turn, agent) -> None:
"""Main's end-of-turn ``session.info`` (``session_workdir._emit_settled_session_info``) for a local
viewer: the first turn builds the agent, so this is when the banner's ``▸ System Prompt`` row, the
- agent's tool list and provider first become known. Never breaks the turn."""
+ agent's tool list and provider first become known. Never breaks the turn.
+
+ A ``model_override`` admission (``/model --once``, ``/moa``) built its agent on the one-turn
+ route. That agent must not become the route Desktop, the TUI, and resume read. Drop it from
+ the cache and publish the policy model and provider."""
if agent is None:
return
with contextlib.suppress(Exception):
+ from gateway.session_cli_turn import cli_turn
from gateway.session_contract import SessionRef
from gateway.session_local import local_session_info
+ from gateway.session_policy import policy_for_source
authority, session_id, _generation = turn._approval_owner
- info = {**agent_inventory(agent),
- **local_session_info(authority, SessionRef(authority.profile_id, session_id))}
+ message_id = getattr(getattr(turn, "_ctx", None), "inbound_message_id", None)
+ one_turn = bool(cli_turn(message_id).get("model_override"))
+ live = None
+ if one_turn:
+ sessions = getattr(authority, "sessions", None)
+ live = sessions.get(session_id) if hasattr(sessions, "get") else None
+ evict = getattr(getattr(turn, "_runner", None), "_evict_cached_agent", None)
+ if live is not None and callable(evict):
+ try:
+ evict(live.route)
+ except Exception:
+ logger.debug("one-turn agent cache drop failed", exc_info=True)
+ ref = SessionRef(authority.profile_id, session_id)
+ info = {**agent_inventory(agent), **local_session_info(authority, ref)}
+ if one_turn and live is not None:
+ try:
+ runner = getattr(authority, "runner", None) or turn._runner
+ policy = policy_for_source(runner, live.source)
+ except Exception:
+ logger.debug("one-turn policy route unavailable", exc_info=True)
+ policy = None
+ if policy is not None:
+ info["model"] = policy.current_model(authority)
+ if policy.provider:
+ info["provider"] = policy.provider
turn._publish_execution("session.info", info)
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.py
index 5426e81443e..ec0ba255828 100644
--- a/hermes_cli/cli_agent_setup_mixin.py
+++ b/hermes_cli/cli_agent_setup_mixin.py
@@ -645,6 +645,9 @@ class CLIAgentSetupMixin:
try:
runtime = runtime_override or _current_runtime(self)
effective_model = model_override or self.model
+ # ``/model --once`` has already staged the pick on the CLI and saved the restore
+ # snapshot. chat retires the previous agent, so the pick has to be on this one.
+ one_turn = getattr(self, "_pending_one_turn_model_restore", None) is not None
# -q never builds the prompt_toolkit app, so the clarify modal can't be
# answered — answer headless instead of polling until clarify_timeout.
single_query_mode = getattr(self, "_single_query_mode", False)
@@ -681,6 +684,7 @@ class CLIAgentSetupMixin:
model_confirm_callback=None if single_query_mode else self._confirm_owner_model_switch,
# Another viewer answering the gateway's clarify/sudo/secret request closes this modal.
modal_withdraw_callback=None if single_query_mode else self._withdraw_gateway_modal,
+ one_turn=one_turn,
reasoning_callback=self._current_reasoning_callback(),
fallback_model=self._fallback_model, thinking_callback=self._on_thinking,
checkpoints_enabled=self.checkpoints_enabled,
diff --git a/hermes_cli/cli_model_switch_mixin.py b/hermes_cli/cli_model_switch_mixin.py
index fc5915703b3..7275c23d2e1 100644
--- a/hermes_cli/cli_model_switch_mixin.py
+++ b/hermes_cli/cli_model_switch_mixin.py
@@ -11,6 +11,8 @@ module-level functions taking ``cli`` and siblings are called as ``HermesCLI.<na
from __future__ import annotations
import copy
+import inspect
+import logging
import sys
import threading
@@ -19,6 +21,8 @@ from agent.i18n import t
from utils import base_url_host_matches
from hermes_cli.cli_agent_setup_mixin import _retire_agent
+logger = logging.getLogger(__name__)
+
# CLI-level fields describing the active model route; snapshotted before a switch / one-turn
# override and restored wholesale on rollback. ``reasoning_config`` rides along because it is
# resolved per model: a failed swap or `/model X --reasoning high --once` must not leave the
@@ -206,6 +210,35 @@ def _run_confirm_and_apply(cli, target, *args) -> None:
target(*args)
+def _one_turn_selection_context(cli):
+ """Context the owner's large-context guard would see, for a ``/model --once`` that does not mutate.
+
+ A live compressor measurement wins. Otherwise refresh ``session.stats``, then the session row's
+ persisted usage anchor (a resume, before this process has run a turn).
+ """
+ from hermes_cli.model_selection_guards import SelectionContext, selection_context_for_agent
+ agent = getattr(cli, "agent", None)
+ if agent is not None and hasattr(agent, "_refresh_stats"):
+ agent._refresh_stats()
+ live = selection_context_for_agent(agent)
+ if live is not None:
+ return live
+ from agent.usage_anchor import persisted_anchor_tokens
+ db = getattr(cli, "_session_db", None)
+ sid = getattr(cli, "session_id", None)
+ if db is None or not sid or not callable(getattr(db, "get_messages_as_conversation", None)):
+ return None
+ try:
+ messages = db.get_messages_as_conversation(sid)
+ except Exception:
+ logger.debug("one-turn selection context unavailable", exc_info=True)
+ return None
+ tokens = persisted_anchor_tokens(db, sid, messages)
+ if not tokens:
+ return None
+ return SelectionContext(context_tokens=tokens, current_model=getattr(cli, "model", None) or None)
+
+
def _ask_switch_anyway(cli, title: str, detail: str) -> bool:
"""The model-guard prompt (switch anyway once, or cancel): True only on an explicit yes."""
choices = [
@@ -265,6 +298,22 @@ def _apply_reasoning_after_switch(cli, effort: str, *, persist_global: bool) ->
_cprint(f" {t('cli.model.reasoning_effort_saved' if saved else 'cli.model.reasoning_effort', effort=effort)}")
+_ONE_TURN_SWITCH_KWARGS = ("once", "restore")
+
+
+def _call_agent_switch(agent, **fields):
+ """``agent.switch_model`` with ``once`` / ``restore`` only when its signature names them.
+
+ ``AIAgent.switch_model`` is a ``**kwargs`` forwarder to a function that rejects them; an
+ in-process agent swaps in place, so it gets the plain switch."""
+ try:
+ named = inspect.signature(agent.switch_model).parameters
+ except (TypeError, ValueError):
+ named = {}
+ return agent.switch_model(**{key: value for key, value in fields.items()
+ if key not in _ONE_TURN_SWITCH_KWARGS or key in named})
+
+
def _commit_model_switch(
cli, result, *, persist_global: bool, one_turn: bool = False, picker: bool = False,
reasoning_effort: str = "") -> None:
@@ -274,8 +323,16 @@ def _commit_model_switch(
``--reasoning`` or the picker's effort step) is applied after the swap."""
from cli import HermesCLI, _cprint
old_model, old_provider = cli.model, getattr(cli, "provider", None)
- snapshot = cli._snapshot_model_runtime() if one_turn else None
- if not cli._stage_and_swap_model(result, old_model):
+ # A second ``--once`` before the turn restores to the route before the first one.
+ snapshot = (getattr(cli, "_pending_one_turn_model_restore", None)
+ or cli._snapshot_model_runtime()) if one_turn else None
+ # ``--once`` must not session.mutate.
+ cli._model_switch_one_turn = bool(one_turn)
+ try:
+ staged = cli._stage_and_swap_model(result, old_model)
+ finally:
+ cli._model_switch_one_turn = False
+ if not staged:
return
# A TUI slash worker replays /model on its shadow CLI; the tui_gateway mirror counts the real switch.
if not getattr(cli, "is_slash_worker", False):
@@ -572,11 +629,13 @@ class CLIModelSwitchMixin:
try:
from hermes_cli.model_selection_guards import (
combined_selection_warning, selection_context_for_agent)
+ primed = getattr(self, "_one_turn_selection_context", None)
warning = combined_selection_warning(
result.new_model, provider=result.target_provider,
base_url=result.base_url or self.base_url or "",
api_key=result.api_key or self.api_key or "", model_info=result.model_info,
- selection_context=selection_context_for_agent(getattr(self, "agent", None)))
+ selection_context=primed if primed is not None else selection_context_for_agent(
+ getattr(self, "agent", None)))
except Exception:
warning = None
if warning is None:
@@ -653,17 +712,17 @@ class CLIModelSwitchMixin:
logger.debug("CLI one-turn model restore via primary runtime failed", exc_info=True)
if hasattr(agent, "switch_model"):
try:
- restored = agent.switch_model(
- new_model=snapshot.get("model", ""), new_provider=snapshot.get("provider", ""),
+ restored = _call_agent_switch(
+ agent, new_model=snapshot.get("model", ""), new_provider=snapshot.get("provider", ""),
api_key=snapshot.get("api_key", ""), base_url=snapshot.get("base_url", ""),
api_mode=snapshot.get("api_mode", ""),
- capabilities=snapshot.get("capabilities"))
+ capabilities=snapshot.get("capabilities"), once=True, restore=True)
except Exception as exc: # health: allow BLE001 -- runs in the turn's finally; reported below
logger.warning("CLI one-turn model restore failed: %s", exc)
restored = exc
if restored is False or isinstance(restored, Exception):
- # The session still runs the one-turn model (the owner's guard prompt was declined, or
- # nobody can answer it): the CLI follows the session instead of claiming the restore.
+ # The previous route did not come back. Stay on the one-turn model instead of
+ # claiming the restore.
for key, value in one_turn.items():
setattr(self, key, value)
notice = t("cli.model.switch_cancelled") if restored is False else t(
@@ -737,10 +796,13 @@ class CLIModelSwitchMixin:
if self.agent is not None:
try:
- if self.agent.switch_model(
- new_model=result.new_model, new_provider=result.target_provider,
- api_key=result.api_key, base_url=result.base_url, api_mode=result.api_mode,
- capabilities=getattr(result, "runtime_capabilities", None)) is False:
+ fields = dict(
+ new_model=result.new_model, new_provider=result.target_provider,
+ api_key=result.api_key, base_url=result.base_url, api_mode=result.api_mode,
+ capabilities=getattr(result, "runtime_capabilities", None))
+ if getattr(self, "_model_switch_one_turn", False):
+ fields["once"] = True
+ if _call_agent_switch(self.agent, **fields) is False:
# Declined at the gateway owner's guard prompt: nothing was committed.
for _k, _v in _cli_snapshot.items():
setattr(self, _k, _v)
@@ -931,11 +993,17 @@ class CLIModelSwitchMixin:
"""Confirm an expensive model switch and apply it (typed /model path). Runs on a worker
thread when the TUI is active (see _run_confirm_and_apply) so the modal can render."""
from cli import _cprint
- if not self._confirm_expensive_model_switch(result):
- _cprint(f" {t('cli.model.switch_cancelled')}")
- return
- _commit_model_switch(self, result, persist_global=persist_global, one_turn=one_turn,
- reasoning_effort=reasoning_effort)
+ # ``--once`` does not reach the owner's mutate guard. A resumed session's compressor is
+ # still cold; the persisted anchor is what that guard would have measured.
+ self._one_turn_selection_context = _one_turn_selection_context(self) if one_turn else None
+ try:
+ if not self._confirm_expensive_model_switch(result):
+ _cprint(f" {t('cli.model.switch_cancelled')}")
+ return
+ _commit_model_switch(self, result, persist_global=persist_global, one_turn=one_turn,
+ reasoning_effort=reasoning_effort)
+ finally:
+ self._one_turn_selection_context = None
def _handle_codex_runtime(self, cmd_original: str) -> None:
"""Handle /codex-runtime — toggle the codex app-server runtime opt-in.
diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.py
index 9afebd01044..4ac97608c8c 100644
--- a/hermes_cli/gateway_agent.py
+++ b/hermes_cli/gateway_agent.py
@@ -77,7 +77,8 @@ class GatewayAgent:
tool_start_callback=None, tool_complete_callback=None, stream_delta_callback=None,
tool_gen_callback=None, notice_callback=None, notice_clear_callback=None,
reaction_callback=None, interim_assistant_callback=None, connection=None,
- push_reasoning=False, model_confirm_callback=None, modal_withdraw_callback=None, **_ignored):
+ push_reasoning=False, model_confirm_callback=None, modal_withdraw_callback=None,
+ one_turn=False, **_ignored):
conn = connection or getattr(session_db, "connection", None)
if conn is None:
raise GatewayClientError("Gateway session unavailable; no local fallback")
@@ -170,7 +171,14 @@ class GatewayAgent:
# 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
+ # ``/model --once``: chat retires the agent that switch_model touched and builds this one.
+ # Capture the pick before ``_apply_info`` copies the session model over it.
+ self._turn_route = self._route_off_session(model, provider) if one_turn else None
self._apply_info(self._state().info)
+ if self._turn_route:
+ self.model = self._turn_route["model"]
+ if self._turn_route.get("provider"):
+ self.provider = self._turn_route["provider"]
self.reasoning_callback = reasoning_callback
self.service_tier = service_tier
state = self._state()
@@ -223,17 +231,41 @@ 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, /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. A guarded target (cost, data policy, large context) the owner refuses
- with ``confirmation_required`` is re-sent with its token only on the user's yes to
- ``model_confirm_callback`` (the owner's warning, as Ink/Desktop/ACP show it): a no returns False with
- nothing written; with no prompt the refusal raises. Any refusal raises: main's callers roll their own
- fields back."""
- if new_model == self.model and (not new_provider or new_provider == self.provider):
+ def _route_off_session(self, model, provider=""):
+ """``{model, provider}`` when the session runs another route, else None."""
+ state = self._state()
+ if not model or not (state.info or {}).get("model") or state.runs_route(model, provider):
+ return None
+ return {"model": model, **({"provider": provider} if provider else {})}
+
+ def switch_model(self, new_model, new_provider="", api_key="", base_url="", api_mode="", capabilities=None, *,
+ once=False, restore=False):
+ """Session-scoped ``/model`` and /resume commit ``session.mutate model``.
+
+ ``once=True`` does not write the session. The next ``chat`` builds a new agent; that
+ constructor carries the pick, because this agent is retired when the route signature
+ changes. ``restore=True`` only puts the previous model back on this object and clears the
+ one-turn route. The admission already has its ``model_override``.
+
+ "Already on this route" is the session row, not ``self.model`` (a one-turn pick sets
+ ``self.model`` without committing). A session switch of that same target still mutates
+ on the generation fence.
+
+ A guarded target the owner refuses with ``confirmation_required`` is re-sent with its token
+ only on the user's yes to ``model_confirm_callback``: a no returns False with nothing
+ written; with no prompt the refusal raises. Any refusal raises: main's callers roll their
+ own fields back."""
+ if once or restore:
+ self._turn_route = None if restore else self._route_off_session(new_model, new_provider)
+ if new_model:
+ self.model = new_model
+ if new_provider:
+ self.provider = new_provider
return True
+ if new_model == self.model and (not new_provider or new_provider == self.provider):
+ if self._route_off_session(new_model, new_provider) is None:
+ self._turn_route = None
+ return True
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)
@@ -260,6 +292,8 @@ class GatewayAgent:
provider = result.get("provider") or new_provider
state.info = {**(state.info or {}), "model": result.get("model") or new_model,
**({"provider": provider} if provider else {})}
+ # The session now runs this route, so a leftover one-turn override must not ride the next submit.
+ self._turn_route = None
self._apply_info(state.info)
return True
@@ -541,7 +575,11 @@ class GatewayAgent:
# Main's batch panel answers the clarify tool's whole question set (one ``clarify`` request).
params["clarify_batch"] = True
info = self._state().info or {}
- if self._moa_preset and (info.get("provider"), info.get("model")) != ("moa", self._moa_preset):
+ pending = self._turn_route
+ if pending and self._route_off_session(**pending):
+ # /model --once: this admission alone runs the pick. The session row stays put.
+ params["model_override"] = dict(pending)
+ elif self._moa_preset and (info.get("provider"), info.get("model")) != ("moa", self._moa_preset):
# /moa one-shot: this admission alone runs the preset (unless it is the session's own
# route); the session's route is untouched.
params["model_override"] = {"model": self._moa_preset, "provider": "moa"}
@@ -583,9 +621,9 @@ class GatewayAgent:
receipt = adopted
else:
self._drain_stale()
+ params = self._submit_params(user_message, persist_user_message, turn_author)
try:
- receipt = self.connection.call("prompt.submit", **self._submit_params(
- user_message, persist_user_message, turn_author))
+ receipt = self.connection.call("prompt.submit", **params)
except GatewayRPCError as exc:
# The owner answered and refused: not a lost connection. Only its own site code
# (session_busy: send again) is a verdict; any other refusal stays unclassified.
@@ -594,6 +632,11 @@ class GatewayAgent:
failure_reason="session_busy" if busy else None, retryable=busy)
except GatewayClientError as exc:
return self._failed(history, user_message, str(exc), failure_reason="gateway_connection")
+ finally:
+ # One admission. A later submit on this agent, including a failed attempt's retry
+ # after the CLI restores, must not send the pick again.
+ if params.get("model_override") and self._turn_route:
+ self._turn_route = None
self._epoch = getattr(self.connection, "epoch", None)
self._admission = (receipt or {}).get("admission_id")
if receipt and receipt.get("execution_generation") is not None:
diff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.py
index eb5abb5a8c8..5a1f066d70a 100644
--- a/hermes_cli/gateway_connection.py
+++ b/hermes_cli/gateway_connection.py
@@ -71,6 +71,12 @@ class SessionState:
if self.info.get("title"):
self.title = self.info["title"]
+ def runs_route(self, model, provider=""):
+ """Whether the session runs ``model`` (and ``provider``, when both sides name one)."""
+ current, current_provider = self.info.get("model"), self.info.get("provider")
+ return bool(current) and model == current and not (
+ provider and current_provider and provider != current_provider)
+
def apply_event(self, kind, payload):
if kind in ("session.info", "session.updated") and isinstance(payload, dict):
self.info.update({k: v for k, v in payload.items() if k != "session_id"})
diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.py
index 1d3c1192afb..88f72fe7aeb 100644
--- a/hermes_cli/gateway_session_store.py
+++ b/hermes_cli/gateway_session_store.py
@@ -34,6 +34,7 @@ _READS = frozenset({
"is_kanban_owned_session", "list_sessions_rich", "search_sessions", "get_next_title_in_lineage",
"get_handoff_state", "get_meta", "get_compression_tip", "resolve_session_by_title", "get_messages",
"session_count", "sanitize_title", "session_yolo_enabled",
+ "get_session_model_config_value",
})
# Writes the gateway already performs itself (persistence, accounting, maintenance).
_GATEWAY_OWNED = frozenset({
diff --git a/tests/gateway/test_one_turn_route_publish.py b/tests/gateway/test_one_turn_route_publish.py
new file mode 100644
index 00000000000..4ede20117ca
--- /dev/null
+++ b/tests/gateway/test_one_turn_route_publish.py
@@ -0,0 +1,86 @@
+"""A one-turn model override must not become the route other clients read, and a same-provider
+override must keep the session endpoint and key."""
+from types import SimpleNamespace
+
+from gateway.session_cli_turn import cli_turn_scope, one_turn_runtime
+from hermes_cli.model_switch import ModelSwitchResult
+
+
+def test_settled_info_publishes_the_policy_route_and_drops_the_cached_agent(monkeypatch):
+ from gateway.session_local_inventory import publish_settled_info
+ published, evicted = [], []
+ policy = SimpleNamespace(current_model=lambda _authority: "session-model", provider="openrouter", source="cli")
+ live = SimpleNamespace(route="route-1", source=SimpleNamespace())
+ authority = SimpleNamespace(profile_id="p", sessions={"s": live})
+ turn = SimpleNamespace(
+ _ctx=SimpleNamespace(inbound_message_id="adm", session_key="route-1"),
+ _approval_owner=(authority, "s", 1),
+ _runner=SimpleNamespace(_evict_cached_agent=lambda key: evicted.append(key)),
+ _publish_execution=lambda kind, payload: published.append((kind, payload)),
+ )
+ agent = SimpleNamespace(model="once-model", provider="anthropic", tools=None, _cached_system_prompt="",
+ context_compressor=None)
+
+ from gateway import session_local, session_policy
+ monkeypatch.setattr(session_local, "local_session_info", lambda *_a, **_k: {
+ "model": "once-model", "provider": "anthropic"})
+ monkeypatch.setattr(session_policy, "policy_for_source", lambda *_a, **_k: policy)
+
+ with cli_turn_scope("adm", {"model_override": {"model": "once-model", "provider": "anthropic"}}):
+ publish_settled_info(turn, agent)
+
+ assert evicted == ["route-1"]
+ assert published and published[0][0] == "session.info"
+ assert published[0][1]["model"] == "session-model"
+ assert published[0][1]["provider"] == "openrouter"
+
+
+def test_same_provider_override_keeps_the_session_endpoint_and_key(monkeypatch):
+ def _resolve(**_k):
+ return ModelSwitchResult(
+ success=True, new_model="openai/gpt-4.1", target_provider="openrouter",
+ api_key="", base_url="https://openrouter.ai/api/v1", api_mode="chat_completions",
+ request_overrides={})
+
+ monkeypatch.setattr("hermes_cli.model_switch.switch_model", _resolve)
+ monkeypatch.setattr("hermes_cli.config.get_compatible_custom_providers", lambda _config: [])
+ pool = object()
+ model, runtime = one_turn_runtime(
+ {"model": "openai/gpt-4.1", "provider": "openrouter"},
+ "session-model",
+ {"provider": "openrouter", "api_key": "sk-session", "base_url": "https://mirror.example/api/v1",
+ "credential_pool": pool, "request_overrides": {"provider": {"only": ["anthropic"]}},
+ "api_mode": "chat_completions"},
+ {})
+ assert model == "openai/gpt-4.1"
+ assert runtime["base_url"] == "https://mirror.example/api/v1"
+ assert runtime["api_key"] == "sk-session"
+ assert runtime["credential_pool"] is pool
+ assert runtime["request_overrides"] == {"provider": {"only": ["anthropic"]}}
+
+
+def _same_provider_override(monkeypatch, provider, model, api_mode, base_url, session):
+ def _resolve(**_k):
+ return ModelSwitchResult(success=True, new_model=model, target_provider=provider, api_key="",
+ base_url=base_url, api_mode=api_mode, request_overrides={})
+
+ monkeypatch.setattr("hermes_cli.model_switch.switch_model", _resolve)
+ monkeypatch.setattr("hermes_cli.config.get_compatible_custom_providers", lambda _config: [])
+ return one_turn_runtime({"model": model, "provider": provider}, "session-model",
+ {"provider": provider, "api_key": "tok-session", **session}, {})[1]
+
+
+def test_same_provider_override_runs_on_the_targets_wire(monkeypatch):
+ """Copilot serves GPT-5 on the Responses API and Claude on chat completions."""
+ runtime = _same_provider_override(
+ monkeypatch, "copilot", "gpt-5.4", "codex_responses", "https://api.githubcopilot.com",
+ {"base_url": "https://api.githubcopilot.com", "api_mode": "chat_completions"})
+ assert runtime["api_mode"] == "codex_responses"
+ assert (runtime["base_url"], runtime["api_key"]) == ("https://api.githubcopilot.com", "tok-session")
+
+
+def test_same_provider_override_reshapes_the_opencode_endpoint_for_its_wire(monkeypatch):
+ runtime = _same_provider_override(
+ monkeypatch, "opencode-zen", "minimax-m2.7", "anthropic_messages", "https://opencode.ai/zen",
+ {"base_url": "https://opencode.ai/zen/v1", "api_mode": "chat_completions"})
+ assert (runtime["api_mode"], runtime["base_url"]) == ("anthropic_messages", "https://opencode.ai/zen")
diff --git a/tests/hermes_cli/test_cli_gateway_model_route.py b/tests/hermes_cli/test_cli_gateway_model_route.py
new file mode 100644
index 00000000000..a92b537acb9
--- /dev/null
+++ b/tests/hermes_cli/test_cli_gateway_model_route.py
@@ -0,0 +1,102 @@
+"""The classic CLI's model choices reach the gateway session.
+
+``/model`` swaps the live agent, and ``/moa`` rebuilds it on the MoA route. Both have to
+show up on the next ``prompt.submit``: a session ``session.mutate model``, or that
+admission's ``model_override``.
+"""
+import queue
+from types import SimpleNamespace
+
+from hermes_cli.gateway_client import GatewayClientError
+from hermes_cli.model_switch import ModelSwitchResult
+
+
+class RecordingConnection:
+ def __init__(self, info):
+ from hermes_cli.gateway_connection import SessionState
+ self.events = queue.Queue()
+ self.calls = []
+ self.closed = False
+ # The session store is truthy until the connection is final.
+ self.final = False
+ self._state = SessionState("s")
+ self._state.info = dict(info)
+
+ def state(self, session_id):
+ return self._state
+
+ def reply(self, *_a, **_k):
+ return True
+
+ def call(self, method, *, timeout=None, **params):
+ self.calls.append((method, params))
+ if method == "session.resume":
+ return {"revision": 7, "execution_generation": 3, "info": dict(self._state.info), "messages": [],
+ "stored_session_id": "s", "session_id": "s", "prompts": [], "pending": []}
+ if method == "session.mutate":
+ if params.get("operation") == "model":
+ self._state.info.update(model=params["payload"]["model"],
+ provider=params["payload"].get("provider") or self._state.info.get("provider"))
+ return {}
+ if method == "prompt.submit":
+ self.events.put({"method": "event", "params": {
+ "type": "message.complete", "session_id": "s", "admission_id": "a1", "execution_generation": 3,
+ "payload": {"text": "ok", "status": "complete", "admission_id": "a1"}}})
+ return {"admission_id": "a1", "status": "queued"}
+ if method == "prompt.receipt":
+ return {"status": "terminal", "outcome": "completed", "result": {"final_response": "ok"}}
+ if method == "config.set":
+ return {}
+ raise GatewayClientError("unsupported_method")
+
+
+def _agent(conn, **kw):
+ from hermes_cli.gateway_agent import GatewayAgent
+ return GatewayAgent(connection=conn, session_id="s", **kw)
+
+
+def _model_routes(conn):
+ """Every model the CLI asked the gateway to run: session switches and one-turn overrides."""
+ mutates = [p["payload"] for m, p in conn.calls if m == "session.mutate" and p.get("operation") == "model"]
+ overrides = [p["model_override"] for m, p in conn.calls if m == "prompt.submit" and "model_override" in p]
+ return mutates, overrides
+
+
+def test_classic_cli_model_switch_reaches_the_gateway_session(monkeypatch):
+ import cli as cli_mod
+ from tests.hermes_cli.test_cli_model_once import _StubCLI
+ conn = RecordingConnection({"model": "old/model", "provider": "openrouter"})
+ stub = _StubCLI()
+ stub.agent = _agent(conn, model="old/model", provider="openrouter")
+ stub._snapshot_model_runtime = cli_mod.HermesCLI._snapshot_model_runtime.__get__(stub)
+ stub._session_db = None
+ stub.session_id = "s"
+ printed = []
+ monkeypatch.setattr(cli_mod, "_cprint", lambda s, *a, **k: printed.append(str(s)))
+ monkeypatch.setattr("hermes_cli.inventory.load_picker_context", lambda: SimpleNamespace(
+ user_providers=None, custom_providers=None,
+ with_overrides=lambda **_: SimpleNamespace(user_providers=None, custom_providers=None)))
+ monkeypatch.setattr("hermes_cli.model_switch.switch_model", lambda **_: ModelSwitchResult(
+ success=True, new_model="claude-sonnet-4.6", target_provider="anthropic", api_key="sk-ant",
+ base_url="https://api.anthropic.com", api_mode="anthropic_messages", provider_label="Anthropic"))
+ monkeypatch.setattr("hermes_cli.model_switch.resolve_display_context_length", lambda *a, **k: None)
+
+ cli_mod.HermesCLI._handle_model_switch(stub, "/model claude-sonnet-4.6 --provider anthropic")
+
+ failed = [line for line in printed if "fail" in line.lower()]
+ assert not failed, ("/model printed a failure", failed)
+ assert stub.model == "claude-sonnet-4.6", stub.model
+ stub.agent.run_conversation("next turn")
+ mutates, overrides = _model_routes(conn)
+ assert mutates or overrides, ("the next turn runs the old model: nothing reached the gateway", conn.calls)
+
+
+def test_classic_cli_moa_turn_runs_on_the_moa_route():
+ """``/moa <prompt>`` retires the agent; the next turn builds one on the MoA preset."""
+ conn = RecordingConnection({"model": "session/model", "provider": "openrouter"})
+ agent = _agent(conn, model="moa-default", provider="moa", base_url="moa://local", api_mode="chat_completions")
+ result = agent.run_conversation("one prompt through MoA")
+ assert not result.get("failed"), result
+ mutates, overrides = _model_routes(conn)
+ routed = [r for r in mutates + overrides if r.get("model") == "moa-default"]
+ assert routed, ("the /moa turn ran the session model, not the MoA preset", conn.calls)
diff --git a/tests/hermes_cli/test_cli_gateway_model_scope.py b/tests/hermes_cli/test_cli_gateway_model_scope.py
new file mode 100644
index 00000000000..0aa0787bcbc
--- /dev/null
+++ b/tests/hermes_cli/test_cli_gateway_model_scope.py
@@ -0,0 +1,283 @@
+"""``/model --once`` is one turn; a session ``/model`` is the session's route.
+
+``--once`` swaps the agent and restores it after one turn, and never writes the session
+row. A session switch writes that row through the owner's fenced ``session.mutate model``.
+Switching onto the route the session already runs commits nothing.
+"""
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_cli.model_switch import ModelSwitchResult
+from tests.hermes_cli.test_cli_gateway_model_route import RecordingConnection, _agent, _model_routes
+
+_CONFIRM_MESSAGE = "Large context: this switch re-reads the whole session."
+
+
+class GuardedConnection(RecordingConnection):
+ """The owner's selection guard: the first model mutate answers ``confirmation_required``."""
+
+ def call(self, method, *, timeout=None, **params):
+ if method == "session.mutate" and params.get("operation") == "model" \
+ and params["payload"].get("confirm") != "tok":
+ self.calls.append((method, params))
+ return {"status": "confirmation_required", "confirm_required": True, "confirm": "tok",
+ "confirm_message": _CONFIRM_MESSAGE}
+ return super().call(method, timeout=timeout, **params)
+
+
+def _cli(monkeypatch, conn):
+ import cli as cli_mod
+ from hermes_cli.gateway_session_store import GatewaySessionStore
+ from tests.hermes_cli.test_cli_model_once import _StubCLI
+ stub = _StubCLI()
+ stub.agent = _agent(conn, model="old/model", provider="openrouter")
+ stub._snapshot_model_runtime = cli_mod.HermesCLI._snapshot_model_runtime.__get__(stub)
+ stub._session_db = GatewaySessionStore(conn)
+ stub.session_id = "s"
+ printed = []
+ monkeypatch.setattr(cli_mod, "_cprint", lambda s, *a, **k: printed.append(str(s)))
+ monkeypatch.setattr(cli_mod, "save_config_value", lambda *a, **k: None)
+ monkeypatch.setattr("hermes_cli.inventory.load_picker_context", lambda: SimpleNamespace(
+ user_providers=None, custom_providers=None,
+ with_overrides=lambda **_: SimpleNamespace(user_providers=None, custom_providers=None)))
+ _pick(monkeypatch, "claude-sonnet-4.6", "anthropic", "https://api.anthropic.com", "anthropic_messages")
+ monkeypatch.setattr("hermes_cli.model_switch.resolve_display_context_length", lambda *a, **k: None)
+ return cli_mod, stub, printed
+
+
+def _pick(monkeypatch, model, provider, base_url, api_mode):
+ monkeypatch.setattr("hermes_cli.model_switch.switch_model", lambda **_: ModelSwitchResult(
+ success=True, new_model=model, target_provider=provider, api_key=f"sk-{provider}",
+ base_url=base_url, api_mode=api_mode, provider_label=provider.title()))
+
+
+def _submits(conn):
+ return [p for m, p in conn.calls if m == "prompt.submit"]
+
+
+def _prepare_for_chat(monkeypatch, cli_mod, stub):
+ """Enough of HermesCLI for the real ``chat``: its retire, ``_init_agent``, the agent thread
+ and the one-turn restore all run. Only the terminal UI around the turn is stubbed."""
+ for name in ("chat", "_chat_run_agent", "_chat_release_turn_audio", "_init_agent",
+ "_resolve_turn_agent_config", "_restore_model_runtime_snapshot"):
+ setattr(stub, name, getattr(cli_mod.HermesCLI, name).__get__(stub))
+ monkeypatch.setattr(cli_mod, "ChatConsole", lambda *a, **k: SimpleNamespace(print=lambda *a, **k: None))
+ stub._ensure_runtime_credentials = lambda: True
+ stub.finalize_preloaded_skills = lambda: None
+ stub._install_tool_callbacks = lambda: None
+ stub._ensure_gateway_session = lambda: None
+ stub._sync_fallback_chain_with_config = lambda agent: None
+ stub._chat_route_images = lambda message, images: message
+
+ def _stage(agent, message):
+ stub.conversation_history.append({"role": "user", "content": message})
+ agent._pending_cli_user_message = {"role": "user", "content": message}
+
+ stub._chat_stage_user_message = _stage
+ stub._reset_stream_state = lambda: None
+ stub._chat_setup_turn_audio = lambda turn, message, voice_input: None
+ stub._chat_monitor_agent_thread = lambda turn, thread: thread.join()
+ stub._chat_settle_turn = lambda turn: None
+ stub._chat_render_turn = lambda turn, thread, interrupt: (turn.result or {}).get("final_response")
+ stub._flush_credit_notices = lambda: None
+ for callback in ("_secret_capture_callback", "_sudo_password_callback", "_approval_callback",
+ "_vault_unlock_callback", "_vault_save_login_callback", "_vault_code_callback"):
+ setattr(stub, callback, None)
+ stub._pending_moa_config = None
+ stub._resumed = False
+ stub.conversation_history = []
+ stub._active_agent_route_signature = None
+ stub.acp_command = None
+ stub.acp_args = []
+ stub.max_turns = 8
+ stub.enabled_toolsets = None
+ stub.disabled_toolsets = None
+ stub.verbose = False
+ stub.tool_progress_mode = "off"
+ stub.system_prompt = ""
+ stub.prefill_messages = None
+ stub.reasoning_config = None
+ stub.service_tier = None
+ stub._reasoning_user_set = False
+ stub._providers_only = None
+ stub._providers_ignore = None
+ stub._providers_order = None
+ stub._provider_sort = None
+ stub._provider_require_params = None
+ stub._provider_data_collection = None
+ stub._openrouter_min_coding_score = None
+ stub._single_query_mode = False
+ stub._clarify_callback = None
+ stub._connection_callback = None
+ stub._confirm_owner_model_switch = lambda refusal: False
+ stub._withdraw_gateway_modal = lambda method: None
+ stub._current_reasoning_callback = lambda: None
+ stub._fallback_model = None
+ stub._on_thinking = None
+ stub.checkpoints_enabled = False
+ stub.checkpoint_max_snapshots = 0
+ stub.checkpoint_max_total_size_mb = 0
+ stub.checkpoint_max_file_size_mb = 0
+ stub.pass_session_id = False
+ stub.ignore_rules = False
+ stub._inline_diffs_enabled = False
+ stub.streaming_enabled = False
+ stub._on_tool_progress = None
+ stub._on_tool_start = None
+ stub._on_tool_complete = None
+ stub._stream_delta = None
+ stub._on_tool_gen_start = None
+ stub._on_notice = None
+ stub._on_notice_clear = None
+ stub._on_reaction = None
+ stub._agent_status_print = lambda *_a, **_k: None
+ stub._pending_title = None
+ stub._auto_load_skills_result = None
+
+
+def _chat_cli(monkeypatch, conn):
+ cli_mod, stub, printed = _cli(monkeypatch, conn)
+ _prepare_for_chat(monkeypatch, cli_mod, stub)
+ return cli_mod, stub, printed
+
+
+def test_model_once_rides_one_turn_and_never_touches_the_session(monkeypatch):
+ conn = RecordingConnection({"model": "old/model", "provider": "openrouter"})
+ cli_mod, stub, printed = _chat_cli(monkeypatch, conn)
+ cli_mod.HermesCLI._handle_model_switch(stub, "/model claude-sonnet-4.6 --provider anthropic --once")
+ assert not [line for line in printed if "fail" in line.lower()], printed
+ assert stub.chat("the once turn") == "ok"
+ assert stub.chat("the turn after") == "ok"
+ mutates, _ = _model_routes(conn)
+ assert not mutates, ("--once wrote the shared session model", mutates)
+ once, after = _submits(conn)
+ assert once.get("model_override") == {"model": "claude-sonnet-4.6", "provider": "anthropic"}, once
+ assert "model_override" not in after, after
+ assert conn.state("s").info["model"] == "old/model"
+ assert (stub.model, stub.agent.model) == ("old/model", "old/model")
+
+
+def test_a_second_once_before_the_turn_restores_the_route_before_the_first(monkeypatch):
+ conn = RecordingConnection({"model": "old/model", "provider": "openrouter"})
+ cli_mod, stub, _printed = _chat_cli(monkeypatch, conn)
+ cli_mod.HermesCLI._handle_model_switch(stub, "/model claude-sonnet-4.6 --provider anthropic --once")
+ _pick(monkeypatch, "gpt-5.4", "openai", "https://api.openai.com/v1", "codex_responses")
+ cli_mod.HermesCLI._handle_model_switch(stub, "/model gpt-5.4 --provider openai --once")
+ stub.chat("the once turn")
+ stub.chat("the turn after")
+ once, after = _submits(conn)
+ assert once.get("model_override") == {"model": "gpt-5.4", "provider": "openai"}, once
+ assert "model_override" not in after, after
+ assert not _model_routes(conn)[0]
+ assert (stub.model, stub.provider, stub.base_url) == ("old/model", "openrouter", "https://openrouter.ai/api/v1")
+
+
+def test_session_switch_of_the_one_turn_target_commits_on_the_fence(monkeypatch):
+ conn = RecordingConnection({"model": "old/model", "provider": "openrouter"})
+ cli_mod, stub, printed = _chat_cli(monkeypatch, conn)
+ cli_mod.HermesCLI._handle_model_switch(stub, "/model claude-sonnet-4.6 --provider anthropic --once")
+ assert not _model_routes(conn)[0], "the one-turn pick wrote the session"
+ cli_mod.HermesCLI._handle_model_switch(stub, "/model claude-sonnet-4.6 --provider anthropic")
+ assert not [line for line in printed if "fail" in line.lower()], printed
+ mutates = [p for m, p in conn.calls if m == "session.mutate" and p.get("operation") == "model"]
+ assert mutates and mutates[-1]["payload"]["model"] == "claude-sonnet-4.6", mutates
+ assert "expected_generation" in mutates[-1], mutates
+ assert conn.state("s").info["model"] == "claude-sonnet-4.6"
+ stub.chat("now the session route")
+ stub.chat("and the next")
+ assert all("model_override" not in submit for submit in _submits(conn)), _submits(conn)
+ assert (stub.model, stub.agent.model) == ("claude-sonnet-4.6", "claude-sonnet-4.6")
+
+
[email protected]("conn_class", [RecordingConnection, GuardedConnection], ids=["plain", "guarded"])
+def test_session_model_switch_commits_the_route_on_the_owner(monkeypatch, conn_class):
+ conn = conn_class({"model": "old/model", "provider": "openrouter"})
+ cli_mod, stub, printed = _cli(monkeypatch, conn)
+ asked = []
+ stub.agent.model_confirm_callback = lambda refusal: asked.append(refusal["confirm_message"]) or True
+ cli_mod.HermesCLI._handle_model_switch(stub, "/model claude-sonnet-4.6 --provider anthropic")
+ assert not [line for line in printed if "fail" in line.lower()], printed
+ assert asked == ([_CONFIRM_MESSAGE] if conn_class is GuardedConnection else [])
+ stub.agent.run_conversation("next turn")
+ mutates = [p for m, p in conn.calls if m == "session.mutate" and p.get("operation") == "model"]
+ assert mutates[-1]["payload"] == {"model": "claude-sonnet-4.6", "provider": "anthropic",
+ **({"confirm": "tok"} if conn_class is GuardedConnection else {})}, mutates
+ assert all("expected_generation" in m for m in mutates), mutates
+ assert conn.state("s").info["model"] == "claude-sonnet-4.6"
+ assert "model_override" not in _submits(conn)[-1], "the session already runs it"
+
+
+def test_once_on_a_resumed_session_asks_before_it_switches(monkeypatch):
+ """The owner's large-context guard reads the persisted anchor. ``--once`` does not mutate,
+ so the CLI has to ask from that anchor when this process has not measured a turn yet."""
+ conn = RecordingConnection({"model": "old/model", "provider": "openrouter"})
+ cli_mod, stub, _printed = _cli(monkeypatch, conn)
+ asked = []
+
+ class _AnchorDB:
+ def get_messages_as_conversation(self, sid):
+ return [{"role": "user", "content": "hello"}]
+
+ def get_session_model_config_value(self, sid, key, default=None):
+ return default
+
+ stub._session_db = _AnchorDB()
+ stub._confirm_expensive_model_switch = cli_mod.HermesCLI._confirm_expensive_model_switch.__get__(stub)
+ stub._prompt_text_input_modal = lambda **kw: asked.append(kw) or "cancel"
+ stub._normalize_slash_confirm_choice = cli_mod.HermesCLI._normalize_slash_confirm_choice.__get__(stub)
+ monkeypatch.setattr("agent.usage_anchor.persisted_anchor_tokens", lambda *_a, **_k: 200_000)
+ cli_mod.HermesCLI._handle_model_switch(stub, "/model claude-sonnet-4.6 --provider anthropic --once")
+ assert asked, "the large-context confirm did not appear"
+ assert any("LARGE CONTEXT" in (kw.get("detail") or "") or "context" in (kw.get("title") or "").lower()
+ for kw in asked), asked
+ assert not _model_routes(conn)[0]
+ assert conn.state("s").info["model"] == "old/model"
+ assert stub._pending_one_turn_model_restore is None
+
+
+def test_one_turn_kwargs_reach_only_a_switch_that_names_them():
+ """``AIAgent.switch_model`` is a lazy ``**kwargs`` forwarder to a function without ``once`` /
+ ``restore``: it gets the plain in-process switch. Its own errors still surface."""
+ from hermes_cli.cli_model_switch_mixin import _call_agent_switch
+ from run_agent import AIAgent
+
+ seen = []
+
+ def _in_process(agent, new_model, new_provider, api_key="", base_url="", api_mode="", capabilities=None):
+ seen.append(new_model)
+ if new_model == "broken":
+ raise TypeError("provider client could not be built")
+ return True
+
+ class _Forwarder:
+ switch_model = AIAgent.switch_model
+
+ class _OneTurnAware:
+ def switch_model(self, new_model, new_provider="", *, once=False, restore=False):
+ seen.append((new_model, once, restore))
+ return True
+
+ import agent.agent_runtime_helpers as helpers
+ original = helpers.switch_model
+ helpers.switch_model = _in_process
+ try:
+ assert _call_agent_switch(_Forwarder(), new_model="next", new_provider="openrouter", once=True) is True
+ assert _call_agent_switch(_Forwarder(), new_model="prev", new_provider="openrouter",
+ once=True, restore=True) is True
+ with pytest.raises(TypeError, match="could not be built"):
+ _call_agent_switch(_Forwarder(), new_model="broken", new_provider="openrouter", once=True)
+ finally:
+ helpers.switch_model = original
+ assert _call_agent_switch(_OneTurnAware(), new_model="next", once=True, restore=True) is True
+ assert seen == ["next", "prev", "broken", ("next", True, True)]
+
+
+def test_switching_to_the_route_the_session_runs_commits_nothing(monkeypatch):
+ conn = RecordingConnection({"model": "old/model", "provider": "openrouter"})
+ cli_mod, stub, _printed = _cli(monkeypatch, conn)
+ _pick(monkeypatch, "old/model", "openrouter", "https://openrouter.ai/api/v1", "chat_completions")
+ cli_mod.HermesCLI._handle_model_switch(stub, "/model old/model --provider openrouter")
+ stub.agent.run_conversation("next turn")
+ mutates, overrides = _model_routes(conn)
+ assert not mutates and not overrides, (mutates, overrides)
diff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.py
index 7b2701fe036..5a712ec0d61 100644
--- a/tests/hermes_cli/test_gateway_agent.py
+++ b/tests/hermes_cli/test_gateway_agent.py
@@ -732,10 +732,10 @@ def test_a_transport_loss_at_submit_is_still_gateway_connection():
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."""
+ """A session-scoped ``/model`` calls ``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.
+ ``/model --once`` is not this path: that pick is one admission's ``model_override``."""
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)
diff --git a/tests/hermes_cli/test_gateway_model_switch_cli.py b/tests/hermes_cli/test_gateway_model_switch_cli.py
index 5ab446ff131..3400de65d36 100644
--- a/tests/hermes_cli/test_gateway_model_switch_cli.py
+++ b/tests/hermes_cli/test_gateway_model_switch_cli.py
@@ -142,18 +142,20 @@ def test_a_declined_owner_warning_switches_nothing(gateway, monkeypatch):
assert any("Model switch cancelled." in line for line in printed)
-def test_a_once_restore_nobody_can_confirm_is_not_committed(gateway, monkeypatch):
- """``/model big --once`` then the restore to the smaller model: the owner can refuse it (large
- context). Without a prompt (-q) the token is never sent: the session stays on the one-turn model,
- the CLI says so and follows it instead of claiming the restore."""
+def test_one_turn_restore_does_not_rewrite_the_session(gateway, monkeypatch):
+ """``/model --once`` never commits, so restoring the previous route is local. An owner guard
+ cannot pin the shared session to the one-turn model, and the next turn is not an override."""
from cli import HermesCLI
conn, client = gateway
- printed = []
- monkeypatch.setattr("cli._cprint", lambda text, *_a, **_k: printed.append(str(text)))
- cli = _cli(model="big-model")
- cli.agent = GatewayAgent(connection=conn, session_id=SID, model="big-model", provider="openrouter")
+ monkeypatch.setattr("cli._cprint", lambda *_a, **_k: None)
+ conn.state(SID).info.update(model="small-model", provider="openrouter")
+ cli = _cli(model="big-model", provider="openrouter")
+ cli.agent = GatewayAgent(connection=conn, session_id=SID, model="small-model", provider="openrouter")
+ assert cli.agent.switch_model(new_model="big-model", new_provider="openrouter", once=True) is True
+ client.calls.clear()
client.mutate_replies = [REFUSAL]
- HermesCLI._restore_model_runtime_snapshot(cli, {"model": "small-model", "provider": "openrouter"})
- assert [m["payload"] for m in _mutations(client)] == [{"model": "small-model", "provider": "openrouter"}]
- assert (cli.model, cli.agent.model) == ("big-model", "big-model")
- assert any("Model not switched" in line and "small-model" in line for line in printed)
+ HermesCLI._restore_model_runtime_snapshot(cli, {
+ "model": "small-model", "provider": "openrouter", "api_key": "k", "base_url": "", "api_mode": ""})
+ assert _mutations(client) == []
+ assert (cli.model, cli.agent.model) == ("small-model", "small-model")
+ assert cli.agent._turn_route is None