The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: keep the Codex catalog fetch shape while capping -900k at max_context_window
teknium1a585ad83b27f
diff --git a/agent/model_metadata.py b/agent/model_metadata.pyindex 3a8a3c22251..b4e10b7d559 100644--- a/agent/model_metadata.py+++ b/agent/model_metadata.py@@ -1708,7 +1708,10 @@ def _verified_codex_ctx_for_slug(model_bare: str) -> Optional[int]:return next((ctx for key, ctx in _CODEX_OAUTH_VERIFIED_ABOVE_ADVERTISED_PREFIXES.items() if base == key or base.startswith((key + "-", key + "."))), None)-_codex_oauth_context_cache: Dict[str, Tuple[Dict[str, int], Dict[str, int], float]] = {}+_codex_oauth_context_cache: Dict[str, Tuple[Dict[str, int], float]] = {}+# ``{slug: max_context_window}`` from the same fetch, keyed by the same token fingerprint. Only the+# opted-in ``-900k`` bump reads it (#105443); a catalog without the field leaves the entry empty.+_codex_oauth_max_context_cache: Dict[str, Dict[str, int]] = {}_CODEX_OAUTH_CONTEXT_CACHE_TTL = 3600 # 1 hour# The Codex models endpoint reads ``client_version`` as a Codex CLI compatibility version and# hides models whose ``minimal_client_version`` is newer, so a made-up version (the old@@ -1737,16 +1740,16 @@ def _extract_chatgpt_account_id(access_token: str) -> Optional[str]:return None-def _fetch_codex_oauth_context_lengths_with_source(access_token: str) -> Tuple[Dict[str, int], Dict[str, int], bool]:- """Codex catalogue ``{slug: context_window}`` and ``{slug: max_context_window}`` plus whether it- came from HTTP. Cached per token fingerprint (windows vary by entitlement; the ``v2:`` key prefix- versions the cache shape so pre-max entries are never misread). An in-process hit reports False:- not a fresh provider confirmation, must not drive persistent writes."""+def _fetch_codex_oauth_context_lengths_with_source(access_token: str) -> Tuple[Dict[str, int], bool]:+ """Codex catalogue ``{slug: context_window}`` plus whether it came from HTTP. Cached per token+ fingerprint (windows vary by entitlement); ``max_context_window`` lands in+ ``_codex_oauth_max_context_cache`` under the same key. An in-process hit reports False: not a+ fresh provider confirmation, must not drive persistent writes."""now = time.time()- cache_key = "v2:" + _codex_oauth_token_fingerprint(access_token)+ cache_key = _codex_oauth_token_fingerprint(access_token)cached = _codex_oauth_context_cache.get(cache_key)- if cached is not None and now - cached[2] < _CODEX_OAUTH_CONTEXT_CACHE_TTL:- return cached[0], cached[1], False+ if cached is not None and now - cached[1] < _CODEX_OAUTH_CONTEXT_CACHE_TTL:+ return cached[0], Falseheaders = {"Authorization": f"Bearer {access_token}"}acct_id = _extract_chatgpt_account_id(access_token)if acct_id:@@ -1756,28 +1759,23 @@ def _fetch_codex_oauth_context_lengths_with_source(access_token: str) -> Tuple[Dresp = requests.get(CODEX_MODELS_CATALOG_URL, headers=headers, timeout=(5, 10), verify=_resolve_requests_verify())if resp.status_code != 200:logger.debug("Codex /models probe returned HTTP %s; falling back to hardcoded defaults", resp.status_code)- return {}, {}, False+ return {}, Falsedata = resp.json()except Exception as exc:logger.debug("Codex /models probe failed: %s", exc)- return {}, {}, False+ return {}, Falseresult: Dict[str, int] = {}max_result: Dict[str, int] = {}for item in data.get("models", []) if isinstance(data, dict) else []:- if not isinstance(item, dict):- continue- slug = item.get("slug")- if not isinstance(slug, str):- continue- ctx = item.get("context_window")- if isinstance(ctx, int) and ctx > 0:+ slug, ctx, max_ctx = (item.get("slug"), item.get("context_window"), item.get("max_context_window")) if isinstance(item, dict) else (None, None, None)+ if isinstance(slug, str) and isinstance(ctx, int) and ctx > 0:result[slug.strip()] = ctx- max_ctx = item.get("max_context_window")- if isinstance(max_ctx, int) and max_ctx > 0:- max_result[slug.strip()] = max_ctx+ if isinstance(max_ctx, int) and max_ctx > 0:+ max_result[slug.strip()] = max_ctxif result:- _codex_oauth_context_cache[cache_key] = (result, max_result, now)- return result, max_result, True+ _codex_oauth_context_cache[cache_key] = (result, now)+ _codex_oauth_max_context_cache[cache_key] = max_result+ return result, Truedef _resolve_codex_oauth_context_length_with_source(model: str, access_token: str = "") -> Tuple[Optional[int], str]:@@ -1787,10 +1785,12 @@ def _resolve_codex_oauth_context_length_with_source(model: str, access_token: stmodel_bare = _strip_provider_prefix(model).strip()if not model_bare:return None, ""- def _apply_verified_bump(ctx: int, source: str) -> Tuple[int, str]:- """Lift an EXACT stale 272K advertisement to the verified cap for opted-in ``-900k`` variants only."""+ def _apply_verified_bump(ctx: int, source: str, catalog_max: Optional[int] = None) -> Tuple[int, str]:+ """Lift an EXACT stale 272K advertisement to the verified cap for opted-in ``-900k`` variants only,+ never above the catalog's own ``max_context_window`` when it publishes one (#105443)."""bumped = _verified_codex_ctx_for_slug(model_bare)if bumped is not None and ctx == _CODEX_OAUTH_STALE_ADVERTISED_CTX:+ bumped = min(bumped, catalog_max) if catalog_max else bumpedlogger.debug("Codex OAuth context for %s: advertised %d raised to live-verified %d", model_bare, ctx, bumped)return bumped, sourcereturn ctx, source@@ -1801,21 +1801,12 @@ def _resolve_codex_oauth_context_length_with_source(model: str, access_token: st# (#92797 review).lookup_bare = _bare_codex_slug(strip_codex_context_variant_suffix(model_bare))if access_token:- live, live_max, fresh_probe = _fetch_codex_oauth_context_lengths_with_source(access_token)+ live, fresh_probe = _fetch_codex_oauth_context_lengths_with_source(access_token)+ live_max = _codex_oauth_max_context_cache.get(_codex_oauth_token_fingerprint(access_token), {})# Exact slug, then case-insensitive in case casing drifts.- hit = live.get(lookup_bare)- if hit is None:- hit = next((ctx for slug, ctx in live.items() if slug.lower() == lookup_bare.lower()), None)- if hit is not None:- ctx, source = _apply_verified_bump(hit, "live" if fresh_probe else "memory")- if ctx != hit:- # Opted-in ``-900k`` variant: never claim more than the authenticated catalogue- # maximum. ``max_context_window`` can sit below the hardcoded live-verified cap- # (e.g. 872K vs 900K, #105443); the hardcoded cap remains the offline fallback.- catalog_max = live_max.get(lookup_bare)- if catalog_max is not None and catalog_max < ctx:- ctx = catalog_max- return ctx, source+ slug = lookup_bare if lookup_bare in live else next((s for s in live if s.lower() == lookup_bare.lower()), None)+ if slug is not None:+ return _apply_verified_bump(live[slug], "live" if fresh_probe else "memory", live_max.get(slug))hit = _longest_key_match(_CODEX_OAUTH_CONTEXT_FALLBACK, lookup_bare.lower())return _apply_verified_bump(hit[1], "fallback") if hit else (None, "")diff --git a/tests/agent/test_model_metadata.py b/tests/agent/test_model_metadata.pyindex 6ec800feb19..e33479d0580 100644--- a/tests/agent/test_model_metadata.py+++ b/tests/agent/test_model_metadata.py@@ -663,73 +663,40 @@ class TestCodexOAuthContextLength:)assert ctx == advertised, f"advertised {advertised} must be trusted"- def test_opted_in_variant_capped_at_live_catalog_max(self):- """An explicit ``-900k`` opt-in may not claim more than the authenticated- catalogue ``max_context_window`` (gpt-5.6-sol advertises 272K context with a- 872K max, below the 900K live-verified cap) — #105443."""+ @pytest.mark.parametrize("catalog_max,expected", [(872_000, 872_000), (None, 900_000), (1_050_000, 900_000)])+ def test_opted_in_variant_capped_at_live_catalog_max(self, catalog_max, expected):+ """An explicit ``-900k`` opt-in resolves to min(900K, catalog ``max_context_window``):+ gpt-5.6 advertises 272K with an 872K max (#105443); a catalog without the field or one+ above the live-verified cap keeps 900K."""from agent.model_metadata import get_model_context_length+ item = {"slug": "gpt-5.6-luna", "context_window": 272_000}+ if catalog_max is not None:+ item["max_context_window"] = catalog_maxfake_response = MagicMock()fake_response.status_code = 200- fake_response.json.return_value = {- "models": [{- "slug": "gpt-5.6-sol",- "context_window": 272_000,- "max_context_window": 872_000,- }]- }- import agent.model_metadata as mm- mm._codex_oauth_context_cache = {}- with patch("agent.model_metadata.requests.get", return_value=fake_response), \- patch("agent.model_metadata.get_cached_context_length", return_value=None), \- patch("agent.model_metadata.save_context_length"):- ctx = get_model_context_length(- model="gpt-5.6-sol-900k",- base_url="https://chatgpt.com/backend-api/codex",- api_key="fake-token",- provider="openai-codex",- )- assert ctx == 872_000-- def test_opted_in_variant_keeps_verified_cap_when_catalog_omits_max(self):- """Without ``max_context_window`` in the catalogue the hardcoded- live-verified 900K cap still applies to opted-in variants."""- from agent.model_metadata import get_model_context_length-- fake_response = MagicMock()- fake_response.status_code = 200- fake_response.json.return_value = {- "models": [{"slug": "gpt-5.6-sol", "context_window": 272_000}]- }- import agent.model_metadata as mm- mm._codex_oauth_context_cache = {}+ fake_response.json.return_value = {"models": [item]}with patch("agent.model_metadata.requests.get", return_value=fake_response), \patch("agent.model_metadata.get_cached_context_length", return_value=None), \patch("agent.model_metadata.save_context_length"):ctx = get_model_context_length(- model="gpt-5.6-sol-900k",+ model="gpt-5.6-luna-900k",base_url="https://chatgpt.com/backend-api/codex",api_key="fake-token",provider="openai-codex",)- assert ctx == 900_000+ assert ctx == expecteddef test_base_slug_keeps_advertised_ctx_even_with_catalog_max(self):"""The catalogue max never leaks into the base slug: extended context is- opt-in via the ``-900k`` alias only."""+ opt-in via the ``-900k`` alias only (#105443)."""from agent.model_metadata import get_model_context_lengthfake_response = MagicMock()fake_response.status_code = 200fake_response.json.return_value = {- "models": [{- "slug": "gpt-5.6-sol",- "context_window": 272_000,- "max_context_window": 872_000,- }]+ "models": [{"slug": "gpt-5.6-sol", "context_window": 272_000, "max_context_window": 872_000}]}- import agent.model_metadata as mm- mm._codex_oauth_context_cache = {}with patch("agent.model_metadata.requests.get", return_value=fake_response), \patch("agent.model_metadata.get_cached_context_length", return_value=None), \patch("agent.model_metadata.save_context_length"):diff --git a/website/docs/developer-guide/context-compression-and-caching.md b/website/docs/developer-guide/context-compression-and-caching.mdindex 193d06a9f4b..86dc824dfd4 100644--- a/website/docs/developer-guide/context-compression-and-caching.md+++ b/website/docs/developer-guide/context-compression-and-caching.md@@ -365,7 +365,10 @@ To use the large window, pick the explicit `-900k` variant in `/model` (e.g.`gpt-5.4-900k`). These are Hermes-side aliases: the suffix is stripped beforethe model id is sent to the backend, and pricing/usage accounting treats themas the base model. Slugs that genuinely enforce 272K (gpt-5.5, gpt-5.4-mini)-have no `-900k` variant.+have no `-900k` variant. When the authenticated Codex catalog publishes a+`max_context_window` below 900K for the base slug (e.g. 872K), the `-900k`+variant resolves to that live maximum instead; 900K remains the offline+fallback and a published maximum above 900K does not raise it.Compaction thresholds follow the window: base slugs (272K) get the **85%autoraise** described above, while `-900k` variants keep your global