The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: refresh the credential that 401'd on the Codex /usage retry
teknium1417b707f5967
diff --git a/agent/account_usage.py b/agent/account_usage.pyindex 6ac88f09e84..2b7346c3e3d 100644--- a/agent/account_usage.py+++ b/agent/account_usage.py@@ -300,6 +300,19 @@ def _resolve_codex_usage_credentials(explicit_key = str(api_key or "").strip()if explicit_key and not force_refresh:return explicit_key, str(base_url or "").strip(), None+ if explicit_key:+ # Forced retry for a live agent's own credential: refresh THAT credential (singleton or the+ # pool entry that issued it), never re-resolve — that would render another pool account's usage.+ try:+ singleton_key = str((_read_codex_tokens().get("tokens") or {}).get("access_token", "") or "").strip()+ except AuthError:+ singleton_key = ""+ if singleton_key != explicit_key:+ from agent.credential_pool import load_pool+ entry = load_pool("openai-codex").try_refresh_matching(api_key_hint=explicit_key)+ if entry is None:+ raise RuntimeError("Could not refresh the Codex credential this session runs on")+ return entry.runtime_api_key, str(entry.runtime_base_url or base_url or "").strip(), None# Only AuthError is caught so tier 3 can run: a broad except would mask a transient refresh/network failure# and hand back a DIFFERENT pool account's usage; such errors must propagate to the fail-open outer guard.# account_id is best-effort: a partial singleton store must not sink a usable credential.@@ -507,9 +520,13 @@ def redeem_codex_reset_credit(except httpx.HTTPStatusError as exc:if exc.response.status_code != 401 or attempt > 0:raise- token, resolved_base_url, account_id = _resolve_codex_usage_credentials(- base_url, api_key, force_refresh=True,- )+ try:+ token, resolved_base_url, account_id = _resolve_codex_usage_credentials(+ base_url, api_key, force_refresh=True,+ )+ except Exception:+ # Refresh token dead too: the 401 hint (re-login) is the actionable message.+ raise exc from Noneexcept httpx.HTTPStatusError as exc:code = exc.response.status_codeif code in (401, 403):diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.pyindex 169ad6958f3..c3c360a4a9f 100644--- a/hermes_cli/auth_codex.py+++ b/hermes_cli/auth_codex.py@@ -470,6 +470,11 @@ def resolve_codex_runtime_credentials(data = {"tokens": imported, "last_refresh": imported.get("last_refresh")}if data is None:pool_token = _pool_codex_access_token()+ if pool_token and force_refresh:+ # Pool-only setup: a forced refresh must rotate the pool entry, not resend its token.+ from agent.credential_pool import load_pool+ refreshed = load_pool("openai-codex").try_refresh_matching(api_key_hint=pool_token)+ pool_token = refreshed.runtime_api_key if refreshed is not None else ""if pool_token:return _codex_runtime_result(pool_token, source="credential_pool", last_refresh=None)pool_rate_limit = _codex_pool_rate_limit_status()diff --git a/tests/agent/test_account_usage.py b/tests/agent/test_account_usage.pyindex d33ab57d099..8da478f8f35 100644--- a/tests/agent/test_account_usage.py+++ b/tests/agent/test_account_usage.py@@ -308,3 +308,40 @@ def test_redeem_missing_credentials_reports_unavailable(monkeypatch):assert result.status == "unavailable"assert "hermes auth" in result.message+++def test_codex_usage_401_retry_refreshes_the_explicit_credential_not_another_account(monkeypatch, codex_usage_payload):+ """A live agent on pool entry B hands its own api_key in; after a 401 the retry must refresh B,+ not re-resolve and render the singleton/pool account A's usage."""+ request_calls = []+ refresh_hints = []+ responses = [_FakeResponse({}, status_code=401), _FakeResponse(codex_usage_payload)]++ class Pool:+ def try_refresh_matching(self, api_key_hint=None, credential_id=None):+ refresh_hints.append(api_key_hint)+ return SimpleNamespace(runtime_api_key="pool-B-fresh", runtime_base_url=None)++ class Client:+ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False++ def get(self, url, headers):+ request_calls.append(headers["Authorization"])+ return responses.pop(0)++ monkeypatch.setattr(account_usage, "resolve_codex_runtime_credentials",+ lambda **kwargs: pytest.fail("must not re-resolve another account's credential"))+ monkeypatch.setattr(account_usage, "_read_codex_tokens", lambda: {"tokens": {"access_token": "singleton-A"}})+ monkeypatch.setattr("agent.credential_pool.load_pool", lambda provider: Pool())+ monkeypatch.setattr(account_usage.httpx, "Client", lambda timeout: Client())++ snapshot = account_usage.fetch_account_usage(+ "openai-codex", base_url="https://chatgpt.com/backend-api/codex", api_key="pool-B-revoked")++ assert snapshot is not None+ assert refresh_hints == ["pool-B-revoked"]+ assert request_calls == ["Bearer pool-B-revoked", "Bearer pool-B-fresh"]diff --git a/tests/hermes_cli/test_auth_codex_provider.py b/tests/hermes_cli/test_auth_codex_provider.pyindex c623c4de9c9..27cc91f1754 100644--- a/tests/hermes_cli/test_auth_codex_provider.py+++ b/tests/hermes_cli/test_auth_codex_provider.py@@ -611,3 +611,30 @@ def _patch_httpx_post(monkeypatch, responses):+++def test_pool_only_force_refresh_rotates_the_pool_entry(tmp_path, monkeypatch):+ """Pool-only setup (empty singleton): ``force_refresh`` must refresh the pool credential+ instead of handing back the same token the caller just got a 401 for."""+ hermes_home = tmp_path / "hermes"+ hermes_home.mkdir(parents=True, exist_ok=True)+ (hermes_home / "auth.json").write_text(json.dumps({+ "version": 1, "providers": {},+ "credential_pool": {"openai-codex": [{+ "source": "device_code", "access_token": "pool-revoked", "refresh_token": "pool-refresh",+ "last_status": "ok", "auth_type": "oauth"}]},+ }))+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ hints = []++ class Pool:+ def try_refresh_matching(self, api_key_hint=None, credential_id=None):+ hints.append(api_key_hint)+ return SimpleNamespace(runtime_api_key="pool-fresh")++ monkeypatch.setattr("agent.credential_pool.load_pool", lambda provider: Pool())++ resolved = resolve_codex_runtime_credentials(force_refresh=True)+ assert resolved["api_key"] == "pool-fresh"+ assert resolved["source"] == "credential_pool"+ assert hints == ["pool-revoked"]