The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(auth): one primary_failure_wording() helper labels quota vs auth failure at all three fallback surfaces
teknium1265e68d7846e
diff --git a/cli.py b/cli.pyindex 7904b91f8b4..d2b6ac42263 100644--- a/cli.py+++ b/cli.py@@ -4636,9 +4636,7 @@ def _run_single_query_mode(cli, query, image, quiet, oneshot, stream_json: boolcli._print_exit_summary(clear_screen=False)# Same exit contract as `-Q`: scripts and the Kanban dispatcher read the outcome from# the exit code. This path used to fall through to an implicit 0 for every outcome.- exit_single_query(_single_query_exit_code(- cli._last_turn_result,- credentials_rate_limited=getattr(cli, "_credentials_rate_limited", False)))+ exit_single_query(_single_query_exit_code(cli._last_turn_result))finally:_finalize_single_query(cli)diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex 56a5a0102a8..507fd2cffde 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -431,6 +431,15 @@ def is_rate_limited_auth_error(error: Exception) -> bool:and error.code == CODEX_RATE_LIMITED_CODE)+def primary_failure_wording(error: Exception) -> tuple[str, str]:+ """``(log_phrase, user_phrase)`` for a primary-provider failure that triggers the fallback+ chain. A 429/quota AuthError leaves the credentials valid; labelling it "auth failed" sends+ operators hunting for an expired token (#117482), so it reads as quota at every surface."""+ if is_rate_limited_auth_error(error):+ return "rate-limited (429)", "Primary provider quota exhausted"+ return "auth failed", "Primary auth failed"++# Entitlement failures: Nous gets a Portal-aware message; other providers a fixed generic one (or# the raw error when no generic text exists for the code)._GENERIC_ENTITLEMENT_MESSAGES = {diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex 9f332f20548..c0159ecb7c2 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -360,7 +360,7 @@ class CLIAgentSetupMixin:order and switch the CLI's requested_provider/model to the first that resolves.None when the error is not auth-related or no fallback resolves."""from cli import _cprint, logger- from hermes_cli.auth import AuthError, is_rate_limited_auth_error+ from hermes_cli.auth import AuthError, primary_failure_wordingfrom hermes_cli.runtime_provider import resolve_runtime_providerif not isinstance(primary_exc, AuthError):return None@@ -381,12 +381,7 @@ class CLIAgentSetupMixin:if _fb_api_key:_fb_kwargs["explicit_api_key"] = _fb_api_keyruntime = resolve_runtime_provider(**_fb_kwargs)- # A 429/quota AuthError leaves the credentials valid; saying "auth failed" sends- # operators hunting for an expired token (#117482).- if is_rate_limited_auth_error(primary_exc):- _why_log, _why = "rate-limited (429)", "Primary provider quota exhausted"- else:- _why_log, _why = "auth failed", "Primary auth failed"+ _why_log, _why = primary_failure_wording(primary_exc) # #117482: quota is not authlogger.warning("Primary provider %s (%s). Falling through to fallback: %s/%s",_why_log, primary_exc, _fb_provider, _fb_model)diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.pyindex ab9b0908895..534f731f673 100644--- a/hermes_cli/runtime_provider.py+++ b/hermes_cli/runtime_provider.py@@ -1107,7 +1107,7 @@ def resolve_runtime_with_fallback(config: Optional[Dict[str, Any]], *, requestedre-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, is_rate_limited_auth_error+ from hermes_cli.auth import AuthError, primary_failure_wordingtry:return resolve_runtime_provider(requested=requested, target_model=target_model,explicit_base_url=explicit_base_url, explicit_api_key=explicit_api_key), None@@ -1136,10 +1136,7 @@ def resolve_runtime_with_fallback(config: Optional[Dict[str, Any]], *, requestedruntime["provider"] = effective_runtime_provider(entry, runtime)# 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)+ logger.warning("Primary provider %s (%s). Falling back to %s/%s",+ primary_failure_wording(primary_exc)[0], primary_exc, provider, model)return runtime, entryraise primary_excdiff --git a/tests/hermes_cli/test_cli_provider_resolution.py b/tests/hermes_cli/test_cli_provider_resolution.pyindex 3082180d9f4..270ccc2d176 100644--- a/tests/hermes_cli/test_cli_provider_resolution.py+++ b/tests/hermes_cli/test_cli_provider_resolution.py@@ -373,8 +373,14 @@ def _quota_auth_error():)-def test_fallback_runtime_quota_outage_is_not_labeled_auth_failure(monkeypatch, tmp_path):- """A 429 at credential resolution is quota, not bad credentials (#117482)."""[email protected](("exc_factory", "expected", "absent"), [+ (_quota_auth_error, "quota exhausted", "auth failed"),+ (lambda: __import__("hermes_cli.auth", fromlist=["AuthError"]).AuthError(+ "no key", provider="openai-codex", code="missing_api_key"), "Primary auth failed", "quota exhausted"),+])+def test_fallback_runtime_labels_quota_outage_and_bad_credentials_distinctly(monkeypatch, tmp_path, exc_factory, expected, absent):+ """A 429 at credential resolution is quota, not bad credentials (#117482); a real+ credential failure keeps the auth-failed wording."""from hermes_cli.cli_agent_setup_mixin import CLIAgentSetupMixinhome = tmp_path / "hermes"@@ -390,38 +396,12 @@ def test_fallback_runtime_quota_outage_is_not_labeled_auth_failure(monkeypatch,shell = CLIAgentSetupMixin.__new__(CLIAgentSetupMixin)shell._fallback_model = [{"provider": "custom", "model": "local-model"}]- runtime = shell._resolve_fallback_runtime(_quota_auth_error())+ runtime = shell._resolve_fallback_runtime(exc_factory())assert runtime is not Noneassert printed- assert "quota exhausted" in printed[-1]- assert "auth failed" not in printed[-1]---def test_fallback_runtime_keeps_auth_failed_wording_for_bad_credentials(monkeypatch, tmp_path):- from hermes_cli.auth import AuthError- from hermes_cli.cli_agent_setup_mixin import CLIAgentSetupMixin-- home = tmp_path / "hermes"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- printed = []- monkeypatch.setattr("cli._cprint", printed.append, raising=False)- monkeypatch.setattr(- "hermes_cli.runtime_provider.resolve_runtime_provider",- lambda **kw: {"provider": "custom", "base_url": "http://x/v1", "api_key": "k"},- )- monkeypatch.setattr("hermes_cli.fallback_config.resolve_entry_api_key", lambda entry: "k")-- shell = CLIAgentSetupMixin.__new__(CLIAgentSetupMixin)- shell._fallback_model = [{"provider": "custom", "model": "local-model"}]- runtime = shell._resolve_fallback_runtime(- AuthError("no key", provider="openai-codex", code="missing_api_key"))-- assert runtime is not None- assert printed- assert "Primary auth failed" in printed[-1]- assert "quota exhausted" not in printed[-1]+ assert expected in printed[-1]+ assert absent not in printed[-1]def test_ensure_runtime_credentials_records_quota_vs_bad_key(monkeypatch, tmp_path):diff --git a/tests/hermes_cli/test_single_query_exit_contract.py b/tests/hermes_cli/test_single_query_exit_contract.pyindex b681c611115..1566f025eac 100644--- a/tests/hermes_cli/test_single_query_exit_contract.py+++ b/tests/hermes_cli/test_single_query_exit_contract.py@@ -88,35 +88,10 @@ def test_a_plain_one_shot_run_reports_its_outcome(monkeypatch, turn_result, expeassert _run_non_quiet(monkeypatch, turn_result) == expected-def test_kanban_worker_quota_during_credential_resolution_is_tempfail_not_auth(monkeypatch):- """A 429 at startup never produces a turn result; the worker must still exit 75 (#117482)."""- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_abc123")- assert cli._single_query_exit_code(None, credentials_rate_limited=True) == KANBAN_RATE_LIMIT_EXIT_CODE- monkeypatch.delenv("HERMES_KANBAN_TASK")- assert cli._single_query_exit_code(None, credentials_rate_limited=True) == 1- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_abc123")- assert cli._single_query_exit_code(None, credentials_rate_limited=False) == 1---def test_quiet_kanban_worker_exits_tempfail_when_credentials_are_rate_limited(monkeypatch):- monkeypatch.setenv("HERMES_KANBAN_TASK", "t_abc123")- monkeypatch.setattr(cli, "_should_seed_interactive", lambda *a, **k: False)- monkeypatch.setattr(cli, "_collect_query_images", lambda q, i: (q, []))- monkeypatch.setattr(cli, "_collect_kanban_task_images", lambda imgs: [])- monkeypatch.setattr(cli, "_finalize_single_query", lambda c: None)- stub = SimpleNamespace(- _claim_active_session=lambda *a, **k: True,- _ensure_runtime_credentials=lambda: False,- _credentials_rate_limited=True,- session_id="s1",- model="gpt-x",- )- with pytest.raises(SystemExit) as exc:- cli._run_single_query_mode(stub, "do the thing", None, True, True)- assert exc.value.code == KANBAN_RATE_LIMIT_EXIT_CODE---def test_quiet_kanban_worker_still_exits_one_on_real_credential_failure(monkeypatch):[email protected](("rate_limited", "expected"), [(True, KANBAN_RATE_LIMIT_EXIT_CODE), (False, 1)])+def test_quiet_kanban_worker_exits_tempfail_when_credentials_are_rate_limited(monkeypatch, rate_limited, expected):+ """A 429 at startup never produces a turn result; the worker must still exit 75 (#117482).+ A real credential failure keeps exit 1."""monkeypatch.setenv("HERMES_KANBAN_TASK", "t_abc123")monkeypatch.setattr(cli, "_should_seed_interactive", lambda *a, **k: False)monkeypatch.setattr(cli, "_collect_query_images", lambda q, i: (q, []))@@ -125,10 +100,10 @@ def test_quiet_kanban_worker_still_exits_one_on_real_credential_failure(monkeypastub = SimpleNamespace(_claim_active_session=lambda *a, **k: True,_ensure_runtime_credentials=lambda: False,- _credentials_rate_limited=False,+ _credentials_rate_limited=rate_limited,session_id="s1",model="gpt-x",)with pytest.raises(SystemExit) as exc:cli._run_single_query_mode(stub, "do the thing", None, True, True)- assert exc.value.code == 1+ assert exc.value.code == expecteddiff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex 55017486a2f..27d0d7754ef 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -20419,6 +20419,28 @@ class TestResolveRuntimeWithFallback:assert resolution.selected_model == "deepseek-v4-pro"assert resolution.used_fallback is True+ def test_quota_auth_error_is_logged_as_rate_limited_not_auth_failed(self, monkeypatch, caplog):+ """#117482 sibling surface: a 429/quota AuthError on the primary reads as quota in the+ gateway's fallback log, never as an auth failure."""+ import logging++ from hermes_cli.auth import CODEX_RATE_LIMITED_CODE, AuthError++ def fake_resolve(**kwargs):+ if kwargs.get("requested") == "openai-codex":+ raise AuthError("quota exhausted (429)", provider="openai-codex",+ code=CODEX_RATE_LIMITED_CODE, relogin_required=False)+ return {"provider": "deepseek", "api_key": "fb-tok"}++ monkeypatch.setattr("hermes_cli.runtime_provider.resolve_runtime_provider", fake_resolve)+ monkeypatch.setattr(server, "_load_fallback_model",+ lambda: [{"provider": "deepseek", "model": "deepseek-v4-pro"}])+ with caplog.at_level(logging.WARNING, logger=server.__name__):+ resolution = server._resolve_runtime_with_fallback({"requested": "openai-codex"})+ assert resolution.used_fallback is True+ assert "Primary rate-limited (429)" in caplog.text+ assert "auth failed" not in caplog.text+def test_auth_error_skips_provider_only_fallback(self, monkeypatch):"""Auth fallback requires one complete provider/model pair."""from hermes_cli.auth import AuthErrordiff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 5c331331613..ee4607ca3fd 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -2259,8 +2259,10 @@ def _resolve_runtime_with_fallback(resolve_kwargs: dict | None = None) -> _Runti# Named custom entries resolve to the bare "custom" billing class; keep the configured# identity so the session/UI shows the provider name, matching the manual-switch path (#98739).runtime["provider"] = effective_runtime_provider(entry, runtime)+ from hermes_cli.auth import primary_failure_wordinglogging.getLogger(__name__).warning(- "Primary auth failed (%s), falling back to %s model %s", primary_exc, fb_provider, fb_model)+ "Primary %s (%s), falling back to %s model %s",+ primary_failure_wording(primary_exc)[0], primary_exc, fb_provider, fb_model)return _RuntimeFallbackResolution(runtime, fb_model, True)except Exception:continue