Skip to content

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.

feat: add Pi/Codex and Cloud Code Assist compatibility routes

Kayzo4bdc1482af32
diff --git a/docs/content/docs/proxy.mdx b/docs/content/docs/proxy.mdx
index d1313f784..cf72774fc 100644
--- a/docs/content/docs/proxy.mdx
+++ b/docs/content/docs/proxy.mdx
@@ -135,6 +135,24 @@ Anthropic API format. The proxy compresses messages, forwards to Anthropic, and
OpenAI API format. The proxy compresses messages, forwards to OpenAI, and returns the response.
+### `POST /v1/responses`
+
+OpenAI Responses API format. The proxy compresses `input` payloads where applicable, forwards the request, and returns the response.
+
+For Codex-compatible clients, the proxy also accepts these alias paths and routes them through the same handler:
+- `POST /v1/codex/responses`
+- `POST /backend-api/responses`
+- `POST /backend-api/codex/responses`
+
+Matching WebSocket and subpath aliases are also supported for Codex flows.
+
+### `POST /v1internal:streamGenerateContent`
+
+Google Cloud Code Assist / Antigravity compatibility endpoint used by Pi-style `google-gemini-cli` and `google-antigravity` providers.
+
+The proxy also accepts:
+- `POST /v1/v1internal:streamGenerateContent`
+
### `POST /v1/compress`
Compression-only endpoint. Compresses messages without calling any LLM. Used by the TypeScript SDK.
diff --git a/headroom/proxy/handlers/gemini.py b/headroom/proxy/handlers/gemini.py
index 1f26bc46f..724cf7ad5 100644
--- a/headroom/proxy/handlers/gemini.py
+++ b/headroom/proxy/handlers/gemini.py
@@ -9,7 +9,7 @@ import json
import logging
import os
import time
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from fastapi import Request
@@ -17,10 +17,35 @@ if TYPE_CHECKING:
logger = logging.getLogger("headroom.proxy")
+DEFAULT_GEMINI_API_URL = "https://generativelanguage.googleapis.com"
+DEFAULT_CLOUDCODE_API_URL = "https://cloudcode-pa.googleapis.com"
+ANTIGRAVITY_DAILY_API_URL = "https://daily-cloudcode-pa.sandbox.googleapis.com"
+ANTIGRAVITY_AUTOPUSH_API_URL = "https://autopush-cloudcode-pa.sandbox.googleapis.com"
+
class GeminiHandlerMixin:
"""Mixin providing Gemini API handler methods for HeadroomProxy."""
+ def _is_cloudcode_antigravity_request(
+ self, body: dict[str, Any], headers: dict[str, str]
+ ) -> bool:
+ """Detect Pi/OpenClaw antigravity requests routed via Cloud Code Assist."""
+ user_agent = headers.get("user-agent", "")
+ return (
+ body.get("requestType") == "agent"
+ or body.get("userAgent") == "antigravity"
+ or user_agent.startswith("antigravity/")
+ )
+
+ def _resolve_cloudcode_base_url(self, is_antigravity: bool) -> str:
+ """Resolve upstream base URL for Pi Cloud Code Assist / Antigravity traffic."""
+ configured = self.GEMINI_API_URL.rstrip("/")
+ if configured and configured != DEFAULT_GEMINI_API_URL:
+ return configured
+ if is_antigravity:
+ return ANTIGRAVITY_DAILY_API_URL
+ return DEFAULT_CLOUDCODE_API_URL
+
def _has_non_text_parts(self, content: dict) -> bool:
"""Check if a Gemini content entry has non-text parts.
@@ -447,6 +472,134 @@ class GeminiHandlerMixin:
},
)
+ async def handle_google_cloudcode_stream(
+ self,
+ request: Request,
+ ) -> StreamingResponse | JSONResponse:
+ """Handle Pi/OpenClaw Google Cloud Code Assist and Antigravity streaming requests."""
+ from fastapi.responses import JSONResponse
+
+ from headroom.proxy.helpers import _read_request_json
+ from headroom.tokenizers import get_tokenizer
+ from headroom.utils import extract_user_query
+
+ start_time = time.time()
+ request_id = await self._next_request_id()
+
+ try:
+ body = await _read_request_json(request)
+ except (json.JSONDecodeError, ValueError) as e:
+ return JSONResponse(
+ status_code=400,
+ content={
+ "error": {
+ "message": f"Invalid request body: {e!s}",
+ "code": 400,
+ }
+ },
+ )
+
+ request_payload = body.get("request")
+ if not isinstance(request_payload, dict):
+ return JSONResponse(
+ status_code=400,
+ content={
+ "error": {
+ "message": "Invalid Cloud Code Assist request: missing request payload",
+ "code": 400,
+ }
+ },
+ )
+
+ model = body.get("model", "unknown")
+ contents = request_payload.get("contents", [])
+ headers = dict(request.headers.items())
+ headers.pop("host", None)
+ headers.pop("content-length", None)
+ headers.pop("accept-encoding", None)
+ tags = self._extract_tags(headers)
+ is_antigravity = self._is_cloudcode_antigravity_request(body, headers)
+
+ system_instruction = request_payload.get("systemInstruction")
+ optimization_system_instruction = None if is_antigravity else system_instruction
+ messages, preserved_indices = self._gemini_contents_to_messages(
+ contents if isinstance(contents, list) else [], optimization_system_instruction
+ )
+ preserved_contents = {
+ idx: contents[idx]
+ for idx in preserved_indices
+ if isinstance(contents, list) and idx < len(contents)
+ }
+
+ tokenizer = get_tokenizer(model)
+ original_tokens = tokenizer.count_messages(messages) if messages else 0
+ optimized_messages = messages
+ optimized_tokens = original_tokens
+ transforms_applied: list[str] = []
+
+ _license_ok = self.usage_reporter.should_compress if self.usage_reporter else True
+ if self.config.optimize and messages and _license_ok:
+ try:
+ context_limit = self.openai_provider.get_context_limit(model)
+ result = self.openai_pipeline.apply(
+ messages=messages,
+ model=model,
+ model_limit=context_limit,
+ context=extract_user_query(messages),
+ )
+ if result.messages != messages:
+ optimized_messages = result.messages
+ transforms_applied = result.transforms_applied
+ original_tokens = result.tokens_before
+ optimized_tokens = result.tokens_after
+ except Exception as e:
+ logger.warning(f"[{request_id}] Cloud Code Assist optimization failed: {e}")
+
+ if optimized_tokens > original_tokens:
+ logger.warning(
+ f"[{request_id}] Cloud Code Assist optimization inflated tokens "
+ f"({original_tokens} -> {optimized_tokens}), reverting to original messages"
+ )
+ optimized_messages = messages
+ optimized_tokens = original_tokens
+ transforms_applied = []
+
+ if optimized_messages != messages:
+ optimized_contents, optimized_system = self._messages_to_gemini_contents(
+ optimized_messages
+ )
+ for orig_idx, original_content in preserved_contents.items():
+ if orig_idx < len(optimized_contents):
+ optimized_contents[orig_idx] = original_content
+ request_payload["contents"] = optimized_contents
+ if not is_antigravity:
+ if optimized_system:
+ request_payload["systemInstruction"] = optimized_system
+ elif "systemInstruction" in request_payload:
+ del request_payload["systemInstruction"]
+
+ tokens_saved = original_tokens - optimized_tokens
+ optimization_latency = (time.time() - start_time) * 1000
+ base_url = self._resolve_cloudcode_base_url(is_antigravity)
+ stream_url = f"{base_url}/v1internal:streamGenerateContent"
+ if request.url.query:
+ stream_url = f"{stream_url}?{request.url.query}"
+
+ return await self._stream_response(
+ stream_url,
+ headers,
+ body,
+ "gemini",
+ model,
+ request_id,
+ original_tokens,
+ optimized_tokens,
+ tokens_saved,
+ transforms_applied,
+ tags,
+ optimization_latency,
+ )
+
async def handle_gemini_stream_generate_content(
self,
request: Request,
diff --git a/headroom/proxy/handlers/streaming.py b/headroom/proxy/handlers/streaming.py
index 3bb3f0b45..aa397c067 100644
--- a/headroom/proxy/handlers/streaming.py
+++ b/headroom/proxy/handlers/streaming.py
@@ -462,7 +462,7 @@ class StreamingMixin:
3. Makes continuation requests until no memory tools remain
4. Streams the final response to the client
"""
- from fastapi.responses import StreamingResponse
+ from fastapi.responses import Response, StreamingResponse
from headroom.proxy.cost import _summarize_transforms
from headroom.proxy.helpers import MAX_SSE_BUFFER_SIZE
@@ -511,6 +511,19 @@ class StreamingMixin:
return StreamingResponse(_error_gen(), media_type="text/event-stream")
+ if upstream_response.status_code >= 400:
+ response_headers = dict(upstream_response.headers)
+ response_headers.pop("content-length", None)
+ response_headers.pop("transfer-encoding", None)
+ response_headers.pop("connection", None)
+ error_content = await upstream_response.aread()
+ await upstream_response.aclose()
+ return Response(
+ content=error_content,
+ status_code=upstream_response.status_code,
+ headers=response_headers,
+ )
+
# Forward upstream ratelimit headers to the client
forwarded_headers = {
k: v for k, v in upstream_response.headers.items() if "ratelimit" in k.lower()
diff --git a/headroom/proxy/server.py b/headroom/proxy/server.py
index 7ee1f19a4..d21f8095b 100644
--- a/headroom/proxy/server.py
+++ b/headroom/proxy/server.py
@@ -2033,6 +2033,11 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
"""OpenAI Responses API (new API introduced March 2025)."""
return await proxy.handle_openai_responses(request)
+ @app.post("/v1/codex/responses")
+ async def openai_v1_codex_responses(request: Request):
+ """Pi/OpenAI Codex compatibility path for OpenAI-style /v1 base URLs."""
+ return await proxy.handle_openai_responses(request)
+
@app.post("/backend-api/responses")
async def openai_codex_responses(request: Request):
"""OpenAI Codex Responses API path preserved from ChatGPT backend."""
@@ -2048,6 +2053,11 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
"""OpenAI Responses API via WebSocket (Codex gpt-5.4+)."""
await proxy.handle_openai_responses_ws(websocket)
+ @app.websocket("/v1/codex/responses")
+ async def openai_v1_codex_responses_ws(websocket: WebSocket):
+ """Pi/OpenAI Codex compatibility WebSocket path for /v1 base URLs."""
+ await proxy.handle_openai_responses_ws(websocket)
+
# OpenAI Responses API sub-endpoints (passthrough).
# Codex sub-agents use /v1/responses/compact and other sub-paths
# that we don't need to compress — just forward with correct auth routing.
@@ -2056,13 +2066,16 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
"""Passthrough for /v1/responses/* sub-endpoints (compact, cancel, etc.)."""
from fastapi.responses import Response
+ from headroom.proxy.handlers.openai import _resolve_codex_routing_headers
+
headers = dict(request.headers.items())
headers.pop("host", None)
+ headers, is_chatgpt_auth = _resolve_codex_routing_headers(headers)
# Route to correct endpoint based on auth mode.
# ChatGPT session auth (codex login) uses chatgpt.com with /responses/...
# path (no /v1/ prefix). API key auth uses api.openai.com/v1/responses/...
- if headers.get("chatgpt-account-id"):
+ if is_chatgpt_auth:
url = f"https://chatgpt.com/backend-api/codex/responses/{sub_path}"
else:
url = f"{proxy.OPENAI_API_URL}/v1/responses/{sub_path}"
@@ -2089,6 +2102,11 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
logger.error(f"Passthrough /v1/responses/{sub_path} failed: {e}")
return Response(content=str(e), status_code=502)
+ @app.api_route("/v1/codex/responses/{sub_path:path}", methods=["GET", "POST", "DELETE"])
+ async def openai_v1_codex_responses_sub(request: Request, sub_path: str):
+ """Passthrough for Pi/OpenAI Codex /v1/codex/responses/* sub-endpoints."""
+ return await openai_responses_sub(request, sub_path)
+
@app.websocket("/backend-api/responses")
async def openai_codex_responses_ws(websocket: WebSocket):
"""OpenAI Codex Responses WebSocket path preserved from ChatGPT backend."""
@@ -2148,6 +2166,16 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
"""Gemini countTokens API with compression applied."""
return await proxy.handle_gemini_count_tokens(request, model)
+ @app.post("/v1internal:streamGenerateContent")
+ async def google_cloudcode_stream_generate_content(request: Request):
+ """Google Cloud Code Assist / Antigravity compatibility streaming endpoint."""
+ return await proxy.handle_google_cloudcode_stream(request)
+
+ @app.post("/v1/v1internal:streamGenerateContent")
+ async def google_cloudcode_stream_generate_content_v1(request: Request):
+ """Compatibility endpoint for clients configured with a /v1 proxy base URL."""
+ return await proxy.handle_google_cloudcode_stream(request)
+
# =========================================================================
# Databricks Native Endpoints
# =========================================================================
diff --git a/tests/test_proxy_codex_route_aliases.py b/tests/test_proxy_codex_route_aliases.py
index 797361f61..d9dd20d0b 100644
--- a/tests/test_proxy_codex_route_aliases.py
+++ b/tests/test_proxy_codex_route_aliases.py
@@ -1,3 +1,6 @@
+import base64
+import json
+
import httpx
from fastapi import WebSocket
from fastapi.responses import JSONResponse
@@ -6,6 +9,16 @@ from fastapi.testclient import TestClient
from headroom.proxy.server import HeadroomProxy, ProxyConfig, create_app
+def _jwt(payload: dict) -> str:
+ header = {"alg": "none", "typ": "JWT"}
+
+ def encode(part: dict) -> str:
+ raw = json.dumps(part, separators=(",", ":")).encode("utf-8")
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
+
+ return f"{encode(header)}.{encode(payload)}."
+
+
def test_codex_responses_aliases_delegate_to_openai_handler(monkeypatch):
async def fake_handle(self, request): # type: ignore[no-untyped-def]
return JSONResponse({"ok": True, "path": request.url.path})
@@ -13,7 +26,11 @@ def test_codex_responses_aliases_delegate_to_openai_handler(monkeypatch):
monkeypatch.setattr(HeadroomProxy, "handle_openai_responses", fake_handle)
with TestClient(create_app(ProxyConfig())) as client:
- for path in ("/backend-api/responses", "/backend-api/codex/responses"):
+ for path in (
+ "/v1/codex/responses",
+ "/backend-api/responses",
+ "/backend-api/codex/responses",
+ ):
response = client.post(path, json={"model": "gpt-5.3-codex"})
assert response.status_code == 200
assert response.json() == {"ok": True, "path": path}
@@ -31,11 +48,19 @@ def test_codex_responses_websocket_aliases_delegate_to_openai_handler(monkeypatc
monkeypatch.setattr(HeadroomProxy, "handle_openai_responses_ws", fake_handle_ws)
with TestClient(create_app(ProxyConfig())) as client:
- for path in ("/backend-api/responses", "/backend-api/codex/responses"):
+ for path in (
+ "/v1/codex/responses",
+ "/backend-api/responses",
+ "/backend-api/codex/responses",
+ ):
with client.websocket_connect(path) as websocket:
assert websocket.receive_json() == {"ok": True, "path": path}
- assert seen_paths == ["/backend-api/responses", "/backend-api/codex/responses"]
+ assert seen_paths == [
+ "/v1/codex/responses",
+ "/backend-api/responses",
+ "/backend-api/codex/responses",
+ ]
def test_codex_responses_subpath_aliases_delegate_to_passthrough():
@@ -55,6 +80,10 @@ def test_codex_responses_subpath_aliases_delegate_to_passthrough():
client.app.state.proxy.http_client = fake_http_client
client.app.state.proxy.OPENAI_API_URL = "https://api.openai.test"
+ pi_response = client.post(
+ "/v1/codex/responses/compact?trace=0",
+ json={"model": "gpt-5.3-codex"},
+ )
api_key_response = client.post(
"/backend-api/responses/compact?trace=1",
json={"model": "gpt-5.3-codex"},
@@ -65,9 +94,52 @@ def test_codex_responses_subpath_aliases_delegate_to_passthrough():
json={"model": "gpt-5.3-codex"},
)
+ assert pi_response.status_code == 200
assert api_key_response.status_code == 200
assert chatgpt_response.status_code == 200
assert fake_http_client.calls == [
+ ("POST", "https://api.openai.test/v1/responses/compact?trace=0"),
("POST", "https://api.openai.test/v1/responses/compact?trace=1"),
("POST", "https://chatgpt.com/backend-api/codex/responses/compact?trace=2"),
]
+
+
+def test_codex_responses_subpath_passthrough_derives_chatgpt_routing_from_jwt():
+ class FakeAsyncClient:
+ def __init__(self) -> None:
+ 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 aclose(self) -> None:
+ return None
+
+ token = _jwt(
+ {
+ "https://api.openai.com/auth": {
+ "chatgpt_account_id": "acct-from-jwt",
+ }
+ }
+ )
+
+ with TestClient(create_app(ProxyConfig())) as client:
+ fake_http_client = FakeAsyncClient()
+ client.app.state.proxy.http_client = fake_http_client
+ client.app.state.proxy.OPENAI_API_URL = "https://api.openai.test"
+
+ response = client.post(
+ "/v1/codex/responses/compact?trace=jwt",
+ headers={"Authorization": f"Bearer {token}"},
+ json={"model": "gpt-5.4"},
+ )
+
+ assert response.status_code == 200
+ assert len(fake_http_client.calls) == 1
+
+ method, url, headers = fake_http_client.calls[0]
+ assert method == "POST"
+ assert url == "https://chatgpt.com/backend-api/codex/responses/compact?trace=jwt"
+ assert headers["authorization"] == f"Bearer {token}"
+ assert headers["ChatGPT-Account-ID"] == "acct-from-jwt"
diff --git a/tests/test_proxy_google_cloudcode_route_aliases.py b/tests/test_proxy_google_cloudcode_route_aliases.py
new file mode 100644
index 000000000..a90595fa6
--- /dev/null
+++ b/tests/test_proxy_google_cloudcode_route_aliases.py
@@ -0,0 +1,91 @@
+from fastapi.responses import JSONResponse
+from fastapi.testclient import TestClient
+
+from headroom.proxy.server import HeadroomProxy, ProxyConfig, create_app
+
+CLOUDCODE_BODY = {
+ "project": "test-project",
+ "model": "gemini-3.1-pro-high",
+ "userAgent": "pi-coding-agent",
+ "request": {
+ "contents": [
+ {
+ "role": "user",
+ "parts": [{"text": "Reply with pong."}],
+ }
+ ]
+ },
+}
+
+ANTIGRAVITY_BODY = {
+ "project": "test-project",
+ "model": "claude-sonnet-4-6",
+ "requestType": "agent",
+ "userAgent": "antigravity",
+ "request": {
+ "contents": [
+ {
+ "role": "user",
+ "parts": [{"text": "Reply with pong."}],
+ }
+ ]
+ },
+}
+
+
+def test_google_cloudcode_alias_routes_delegate_to_handler(monkeypatch):
+ async def fake_handle(self, request): # type: ignore[no-untyped-def]
+ return JSONResponse({"ok": True, "path": request.url.path})
+
+ monkeypatch.setattr(HeadroomProxy, "handle_google_cloudcode_stream", fake_handle)
+
+ with TestClient(create_app(ProxyConfig())) as client:
+ for path in (
+ "/v1internal:streamGenerateContent",
+ "/v1/v1internal:streamGenerateContent",
+ ):
+ response = client.post(path, params={"alt": "sse"}, json=CLOUDCODE_BODY)
+ assert response.status_code == 200
+ assert response.json() == {"ok": True, "path": path}
+
+
+def test_antigravity_cloudcode_route_uses_daily_endpoint(monkeypatch):
+ async def fake_stream(self, url, _headers, _body, provider, model, *_args, **_kwargs): # type: ignore[no-untyped-def]
+ return JSONResponse({"url": url, "provider": provider, "model": model})
+
+ monkeypatch.setattr(HeadroomProxy, "_stream_response", fake_stream)
+
+ with TestClient(create_app(ProxyConfig(optimize=False))) as client:
+ response = client.post(
+ "/v1internal:streamGenerateContent",
+ params={"alt": "sse"},
+ json=ANTIGRAVITY_BODY,
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {
+ "url": "https://daily-cloudcode-pa.sandbox.googleapis.com/v1internal:streamGenerateContent?alt=sse",
+ "provider": "gemini",
+ "model": "claude-sonnet-4-6",
+ }
+
+
+def test_cloudcode_route_uses_default_cloudcode_endpoint(monkeypatch):
+ async def fake_stream(self, url, _headers, _body, provider, model, *_args, **_kwargs): # type: ignore[no-untyped-def]
+ return JSONResponse({"url": url, "provider": provider, "model": model})
+
+ monkeypatch.setattr(HeadroomProxy, "_stream_response", fake_stream)
+
+ with TestClient(create_app(ProxyConfig(optimize=False))) as client:
+ response = client.post(
+ "/v1/v1internal:streamGenerateContent",
+ params={"alt": "sse"},
+ json=CLOUDCODE_BODY,
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {
+ "url": "https://cloudcode-pa.googleapis.com/v1internal:streamGenerateContent?alt=sse",
+ "provider": "gemini",
+ "model": "gemini-3.1-pro-high",
+ }
diff --git a/tests/test_proxy_streaming_ratelimit_headers.py b/tests/test_proxy_streaming_ratelimit_headers.py
index 6c1d306b3..8af5e8ff0 100644
--- a/tests/test_proxy_streaming_ratelimit_headers.py
+++ b/tests/test_proxy_streaming_ratelimit_headers.py
@@ -68,6 +68,7 @@ class TestStreamingRatelimitHeaderForwarding:
if extra_headers:
headers.update(extra_headers)
mock_response.headers = httpx.Headers(headers)
+ mock_response.status_code = 200
# Simulate a simple SSE stream
sse_data = (
@@ -198,6 +199,44 @@ class TestStreamingRatelimitHeaderForwarding:
# No ratelimit headers to forward
assert result.headers.get("anthropic-ratelimit-tokens-limit") is None
+ @pytest.mark.asyncio
+ async def test_upstream_http_error_preserves_status_and_body(self):
+ """Upstream non-200 streaming responses should preserve HTTP status/body."""
+ proxy = self._create_mock_proxy()
+ mock_response = self._create_mock_upstream_response()
+ mock_response.status_code = 503
+ mock_response.aread = AsyncMock(
+ return_value=b'{"error":{"message":"capacity exhausted"}}'
+ )
+ mock_response.aclose = AsyncMock()
+
+ mock_request = MagicMock()
+ proxy.http_client.build_request = MagicMock(return_value=mock_request)
+ proxy.http_client.send = AsyncMock(return_value=mock_response)
+
+ result = await proxy._stream_response(
+ url="https://api.anthropic.com/v1/messages",
+ headers={"x-api-key": "sk-test"},
+ body={
+ "model": "claude-sonnet-4-20250514",
+ "max_tokens": 100,
+ "stream": True,
+ "messages": [{"role": "user", "content": "hi"}],
+ },
+ provider="anthropic",
+ model="claude-sonnet-4-20250514",
+ request_id="test-http-error",
+ original_tokens=10,
+ optimized_tokens=10,
+ tokens_saved=0,
+ transforms_applied=[],
+ tags={},
+ optimization_latency=0.0,
+ )
+
+ assert result.status_code == 503
+ assert result.body == b'{"error":{"message":"capacity exhausted"}}'
+
@pytest.mark.asyncio
async def test_connect_error_returns_sse_error(self):
"""Connection errors should return an SSE error event (not crash)."""