Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
Add codex model discovery and logging fixes
ehendrix23e0b863cb6d36
diff --git a/headroom/cli/proxy.py b/headroom/cli/proxy.pyindex f0c478adc..41872ca8b 100644--- a/headroom/cli/proxy.py+++ b/headroom/cli/proxy.py@@ -204,6 +204,13 @@ def _selected_context_tool() -> str:"Env: HEADROOM_ANTHROPIC_PRE_UPSTREAM_MEMORY_CONTEXT_TIMEOUT_SECONDS."),)+ "--log-level",+ type=click.Choice(["debug", "info", "warning", "error"], case_sensitive=False),+ default=None,+ envvar="HEADROOM_LOG_LEVEL",+ help="Set Headroom proxy file log level. Env: HEADROOM_LOG_LEVEL.",+)@click.option("--log-file", default=None, help="Path to JSONL log file")@click.option("--log-messages",@@ -454,6 +461,7 @@ def proxy(anthropic_pre_upstream_concurrency: int | None,anthropic_pre_upstream_acquire_timeout_seconds: float | None,anthropic_pre_upstream_memory_context_timeout_seconds: float | None,+ log_level: str | None,log_file: str | None,log_messages: bool,codex_wire_debug: bool,@@ -505,6 +513,9 @@ def proxy(OPENAI_BASE_URL=http://localhost:8787/v1 your-app"""# Import here to avoid slow startup+ if log_level:+ os.environ["HEADROOM_LOG_LEVEL"] = log_level.upper()+try:from headroom.proxy.server import ProxyConfig, run_serverexcept ImportError as e:diff --git a/headroom/providers/proxy_routes.py b/headroom/providers/proxy_routes.pyindex 96a006db6..228ea3e4d 100644--- a/headroom/providers/proxy_routes.py+++ b/headroom/providers/proxy_routes.py@@ -3,8 +3,12 @@from __future__ import annotations+import jsonimport logging-from typing import Any, cast+import os+import time+from typing import Any, TypedDict, cast+from urllib.parse import quotefrom fastapi import FastAPI, Request, WebSocketfrom fastapi.responses import Response@@ -13,6 +17,15 @@ from headroom.proxy.handlers.openai import _resolve_codex_routing_headerslogger = logging.getLogger("headroom.proxy.routes")+_CODEX_MODELS_CACHE: dict[tuple[str, str], tuple[float, tuple[str, ...]]] = {}+++class OpenAIModelItem(TypedDict):+ id: str+ object: str+ created: int+ owned_by: str+def _api_target(proxy: Any, provider_name: str) -> str:legacy_attrs = {@@ -51,8 +64,9 @@ def _select_passthrough_base_url(proxy: Any, headers: dict[str, str]) -> str:# bearer tokens (issue #478). Codex polls `/v1/models` every few seconds# to populate its model-picker UI, so the 403 storm is noisy and breaks# refresh. The fix: when Codex hits `/v1/models` under ChatGPT auth,-# synthesize an OpenAI-compatible response from the known-supported-# Codex/ChatGPT model set instead of forwarding to a 403.+# fetch the Codex-specific registry first and synthesize an+# OpenAI-compatible response from its slugs. If that registry is+# unavailable, fall back to the known-supported static set.## The list mirrors what Codex itself ships in its built-in model# registry (the same models its provider config exposes); it's the@@ -68,22 +82,44 @@ _CHATGPT_AUTH_CODEX_MODELS: tuple[str, ...] = ()-def _synthetic_models_list_response() -> Response:- """OpenAI-compatible `/v1/models` payload for Codex ChatGPT auth."""- import json+def _codex_client_version(requested_client_version: str | None = None) -> str:+ if requested_client_version:+ return requested_client_version+ return os.getenv("HEADROOM_CODEX_CLIENT_VERSION", "0.130.0")++def _codex_models_cache_ttl_seconds() -> float:+ raw_value = os.getenv("HEADROOM_CODEX_MODELS_CACHE_TTL_SECONDS", "300")+ try:+ return max(0.0, float(raw_value))+ except ValueError:+ logger.warning(+ "Invalid HEADROOM_CODEX_MODELS_CACHE_TTL_SECONDS=%r; disabling Codex models cache",+ raw_value,+ )+ return 0.0+++def _openai_model_item(model_id: str) -> OpenAIModelItem:+ return {+ "id": model_id,+ "object": "model",+ "created": 0,+ "owned_by": "openai",+ }+++def _models_list_response(model_ids: tuple[str, ...], *, source: str) -> Response:payload = {"object": "list",- "data": [- {- "id": model_id,- "object": "model",- "created": 0,- "owned_by": "openai",- }- for model_id in _CHATGPT_AUTH_CODEX_MODELS- ],+ "data": [_openai_model_item(model_id) for model_id in model_ids],}+ logger.debug(+ "Returning Codex model metadata response source=%s model_ids=%s payload=%s",+ source,+ list(model_ids),+ payload,+ )return Response(content=json.dumps(payload),status_code=200,@@ -91,10 +127,13 @@ def _synthetic_models_list_response() -> Response:)+def _synthetic_models_list_response() -> Response:+ """OpenAI-compatible `/v1/models` payload for Codex ChatGPT auth."""+ return _models_list_response(_CHATGPT_AUTH_CODEX_MODELS, source="static_fallback")++def _synthetic_model_get_response(model_id: str) -> Response:"""OpenAI-compatible `/v1/models/{id}` payload."""- import json-if model_id not in _CHATGPT_AUTH_CODEX_MODELS:return Response(content=json.dumps(@@ -109,16 +148,133 @@ def _synthetic_model_get_response(model_id: str) -> Response:status_code=404,headers={"content-type": "application/json"},)+ return Response(+ content=json.dumps(_openai_model_item(model_id)),+ status_code=200,+ headers={"content-type": "application/json"},+ )+++def _normalize_codex_registry_headers(headers: dict[str, str]) -> tuple[dict[str, str], str]:+ upstream_headers = dict(headers)+ upstream_headers.pop("host", None)+ account_id = (+ upstream_headers.get("chatgpt-account-id")+ or upstream_headers.get("ChatGPT-Account-ID")+ or ""+ )+ if account_id:+ upstream_headers["chatgpt-account-id"] = account_id+ upstream_headers.pop("ChatGPT-Account-ID", None)+ upstream_headers["accept"] = "application/json"+ upstream_headers.pop("Accept", None)+ return upstream_headers, account_id+++async def _fetch_chatgpt_codex_model_ids(+ proxy: Any,+ headers: dict[str, str],+ requested_client_version: str | None,+) -> tuple[str, ...] | None:+ client_version = _codex_client_version(requested_client_version)+ upstream_headers, account_id = _normalize_codex_registry_headers(headers)+ cache_key = (account_id, client_version)+ cache_ttl = _codex_models_cache_ttl_seconds()+ now = time.monotonic()+ cached = _CODEX_MODELS_CACHE.get(cache_key)+ if cached is not None:+ cached_at, cached_model_ids = cached+ if cache_ttl > 0 and now - cached_at < cache_ttl:+ logger.debug(+ "Using cached Codex model IDs from upstream model registry: %s",+ list(cached_model_ids),+ )+ return cached_model_ids+ _CODEX_MODELS_CACHE.pop(cache_key, None)++ url = (+ "https://chatgpt.com/backend-api/codex/models"+ f"?client_version={quote(client_version, safe='')}"+ )+ try:+ assert proxy.http_client is not None+ resp = await proxy.http_client.get(+ url,+ headers=upstream_headers,+ timeout=15.0,+ )+ if resp.status_code >= 400:+ logger.warning(+ "Codex model registry fetch failed: HTTP %s: %s",+ resp.status_code,+ resp.text[:300],+ )+ return None++ data = resp.json()+ models_raw = data.get("models") if isinstance(data, dict) else None+ if not isinstance(models_raw, list):+ logger.warning("Codex model registry response did not contain models[]")+ return None++ model_ids = tuple(+ slug+ for entry in models_raw+ if isinstance(entry, dict)+ for slug in (entry.get("slug"),)+ if isinstance(slug, str) and slug+ )+ if not model_ids:+ logger.warning("Codex model registry returned no model slugs")+ return None++ if cache_ttl > 0:+ _CODEX_MODELS_CACHE[cache_key] = (now, model_ids)+ logger.info("Fetched %d Codex models from upstream model registry", len(model_ids))+ logger.debug("Fetched Codex model IDs from upstream model registry: %s", list(model_ids))+ return model_ids+ except Exception:+ logger.exception("Codex model registry fetch failed")+ return None+++async def _fetch_chatgpt_codex_models_response(+ proxy: Any,+ headers: dict[str, str],+ requested_client_version: str | None,+) -> Response | None:+ model_ids = await _fetch_chatgpt_codex_model_ids(proxy, headers, requested_client_version)+ if model_ids is None:+ return None+ return _models_list_response(model_ids, source="upstream_registry")+++async def _fetch_chatgpt_codex_model_get_response(+ proxy: Any,+ headers: dict[str, str],+ model_id: str,+ requested_client_version: str | None,+) -> Response | None:+ model_ids = await _fetch_chatgpt_codex_model_ids(proxy, headers, requested_client_version)+ if model_ids is None:+ return None+ if model_id in model_ids:+ return Response(+ content=json.dumps(_openai_model_item(model_id)),+ status_code=200,+ headers={"content-type": "application/json"},+ )return Response(content=json.dumps({- "id": model_id,- "object": "model",- "created": 0,- "owned_by": "openai",+ "error": {+ "message": f"Model {model_id!r} not available under ChatGPT auth",+ "type": "invalid_request_error",+ "code": "model_not_found",+ }}),- status_code=200,+ status_code=404,headers={"content-type": "application/json"},)@@ -134,13 +290,28 @@ async def _handle_chatgpt_model_metadata(if not is_chatgpt_auth:return None- # Short-circuit `/backend-api/models[/{id}]` — chatgpt.com returns- # 403 here for OAuth tokens; synthesize a Codex-compatible response- # locally so the model-picker refresh succeeds (issue #478).+ # Avoid generic `/backend-api/models[/{id}]`, which returns 403 for+ # OAuth tokens, but prefer the Codex-specific registry when available.+ requested_client_version = request.query_params.get("client_version")if upstream_path == "/backend-api/models":+ upstream_response = await _fetch_chatgpt_codex_models_response(+ proxy,+ headers,+ requested_client_version,+ )+ if upstream_response is not None:+ return upstream_responsereturn _synthetic_models_list_response()if upstream_path.startswith("/backend-api/models/"):model_id = upstream_path[len("/backend-api/models/") :]+ upstream_response = await _fetch_chatgpt_codex_model_get_response(+ proxy,+ headers,+ model_id,+ requested_client_version,+ )+ if upstream_response is not None:+ return upstream_responsereturn _synthetic_model_get_response(model_id)url = f"https://chatgpt.com{upstream_path}"diff --git a/headroom/proxy/helpers.py b/headroom/proxy/helpers.pyindex 4b46e1323..aeb3c69e6 100644--- a/headroom/proxy/helpers.py+++ b/headroom/proxy/helpers.py@@ -910,6 +910,14 @@ def _headroom_log_dir() -> Path:return _paths.log_dir()+def _file_log_level() -> int:+ raw_level = os.environ.get("HEADROOM_LOG_LEVEL", "INFO").strip().upper()+ level = getattr(logging, raw_level, None)+ if isinstance(level, int):+ return level+ return logging.INFO++def _setup_file_logging() -> None:"""Add a RotatingFileHandler to the headroom root logger.@@ -929,7 +937,8 @@ def _setup_file_logging() -> None:backupCount=5,encoding="utf-8",)- handler.setLevel(logging.INFO)+ log_level = _file_log_level()+ handler.setLevel(log_level)handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))@@ -937,6 +946,7 @@ def _setup_file_logging() -> None:# Disable propagation to root to avoid duplicate writes when# wrap.py redirects stderr to the same log file.headroom_logger = logging.getLogger("headroom")+ headroom_logger.setLevel(log_level)if not any(isinstance(h, RotatingFileHandler) for h in headroom_logger.handlers):headroom_logger.addHandler(handler)headroom_logger.propagate = Falsediff --git a/tests/test_provider_proxy_routes.py b/tests/test_provider_proxy_routes.pyindex 23e2c0460..501faf9fe 100644--- a/tests/test_provider_proxy_routes.py+++ b/tests/test_provider_proxy_routes.py@@ -339,14 +339,126 @@ def test_gemini_batch_embed_contents_passthrough_uses_gemini_target(monkeypatch)]-def test_v1_models_returns_synthetic_list_under_chatgpt_auth() -> None:+def test_v1_models_fetches_codex_registry_under_chatgpt_auth(monkeypatch) -> None:+ monkeypatch.setenv("HEADROOM_CODEX_CLIENT_VERSION", "0.130.0")+ monkeypatch.setenv("HEADROOM_CODEX_MODELS_CACHE_TTL_SECONDS", "0")+ proxy_routes = importlib.import_module("headroom.providers.proxy_routes")+ debug_messages: list[tuple[str, tuple[object, ...]]] = []+ monkeypatch.setattr(+ proxy_routes.logger,+ "debug",+ lambda message, *args: debug_messages.append((message, args)),+ )++ class FakeAsyncClient:+ def __init__(self) -> None:+ self.calls: list[tuple[str, str, dict[str, str]]] = []++ async def get(self, url, **kwargs): # type: ignore[no-untyped-def]+ self.calls.append(("GET", url, dict(kwargs.get("headers", {}))))+ return httpx.Response(+ 200,+ json={+ "models": [+ {"slug": "gpt-5.5"},+ {"slug": "gpt-5.3-codex-spark"},+ ]+ },+ )++ async def aclose(self) -> None:+ return None++ with TestClient(_app()) as client:+ fake_http_client = FakeAsyncClient()+ client.app.state.proxy.http_client = fake_http_client+ response = client.get(+ "/v1/models?client_version=0.135.0",+ headers={+ "authorization": "Bearer eyJ-chatgpt-oauth-token",+ "chatgpt-account-id": "test-account",+ "originator": "Codex Desktop",+ },+ )++ assert response.status_code == 200+ payload = response.json()+ assert payload == {+ "object": "list",+ "data": [+ {+ "id": "gpt-5.5",+ "object": "model",+ "created": 0,+ "owned_by": "openai",+ },+ {+ "id": "gpt-5.3-codex-spark",+ "object": "model",+ "created": 0,+ "owned_by": "openai",+ },+ ],+ }+ assert len(fake_http_client.calls) == 1+ method, url, headers = fake_http_client.calls[0]+ assert method == "GET"+ assert url == "https://chatgpt.com/backend-api/codex/models?client_version=0.135.0"+ assert headers["authorization"] == "Bearer eyJ-chatgpt-oauth-token"+ assert headers["chatgpt-account-id"] == "test-account"+ assert headers["originator"] == "Codex Desktop"+ assert headers["accept"] == "application/json"+ assert "Accept" not in headers+ assert debug_messages == [+ (+ "Fetched Codex model IDs from upstream model registry: %s",+ (["gpt-5.5", "gpt-5.3-codex-spark"],),+ ),+ (+ "Returning Codex model metadata response source=%s model_ids=%s payload=%s",+ (+ "upstream_registry",+ ["gpt-5.5", "gpt-5.3-codex-spark"],+ {+ "object": "list",+ "data": [+ {+ "id": "gpt-5.5",+ "object": "model",+ "created": 0,+ "owned_by": "openai",+ },+ {+ "id": "gpt-5.3-codex-spark",+ "object": "model",+ "created": 0,+ "owned_by": "openai",+ },+ ],+ },+ ),+ ),+ ]+++def test_v1_models_falls_back_to_synthetic_list_under_chatgpt_auth(monkeypatch) -> None:"""Issue #478: under Codex ChatGPT-subscription OAuth, the proxymust NOT forward `/v1/models` to chatgpt.com/backend-api/models- (which returns 403). Synthesize an OpenAI-compatible response with- the known-supported Codex/ChatGPT model set instead, so Codex's- model-picker refresh succeeds.+ (which returns 403). If the Codex-specific registry also fails,+ synthesize an OpenAI-compatible response with the known-supported+ Codex/ChatGPT model set instead, so Codex's model-picker refresh succeeds."""+ monkeypatch.setenv("HEADROOM_CODEX_MODELS_CACHE_TTL_SECONDS", "0")++ class FakeAsyncClient:+ async def get(self, url, **kwargs): # type: ignore[no-untyped-def]+ return httpx.Response(403, json={"error": "forbidden"})++ async def aclose(self) -> None:+ return None+with TestClient(_app()) as client:+ client.app.state.proxy.http_client = FakeAsyncClient()# ChatGPT auth detected via Bearer + ChatGPT account header# (mirrors what Codex Desktop sends).response = client.get(@@ -370,13 +482,32 @@ def test_v1_models_returns_synthetic_list_under_chatgpt_auth() -> None:assert entry["owned_by"] == "openai"-def test_v1_models_get_single_synthetic_under_chatgpt_auth() -> None:+def test_v1_models_get_single_dynamic_under_chatgpt_auth(monkeypatch) -> None:"""The single-model variant (`/v1/models/{id}`) is also called by- Codex for some flows. Must return a synthetic OpenAI-compatible- payload for known models, 404 for unknown."""+ Codex for some flows. It should use the Codex registry first so+ dynamically exposed model slugs validate consistently."""+ monkeypatch.setenv("HEADROOM_CODEX_MODELS_CACHE_TTL_SECONDS", "300")+ importlib.import_module("headroom.providers.proxy_routes")._CODEX_MODELS_CACHE.clear()++ class FakeAsyncClient:+ def __init__(self) -> None:+ self.calls = 0++ async def get(self, url, **kwargs): # type: ignore[no-untyped-def]+ self.calls += 1+ return httpx.Response(+ 200,+ json={"models": [{"slug": "gpt-5.5"}, {"slug": "gpt-5.3-codex-spark"}]},+ )++ async def aclose(self) -> None:+ return None+with TestClient(_app()) as client:+ fake_http_client = FakeAsyncClient()+ client.app.state.proxy.http_client = fake_http_clientok = client.get(- "/v1/models/gpt-5.5",+ "/v1/models/gpt-5.3-codex-spark",headers={"authorization": "Bearer eyJ-chatgpt-oauth-token","chatgpt-account-id": "test-account",@@ -391,12 +522,13 @@ def test_v1_models_get_single_synthetic_under_chatgpt_auth() -> None:)assert ok.status_code == 200assert ok.json() == {- "id": "gpt-5.5",+ "id": "gpt-5.3-codex-spark","object": "model","created": 0,"owned_by": "openai",}assert unknown.status_code == 404+ assert fake_http_client.calls == 1def test_v1_models_still_forwards_under_non_chatgpt_auth() -> None:diff --git a/tests/test_proxy_codex_route_aliases.py b/tests/test_proxy_codex_route_aliases.pyindex d3d38dd7f..d5804aa90 100644--- a/tests/test_proxy_codex_route_aliases.py+++ b/tests/test_proxy_codex_route_aliases.py@@ -159,25 +159,26 @@ def test_codex_responses_subpath_passthrough_derives_chatgpt_routing_from_jwt(paassert headers["ChatGPT-Account-ID"] == "acct-from-jwt"-def test_codex_model_metadata_synthesises_response_for_chatgpt_auth():+def test_codex_model_metadata_fetches_codex_registry_for_chatgpt_auth(monkeypatch):"""Issue #478: under Codex ChatGPT-subscription OAuth, the proxymust NOT forward `/v1/models[/{id}]` to chatgpt.com/backend-api —- that endpoint returns 403 to OAuth tokens, breaking Codex's model- refresh. Headroom synthesises an OpenAI-compatible payload locally- so the picker UI populates correctly.-- The earlier version of this test asserted the buggy forward- behaviour; flipped here to lock the synthetic-response contract- so the bug can't return.+ that endpoint returns 403 to OAuth tokens. Instead, Headroom should+ fetch the Codex-specific model registry and synthesize an+ OpenAI-compatible payload from its slugs."""+ monkeypatch.setenv("HEADROOM_CODEX_CLIENT_VERSION", "0.130.0")+ monkeypatch.setenv("HEADROOM_CODEX_MODELS_CACHE_TTL_SECONDS", "0")class FakeAsyncClient:def __init__(self):self.calls: list[tuple[str, str, dict[str, str]]] = []- async def request(self, method, url, **kwargs): # type: ignore[no-untyped-def]- self.calls.append((method, url, dict(kwargs.get("headers", {}))))- return httpx.Response(200, json={"method": method, "url": url})+ async def get(self, url, **kwargs): # type: ignore[no-untyped-def]+ self.calls.append(("GET", url, dict(kwargs.get("headers", {}))))+ return httpx.Response(+ 200,+ json={"models": [{"slug": "gpt-5.5"}, {"slug": "gpt-5.3-codex-spark"}]},+ )async def aclose(self):return None@@ -204,14 +205,19 @@ def test_codex_model_metadata_synthesises_response_for_chatgpt_auth():headers={"Authorization": f"Bearer {token}"},)unknown_response = client.get(- "/v1/models/gpt-5.3-codex?client_version=0.130.0",+ "/v1/models/gpt-99-future?client_version=0.130.0",headers={"Authorization": f"Bearer {token}"},)- # No upstream call must be made — the response is synthesised locally.- assert fake_http_client.calls == [], (- f"Expected zero upstream calls; got {fake_http_client.calls}"- )+ assert len(fake_http_client.calls) == 3+ for method, url, headers in fake_http_client.calls:+ assert method == "GET"+ assert url == "https://chatgpt.com/backend-api/codex/models?client_version=0.130.0"+ assert headers["authorization"] == f"Bearer {token}"+ assert headers["chatgpt-account-id"] == "acct-from-jwt"+ assert headers["accept"] == "application/json"+ assert "ChatGPT-Account-ID" not in headers+ assert "Accept" not in headers# List endpoint returns a non-empty OpenAI-compatible list.assert list_response.status_code == 200@@ -219,7 +225,10 @@ def test_codex_model_metadata_synthesises_response_for_chatgpt_auth():assert list_payload["object"] == "list"assert isinstance(list_payload["data"], list)assert len(list_payload["data"]) > 0- assert "gpt-5.5" in {entry["id"] for entry in list_payload["data"]}+ assert {entry["id"] for entry in list_payload["data"]} == {+ "gpt-5.5",+ "gpt-5.3-codex-spark",+ }# Single-model GET returns a model object when known.assert known_response.status_code == 200@@ -231,6 +240,5 @@ def test_codex_model_metadata_synthesises_response_for_chatgpt_auth():"owned_by": "openai",}- # Unknown model variants 404 — the synthetic set is bounded to the- # ChatGPT-auth-supported list.+ # Unknown model variants 404 against the dynamic registry.assert unknown_response.status_code == 404