Skip to content

The agent that grows with you

fix(oneshot): consult the fallback chain at provider resolution time

Tranquil-Flowb1d49279998a
diff --git a/hermes_cli/oneshot.py b/hermes_cli/oneshot.py
index c024926e371..bc42dc5b49e 100644
--- a/hermes_cli/oneshot.py
+++ b/hermes_cli/oneshot.py
@@ -13,6 +13,7 @@ import logging
import os
import sys
from contextlib import redirect_stderr, redirect_stdout
+import dataclasses
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
@@ -511,7 +512,7 @@ def _run_agent(
``(final_response, run_result)``. Imports are local to keep CLI startup cheap. *ledger* (set when
``--usage-file`` is requested) attaches this run's auxiliary usage to the result."""
from hermes_cli.config import load_config
- from hermes_cli.runtime_provider import resolve_runtime_provider
+ from hermes_cli.runtime_provider import resolve_runtime_with_fallback
from hermes_cli.tools_config import _get_platform_tools
from run_agent import AIAgent
@@ -523,12 +524,19 @@ def _run_agent(
session_db = _create_session_db_for_oneshot()
resume_sid, conversation_history, resume_meta = _load_resume_target(session_db, resume)
choice = _apply_stored_session_runtime(choice, resume_meta, explicit_model=bool((model or "").strip()))
- runtime = resolve_runtime_provider(
+ # Resolution-time fallback (#81209): a quota-exhausted/expired primary raises AuthError here, before
+ # AIAgent (and its mid-session ``fallback_model`` wiring) exists, so walk the chain like the gateway.
+ runtime, fallback_entry = resolve_runtime_with_fallback(
+ cfg,
requested=choice.provider,
target_model=choice.model or None,
explicit_base_url=choice.base_url,
explicit_api_key=choice.api_key,
)
+ if fallback_entry is not None:
+ # The chosen entry names the model that will be sent; the primary's stored api_mode no longer applies.
+ choice = dataclasses.replace(choice, model=fallback_entry["model"], provider=runtime.get("provider"),
+ api_mode=None)
if choice.api_mode:
runtime["api_mode"] = choice.api_mode
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.py
index 68da8dec168..1a5aadcbc3c 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -1008,3 +1008,46 @@ def __getattr__(name): # PEP 562 — lazy so no import cycles
warn_once(__name__, name, *target)
return getattr(importlib.import_module(target[0]), target[1])
# ---- END PLUGIN-COMPAT ----
+
+
+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]]]:
+ """``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.
+ """
+ from hermes_cli.auth import AuthError
+ resolve = resolve or resolve_runtime_provider
+ try:
+ return resolve(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):
+ provider = (entry.get("provider") or "").strip().lower()
+ model = (entry.get("model") or "").strip()
+ if not provider or not model:
+ continue
+ kwargs: Dict[str, Any] = {"requested": provider, "target_model": model}
+ if entry.get("base_url"):
+ kwargs["explicit_base_url"] = entry["base_url"]
+ if entry_key := resolve_entry_api_key(entry):
+ kwargs["explicit_api_key"] = entry_key
+ try:
+ runtime = resolve(**kwargs)
+ except Exception as fb_exc:
+ logger.debug("Fallback entry %s/%s failed: %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)
+ return runtime, entry
+ raise primary_exc
diff --git a/tests/hermes_cli/test_oneshot_fallback.py b/tests/hermes_cli/test_oneshot_fallback.py
new file mode 100644
index 00000000000..e55842429db
--- /dev/null
+++ b/tests/hermes_cli/test_oneshot_fallback.py
@@ -0,0 +1,89 @@
+"""#81209: ``hermes -z`` must consult the fallback chain at *resolution* time.
+
+A quota-exhausted / expired primary raises ``AuthError`` from ``resolve_runtime_provider`` before
+``AIAgent`` exists, so the mid-session ``fallback_model`` wiring never gets a chance. The shared
+``resolve_runtime_with_fallback`` helper gives oneshot the gateway's resolution-time behaviour."""
+
+import pytest
+
+from hermes_cli.auth import AuthError
+from hermes_cli.runtime_provider import resolve_runtime_with_fallback
+
+_CFG = {"fallback_providers": [
+ {"provider": "anthropic", "model": "claude-x", "api_key": "fb-key"},
+ {"provider": "openai", "model": "gpt-x"},
+]}
+
+
+class TestResolveRuntimeWithFallback:
+ def test_auth_error_walks_chain_in_order_and_re_raises_primary(self):
+ calls = []
+
+ def fake_resolve(**kw):
+ calls.append(kw)
+ if kw.get("requested") == "openai-codex":
+ raise AuthError("Codex provider quota exhausted (429); retry after 39750s.")
+ if kw.get("requested") == "anthropic":
+ 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)
+ 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"]
+ assert calls[1]["explicit_api_key"] == "fb-key" and calls[1]["target_model"] == "claude-x"
+
+ def all_fail(**kw):
+ raise AuthError("primary down" if kw.get("requested") == "openai-codex" else "fallback down")
+
+ with pytest.raises(AuthError, match="primary down"): # primary-error precedence
+ resolve_runtime_with_fallback(_CFG, requested="openai-codex", resolve=all_fail)
+
+ def test_misconfiguration_is_never_rerouted(self):
+ def typo(**kw):
+ raise ValueError("Unknown provider 'antropic'")
+
+ 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)
+
+
+def test_run_agent_falls_back_when_primary_resolution_raises_auth_error(monkeypatch):
+ """End-to-end: ``_run_agent`` builds AIAgent against the fallback entry's provider/model (#81209)."""
+ import hermes_cli.oneshot as oneshot_mod
+
+ captured = {}
+
+ class _FakeAgent:
+ def __init__(self, **kwargs):
+ captured.update(kwargs)
+
+ def __setattr__(self, name, _value):
+ pass
+
+ def run_conversation(self, _prompt, conversation_history=None):
+ return {"final_response": "pong", "session_id": "s"}
+
+ def close(self):
+ pass
+
+ def fake_resolve(**kw):
+ # A config-sourced model resolves with requested=None: the ladder reads model.provider itself.
+ if kw.get("requested") in (None, "openai-codex"):
+ raise AuthError("Codex provider quota exhausted (429); retry after 39750s. Credentials are still valid.")
+ return {"api_key": "fb", "base_url": None, "provider": kw["requested"], "api_mode": "chat", "credential_pool": None}
+
+ cfg = {"model": {"default": "gpt-5.4", "provider": "openai-codex"}, **_CFG}
+ monkeypatch.setattr(oneshot_mod, "_create_session_db_for_oneshot", lambda: None)
+ monkeypatch.setattr("hermes_cli.config.load_config", lambda: cfg)
+ monkeypatch.setattr("hermes_cli.runtime_provider.resolve_runtime_provider", fake_resolve)
+ monkeypatch.setattr("hermes_cli.tools_config._get_platform_tools", lambda _cfg, _p: [])
+ monkeypatch.setattr("hermes_cli.mcp_startup.ensure_mcp_discovery_before_agent_build", lambda **_kw: None)
+ monkeypatch.setattr("run_agent.AIAgent", _FakeAgent)
+
+ text, _ = oneshot_mod._run_agent("Health check: reply pong.")
+
+ assert text == "pong"
+ assert (captured["provider"], captured["model"]) == ("anthropic", "claude-x")
+ assert captured["api_key"] == "fb"
diff --git a/website/docs/user-guide/features/fallback-providers.md b/website/docs/user-guide/features/fallback-providers.md
index d8cf8f73af8..5e3a92210d3 100644
--- a/website/docs/user-guide/features/fallback-providers.md
+++ b/website/docs/user-guide/features/fallback-providers.md
@@ -186,7 +186,7 @@ fallback_providers:
| Context | Fallback Supported |
|---------|-------------------|
-| CLI sessions | ✔ |
+| CLI sessions (interactive and `hermes -z` one-shot) | ✔ (at startup when the primary's credentials/quota fail, and mid-session) |
| Messaging gateway (Telegram, Discord, etc.) | ✔ |
| Subagent delegation | ✔ (`delegation.fallback_providers` when set; otherwise only unpinned children inherit the parent chain; `[]` disables) |
| Cron jobs | ✔ (cron agents inherit configured fallback providers) |