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
fix(proxy): support Codex Live HTTP call creation (#3464)
Radhakrishnan Pachyappan53982aefb801
diff --git a/headroom/providers/codex/live.py b/headroom/providers/codex/live.pyindex 034d5c6a2..435873c53 100644--- a/headroom/providers/codex/live.py+++ b/headroom/providers/codex/live.py@@ -4,18 +4,25 @@ from __future__ import annotationsimport asyncioimport contextlib+import jsonimport loggingimport osfrom collections.abc import Mappingfrom typing import Any, cast-from fastapi import WebSocket+from fastapi import Request, WebSocket+from fastapi.responses import Responsefrom headroom.copilot_auth import apply_copilot_api_auth, build_copilot_upstream_url-from headroom.providers.codex.endpoints import codex_backend_ws_url+from headroom.providers.codex.endpoints import codex_backend_url, codex_backend_ws_url+from headroom.providers.codex.headers import drop_headerfrom headroom.providers.codex.runtime import resolve_codex_routingfrom headroom.proxy.handlers.openai import _is_allowed_websocket_origin-from headroom.proxy.helpers import _strip_internal_headers, merge_extra_headers+from headroom.proxy.helpers import (+ _strip_internal_headers,+ merge_extra_headers,+ sanitize_forwarded_response_headers,+)from headroom.proxy.ws_headers import WS_HOP_BY_HOP_HEADERSlogger = logging.getLogger("headroom.providers.codex.live")@@ -28,6 +35,7 @@ CODEX_LIVE_ROUTE_PATHS: tuple[str, ...] = ()CODEX_LIVE_WS_PATH_ENV = "HEADROOM_CODEX_LIVE_WS_PATH"DEFAULT_CODEX_LIVE_WS_PATH = "/live"+CODEX_LIVE_CALLS_QUERY = "intent=quicksilver&architecture=avas"def codex_live_ws_path() -> str:@@ -70,6 +78,63 @@ def _ensure_live_authorization(headers: Mapping[str, str]) -> dict[str, str]:return {**headers, "Authorization": f"Bearer {api_key}"}+async def handle_codex_live_http(+ request: Request,+ http_client: Any,+ openai_base_url: str,+ inbound_path: str,+) -> Response | None:+ """Forward ChatGPT Codex Live call creation over HTTP.++ Routing is resolved from headers alone, before the body is touched: a+ non-ChatGPT-authenticated request must return `None` with the inbound+ stream still unread, so the caller's generic passthrough fallback can+ read it. Consuming `request.form()` first would leave that fallback+ reading an already-drained stream (or, for a JSON body, wrongly reject+ it here instead of falling through).+ """+ upstream_headers = dict(request.headers.items())+ drop_header(upstream_headers, "host")+ drop_header(upstream_headers, "accept-encoding")+ drop_header(upstream_headers, "content-length")+ drop_header(upstream_headers, "content-type")+ upstream_headers = _strip_internal_headers(upstream_headers)+ decision = resolve_codex_routing(upstream_headers)+ if not decision.is_chatgpt_auth:+ return None++ form = await request.form()+ sdp = form.get("sdp")+ session = form.get("session")+ if not isinstance(sdp, str) or not isinstance(session, str):+ return Response(content="Missing sdp or session form field.", status_code=400)+ try:+ session_payload = json.loads(session)+ except json.JSONDecodeError:+ return Response(content="Invalid session JSON.", status_code=400)++ try:+ response = await http_client.request(+ "POST",+ codex_backend_url("/realtime/calls", CODEX_LIVE_CALLS_QUERY),+ headers=decision.headers,+ json={"sdp": sdp, "session": session_payload},+ timeout=120.0,+ )+ except Exception:+ logger.exception("Codex Live HTTP call creation failed path=%s", inbound_path)+ return Response(content="Upstream request failed.", status_code=502)+ return Response(+ content=response.content,+ status_code=response.status_code,+ # `response.content` is already decoded by httpx; replaying the+ # upstream's content-encoding/content-length onto it makes the+ # downstream client try to decompress plain bytes a second time.+ # `Location` (and everything else) survives untouched.+ headers=sanitize_forwarded_response_headers(response.headers),+ )++_NON_WIRE_CLOSE_CODES = {1004, 1005, 1006, 1015}diff --git a/headroom/providers/proxy_routes.py b/headroom/providers/proxy_routes.pyindex 5cf11ea47..f5e0b6c59 100644--- a/headroom/providers/proxy_routes.py+++ b/headroom/providers/proxy_routes.py@@ -14,6 +14,7 @@ from headroom.providers.codex.endpoints import codex_backend_urlfrom headroom.providers.codex.headers import drop_headerfrom headroom.providers.codex.live import (CODEX_LIVE_ROUTE_PATHS,+ handle_codex_live_http,handle_codex_live_websocket,)from headroom.providers.codex.responses import handle_chatgpt_codex_responses_subpath@@ -213,6 +214,25 @@ def _register_openai_responses_routes(app: FastAPI, proxy: Any) -> None:def _register_codex_live_routes(app: FastAPI, proxy: Any) -> None:for path in CODEX_LIVE_ROUTE_PATHS:+ async def codex_live_http(request: Request, route_path: str = path):+ response = await handle_codex_live_http(+ request,+ proxy.http_client,+ _api_target(proxy, "openai"),+ route_path,+ )+ if response is not None:+ return response+ return await proxy.handle_passthrough(+ request,+ _api_target(proxy, "openai"),+ route_path,+ "openai",+ )++ codex_live_http.__name__ = path.strip("/").replace("/", "_") + "_live_http"+ app.post(path)(codex_live_http)+def register_websocket_route(route_path: str) -> None:async def codex_live_websocket(websocket: WebSocket):await handle_codex_live_websocket(diff --git a/tests/test_codex_live.py b/tests/test_codex_live.pyindex b5aa57fa3..b30fd54d8 100644--- a/tests/test_codex_live.py+++ b/tests/test_codex_live.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport asyncioimport base64+import http.serverimport jsonimport loggingimport os@@ -13,6 +14,7 @@ from types import SimpleNamespacefrom typing import Anyfrom unittest.mock import patch+import httpximport pytestimport uvicornimport websockets@@ -26,6 +28,7 @@ from headroom.providers.codex.live import (_forward_headers,codex_live_websocket_url,codex_live_ws_path,+ handle_codex_live_http,handle_codex_live_websocket,)from headroom.providers.codex.runtime import resolve_codex_routing@@ -107,6 +110,135 @@ def test_live_auth_modes_and_derived_paths(monkeypatch) -> None:)+async def test_live_http_call_creation_forwards_json_and_location() -> None:+ token = _jwt(+ {+ "https://api.openai.com/auth": {"chatgpt_account_id": "acct-live"},+ }+ )++ class FakeRequest:+ headers = {+ "authorization": f"Bearer {token}",+ "host": "proxy.test",+ "content-length": "123",+ "content-type": "multipart/form-data; boundary=test",+ }++ async def form(self): # type: ignore[no-untyped-def]+ return {"sdp": "v=0", "session": '{"type":"realtime"}'}++ class FakeHttpClient:+ def __init__(self) -> None:+ self.call: tuple[str, str, dict[str, str], dict[str, object]] | None = None++ async def request(self, method, url, **kwargs): # type: ignore[no-untyped-def]+ self.call = (method, url, dict(kwargs["headers"]), kwargs["json"])+ return SimpleNamespace(+ content=b'{"ok":true}',+ status_code=201,+ headers={"Location": "/backend-api/codex/realtime/calls/1"},+ )++ client = FakeHttpClient()+ response = await handle_codex_live_http(+ FakeRequest(),+ client,+ "https://api.openai.test",+ "/v1/live",+ )++ assert client.call == (+ "POST",+ "https://chatgpt.com/backend-api/codex/realtime/calls?intent=quicksilver&architecture=avas",+ {+ "authorization": f"Bearer {token}",+ "ChatGPT-Account-ID": "acct-live",+ },+ {"sdp": "v=0", "session": {"type": "realtime"}},+ )+ assert response is not None+ assert response.status_code == 201+ assert response.headers["Location"] == "/backend-api/codex/realtime/calls/1"+ assert response.body == b'{"ok":true}'+++async def test_live_http_call_creation_strips_internal_headers_and_stale_compression_headers() -> (+ None+):+ """Regression for PR #3464 review: internal x-headroom-* headers must+ never reach the upstream call, and a compressed upstream response must+ not have its content-encoding/content-length replayed onto the+ already-decoded body httpx hands back (that makes the downstream client+ try to decompress plain bytes a second time). `Location` must survive.+ """+ token = _jwt(+ {+ "https://api.openai.com/auth": {"chatgpt_account_id": "acct-live"},+ }+ )++ class FakeRequest:+ headers = {+ "authorization": f"Bearer {token}",+ "host": "proxy.test",+ "content-type": "multipart/form-data; boundary=test",+ "x-headroom-proxy-token": "internal-secret",+ "x-headroom-bypass": "true",+ }++ async def form(self): # type: ignore[no-untyped-def]+ return {"sdp": "v=0", "session": '{"type":"realtime"}'}++ class FakeHttpClient:+ def __init__(self) -> None:+ self.call: tuple[str, str, dict[str, str], dict[str, object]] | None = None++ async def request(self, method, url, **kwargs): # type: ignore[no-untyped-def]+ self.call = (method, url, dict(kwargs["headers"]), kwargs["json"])+ # httpx already decoded the (gzip) body; the upstream response+ # object still carries the wire-framing headers describing the+ # *compressed* bytes, which is what a real httpx.Response looks+ # like after transparent decompression.+ return SimpleNamespace(+ content=b'{"ok":true}',+ status_code=201,+ headers={+ "Location": "/backend-api/codex/realtime/calls/1",+ "Content-Encoding": "gzip",+ "Content-Length": "9999",+ "Transfer-Encoding": "chunked",+ },+ )++ client = FakeHttpClient()+ response = await handle_codex_live_http(+ FakeRequest(),+ client,+ "https://api.openai.test",+ "/v1/live",+ )++ assert response is not None+ assert client.call is not None+ sent_headers = client.call[2]+ lowered_sent = {key.lower() for key in sent_headers}+ assert "x-headroom-proxy-token" not in lowered_sent+ assert "x-headroom-bypass" not in lowered_sent+ assert sent_headers["authorization"] == f"Bearer {token}"+ assert sent_headers["ChatGPT-Account-ID"] == "acct-live"++ lowered_response = {key.lower(): value for key, value in response.headers.items()}+ assert "content-encoding" not in lowered_response+ assert "transfer-encoding" not in lowered_response+ assert lowered_response["location"] == "/backend-api/codex/realtime/calls/1"+ assert response.body == b'{"ok":true}'+ # Starlette computes content-length from the actual (decoded) body.+ assert lowered_response["content-length"] == str(len(b'{"ok":true}'))++def test_live_headers_strip_internal_and_handshake_headers_without_beta_injection() -> None:headers = _forward_headers({@@ -579,3 +711,112 @@ async def test_live_rg4_real_uvicorn_and_websockets_binary_round_trip() -> None:os.environ.pop("HEADROOM_REQUIRE_RUST_CORE", None)else:os.environ["HEADROOM_REQUIRE_RUST_CORE"] = previous+++class _LoopbackHttpUpstream:+ """Minimal HTTP upstream that echoes the request it received.++ Used to prove, through the *actual registered* `/v1/live` route and its+ passthrough fallback, that a non-ChatGPT-authenticated request reaches+ the upstream with its body intact -- not consumed and errored out by+ `handle_codex_live_http` before falling through.+ """++ def __init__(self) -> None:+ self.port = _free_port()+ self.requests: list[dict[str, Any]] = []+ outer = self++ class _Handler(http.server.BaseHTTPRequestHandler):+ def do_POST(self) -> None: # noqa: N802+ length = int(self.headers.get("Content-Length", 0))+ body = self.rfile.read(length)+ outer.requests.append(+ {"path": self.path, "headers": dict(self.headers), "body": body}+ )+ payload = b'{"echoed":true}'+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++ def log_message(self, *args: Any) -> None: # noqa: ANN401+ del args++ self.server = http.server.ThreadingHTTPServer(("127.0.0.1", self.port), _Handler)+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)++ def start(self) -> None:+ self.thread.start()++ def stop(self) -> None:+ self.server.shutdown()+ self.thread.join(timeout=5.0)+++async def test_live_http_non_chatgpt_multipart_falls_through_with_body_intact() -> None:+ """Regression for PR #3464 review: a real multipart request without+ ChatGPT auth must fall through to the passthrough fallback with its+ body still readable -- not a 500 from `RuntimeError: Stream consumed`.+ """+ previous = os.environ.get("HEADROOM_REQUIRE_RUST_CORE")+ os.environ["HEADROOM_REQUIRE_RUST_CORE"] = "false"+ upstream = _LoopbackHttpUpstream()+ upstream.start()+ proxy = _ProxyThread(_free_port(), upstream.port)+ proxy.start()+ try:+ async with httpx.AsyncClient() as client:+ response = await client.post(+ f"http://127.0.0.1:{proxy.server.config.port}/v1/live",+ files={+ "sdp": (None, "v=0"),+ "session": (None, '{"type":"realtime"}'),+ },+ # No Authorization / ChatGPT-Account-ID header: not ChatGPT auth.+ )+ assert response.status_code == 200+ assert response.json() == {"echoed": True}+ assert len(upstream.requests) == 1+ assert b"v=0" in upstream.requests[0]["body"]+ finally:+ proxy.stop()+ upstream.stop()+ if previous is None:+ os.environ.pop("HEADROOM_REQUIRE_RUST_CORE", None)+ else:+ os.environ["HEADROOM_REQUIRE_RUST_CORE"] = previous+++async def test_live_http_non_chatgpt_json_body_falls_through_instead_of_400() -> None:+ """Regression for PR #3464 review: a JSON (non-multipart) request must+ fall through to the passthrough fallback, not receive the handler's own+ "Missing sdp or session form field" 400.+ """+ previous = os.environ.get("HEADROOM_REQUIRE_RUST_CORE")+ os.environ["HEADROOM_REQUIRE_RUST_CORE"] = "false"+ upstream = _LoopbackHttpUpstream()+ upstream.start()+ proxy = _ProxyThread(_free_port(), upstream.port)+ proxy.start()+ try:+ async with httpx.AsyncClient() as client:+ response = await client.post(+ f"http://127.0.0.1:{proxy.server.config.port}/v1/live",+ json={"unrelated": "payload"},+ # No Authorization / ChatGPT-Account-ID header: not ChatGPT auth.+ )+ assert response.status_code == 200+ assert response.json() == {"echoed": True}+ assert len(upstream.requests) == 1+ assert json.loads(upstream.requests[0]["body"]) == {"unrelated": "payload"}+ finally:+ proxy.stop()+ upstream.stop()+ if previous is None:+ os.environ.pop("HEADROOM_REQUIRE_RUST_CORE", None)+ else:+ os.environ["HEADROOM_REQUIRE_RUST_CORE"] = previous