Skip to content

The agent that grows with you

fix(gateway): route AuthError fallback through resolve_runtime_with_fallback

teknium150274afa6c35
diff --git a/gateway/run.py b/gateway/run.py
index 8ee83f0a34d..7ed20012737 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -40,7 +40,6 @@ from agent.interrupt_compat import request_hard_interrupt
from agent.turn_context import compression_made_progress
from agent.session_activity import ActivityProvenance
from hermes_cli.config import _is_ssh_remote_tilde_cwd, cfg_get
-from hermes_cli.fallback_config import get_fallback_chain
# Per-session AIAgent cache bounds (agents are heavy); see _enforce_agent_cache_cap/_session_housekeeping_watcher.
_AGENT_CACHE_MAX_SIZE = 128
@@ -2198,28 +2197,20 @@ _CONVERSATION_SCOPED_STATE: tuple = (
def _resolve_runtime_agent_kwargs() -> dict:
"""Resolve provider credentials for gateway-created AIAgent instances.
- ``resolve_runtime_provider()`` may fall back to env vars; behavioral config is config.yaml only."""
+ ``resolve_runtime_provider()`` may fall back to env vars; behavioral config is config.yaml only.
+ An ``AuthError`` from the primary walks the configured fallback chain through the shared
+ ``resolve_runtime_with_fallback`` (the gateway keeps no resolver loop of its own)."""
from hermes_cli.runtime_provider import (
- resolve_runtime_provider, format_runtime_provider_error, _get_model_config)
- from hermes_cli.auth import AuthError, is_rate_limited_auth_error
+ resolve_runtime_with_fallback, format_runtime_provider_error, _get_model_config)
try:
- runtime = resolve_runtime_provider()
- except AuthError as auth_exc:
- # Rate-limit cap vs real auth failure: both use the fallback chain; the log must not mislabel.
- # Distinguish a transient rate-limit/quota cap (credentials are fine, re-auth cannot help) from a
- # genuine auth failure (expired/revoked token). See #32790.
- if is_rate_limited_auth_error(auth_exc):
- logger.warning("Primary provider rate-limited (429): %s — trying fallback", auth_exc)
- else:
- logger.warning("Primary provider auth failed: %s — trying fallback", auth_exc)
- fb_config = _try_resolve_fallback_provider()
- if fb_config is not None:
- return fb_config
- raise RuntimeError(format_runtime_provider_error(auth_exc)) from auth_exc
+ runtime, fallback_entry = resolve_runtime_with_fallback(_load_gateway_config())
except Exception as exc:
raise RuntimeError(format_runtime_provider_error(exc)) from exc
+ if fallback_entry is not None:
+ # The entry's model is the one this agent must send (#112600).
+ return {**_runtime_agent_kwargs(runtime), "model": fallback_entry["model"]}
capabilities = runtime.get("capabilities")
capabilities = (
@@ -2379,39 +2370,6 @@ def _credential_pool_for_provider(provider: Optional[str]):
return None
-def _try_resolve_fallback_provider() -> dict | None:
- """Attempt to resolve credentials from the fallback_model/fallback_providers config."""
- from hermes_cli.runtime_provider import resolve_runtime_provider
- try:
- cfg = _load_gateway_config()
- fb_list = get_fallback_chain(cfg)
- if not fb_list:
- return None
- for entry in fb_list:
- try:
- from hermes_cli.fallback_config import effective_runtime_provider, resolve_entry_api_key
- runtime = resolve_runtime_provider(
- requested=entry.get("provider"), explicit_base_url=entry.get("base_url"),
- explicit_api_key=resolve_entry_api_key(entry), target_model=entry.get("model") or None)
- # Named custom entries resolve to the bare "custom" billing class; persist the configured
- # identity so UI/billing rows match the manual-switch path (#98739).
- runtime["provider"] = effective_runtime_provider(entry, runtime)
- # Log the config `provider`, not the runtime category (Ollama would log "openrouter").
- logger.info(
- # Log the literal `provider` key from config, not the resolved runtime category — an
- # Ollama fallback resolves through the OpenAI-compatible path and would otherwise be
- # logged as "openrouter", contradicting the operator's config (#32790).
- "Fallback provider resolved: %s model=%s",
- entry.get("provider") or runtime.get("provider"), entry.get("model"))
- return {**_runtime_agent_kwargs(runtime), "model": entry.get("model")}
- except Exception as fb_exc:
- logger.debug("Fallback entry %s failed: %s", entry.get("provider"), fb_exc)
- continue
- except Exception:
- pass
- return None
-
-
def _event_media_type_at(event, index: int) -> str:
"""Per-attachment MIME at *index*; "" when the adapter set only a message-level type."""
media_types = getattr(event, "media_types", None) or []
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.py
index d5b04b055ab..72606f2e197 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -1024,22 +1024,21 @@ def __getattr__(name): # PEP 562 — lazy so no import cycles
def resolve_runtime_with_fallback(config: Optional[Dict[str, Any]], *, requested: Optional[str] = None,
target_model: Optional[str] = None, explicit_base_url: Optional[str] = None,
explicit_api_key: Optional[str] = None,
- resolve=None) -> tuple[Dict[str, Any], Optional[Dict[str, Any]]]:
+ ) -> tuple[Dict[str, Any], Optional[Dict[str, Any]]]:
"""``resolve_runtime_provider`` plus resolution-time fallback: ``(runtime, fallback_entry_or_None)``.
Only an ``AuthError`` from the primary (missing/expired credentials, exhausted quota, cooled-down pool)
- walks ``get_fallback_chain(config)`` in order and returns the first entry that resolves — the same
- trigger the gateway and interactive CLI use. ``ValueError``/other errors are genuine misconfiguration
- (unknown ``--provider`` ...) and propagate unchanged, so a typo is never silently rerouted onto a
- provider the operator did not ask for. When every entry fails, the *primary* error is re-raised: a
- fallback entry's failure is not what the operator configured first (#81209). ``resolve`` is the
- resolver to call (tests inject a fake); the entry's ``model`` is the model the caller must send.
+ walks ``get_fallback_chain(config)`` in order and returns the first entry that resolves — the single
+ resolution-time walker shared by the gateway and oneshot. ``ValueError``/other errors are genuine
+ misconfiguration (unknown ``--provider`` ...) and propagate unchanged, so a typo is never silently
+ rerouted onto a provider the operator did not ask for. When every entry fails, the *primary* error is
+ re-raised: a fallback entry's failure is not what the operator configured first (#81209). The entry's
+ ``model`` is the model the caller must send.
"""
- from hermes_cli.auth import AuthError
- resolve = resolve or resolve_runtime_provider
+ from hermes_cli.auth import AuthError, is_rate_limited_auth_error
try:
- return resolve(requested=requested, target_model=target_model, explicit_base_url=explicit_base_url,
- explicit_api_key=explicit_api_key), None
+ return resolve_runtime_provider(requested=requested, target_model=target_model,
+ explicit_base_url=explicit_base_url, explicit_api_key=explicit_api_key), None
except AuthError as primary_exc:
from hermes_cli.fallback_config import effective_runtime_provider, get_fallback_chain, resolve_entry_api_key
for entry in get_fallback_chain(config):
@@ -1053,12 +1052,22 @@ def resolve_runtime_with_fallback(config: Optional[Dict[str, Any]], *, requested
if entry_key := resolve_entry_api_key(entry):
kwargs["explicit_api_key"] = entry_key
try:
- runtime = resolve(**kwargs)
- except Exception as fb_exc:
+ runtime = resolve_runtime_provider(**kwargs)
+ except AuthError as fb_exc:
logger.debug("Fallback entry %s/%s failed: %s", provider, model, fb_exc)
continue
+ except Exception as fb_exc:
+ # Not a credential problem: a mistyped provider/base_url must be visible, not silently skipped.
+ logger.warning("Fallback entry %s/%s is misconfigured and was skipped: %s", provider, model, fb_exc)
+ continue
# Named custom entries resolve to the bare "custom" class; persist the configured identity (#98739).
runtime["provider"] = effective_runtime_provider(entry, runtime)
- logger.warning("Primary provider auth failed (%s). Falling back to %s/%s", primary_exc, provider, model)
+ # A rate-limit/quota cap is transient (credentials are fine, re-auth cannot help); the log must not
+ # mislabel it as an auth failure (#32790).
+ if is_rate_limited_auth_error(primary_exc):
+ logger.warning("Primary provider rate-limited (429): %s. Falling back to %s/%s",
+ primary_exc, provider, model)
+ else:
+ logger.warning("Primary provider auth failed (%s). Falling back to %s/%s", primary_exc, provider, model)
return runtime, entry
raise primary_exc
diff --git a/tests/gateway/test_agent_cache.py b/tests/gateway/test_agent_cache.py
index 78977688373..21ec4c6c246 100644
--- a/tests/gateway/test_agent_cache.py
+++ b/tests/gateway/test_agent_cache.py
@@ -89,7 +89,7 @@ class TestAgentConfigSignature:
monkeypatch.setattr(
runtime_provider,
"resolve_runtime_provider",
- lambda: {
+ lambda **_kw: {
"api_key": "test-key",
"base_url": "https://trusted-proxy.example/v1",
"provider": "custom",
diff --git a/tests/gateway/test_custom_provider_request_overrides.py b/tests/gateway/test_custom_provider_request_overrides.py
index f052cdc8ffe..139b543f8c2 100644
--- a/tests/gateway/test_custom_provider_request_overrides.py
+++ b/tests/gateway/test_custom_provider_request_overrides.py
@@ -87,7 +87,7 @@ def _make_source() -> SessionSource:
def test_resolve_runtime_agent_kwargs_preserves_request_overrides(monkeypatch):
monkeypatch.setattr(
"hermes_cli.runtime_provider.resolve_runtime_provider",
- lambda: {
+ lambda **_kw: {
"api_key": "***",
"base_url": "https://example.test/v1",
"provider": "custom",
diff --git a/tests/gateway/test_runtime_provider_override_target_model.py b/tests/gateway/test_runtime_provider_override_target_model.py
index 078430084f7..d2478008635 100644
--- a/tests/gateway/test_runtime_provider_override_target_model.py
+++ b/tests/gateway/test_runtime_provider_override_target_model.py
@@ -27,11 +27,23 @@ def test_provider_override_runtime_uses_the_override_model(_zen_free_default_hom
def test_fallback_chain_runtime_uses_the_entry_model(_zen_free_default_home, monkeypatch):
+ """The gateway's AuthError fallback goes through the shared ``resolve_runtime_with_fallback``
+ walker (no gateway-private loop) and keeps the entry's own model."""
import gateway.run as gateway_run
+ import hermes_cli.runtime_provider as rp
+ from hermes_cli.auth import AuthError
+ real_resolve = rp.resolve_runtime_provider
+
+ def primary_auth_fails(**kw):
+ if kw.get("requested") is None: # the primary, resolved from config.yaml
+ raise AuthError("primary quota exhausted (429)")
+ return real_resolve(**kw)
+
+ monkeypatch.setattr(rp, "resolve_runtime_provider", primary_auth_fails)
monkeypatch.setattr(gateway_run, "_load_gateway_config",
lambda: {"fallback_model": [{"provider": "opencode-go", "model": "mimo-v2.5"}]})
- fb = gateway_run._try_resolve_fallback_provider()
- assert fb is not None
+ fb = gateway_run._resolve_runtime_agent_kwargs()
assert fb["model"] == "mimo-v2.5"
+ assert fb["provider"] == "opencode-go"
assert fb["base_url"] == "https://opencode.ai/zen/go/v1"
diff --git a/tests/hermes_cli/test_oneshot_fallback.py b/tests/hermes_cli/test_oneshot_fallback.py
index e55842429db..47ca0ed66c0 100644
--- a/tests/hermes_cli/test_oneshot_fallback.py
+++ b/tests/hermes_cli/test_oneshot_fallback.py
@@ -16,7 +16,7 @@ _CFG = {"fallback_providers": [
class TestResolveRuntimeWithFallback:
- def test_auth_error_walks_chain_in_order_and_re_raises_primary(self):
+ def test_auth_error_walks_chain_in_order_and_re_raises_primary(self, monkeypatch):
calls = []
def fake_resolve(**kw):
@@ -27,8 +27,8 @@ class TestResolveRuntimeWithFallback:
raise AuthError("anthropic key missing")
return {"provider": kw["requested"], "api_key": "k"}
- runtime, entry = resolve_runtime_with_fallback(_CFG, requested="openai-codex", target_model="gpt-5.4",
- resolve=fake_resolve)
+ monkeypatch.setattr("hermes_cli.runtime_provider.resolve_runtime_provider", fake_resolve)
+ runtime, entry = resolve_runtime_with_fallback(_CFG, requested="openai-codex", target_model="gpt-5.4")
assert (runtime["provider"], entry["model"]) == ("openai", "gpt-x")
# Chain walked in config order; the first entry got its inline api_key and its own model.
assert [c.get("requested") for c in calls] == ["openai-codex", "anthropic", "openai"]
@@ -37,16 +37,33 @@ class TestResolveRuntimeWithFallback:
def all_fail(**kw):
raise AuthError("primary down" if kw.get("requested") == "openai-codex" else "fallback down")
+ monkeypatch.setattr("hermes_cli.runtime_provider.resolve_runtime_provider", all_fail)
with pytest.raises(AuthError, match="primary down"): # primary-error precedence
- resolve_runtime_with_fallback(_CFG, requested="openai-codex", resolve=all_fail)
+ resolve_runtime_with_fallback(_CFG, requested="openai-codex")
- def test_misconfiguration_is_never_rerouted(self):
+ def test_misconfiguration_is_never_rerouted(self, monkeypatch, caplog):
def typo(**kw):
raise ValueError("Unknown provider 'antropic'")
+ monkeypatch.setattr("hermes_cli.runtime_provider.resolve_runtime_provider", typo)
with pytest.raises(ValueError):
- resolve_runtime_with_fallback(_CFG, requested="antropic", resolve=typo)
- assert resolve_runtime_with_fallback({}, resolve=lambda **kw: {"provider": "p"}) == ({"provider": "p"}, None)
+ resolve_runtime_with_fallback(_CFG, requested="antropic")
+ monkeypatch.setattr("hermes_cli.runtime_provider.resolve_runtime_provider", lambda **kw: {"provider": "p"})
+ assert resolve_runtime_with_fallback({}) == ({"provider": "p"}, None)
+
+ # A misconfigured *fallback* entry is skipped, but loudly: a typo must not vanish at debug level.
+ def primary_down_first_entry_typo(**kw):
+ if kw.get("requested") == "openai-codex":
+ raise AuthError("primary down")
+ if kw.get("requested") == "anthropic":
+ raise ValueError("Unknown provider")
+ return {"provider": kw["requested"]}
+
+ monkeypatch.setattr("hermes_cli.runtime_provider.resolve_runtime_provider", primary_down_first_entry_typo)
+ with caplog.at_level("WARNING", logger="hermes_cli.runtime_provider"):
+ _, entry = resolve_runtime_with_fallback(_CFG, requested="openai-codex")
+ assert entry["provider"] == "openai"
+ assert any("anthropic/claude-x is misconfigured" in r.getMessage() for r in caplog.records)
def test_run_agent_falls_back_when_primary_resolution_raises_auth_error(monkeypatch):