Skip to content

The agent that grows with you

fix(models): keep account-gated Codex rows when discovery falls back

FroRaut3fbace2e7640
diff --git a/hermes_cli/codex_models.py b/hermes_cli/codex_models.py
index a993cc84db4..c53f14cb768 100644
--- a/hermes_cli/codex_models.py
+++ b/hermes_cli/codex_models.py
@@ -10,6 +10,10 @@ from typing import List, Optional
logger = logging.getLogger(__name__)
+
+class CodexFallbackModels(list[str]):
+ """Compatibility hints after failed account discovery, not an account catalog."""
+
# Curated offline fallback (first-run, transient API failure). Only slugs the ChatGPT Codex
# OAuth backend actually accepts: the public API's "-pro" variants and the retired
# gpt-5.3-codex / gpt-5.2-codex / gpt-5.1-codex-max / gpt-5.1-codex-mini return HTTP 400 there
@@ -106,7 +110,8 @@ def codex_catalog_credential_identity() -> str:
"""Identity of the credential live discovery would use right now, for the catalog cache key.
Access/refresh tokens rotate in place while the account-scoped catalog stays authoritative for
- the same ChatGPT principal, so the key is ``(chatgpt_account_id, sub)``, not the token. An
+ the same ChatGPT principal and route, so the key includes the principal and resolved base URL,
+ not the rotating token. An
expired token is its own state: ``_codex_catalog`` serves the static fallback for it, and that
fallback must not outlive the refresh under the healthy principal's key. Opaque non-JWT tokens
fall back to the token itself (the caller hashes every part before anything is persisted).
@@ -114,17 +119,20 @@ def codex_catalog_credential_identity() -> str:
from hermes_cli.auth import _codex_access_token_is_expiring, resolve_codex_runtime_credentials
try:
- token = str(resolve_codex_runtime_credentials(read_only=True).get("api_key") or "")
+ creds = resolve_codex_runtime_credentials(read_only=True)
+ token = str(creds.get("api_key") or "")
+ from hermes_cli.auth_codex import _codex_base_url
+ route = str(creds.get("base_url") or _codex_base_url()).strip().rstrip("/")
except Exception: # AuthError (no/exhausted creds) or the pytest seat belt: no live catalog either way
token = ""
if not token:
return "missing"
if _codex_access_token_is_expiring(token, 0):
- return "expired"
+ return "expired\n" + route
from agent.credential_pool import _codex_principal_identity
principal = _codex_principal_identity(token)
- return "/".join(principal) if principal else token
+ return ("/".join(principal) if principal else token) + "\n" + route
def _ranked_slugs(entries: object) -> List[str]:
@@ -216,6 +224,6 @@ def get_codex_model_ids(access_token: Optional[str] = None, base_url: Optional[s
if api_models:
return _finalize_codex_models(api_models)
default_model = _read_default_model(codex_home)
- return _finalize_codex_models(_drop_undiscovered_astra(_dedupe([
+ return CodexFallbackModels(_finalize_codex_models(_drop_undiscovered_astra(_dedupe([
*([default_model] if default_model else []), *_read_cache_models(codex_home),
- *DEFAULT_CODEX_MODELS])))
+ *DEFAULT_CODEX_MODELS]))))
diff --git a/hermes_cli/models.py b/hermes_cli/models.py
index efe4d49f944..54d105b9def 100644
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@ -1320,7 +1320,7 @@ def _openai_discovery_base_url(provider: str) -> str:
def _codex_catalog(normalized: str, force_refresh: bool) -> list[str]:
- from hermes_cli.codex_models import get_codex_model_ids
+ from hermes_cli.codex_models import CodexFallbackModels, get_codex_model_ids
# Live OAuth token so the picker matches what ChatGPT lists for this account; hardcoded
# catalog without a token / when unreachable. Read-only (#68004): a picker never imports,
@@ -1338,7 +1338,10 @@ def _codex_catalog(normalized: str, force_refresh: bool) -> list[str]:
access_token = None
except Exception:
access_token = None
- return get_codex_model_ids(access_token=access_token, base_url=base_url)
+ models = get_codex_model_ids(access_token=access_token, base_url=base_url)
+ # Account-gated rows such as Astra are absent from the offline hints. Do not
+ # cache those hints as a successful account fetch or replace a verified row.
+ return CuratedFallbackModels(models) if isinstance(models, CodexFallbackModels) else models
_COPILOT_ACP_SESSION_MEMO_TTL = 300.0 # 5 min; SWR disk cache handles the rest
diff --git a/tests/hermes_cli/test_codex_models.py b/tests/hermes_cli/test_codex_models.py
index 244cb25c575..51d1cde546a 100644
--- a/tests/hermes_cli/test_codex_models.py
+++ b/tests/hermes_cli/test_codex_models.py
@@ -76,6 +76,32 @@ def test_picker_never_synthesizes_900k_for_pro_or_unknown_slugs():
assert "gpt-5.6-nova-900k" not in out
+def test_live_sol_minor_version_gets_adjacent_large_context_variant(monkeypatch):
+ from hermes_cli import codex_models
+ from agent.model_metadata import strip_codex_context_variant_suffix
+
+ monkeypatch.setattr(codex_models, "_fetch_models_from_api", lambda *_args, **_kw: ["gpt-6.1-sol"])
+ rows = codex_models.get_codex_model_ids(access_token="test-account")
+ assert rows.index("gpt-6.1-sol-900k") == rows.index("gpt-6.1-sol") + 1
+ assert strip_codex_context_variant_suffix("gpt-6.1-sol-900k") == "gpt-6.1-sol"
+
+
+def test_catalog_identity_stays_stable_for_rotation_but_changes_with_route(monkeypatch):
+ from hermes_cli import auth, codex_models
+ import agent.credential_pool as pool
+
+ credentials = {"api_key": "first-token", "base_url": "https://first.example/codex/"}
+ monkeypatch.setattr(auth, "resolve_codex_runtime_credentials", lambda **_: dict(credentials))
+ monkeypatch.setattr(auth, "_codex_access_token_is_expiring", lambda *_: False)
+ monkeypatch.setattr(pool, "_codex_principal_identity", lambda _: ("account", "subject"))
+ first = codex_models.codex_catalog_credential_identity()
+ credentials["api_key"] = "rotated-token"
+ credentials["base_url"] = "https://first.example/codex"
+ assert codex_models.codex_catalog_credential_identity() == first
+ credentials["base_url"] = "https://second.example/codex"
+ assert codex_models.codex_catalog_credential_identity() != first
+
+
diff --git a/tests/hermes_cli/test_model_cache_fallback_rows.py b/tests/hermes_cli/test_model_cache_fallback_rows.py
index c19133a6a51..a989711fd8b 100644
--- a/tests/hermes_cli/test_model_cache_fallback_rows.py
+++ b/tests/hermes_cli/test_model_cache_fallback_rows.py
@@ -80,3 +80,46 @@ def test_copilot_catalog_marks_the_static_list_as_fallback_on_a_failed_live_fetc
rows = mod.provider_model_ids(slug)
assert isinstance(rows, mod.CuratedFallbackModels), slug
assert rows == list(mod._PROVIDER_MODELS["copilot"])
+
+
+def test_codex_failed_discovery_retains_cache_without_advertising_stale_astra(monkeypatch, tmp_path):
+ from hermes_cli import auth, codex_models
+
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path))
+ monkeypatch.setattr(auth, "resolve_codex_runtime_credentials", lambda **_: {"api_key": "test-token"})
+ monkeypatch.setattr(auth, "_codex_access_token_is_expiring", lambda *_: False)
+ monkeypatch.setattr(codex_models, "_fetch_models_from_api", lambda *_args, **_kw: [])
+ stale_at = time.time() - 7200
+ cache = {"openai-codex": {"fp": "fp", "at": stale_at, "models": ["gpt-6-astra"]}}
+ with patch.object(mod, "_load_provider_models_cache", return_value=cache), \
+ patch.object(mod, "_credential_fingerprint", return_value="fp"), \
+ patch.object(mod, "_save_provider_models_cache") as save:
+ rows = mod.provider_model_ids("openai-codex", force_refresh=True)
+ assert isinstance(rows, mod.CuratedFallbackModels)
+ assert "gpt-6-astra" not in rows
+ # Retain the verified row for later recovery without advertising account-gated
+ # models after failed discovery or refreshing the row timestamp.
+ assert mod.cached_provider_model_ids("openai-codex", force_refresh=True) == []
+ assert cache["openai-codex"] == {"fp": "fp", "at": stale_at, "models": ["gpt-6-astra"]}
+ save.assert_not_called()
+
+
+def test_codex_cold_fallback_retries_after_short_ttl(monkeypatch, tmp_path):
+ from hermes_cli import auth, codex_models
+
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path))
+ monkeypatch.setattr(auth, "resolve_codex_runtime_credentials", lambda **_: {"api_key": "test-token"})
+ monkeypatch.setattr(auth, "_codex_access_token_is_expiring", lambda *_: False)
+ responses = iter([[], ["gpt-6-astra"]])
+ monkeypatch.setattr(codex_models, "_fetch_models_from_api", lambda *_args, **_kw: next(responses))
+ cache = {}
+ with patch.object(mod, "_load_provider_models_cache", return_value=cache), \
+ patch.object(mod, "_credential_fingerprint", return_value="fp"), \
+ patch.object(mod, "_save_provider_models_cache"), \
+ patch.object(mod, "_spawn_swr_refresh") as spawn:
+ mod.cached_provider_model_ids("openai-codex")
+ assert cache["openai-codex"]["fallback"] is True
+ cache["openai-codex"]["at"] = time.time() - mod._PROVIDER_MODELS_FALLBACK_TTL - 1
+ assert "gpt-6-astra" in mod.cached_provider_model_ids("openai-codex")
+ assert "fallback" not in cache["openai-codex"]
+ spawn.assert_not_called()