The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: exhausted OAuth credential pool reports the cooldown and reset time, not "no credentials"
teknium11710f8413db8
diff --git a/agent/auxiliary_unavailable.py b/agent/auxiliary_unavailable.pyindex f7cd93cef89..81b5759e47c 100644--- a/agent/auxiliary_unavailable.py+++ b/agent/auxiliary_unavailable.py@@ -10,6 +10,7 @@ name it, and warns ONCE per distinct message so operators see it without debug limport contextlibimport loggingimport threading+import timefrom typing import Optionallogger = logging.getLogger(__name__)@@ -51,14 +52,53 @@ def _sentence(text: object) -> str:return str(text).strip().rstrip(".") + "."+def pool_cooldown_message(provider_id: str) -> Optional[str]:+ """The "all N credentials … are cooling down" error when the provider's pool is fully benched.++ ``resolve_provider_client()`` returns ``None`` both when no credential exists and when every+ pool entry sits in a 429/quota cooldown, so the raise sites could only say "no credentials+ were found. Run hermes auth add …" — wrong on both counts for a valid OAuth grant that is+ merely rate-limited (#56810). Read the persisted pool state (no seeding, no writes) and name+ the cooldown and its reset time instead; ``None`` when the pool is empty or a credential is+ usable (the caller keeps the missing-credential diagnostic).+ """+ from agent.credential_pool import STATUS_DEAD, PooledCredential, _exhausted_until+ from hermes_cli.auth import read_credential_pool++ entries = []+ with contextlib.suppress(Exception):+ entries = [PooledCredential.from_dict(provider_id, e)+ for e in read_credential_pool(provider_id) if isinstance(e, dict)]+ live = [e for e in entries if e.last_status != STATUS_DEAD]+ if not live:+ return None+ now = time.time()+ resets = [until for e in live+ for until in (_exhausted_until(e, sole_credential=len(live) == 1),)+ if until is not None and until > now]+ if len(resets) != len(live):+ return None+ when = time.strftime("%Y-%m-%d %H:%M %Z", time.localtime(min(resets)))+ which = ("its only credential is" if len(live) == 1+ else f"all {len(live)} credentials are")+ return (f"Provider '{provider_id}' is set in config.yaml but {which} cooling down after a "+ f"rate limit / quota error (429); the next one resets at {when}. Wait for the reset, "+ f"add another credential with `hermes auth add {provider_id}`, or switch to a "+ "different provider with `hermes model`.")++def missing_provider_credentials_message(provider_id: str) -> str:"""The "Provider 'X' is set in config.yaml but …" error for an explicit provider with no credentials.The remedy comes from the registry, never from the provider id: ``f"{id.upper()}_API_KEY"``invents names nothing reads (alibaba → ALIBABA_API_KEY instead of DASHSCOPE_API_KEY, and theunsettable MINIMAX-OAUTH_API_KEY for OAuth ids, #114405 / #78996). OAuth providers have no key- env var at all, so they are pointed at the sign-in command instead.+ env var at all, so they are pointed at the sign-in command instead. A pool whose every+ credential is cooling down is not "missing" — that case names the cooldown (#56810)."""+ cooldown = pool_cooldown_message(provider_id)+ if cooldown:+ return cooldownpconfig = Nonewith contextlib.suppress(Exception):from hermes_cli.auth import PROVIDER_REGISTRYdiff --git a/tests/agent/test_missing_provider_credentials_hint.py b/tests/agent/test_missing_provider_credentials_hint.pyindex 26999d0c891..eb393e2c80d 100644--- a/tests/agent/test_missing_provider_credentials_hint.py+++ b/tests/agent/test_missing_provider_credentials_hint.py@@ -52,3 +52,68 @@ def test_main_init_shares_helper_and_no_registry_provider_gets_an_invented_env_vassert invented in pconfig.api_key_env_vars, (pid, message)if not pconfig.api_key_env_vars:assert "_API_KEY environment variable" not in message, (pid, message)+++def _write_exhausted_codex_pool(home, *, count: int, reset_at: float):+ """Persist a Codex OAuth pool the way ``mark_exhausted`` leaves it after a 429."""+ import json+ import time++ from agent.credential_pool import PooledCredential++ entries = [PooledCredential(+ provider="openai-codex", id=f"codex-{i}", label=f"acct{i}", auth_type="oauth", priority=i,+ source="manual", access_token=f"eyJ.fake.{i}", refresh_token="rt", last_status="exhausted",+ last_status_at=time.time() - 60, last_error_code=429, last_error_reason="usage_limit_reached",+ last_error_reset_at=reset_at).to_dict() for i in range(count)]+ (home / "auth.json").write_text(json.dumps({"version": 1, "credential_pool": {"openai-codex": entries}}))+++def test_exhausted_oauth_pool_reports_cooldown_not_missing_credentials(tmp_path, monkeypatch):+ """#56810: a valid OAuth grant in 429 cooldown is not "no credentials … hermes auth add".++ Both raise sites (main-agent init and the auxiliary ladder) render the pool state: how many+ credentials are benched and when the next one resets.+ """+ import time+ from types import SimpleNamespace++ from agent.agent_init import _routed_client_kwargs++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setenv("HOME", str(tmp_path)) # never adopt the host's Codex CLI tokens+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ reset_at = time.time() + 3 * 3600+ _write_exhausted_codex_pool(tmp_path, count=2, reset_at=reset_at)+ (tmp_path / "config.yaml").write_text(yaml.safe_dump({+ "model": {"provider": "openai-codex", "default": "test-model"},+ "auxiliary": {"compression": {"provider": "openai-codex", "model": "test-model"}},+ }), encoding="utf-8")+ expected_time = time.strftime("%Y-%m-%d %H:%M", time.localtime(reset_at))++ agent = SimpleNamespace(provider="openai-codex", model="test-model", base_url=None, api_key=None,+ _fallback_activated=False, _explicit_provider="openai-codex")+ with pytest.raises(RuntimeError) as excinfo:+ _routed_client_kwargs(agent, None, 60)+ message = str(excinfo.value)+ assert "all 2 credentials are cooling down" in message+ assert expected_time in message+ assert "no credentials were found" not in message++ from agent.auxiliary_client import call_llm+ from agent.auxiliary_unavailable import AuxiliaryClientUnavailable++ with pytest.raises(AuxiliaryClientUnavailable) as aux_exc:+ call_llm(task="compression", messages=[{"role": "user", "content": "hi"}], max_tokens=5)+ assert "cooling down" in str(aux_exc.value)+ assert "no credentials were found" not in str(aux_exc.value)+++def test_elapsed_cooldown_or_empty_pool_keeps_missing_credentials_text(tmp_path, monkeypatch):+ """Control: a pool whose cooldown already elapsed (or no pool at all) is not called "cooling down"."""+ import time++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ assert "cooling down" not in missing_provider_credentials_message("openai-codex")+ _write_exhausted_codex_pool(tmp_path, count=1, reset_at=time.time() - 60)+ assert "cooling down" not in missing_provider_credentials_message("openai-codex")