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): keep OpenCode Zen /responses requests streaming (#3659)
Alvaro Cavalcanti6f404de54e3a
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex fc6d1a464..41406ef5d 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -90,6 +90,7 @@ from headroom.proxy.output_shaper import shaper_enabled_for, steering_allowed_fofrom headroom.proxy.passthrough import (custom_base_passthrough_telemetry as _custom_base_passthrough_telemetry,)+from headroom.proxy.passthrough import is_opencode_zen_basefrom headroom.proxy.project_context import (classify_project,get_current_project,@@ -1189,13 +1190,21 @@ def _should_buffer_openai_responses_stream_ccr(ccr_response_handler_enabled: bool,tools: Any,is_chatgpt_auth: bool,+ upstream_base_url: str | None = None,) -> bool:- """Return whether streaming Responses CCR should use buffered JSON mode."""+ """Return whether streaming Responses CCR should use buffered JSON mode.++ OpenCode Zen validates OpenCode-client attribution on the wire and rejects+ requests Headroom has reshaped (``stream:false`` plus+ ``accept: application/json``) with ``403 FreeTierError`` (#3656). Leave the+ client's streaming request untouched for that gateway.+ """return bool(streamand ccr_response_handler_enabledand not is_chatgpt_auth+ and not is_opencode_zen_base(upstream_base_url)and _has_headroom_retrieve_tool_responses(tools))@@ -5572,10 +5581,13 @@ class OpenAIHandlerMixin:# This handler also honors `x-headroom-base-url` (resolved further# below); resolve it here too so the secret headers are gated on the# real destination rather than merged before it is known.+ # Resolve the client-supplied upstream once: the secret-header gate,+ # the routing decision, and the CCR streaming decision all need it.+ upstream_base_url = _resolve_openai_upstream_base(request.headers)headers = merge_extra_headers(headers,self.config.openai_extra_headers,- upstream_url=_resolve_openai_upstream_base(request.headers),+ upstream_url=upstream_base_url,config=self.config,)# Mirror the WS handler: never forward Codex's client-only lite header@@ -5889,7 +5901,6 @@ class OpenAIHandlerMixin:if is_chatgpt_auth:url = codex_responses_http_url()else:- upstream_base_url = _resolve_openai_upstream_base(request.headers)handler_path = (_resolve_openai_handler_path(request.headers, handler_path=_OPENAI_RESPONSES_PATH)if upstream_base_url is not None@@ -6117,6 +6128,7 @@ class OpenAIHandlerMixin:ccr_response_handler_enabled=_ccr_response_handler_enabled,tools=body.get("tools"),is_chatgpt_auth=is_chatgpt_auth,+ upstream_base_url=upstream_base_url,)if buffered_stream_ccr:if body.get("stream") is not False:diff --git a/headroom/proxy/passthrough.py b/headroom/proxy/passthrough.pyindex 720710bc2..13019de1f 100644--- a/headroom/proxy/passthrough.py+++ b/headroom/proxy/passthrough.py@@ -7,6 +7,23 @@ from urllib.parse import urlparseOPENCODE_ZEN_HOSTS = {"opencode.ai", "www.opencode.ai"}+def is_opencode_zen_base(base_url: str | None) -> bool:+ """Return True when ``base_url`` targets the OpenCode Zen gateway.++ Zen validates OpenCode-client attribution on the wire, so requests that+ Headroom rewrites are rejected even though the caller *is* the OpenCode+ client. Callers that would otherwise change the upstream request shape+ should stay transparent when this returns True.+ """+ if not base_url:+ return False+ try:+ host = (urlparse(base_url.strip()).hostname or "").lower()+ except ValueError:+ return False+ return host in OPENCODE_ZEN_HOSTS++def custom_base_passthrough_telemetry(method: str, path: str, base_url: str) -> tuple[str, str]:"""Return passthrough telemetry metadata for narrow custom-base exceptions."""# OpenCode Zen sends provider-prefixed OpenAI-compatible traffic throughdiff --git a/tests/test_proxy_openai_responses_stream_ccr.py b/tests/test_proxy_openai_responses_stream_ccr.pyindex 6102346cd..2031d226b 100644--- a/tests/test_proxy_openai_responses_stream_ccr.py+++ b/tests/test_proxy_openai_responses_stream_ccr.py@@ -15,12 +15,18 @@ def _unrelated_tool() -> dict[str, str]:return {"type": _TOOL_TYPE_FUNCTION, "name": _UNRELATED_TOOL_NAME}-def _should_buffer(*, tools: list[dict[str, str]], is_chatgpt_auth: bool) -> bool:+def _should_buffer(+ *,+ tools: list[dict[str, str]],+ is_chatgpt_auth: bool,+ upstream_base_url: str | None = None,+) -> bool:return _should_buffer_openai_responses_stream_ccr(stream=True,ccr_response_handler_enabled=True,tools=tools,is_chatgpt_auth=is_chatgpt_auth,+ upstream_base_url=upstream_base_url,)@@ -34,3 +40,19 @@ def test_responses_ccr_keeps_chatgpt_oauth_requests_streaming() -> None:def test_responses_ccr_ignores_requests_without_retrieve_tool() -> None:assert not _should_buffer(tools=[_unrelated_tool()], is_chatgpt_auth=False)+++def test_responses_ccr_keeps_opencode_zen_requests_streaming() -> None:+ assert not _should_buffer(+ tools=[_ccr_tool()],+ is_chatgpt_auth=False,+ upstream_base_url="https://opencode.ai",+ )+++def test_responses_ccr_still_buffers_other_custom_bases() -> None:+ assert _should_buffer(+ tools=[_ccr_tool()],+ is_chatgpt_auth=False,+ upstream_base_url="https://gateway.example.com",+ )diff --git a/tests/test_proxy_passthrough.py b/tests/test_proxy_passthrough.pyindex c7e7f1572..63fa8e53c 100644--- a/tests/test_proxy_passthrough.py+++ b/tests/test_proxy_passthrough.py@@ -1,4 +1,4 @@-from headroom.proxy.passthrough import custom_base_passthrough_telemetry+from headroom.proxy.passthrough import custom_base_passthrough_telemetry, is_opencode_zen_basedef test_custom_base_passthrough_telemetry_recognizes_opencode_zen_chat() -> None:@@ -35,3 +35,17 @@ def test_custom_base_passthrough_telemetry_ignores_non_matching_traffic() -> Non"/zen/v1/chat/completions","://bad-url",) == ("", "")+++def test_is_opencode_zen_base_recognizes_zen_origins() -> None:+ assert is_opencode_zen_base("https://opencode.ai")+ assert is_opencode_zen_base("https://www.opencode.ai")+ assert is_opencode_zen_base("https://opencode.ai/zen")+++def test_is_opencode_zen_base_rejects_other_or_missing_bases() -> None:+ assert not is_opencode_zen_base(None)+ assert not is_opencode_zen_base("")+ assert not is_opencode_zen_base("https://custom.example")+ assert not is_opencode_zen_base("https://opencode.ai.evil.example")+ assert not is_opencode_zen_base("://bad-url")