Skip to content

The agent that grows with you

fix(gateway): `-m <alias>` routes to the alias host, resolution failures fail the turn, pooled named providers keep their keys

teknium15fd3fcf1dbac
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 4412f0dddf0..57135aa5ad4 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -1034,30 +1034,37 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
)
except Exception as exc:
# Model/credential resolution failed before the turn began; the raw text (URLs, status
- # codes) belongs in the log, and the chat gets the commands that fix it.
+ # codes) belongs in the log, and the chat gets the commands that fix it. The result is
+ # a FAILED turn: a one-shot client exits non-zero, transcript persistence closes the
+ # turn, and an API receipt reports failure, never a completed turn with an apology.
logger.warning("Model resolution failed for session %s: %s", ctx.session_key or "", exc)
from hermes_state_runtime import RuntimeStoreError
+ from agent.turn_failure_copy import stamp_failure
+
+ def _unresolved(text: str) -> dict:
+ return stamp_failure({"final_response": text, "messages": [], "api_calls": 0, "tools": [],
+ "failed": True, "completed": False, "error": str(exc)},
+ "auth_permanent", False)
if isinstance(exc, RuntimeStoreError):
# Session-policy refusals carry a stable reason code (e.g. a CLI launch key
# revoked by daemon restart): keep it in the reply so clients can act on it, and
# do not suggest /login — the profile's own credentials were never in play.
- text = (f"⚠️ This session's launch credentials are no longer available "
- f"({exc.reason}), so this message wasn't processed. Start a new "
- "session from the CLI to bind them again.")
- return {"final_response": text, "messages": [], "api_calls": 0, "tools": []}
+ return _unresolved(f"⚠️ This session's launch credentials are no longer available "
+ f"({exc.reason}), so this message wasn't processed. Start a new "
+ "session from the CLI to bind them again.")
from hermes_cli.auth import is_rate_limited_auth_error
if is_rate_limited_auth_error(exc.__cause__):
# Quota cap with valid credentials: /login cannot help; name the reset window (#89401).
from gateway.run import _gateway_provider_error_reply
- return {"final_response": _gateway_provider_error_reply(str(exc)),
- "messages": [], "api_calls": 0, "tools": []}
- return {
- "final_response": (
- "⚠️ I couldn't connect to the AI model service, so this message wasn't processed. "
- "Use /login to sign in again, or /model to pick a different model. If it keeps "
- "failing, run `hermes doctor` on the host."),
- "messages": [], "api_calls": 0, "tools": [],
- }
+ return _unresolved(_gateway_provider_error_reply(str(exc)))
+ if ctx.source.platform == Platform.LOCAL:
+ # The local operator reads the terminal: the resolver's own sentence ("provider
+ # 'custom' resolved without credentials ...") is the diagnosis; /login is not.
+ return _unresolved(f"⚠️ {exc}")
+ return _unresolved(
+ "⚠️ I couldn't connect to the AI model service, so this message wasn't processed. "
+ "Use /login to sign in again, or /model to pick a different model. If it keeps "
+ "failing, run `hermes doctor` on the host.")
pr = runner._provider_routing
reasoning_config = (policy.reasoning_config if policy else
runner._resolve_session_reasoning_config(source=ctx.source, session_key=ctx.session_key, model=model))
diff --git a/gateway/session_local.py b/gateway/session_local.py
index a7e6f07c3f3..3c45bd73e42 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -111,7 +111,10 @@ def create_local_session(authority, actor, params, *, trusted_policy=None, trust
elif any(params.get(name) is True for name in BYPASS_FIELDS):
policy = _bypass_policy(params, private_secrets=private_secrets)
else:
- policy = build_policy(params, _load_gateway_config(), private_secrets=private_secrets)
+ from gateway.session_local_route import resolve_launch_route
+ config = _load_gateway_config()
+ params = resolve_launch_route(params, config)
+ policy = build_policy(params, config, private_secrets=private_secrets)
if policy.model is None:
policy = replace(policy, model=_resolve_gateway_model(policy.config()))
request_id = params.get('request_id', uuid.uuid4().hex)
diff --git a/gateway/session_local_route.py b/gateway/session_local_route.py
new file mode 100644
index 00000000000..408cceae380
--- /dev/null
+++ b/gateway/session_local_route.py
@@ -0,0 +1,37 @@
+"""``-m <alias | provider:model | provider/model>`` at ``session.create``, resolved by the owner."""
+from __future__ import annotations
+
+
+def resolve_launch_route(params: dict, config: dict) -> dict:
+ """Return ``params`` with an explicit launch model decoded the way every other startup path does.
+
+ The client sends the raw ``-m`` string; the authority owns the profile whose ``model_aliases:``
+ / ``providers:`` define it. Unresolved, the alias name becomes the model sent to the profile
+ DEFAULT provider, and the alias's own endpoint/key are never used (#103933/#107191/#109440).
+ Same owner as HermesCLI / oneshot / the TUI factory: ``resolve_startup_model_route``. A plain
+ model id (no alias, no qualifier) is returned untouched; explicit ``--base-url``/``--api-key``
+ launches already carry their route.
+ """
+ model = params.get('model')
+ if not isinstance(model, str) or not model.strip() or 'base_url' in params or 'api_key' in params:
+ return params
+ from hermes_cli.model_switch import resolve_startup_model_route
+ model_cfg = config.get('model')
+ if not isinstance(model_cfg, dict):
+ model_cfg = {}
+ explicit_provider = str(params.get('provider') or '').strip()
+ route = resolve_startup_model_route(
+ model, explicit_provider=explicit_provider,
+ current_provider=(explicit_provider or str(model_cfg.get('provider') or '')).strip().lower(),
+ user_providers=config.get('providers'), custom_providers=config.get('custom_providers'))
+ if route is None:
+ return params
+ resolved = dict(params, model=route.model)
+ if route.provider:
+ resolved['provider'] = route.provider
+ if route.base_url:
+ resolved['base_url'] = route.base_url
+ if route.api_key:
+ # An alias key is a launch key: authority memory only, revoked by restart (bind_launch_key).
+ resolved['api_key'] = route.api_key
+ return resolved
diff --git a/hermes_cli/runtime_provider_custom.py b/hermes_cli/runtime_provider_custom.py
index d4b5e0e6ca3..7f7356d4191 100644
--- a/hermes_cli/runtime_provider_custom.py
+++ b/hermes_cli/runtime_provider_custom.py
@@ -550,10 +550,13 @@ def _resolve_named_custom_runtime(*, requested_provider: str, explicit_api_key:
base_url = ((explicit_base_url or "").strip() or custom_provider.get("base_url", "")).rstrip("/")
if not base_url:
return None
+ # The credential pool is the profile's auth store (``hermes auth add``), not config: a frozen
+ # config snapshot still owes a pooled ``providers:`` entry its keys, or the turn ships the
+ # ``no-key-required`` placeholder to a host that wants one (C11 pool rows).
pool_result = rp._try_resolve_from_custom_pool(
base_url, "custom", custom_provider.get("api_mode"),
provider_name=custom_provider.get("provider_key") or custom_provider.get("name"),
- ) if config is None else None
+ )
if pool_result:
# The pool doesn't know the custom_providers fields — propagate them here too.
_apply_custom_provider_extras(custom_provider, target_model, pool_result)
diff --git a/tests/gateway/test_local_model_connection_reply.py b/tests/gateway/test_local_model_connection_reply.py
index 8232a434e8c..8a67da09c45 100644
--- a/tests/gateway/test_local_model_connection_reply.py
+++ b/tests/gateway/test_local_model_connection_reply.py
@@ -216,3 +216,35 @@ class TestQuotaExhaustedIsNotAnAuthFailure:
result = TurnRunner(runner, ctx).run_sync()
reply = result["final_response"]
assert "/login" not in reply and "resets in ~33h" in reply and result["api_calls"] == 0
+
+ def test_turn_runner_resolution_failure_is_a_failed_turn_with_local_detail(self, monkeypatch):
+ """A pre-agent resolution failure is a FAILED result (one-shot exits non-zero, the turn
+ is closed in the transcript), and a LOCAL session sees the resolver's own diagnosis —
+ ``hermes chat -q`` on a bare ``custom`` must print the no-credentials error and exit
+ non-zero, not ``rc 0`` with a /login hint (C11 bare_custom_without_base_url_fails_fast)."""
+ from types import SimpleNamespace
+ import gateway.run as gateway_run
+ from gateway.config import Platform
+ from gateway.run_turn_runner import TurnRunner
+ from gateway.session import SessionSource
+ from gateway.turn_context import TurnContext
+
+ detail = "provider 'custom' resolved without credentials (no endpoint or API key configured)."
+
+ def _resolve(**_kwargs):
+ raise RuntimeError(detail)
+
+ monkeypatch.setattr(gateway_run, "_current_max_iterations", lambda: 30)
+ runner = SimpleNamespace(_resolve_session_agent_runtime=_resolve,
+ _get_system_prompt_for_channel=lambda *a, **k: "",
+ _ephemeral_system_prompt="", _adapter_for_source=lambda _s: None)
+ for platform, chat_id in ((Platform.LOCAL, "local-1"), (Platform.SLACK, "C1")):
+ ctx = TurnContext(source=SessionSource(platform=platform, chat_id=chat_id, chat_type="dm"),
+ session_key=f"{platform.value}:{chat_id}", user_config={}, message="Hi")
+ result = TurnRunner(runner, ctx).run_sync()
+ assert result["failed"] is True and result["completed"] is False and result["api_calls"] == 0
+ assert result["failure_reason"] and result["error"] == detail
+ if platform == Platform.LOCAL:
+ assert detail in result["final_response"] and "/login" not in result["final_response"]
+ else:
+ assert detail not in result["final_response"] and "/login" in result["final_response"]
diff --git a/tests/gateway/test_session_local_route.py b/tests/gateway/test_session_local_route.py
new file mode 100644
index 00000000000..7494a31f713
--- /dev/null
+++ b/tests/gateway/test_session_local_route.py
@@ -0,0 +1,63 @@
+"""``-m <alias>`` at session.create is decoded by the owner against the profile's own aliases.
+
+Pinned by the C11 truth table (alias_startup_q_api_key / alias_startup_q_key_env /
+alias_startup_oneshot_z): the raw alias name must never become the model sent to the profile's
+DEFAULT provider with that provider's key.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+
+def home(tmp_path, monkeypatch):
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ monkeypatch.setenv("ALIAS_HOST_KEY", "sk-alias-env-secret")
+ (hermes_home / "config.yaml").write_text(
+ "model:\n provider: custom\n base_url: http://127.0.0.1:1/v1\n default: model-main\n"
+ "providers:\n named-host:\n base_url: http://127.0.0.1:2/v1\n model: model-named\n"
+ "model_aliases:\n"
+ " alias-host: {model: model-alias, provider: custom, base_url: http://127.0.0.1:3/v1, api_key: sk-alias-literal}\n"
+ " alias-env: {model: model-alias-env, provider: custom, base_url: http://127.0.0.1:3/v1, key_env: ALIAS_HOST_KEY}\n",
+ encoding="utf-8")
+ from hermes_cli import model_switch
+ model_switch.DIRECT_ALIASES.clear()
+ return hermes_home
+
+
+def _config():
+ from gateway.run import _load_gateway_config
+ return _load_gateway_config()
+
+
+def test_alias_launch_carries_alias_endpoint_and_key(home):
+ from gateway.session_local_route import resolve_launch_route
+ literal = resolve_launch_route({"model": "alias-host", "source": "cli"}, _config())
+ assert (literal["model"], literal["provider"], literal["base_url"], literal["api_key"]) == (
+ "model-alias", "custom", "http://127.0.0.1:3/v1", "sk-alias-literal")
+ env = resolve_launch_route({"model": "alias-env"}, _config())
+ assert (env["model"], env["base_url"], env["api_key"]) == ("model-alias-env", "http://127.0.0.1:3/v1", "sk-alias-env-secret")
+ # Qualified `provider:model` selects the named provider; a plain id and an explicit
+ # endpoint launch pass through untouched (their route is already decided).
+ qualified = resolve_launch_route({"model": "custom:named-host:model-named"}, _config())
+ assert (qualified["model"], qualified["provider"]) == ("model-named", "custom:named-host")
+ plain = {"model": "model-main", "source": "cli"}
+ assert resolve_launch_route(plain, _config()) == plain
+ explicit = {"model": "alias-host", "base_url": "http://127.0.0.1:9/v1"}
+ assert resolve_launch_route(explicit, _config()) == explicit
+
+
+def test_alias_key_is_a_launch_key_not_durable_policy(home):
+ """The alias's credential rides ``api_key`` (authority memory, revoked by restart), and the
+ frozen policy config carries the alias endpoint, never the profile default's."""
+ from gateway.session_local_route import resolve_launch_route
+ from gateway.session_policy import build_policy
+ params = resolve_launch_route({"model": "alias-host", "source": "cli", "cwd": str(home)}, _config())
+ policy = build_policy(params, _config(), private_secrets={})
+ assert policy.model == "model-alias" and policy.base_url == "http://127.0.0.1:3/v1"
+ assert "sk-alias-literal" not in policy.config_json + policy.request_json