The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(models): keep Codex catalogs across token rotation
KCAYAAI4ae78e397968
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex 3473e436496..4e5043dd69b 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -528,7 +528,7 @@ def _load_global_auth_store() -> Dict[str, Any]:except Exception:passtry:- store = _load_auth_store(global_path)+ store = _load_auth_store(global_path, preserve_corrupt=False)except Exception:_global_auth_store_cache = Nonereturn {}@@ -658,7 +658,9 @@ def _empty_auth_store() -> Dict[str, Any]:return {"version": AUTH_STORE_VERSION, "providers": {}}-def _load_auth_store(auth_file: Optional[Path] = None) -> Dict[str, Any]:+def _load_auth_store(+ auth_file: Optional[Path] = None, *, preserve_corrupt: bool = True,+) -> Dict[str, Any]:auth_file = auth_file or _auth_file_path()if not auth_file.exists():return _empty_auth_store()@@ -677,18 +679,21 @@ def _load_auth_store(auth_file: Optional[Path] = None) -> Dict[str, Any]:# Genuine corruption: unparseable JSON or non-UTF-8 bytes. Preserve a copy, but never# advertise a backup that was not written.corrupt_path = auth_file.with_suffix(".json.corrupt")- try:- shutil.copy2(auth_file, corrupt_path)- preserved = True- except Exception:- preserved = False- logger.debug("auth: could not preserve a copy of the corrupt store at %s", corrupt_path,- exc_info=True)+ preserved = False+ if preserve_corrupt:+ try:+ shutil.copy2(auth_file, corrupt_path)+ preserved = True+ except Exception:+ logger.debug(+ "auth: could not preserve a copy of the corrupt store at %s",+ corrupt_path, exc_info=True)logger.warning(- "auth: failed to parse %s (%s), starting with empty store. %s %s",+ "auth: failed to parse %s (%s), starting with empty store.%s",auth_file, exc,- "Corrupt file preserved at" if preserved else "A copy could NOT be preserved at",- corrupt_path)+ (f" Corrupt file preserved at {corrupt_path}" if preserved else+ " Corrupt backup skipped for this read-only operation." if not preserve_corrupt else+ f" A copy could NOT be preserved at {corrupt_path}"))return _empty_auth_store()if isinstance(raw, dict) and (@@ -867,12 +872,16 @@ def is_runtime_provider_routable(provider_id: str) -> bool:return True-def read_credential_pool(provider_id: Optional[str] = None) -> Dict[str, Any]:+def read_credential_pool(+ provider_id: Optional[str] = None, *, preserve_corrupt: bool = True,+) -> Dict[str, Any]:"""Return the persisted credential pool, or one provider slice.In profile mode the global-root ``auth.json`` is a read-only fallback applied per provider ONLYwhen the profile has zero entries for it (``hermes auth add`` in the profile shadows global)."""- pool = _load_auth_store().get("credential_pool")+ store = (_load_auth_store() if preserve_corrupt else+ _load_auth_store(preserve_corrupt=False))+ pool = store.get("credential_pool")pool = pool if isinstance(pool, dict) else {}global_pool = _load_global_auth_store().get("credential_pool")global_pool = global_pool if isinstance(global_pool, dict) else {}diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.pyindex 2e0a13e6fae..d3f4e8a55d4 100644--- a/hermes_cli/auth_codex.py+++ b/hermes_cli/auth_codex.py@@ -10,15 +10,15 @@ so ``hermes_cli.auth.<name>`` patches still intercept (and no import cycle).from __future__ import annotations-import loggingimport hashlibimport json+import loggingimport osimport threadingimport timefrom contextlib import suppressfrom pathlib import Path-from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Tuple+from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Tuple, castfrom hermes_cli.auth_constants import (_decode_jwt_claims, AUTH_LOCK_TIMEOUT_SECONDS, AuthError,CODEX_ACCESS_TOKEN_REFRESH_SKEW_SECONDS, CODEX_OAUTH_CLIENT_ID, CODEX_OAUTH_TOKEN_URL,@@ -78,19 +78,26 @@ def _codex_runtime_result("source": source, "last_refresh": last_refresh, "auth_mode": "chatgpt"}-def _load_auth_store_maybe_locked(lock: bool) -> Dict[str, Any]:+def _load_auth_store_maybe_locked(+ lock: bool, *, preserve_corrupt: bool = True,+) -> Dict[str, Any]:"""Load the auth store, taking the cross-process lock unless the caller already holds it."""from hermes_cli.auth import _auth_store_lock, _load_auth_storeif lock:with _auth_store_lock():- return _load_auth_store()- return _load_auth_store()+ return (_load_auth_store() if preserve_corrupt else+ _load_auth_store(preserve_corrupt=False))+ return (_load_auth_store() if preserve_corrupt else+ _load_auth_store(preserve_corrupt=False))-def _read_codex_tokens(*, _lock: bool = True) -> Dict[str, Any]:+def _read_codex_tokens(+ *, _lock: bool = True, _preserve_corrupt: bool = True,+) -> Dict[str, Any]:"""Read Codex OAuth tokens from Hermes auth store (~/.hermes/auth.json)."""from hermes_cli.auth import _load_provider_state, _nonempty_str- auth_store = _load_auth_store_maybe_locked(_lock)+ auth_store = _load_auth_store_maybe_locked(+ _lock, preserve_corrupt=_preserve_corrupt)state = _load_provider_state(auth_store, "openai-codex")if not state:raise _codex_err(_NO_CREDENTIALS_MSG.format(relogin=_codex_relogin_command()),@@ -578,7 +585,7 @@ def resolve_codex_runtime_credentials(# A read-only report takes no store lock: ``_save_auth_store`` replaces auth.json# atomically, and materialising ``auth.lock`` is itself a write a diagnostic must not# make. No recovery follows a read-only read, so no observed token is needed.- data = _read_codex_tokens(_lock=False)+ data = _read_codex_tokens(_lock=False, _preserve_corrupt=False)else:with _auth_store_lock():# Observe the singleton in the same locked snapshot the read validates, so recovery@@ -597,7 +604,7 @@ def resolve_codex_runtime_credentials(if imported:data = {"tokens": imported, "last_refresh": imported.get("last_refresh")}if data is None:- pool_token = _pool_codex_access_token()+ pool_token = _pool_codex_access_token(preserve_corrupt=not read_only)if pool_token and force_refresh and not read_only:# Pool-only setup: a forced refresh must rotate the pool entry, not resend its token.from agent.credential_pool import load_pool@@ -605,12 +612,11 @@ def resolve_codex_runtime_credentials(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()+ pool_rate_limit = _codex_pool_rate_limit_status(preserve_corrupt=not read_only)if pool_rate_limit:- # Before surfacing the persisted cooldown, ask the usage endpoint whether the quota- # reset early (banked reset redeemed, plan upgraded): ``last_error_reset_at`` can be- # days in the future while the account is already usable again.- if _probe_codex_pool_entry_quota_restored(pool_rate_limit):+ # Before surfacing the persisted cooldown, the runtime may ask whether quota reset early.+ # Read-only callers must never refresh OAuth, query usage or rewrite cooldown state.+ if not read_only and _probe_codex_pool_entry_quota_restored(pool_rate_limit):logger.info("Codex quota restored upstream — clearing stale pool cooldown(s).")clear_codex_pool_quota_cooldowns()pool_token = _pool_codex_access_token()@@ -841,7 +847,9 @@ def _codex_pool_dicts(entries: Optional[List[Any]]) -> Iterator[Dict[str, Any]]:yield entry-def _codex_pool_rate_limit_status() -> Optional[Dict[str, Any]]:+def _codex_pool_rate_limit_status(+ *, preserve_corrupt: bool = True,+) -> Optional[Dict[str, Any]]:"""Return metadata for a pool-only Codex credential in quota cooldown.Reads through ``read_credential_pool`` so a named profile with no Codex rows of its own sees@@ -850,7 +858,9 @@ def _codex_pool_rate_limit_status() -> Optional[Dict[str, Any]]:from agent.credential_pool import _parse_absolute_timestamptry:now = time.time()- for entry in _codex_pool_dicts(read_credential_pool("openai-codex")):+ entries = cast(List[Any], read_credential_pool(+ "openai-codex", preserve_corrupt=preserve_corrupt))+ for entry in _codex_pool_dicts(entries):token = entry.get("access_token")if not _nonempty_str(token) or not _entry_is_rate_limit_exhausted(entry):continue@@ -874,7 +884,7 @@ def _pool_entries(auth_store: Dict[str, Any], provider_id: str) -> Optional[Listreturn entries if isinstance(entries, list) else None-def _pool_codex_access_token() -> str:+def _pool_codex_access_token(*, preserve_corrupt: bool = True) -> str:"""First non-empty pool access_token not in an exhaustion cooldown window, else "".Fallback for ``resolve_codex_runtime_credentials`` when the singleton has no creds; reads@@ -883,7 +893,9 @@ def _pool_codex_access_token() -> str:from agent.credential_pool import _parse_absolute_timestampfrom hermes_cli.auth import _nonempty_str, read_credential_pooltry:- for entry in _codex_pool_dicts(read_credential_pool("openai-codex")):+ entries = cast(List[Any], read_credential_pool(+ "openai-codex", preserve_corrupt=preserve_corrupt))+ for entry in _codex_pool_dicts(entries):token = entry.get("access_token")# Same normaliser as ``_codex_pool_rate_limit_status``: a millisecond epoch compared# raw reads as far-future here and as elapsed there, hiding a usable entry (#103349).diff --git a/hermes_cli/codex_models.py b/hermes_cli/codex_models.pyindex e5d85602a71..4125dab0aaa 100644--- a/hermes_cli/codex_models.py+++ b/hermes_cli/codex_models.py@@ -2,6 +2,7 @@from __future__ import annotations+import hashlibimport jsonimport loggingimport os@@ -98,6 +99,26 @@ def _drop_undiscovered_astra(model_ids: List[str]) -> List[str]:return [model for model in model_ids if not is_astra_model(model)]+def codex_catalog_credential_identity() -> str:+ """Stable, non-secret identity of the credential used for live discovery.++ OAuth access and refresh tokens rotate in place, while the account-scoped+ model catalog remains authoritative for the same ChatGPT principal. Unknown+ token formats fall back to a token digest so a credential replacement still+ invalidates the cache conservatively.+ """+ try:+ from agent.credential_pool import _codex_principal_identity+ from hermes_cli.auth import resolve_codex_runtime_credentials++ token = str(resolve_codex_runtime_credentials(read_only=True).get("api_key") or "")+ except Exception:+ return "missing"+ principal = _codex_principal_identity(token)+ basis = json.dumps(principal, separators=(",", ":")).encode() if principal else token.encode()+ return hashlib.blake2b(basis, digest_size=8).hexdigest() if basis else "missing"++def _ranked_slugs(entries: object) -> List[str]:"""Visible slugs from a Codex catalog ``models`` list, sorted by (priority, slug), deduped.diff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex b31397f6489..8a5574fada0 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -1712,9 +1712,12 @@ def _provider_models_cache_path() -> Path:def _credential_fingerprint(provider: str) -> str:- """Short hash of the credentials ``provider_model_ids(provider)`` would see right now: api-key /- base-url env vars from ``PROVIDER_REGISTRY`` plus the mtimes of ``auth.json`` and external- credential files (OAuth re-auth busts the cache without parsing every file shape)."""+ """Short hash of the credentials ``provider_model_ids(provider)`` would see right now.++ API-key providers include their configured values and credential-file mtimes. Codex uses the+ stable principal selected by its read-only resolver: routine token and pool-state writes must+ not discard an account-scoped catalog, while a real account switch must invalidate it.+ """import hashlibparts: list[str] = []@@ -1786,16 +1789,21 @@ def _credential_fingerprint(provider: str) -> str:except Exception:pass- try:- from hermes_constants import get_hermes_home- for rel in ("auth.json", "credentials.json"):- _mtime_part(rel, get_hermes_home() / rel)- except Exception:- pass- for rel in ("~/.codex/auth.json", "~/.claude/.credentials.json",- "~/.config/github-copilot/hosts.json", "~/.minimax/credentials.json"):- path = os.path.expanduser(rel)- _mtime_part(path, path)+ if provider == "openai-codex":+ from hermes_cli.codex_models import codex_catalog_credential_identity++ parts.append(f"codex_identity={codex_catalog_credential_identity()}")+ else:+ try:+ from hermes_constants import get_hermes_home+ for rel in ("auth.json", "credentials.json"):+ _mtime_part(rel, get_hermes_home() / rel)+ except Exception:+ pass+ for rel in ("~/.codex/auth.json", "~/.claude/.credentials.json",+ "~/.config/github-copilot/hosts.json", "~/.minimax/credentials.json"):+ path = os.path.expanduser(rel)+ _mtime_part(path, path)blob = "|".join(parts).encode("utf-8", errors="replace")# blake2b, not sha256: fingerprint only (collisions = a harmless cache miss), and CodeQL'sdiff --git a/tests/hermes_cli/test_global_auth_store_memo.py b/tests/hermes_cli/test_global_auth_store_memo.pyindex a8f062cfce3..4c853506fc0 100644--- a/tests/hermes_cli/test_global_auth_store_memo.py+++ b/tests/hermes_cli/test_global_auth_store_memo.py@@ -66,9 +66,9 @@ class TestLoadGlobalAuthStoreMemo:reads = {"n": 0}orig = auth_mod._load_auth_store- def counting_load(store_path=None):+ def counting_load(store_path=None, **kwargs):reads["n"] += 1- return orig(store_path)+ return orig(store_path, **kwargs)monkeypatch.setattr(auth_mod, "_load_auth_store", counting_load)@@ -90,9 +90,9 @@ class TestLoadGlobalAuthStoreMemo:reads = {"n": 0}orig = auth_mod._load_auth_store- def counting_load(store_path=None):+ def counting_load(store_path=None, **kwargs):reads["n"] += 1- return orig(store_path)+ return orig(store_path, **kwargs)monkeypatch.setattr(auth_mod, "_load_auth_store", counting_load)diff --git a/tests/hermes_cli/test_model_cache_swr.py b/tests/hermes_cli/test_model_cache_swr.pyindex bdeda9df86c..02cae1af684 100644--- a/tests/hermes_cli/test_model_cache_swr.py+++ b/tests/hermes_cli/test_model_cache_swr.py@@ -10,6 +10,9 @@ and refreshed off-thread for the next open.from __future__ import annotations+import base64+import json+import osimport timefrom unittest.mock import patch@@ -87,6 +90,64 @@ class TestProviderModelsSWR:assert out == ["new-key-models"]spawn.assert_not_called()+ def test_codex_token_rotation_keeps_account_gated_models_for_same_principal(+ self, tmp_path, monkeypatch,+ ):+ import hermes_cli.models as mod++ def jwt(account_id, subject, nonce):+ def segment(value):+ raw = json.dumps(value, separators=(",", ":")).encode()+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()++ claims = {+ "sub": subject,+ "nonce": nonce,+ "https://api.openai.com/auth": {"chatgpt_account_id": account_id},+ }+ return f"{segment({'alg': 'none'})}.{segment(claims)}.sig"++ auth_path = tmp_path / "auth.json"+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setenv("HOME", str(tmp_path))++ def write_auth(token, request_count, mtime_ns):+ auth_path.write_text(json.dumps({+ "version": 1,+ "credential_pool": {+ "openai-codex": [{+ "id": "primary",+ "access_token": token,+ "refresh_token": "refresh",+ "request_count": request_count,+ }],+ },+ }), encoding="utf-8")+ os.utime(auth_path, ns=(mtime_ns, mtime_ns))++ write_auth(jwt("account-a", "user-a", "first"), 0, 1_000_000_000)+ astra_models = ["gpt-6-astra", "gpt-6-astra-900k"]+ mod.update_provider_cache_entry("openai-codex", astra_models)++ # Routine OAuth rotation and pool counters rewrite auth.json, but the+ # account-scoped catalog is still authoritative for the same principal.+ write_auth(jwt("account-a", "user-a", "rotated"), 12, 2_000_000_000)+ with patch.object(mod, "_spawn_swr_refresh") as spawn:+ assert mod.cached_provider_model_ids("openai-codex", non_blocking=True) == astra_models+ spawn.assert_not_called()++ # Either principal component changing means a different entitlement boundary.+ write_auth(jwt("account-a", "user-b", "new-member"), 0, 3_000_000_000)+ with patch.object(mod, "_spawn_swr_refresh") as spawn:+ assert mod.cached_provider_model_ids("openai-codex", non_blocking=True) == []+ spawn.assert_called_once_with("openai-codex")++ mod.update_provider_cache_entry("openai-codex", astra_models)+ write_auth(jwt("account-b", "user-b", "new-account"), 0, 4_000_000_000)+ with patch.object(mod, "_spawn_swr_refresh") as spawn:+ assert mod.cached_provider_model_ids("openai-codex", non_blocking=True) == []+ spawn.assert_called_once_with("openai-codex")+def test_force_refresh_bypasses_swr(self):import hermes_cli.models as moddiff --git a/tests/hermes_cli/test_oauth_status_pool_observation.py b/tests/hermes_cli/test_oauth_status_pool_observation.pyindex c5fe46875ef..7686c6e200e 100644--- a/tests/hermes_cli/test_oauth_status_pool_observation.py+++ b/tests/hermes_cli/test_oauth_status_pool_observation.py@@ -13,6 +13,8 @@ import base64import jsonimport time+import pytest+from agent import credential_poolfrom agent.credential_pool import load_poolfrom hermes_cli.auth import AuthError, DEFAULT_CODEX_BASE_URL, get_codex_auth_status@@ -94,6 +96,62 @@ def test_status_snapshot_leaves_round_robin_order_and_counts_untouched(tmp_path,assert _persisted_pool(home) != before+def test_read_only_resolver_never_probes_or_mutates_an_exhausted_pool(tmp_path, monkeypatch):+ import hermes_cli.auth_codex as auth_codex+ from hermes_cli.auth import resolve_codex_runtime_credentials++ home, _ = _pool_only_codex_home(+ tmp_path, monkeypatch, access_tokens=[_jwt_with_exp(-3600)])+ payload = json.loads((home / "auth.json").read_text(encoding="utf-8"))+ entry = payload["credential_pool"]["openai-codex"][0]+ entry.update({+ "last_status": "exhausted",+ "last_error_code": 429,+ "last_error_reason": "usage_limit_reached",+ "last_error_reset_at": time.time() + 3600,+ })+ (home / "auth.json").write_text(json.dumps(payload), encoding="utf-8")+ before = (home / "auth.json").read_bytes()+ calls = []++ monkeypatch.setattr(+ auth_codex,+ "_probe_codex_pool_entry_quota_restored",+ lambda _entry: calls.append("probe") or True,+ )+ monkeypatch.setattr(+ auth_codex,+ "clear_codex_pool_quota_cooldowns",+ lambda: calls.append("clear") or 1,+ )++ with pytest.raises(AuthError):+ resolve_codex_runtime_credentials(read_only=True)++ assert calls == []+ assert (home / "auth.json").read_bytes() == before+ assert not (home / "auth.lock").exists()+++def test_read_only_resolver_does_not_back_up_a_malformed_auth_store(tmp_path, monkeypatch):+ from hermes_cli.auth import resolve_codex_runtime_credentials++ home = tmp_path / "home"+ home.mkdir()+ auth_path = home / "auth.json"+ malformed = b'{"credential_pool":'+ auth_path.write_bytes(malformed)+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / "missing-codex-home"))++ with pytest.raises(AuthError):+ resolve_codex_runtime_credentials(read_only=True)++ assert auth_path.read_bytes() == malformed+ assert not auth_path.with_suffix(".json.corrupt").exists()+ assert not (home / "auth.lock").exists()++def _singleton_only_codex_home(tmp_path, monkeypatch, *, tokens: dict, codex_cli_tokens: dict):"""HERMES_HOME whose Codex credentials are the ``providers.openai-codex`` singleton only, with avalid Codex CLI login sitting beside it in ``CODEX_HOME``."""