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.

fix(wrap): preserve pre-set ANTHROPIC_BASE_URL as proxy upstream (#1358)

Ben Younesbb1ab6afd35a
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.py
index c5428b94f..6852e0259 100644
--- a/headroom/cli/wrap.py
+++ b/headroom/cli/wrap.py
@@ -5625,6 +5625,42 @@ def wrap_selfheal(marker: str | None) -> None:
# Claude Code
# =============================================================================
+# Hostnames that mean "this machine" — used to avoid feeding the proxy its own
+# URL back as the upstream when the user already had ANTHROPIC_BASE_URL pointed
+# at a previous Headroom instance.
+_LOCAL_HOSTNAMES = frozenset({"localhost", "127.0.0.1", "::1"})
+
+
+def _detect_inbound_anthropic_upstream(port: int) -> str | None:
+ """Return a pre-set ANTHROPIC_BASE_URL that is NOT this proxy, else None.
+
+ Issue #1353: users who already route Claude Code at a LiteLLM (or any
+ custom Anthropic-compatible) gateway via ``ANTHROPIC_BASE_URL`` lose that
+ routing when they run ``headroom wrap claude`` — wrap overwrites
+ ANTHROPIC_BASE_URL with the local proxy URL and silently forwards to
+ api.anthropic.com instead of the LiteLLM URL the user configured. Treat
+ the pre-existing value as the proxy's upstream so compression layers on
+ top of the user's gateway instead of replacing it. URLs pointing at this
+ proxy instance are ignored to avoid a self-referential forwarding loop.
+ """
+
+ base_url = (os.environ.get("ANTHROPIC_BASE_URL") or "").strip()
+ if not base_url:
+ return None
+ try:
+ parsed = urllib.parse.urlsplit(base_url)
+ except ValueError:
+ return None
+ hostname = (parsed.hostname or "").lower()
+ if hostname in _LOCAL_HOSTNAMES:
+ try:
+ parsed_port = parsed.port
+ except ValueError:
+ return None
+ if parsed_port == port:
+ return None
+ return base_url
+
@wrap.command(context_settings={"ignore_unknown_options": True})
@_retired_context_tool_option
@@ -5851,6 +5887,20 @@ def claude(
proxy_url = _claude_proxy_base_url(port)
vertex_upstream = _vertex_target_api_url_from_claude_env(proxy_url) if use_vertex else None
+ # Issue #1353: when none of the explicit override channels (Foundry,
+ # Vertex, ANTHROPIC_TARGET_API_URL) apply, inherit a pre-existing
+ # ANTHROPIC_BASE_URL as the upstream so wrap doesn't silently revert
+ # the user's LiteLLM/custom-gateway routing back to api.anthropic.com.
+ custom_upstream: str | None = None
+ if (
+ not foundry_upstream
+ and not use_vertex
+ and not os.environ.get("ANTHROPIC_TARGET_API_URL")
+ ):
+ custom_upstream = _detect_inbound_anthropic_upstream(port)
+
+ upstream_for_proxy = foundry_upstream or custom_upstream
+
_register_proxy_client(port)
proxy_holder[0], actual_port = _ensure_proxy(
port,
@@ -5861,7 +5911,7 @@ def claude(
code_graph=code_graph,
backend=backend,
region=region,
- anthropic_api_url=foundry_upstream,
+ anthropic_api_url=upstream_for_proxy,
vertex_api_url=vertex_upstream,
clear_vertex_api_url=use_vertex and vertex_upstream is None,
)
@@ -5907,6 +5957,8 @@ def claude(
click.echo(
f" Foundry mode: ANTHROPIC_FOUNDRY_BASE_URL={_foundry_proxy_url(proxy_url)} → upstream {foundry_upstream}"
)
+ elif custom_upstream:
+ click.echo(f" ANTHROPIC_BASE_URL={proxy_url} → upstream {custom_upstream}")
else:
click.echo(f" ANTHROPIC_BASE_URL={proxy_url}")
# Issue #1779: Claude Code 2.1.196+ deterministically disables
diff --git a/tests/test_cli/test_wrap_claude_inbound_upstream.py b/tests/test_cli/test_wrap_claude_inbound_upstream.py
new file mode 100644
index 000000000..c1c0448ea
--- /dev/null
+++ b/tests/test_cli/test_wrap_claude_inbound_upstream.py
@@ -0,0 +1,56 @@
+"""Tests for inbound ANTHROPIC_BASE_URL → upstream forwarding (issue #1353).
+
+Verifies that `headroom wrap claude` preserves a pre-existing custom
+ANTHROPIC_BASE_URL (e.g. a LiteLLM gateway) as the proxy's Anthropic upstream
+instead of silently reverting routing to api.anthropic.com.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from headroom.cli import wrap as wrap_cli
+
+_PROXY_PORT = 8787
+_LITELLM_URL = "https://litellm.example.internal/anthropic"
+_MALFORMED_LOCAL_PORT_URL = "http://localhost:notaport"
+
+
+def test_detects_custom_litellm_upstream(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("ANTHROPIC_BASE_URL", _LITELLM_URL)
+ assert wrap_cli._detect_inbound_anthropic_upstream(_PROXY_PORT) == _LITELLM_URL
+
+
+def test_returns_none_when_unset(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False)
+ assert wrap_cli._detect_inbound_anthropic_upstream(_PROXY_PORT) is None
+
+
+def test_returns_none_when_blank(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("ANTHROPIC_BASE_URL", " ")
+ assert wrap_cli._detect_inbound_anthropic_upstream(_PROXY_PORT) is None
+
+
+ "url",
+ [
+ f"http://127.0.0.1:{_PROXY_PORT}",
+ f"http://localhost:{_PROXY_PORT}",
+ f"http://127.0.0.1:{_PROXY_PORT}/",
+ f"http://LOCALHOST:{_PROXY_PORT}/v1",
+ ],
+)
+def test_returns_none_for_self_pointing_url(monkeypatch: pytest.MonkeyPatch, url: str) -> None:
+ monkeypatch.setenv("ANTHROPIC_BASE_URL", url)
+ assert wrap_cli._detect_inbound_anthropic_upstream(_PROXY_PORT) is None
+
+
+def test_returns_localhost_on_different_port(monkeypatch: pytest.MonkeyPatch) -> None:
+ other_port_url = f"http://127.0.0.1:{_PROXY_PORT + 1}"
+ monkeypatch.setenv("ANTHROPIC_BASE_URL", other_port_url)
+ assert wrap_cli._detect_inbound_anthropic_upstream(_PROXY_PORT) == other_port_url
+
+
+def test_returns_none_for_malformed_local_port(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("ANTHROPIC_BASE_URL", _MALFORMED_LOCAL_PORT_URL)
+ assert wrap_cli._detect_inbound_anthropic_upstream(_PROXY_PORT) is None