From 5fd3fcf1dbac208879852861e87f5e2e5e4dab72 Mon Sep 17 00:00:00 2001 From: teknium1 <127238744+teknium1@users.noreply.github.com> Date: Thu, 24 Sep 2026 04:14:06 -0700 Subject: [PATCH] fix(gateway): `-m ` routes to the alias host, resolution failures fail the turn, pooled named providers keep their keys Three routing defects the C11 truth table (tests/e2e/core/tenancy/test_routing_truth_table.py) caught on the unified gateway runtime: - `hermes chat -q -m ` / `hermes -z -m `: the client sent the raw alias name as `session.create model=`, so the turn ran the ALIAS NAME against the profile default provider with the default key. `gateway/session_local_route.py::resolve_launch_route` decodes it at the owner through `resolve_startup_model_route` (the same owner HermesCLI, oneshot and the TUI factory use), carrying the alias's own endpoint as `base_url` and its key as a launch key. - A pre-agent model/credential resolution failure returned a COMPLETED turn with a "/login" apology, so `hermes chat -q` on a credential-less bare `custom` exited 0 and the failed turn was never closed in the transcript. The result is now `failed` with a stamped `failure_reason`, and a LOCAL session sees the resolver's own diagnosis (the operator reads the terminal; /login is not the cure). - `_resolve_named_custom_runtime(config=frozen)` skipped the credential pool, so a pooled `providers:` entry created from a frozen policy shipped `no-key-required`. The pool is the profile's auth store, not config; it is consulted regardless of the config source. Validation: the 19 truth-table cases go 13/19 -> 19/19; the new turn-runner invariant is red on the pre-fix tree and green after; 242 neighbouring gateway/runtime-provider tests pass. --- gateway/run_turn_runner.py | 35 ++++++----- gateway/session_local.py | 5 +- gateway/session_local_route.py | 37 +++++++++++ hermes_cli/runtime_provider_custom.py | 5 +- .../test_local_model_connection_reply.py | 32 ++++++++++ tests/gateway/test_session_local_route.py | 63 +++++++++++++++++++ 6 files changed, 161 insertions(+), 16 deletions(-) create mode 100644 gateway/session_local_route.py create mode 100644 tests/gateway/test_session_local_route.py diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py index 4412f0dddf..57135aa5ad 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 a7e6f07c3f..3c45bd73e4 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 0000000000..408cceae38 --- /dev/null +++ b/gateway/session_local_route.py @@ -0,0 +1,37 @@ +"""``-m `` 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 d4b5e0e6ca..7f7356d419 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 8232a434e8..8a67da09c4 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 0000000000..7494a31f71 --- /dev/null +++ b/tests/gateway/test_session_local_route.py @@ -0,0 +1,63 @@ +"""``-m `` 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 + + +@pytest.fixture +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