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(wrap): let `wrap opencode` target a third-party OpenAI-compatible upstream (#3125)
Ayush Kumar Jha0d7d61d5ccae
diff --git a/README.md b/README.mdindex c6cf1659b..ed379c49a 100644--- a/README.md+++ b/README.md@@ -236,7 +236,7 @@ Saved** card then reads `measured` rather than `estimated`, with the band.| Copilot CLI | ✅ | starts proxy + launches || VS Code Copilot | ✅ | transparent proxy; keeps the selected model || OpenClaw | ✅ | installs as a ContextEngine plugin |-| OpenCode | ✅ | injects config · starts proxy + launches |+| OpenCode | ✅ | injects config · starts proxy + launches [^third-party-upstream] || Cline | ✅ | starts proxy + injects config || Continue | ✅ | starts proxy + injects config || Goose | ✅ | starts proxy + launches |@@ -247,6 +247,8 @@ Saved** card then reads `measured` rather than `estimated`, with the band.| Kimi CLI | ✅ | OAuth bearer forwarded — log in once || ZCode | ✅ | starts the proxy and prints base URLs for ZCode settings |+[^third-party-upstream]: `headroom wrap` routes OpenAI-compatible traffic to the default upstream (`https://api.openai.com/v1`). For a third-party OpenAI-compatible provider (DeepSeek, Together, OpenRouter, a self-hosted gateway), pass `--openai-api-url https://api.deepseek.com/v1` — or set `OPENAI_TARGET_API_URL` before wrapping — otherwise your provider key is sent to OpenAI and rejected with `401 Incorrect API key provided`. See [OpenCode + DeepSeek](docs/content/docs/opencode-deepseek.mdx).+Any OpenAI-compatible client works through `headroom proxy`. MCP-native clients:`headroom mcp install`. Undo durable wrapping with `headroom unwrap <tool>`(`claude`, `copilot`, `codex`, `grok`, `kimi`, `omp`, `opencode`, `openclaw`,diff --git a/docs/content/docs/opencode-deepseek.mdx b/docs/content/docs/opencode-deepseek.mdxindex b649222e3..f51bc832a 100644--- a/docs/content/docs/opencode-deepseek.mdx+++ b/docs/content/docs/opencode-deepseek.mdx@@ -201,9 +201,57 @@ API key to the proxy, and the proxy forwards it to DeepSeek. Make sure### Models appear but requests fail-You ran `headroom wrap opencode`. That command replaces your config with Claude-and GPT models. **Do not use `headroom wrap`.** Configure OpenCode manually as-shown above, and launch OpenCode directly with `opencode`.+You ran `headroom wrap opencode` without telling it about DeepSeek. Without an+explicit upstream the proxy it starts forwards OpenAI-compatible traffic to+OpenAI, so wrap leaves the `apiKey` and `models` entries from step 4 out of the+`headroom` provider rather than send your DeepSeek key there. Pass+`--openai-api-url` as shown in the next section, or launch OpenCode directly+with `opencode` against the proxy you started in step 3.++### I used `headroom wrap opencode` and get "Incorrect API key provided"++```+Incorrect API key provided: sk-13005***********************898d.+You can find your API key at https://platform.openai.com/account/api-keys.+```++That 401 comes from **OpenAI**, not DeepSeek. `headroom wrap opencode` starts+the proxy for you, and unless it is told otherwise the proxy forwards+OpenAI-compatible traffic to its default upstream, `https://api.openai.com/v1`.+Your DeepSeek key is then presented to OpenAI, which rejects it and points you+at a dashboard for a key you never had.++Pass the upstream to wrap, exactly like `headroom proxy --openai-api-url`:++```bash+headroom wrap opencode --openai-api-url https://api.deepseek.com/v1+```++The equivalent environment variable also works, and is honored by both+commands:++```bash+OPENAI_TARGET_API_URL=https://api.deepseek.com/v1 headroom wrap opencode+```++If a proxy is already running on the port with a different upstream, stop it+first (`headroom unwrap opencode`) — wrap will not silently re-point a proxy+that other clients may be sharing.++### When is `headroom wrap opencode` safe?++- **Safe as-is** when your traffic goes to the default upstreams — OpenAI+ (`api.openai.com`) or Anthropic (`api.anthropic.com`).+- **Needs `--openai-api-url`** (or `OPENAI_TARGET_API_URL`) for any third-party+ OpenAI-compatible provider: DeepSeek, Together, OpenRouter, Groq, a+ self-hosted gateway, and so on.+- **Keep the step 4 provider entries.** OpenCode only offers the+ `headroom/<id>` models listed under `provider.headroom.models`, and DeepSeek+ needs your key in `options.apiKey` (for example `"{env:DEEPSEEK_API_KEY}"`).+ With `--openai-api-url`, wrap keeps both. It rewrites the provider's `npm`,+ `name` and `baseURL` and adds its default `gpt-4o` and `gpt-4.1` ids next to+ your models. Without the flag it leaves your key and models out, because the+ proxy would forward them to OpenAI.### "headroom" command not found@@ -231,7 +279,6 @@ shaper is active immediately — the numbers just need calibration.## What's NOT in this guide- **Claude or GPT models** — this setup uses DeepSeek exclusively-- **`headroom wrap`** — do not use it; it overrides the config- **Deprecated model names** — `deepseek-chat` and `deepseek-reasoner` arecompatibility aliases slated for removal; use `deepseek-v4-pro` and`deepseek-v4-flash` insteaddiff --git a/docs/content/docs/opencode.mdx b/docs/content/docs/opencode.mdxindex 7ce257f88..b0c395fda 100644--- a/docs/content/docs/opencode.mdx+++ b/docs/content/docs/opencode.mdx@@ -41,6 +41,7 @@ headroom wrap opencode \--no-serena \--code-graph \--no-proxy \+ --openai-api-url https://api.deepseek.com/v1 \--learn \--memory \--backend anthropic \@@ -49,6 +50,32 @@ headroom wrap opencode \-- <opencode args>```+Pass `--openai-api-url` when OpenCode should route through a third-party+OpenAI-compatible provider instead of OpenAI itself — DeepSeek, Together,+OpenRouter, or a self-hosted gateway. Without it, OpenAI-compatible traffic is+forwarded to the default upstream (`https://api.openai.com/v1`), so a+non-OpenAI key is rejected with `401 Incorrect API key provided`. Setting+`OPENAI_TARGET_API_URL` before wrapping has the same effect. See+[OpenCode + DeepSeek](/docs/opencode-deepseek) for a full walkthrough.++The flag means the same thing whether or not wrap starts the proxy:++```bash+# wrap starts the proxy and points it at DeepSeek+headroom wrap opencode --openai-api-url https://api.deepseek.com/v1++# reuse a proxy you started yourself — it must already target that upstream+headroom proxy --port 8787 --openai-api-url https://api.deepseek.com/v1+headroom wrap opencode --no-proxy --openai-api-url https://api.deepseek.com/v1+```++With `--no-proxy`, wrap never starts or re-points a proxy. It checks the one+listening on `--port` and exits with an error — before it rewrites+`opencode.json` — if nothing is listening, the listener is not a Headroom+proxy, or it forwards OpenAI-compatible traffic to a different upstream. Start+the proxy with the upstream you want, or drop `--no-proxy` and let wrap start+it.+## Provider Model MappingThe generated `headroom` provider exposes these models through the proxy:@@ -69,6 +96,7 @@ The default model is `headroom/claude-sonnet-4-6`. Change it in `opencode.json`|---|---|| `OPENCODE_CONFIG_CONTENT` | JSON payload with provider, plugin, and optional local MCP config injected by `wrap` || `HEADROOM_PROXY_URL` | Proxy URL passed to Headroom MCP when a non-default port is used, and to the native plugin when configured |+| `OPENAI_TARGET_API_URL` | Upstream for OpenAI-compatible traffic when `--openai-api-url` is not passed; defaults to `https://api.openai.com/v1` || `HEADROOM_OPENCODE_EXCLUDE_HOSTS` | Comma-separated hosts (and their subdomains) the native plugin sends straight upstream instead of through the proxy, for example `opencode.ai,.corp.internal` |## Failure Learningdiff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.pyindex 001c5c230..1c5a288e1 100644--- a/headroom/cli/wrap.py+++ b/headroom/cli/wrap.py@@ -4020,6 +4020,48 @@ def _normalize_proxy_api_url(url: object, *, strip_provider_v1: bool = True) ->return normalized or None+def _require_no_proxy_openai_upstream(port: int, openai_api_url: str) -> dict[str, Any]:+ """Refuse ``--no-proxy`` unless the proxy on ``port`` already targets ``openai_api_url``.++ ``--no-proxy`` reuses a listener wrap does not own, so it can neither+ start nor re-point one. Reusing it unchecked would present a third-party+ key (DeepSeek, Together, ...) to whatever upstream that proxy was started+ with — usually OpenAI, which rejects it with a 401 — while the flag+ implies the key went to the requested provider (#3107). Fail closed+ instead: require a healthy Headroom listener whose advertised upstream+ matches exactly after normalization.+ """+ helpers = _live_wrap_module()+ start_cmd = f"headroom proxy --port {port} --openai-api-url {openai_api_url}"+ if not helpers._check_proxy(port):+ raise click.ClickException(+ f"No Headroom proxy is listening on port {port}, so --no-proxy cannot honor "+ f"the requested OpenAI-compatible upstream {openai_api_url}. "+ f"Start it separately with `{start_cmd}`, or drop --no-proxy so wrap can start it."+ )+ running_config: dict[str, Any] | None = helpers._proxy_health_config(+ helpers._query_proxy_health(port)+ )+ if running_config is None:+ running_config = helpers._query_proxy_config(port)+ if running_config is None:+ raise click.ClickException(+ f"The listener on port {port} did not report a Headroom config, so wrap "+ f"cannot confirm it forwards to {openai_api_url}. "+ f"Start a Headroom proxy separately with `{start_cmd}`, or drop --no-proxy "+ "so wrap can start it."+ )+ running_url = running_config.get("openai_api_url")+ if _normalize_proxy_api_url(running_url) != _normalize_proxy_api_url(openai_api_url):+ raise click.ClickException(+ f"The Headroom proxy on port {port} forwards OpenAI-compatible traffic to "+ f"{running_url or 'https://api.openai.com/v1'}, not {openai_api_url}. "+ f"Restart it with `{start_cmd}`, or drop --no-proxy so wrap can restart it "+ "when no other wrapper is attached."+ )+ return running_config++def _proxy_version(payload: dict[str, Any] | None) -> str | None:"""Return the running proxy version when it exposes one."""if payload is None:@@ -4597,6 +4639,7 @@ def _ensure_proxy_unlocked(anyllm_provider: str | None = None,region: str | None = None,openai_api_url: str | None = None,+ require_openai_api_url: bool = False,anthropic_api_url: str | None = None,vertex_api_url: str | None = None,clear_vertex_api_url: bool = False,@@ -5061,7 +5104,13 @@ def _ensure_proxy_unlocked(click.echo(f" Error: {e}")raise SystemExit(1) from eelse:- if not helpers._check_proxy(port):+ if require_openai_api_url and openai_api_url:+ # A user-chosen upstream cannot be applied to a proxy wrap does+ # not own; fail closed unless the running one already matches.+ running_config = _require_no_proxy_openai_upstream(port, openai_api_url)+ click.echo(f" Proxy on port {port} already targets {openai_api_url}")+ _warn_proxy_mode_mismatch(running_config)+ elif not helpers._check_proxy(port):click.echo(f" Warning: No proxy detected on port {port}")elif vertex_api_url or clear_vertex_api_url or os.environ.get("HEADROOM_MODE"):health_payload = helpers._query_proxy_health(port)@@ -8170,6 +8219,16 @@ def openclaw(is_flag=True,help="Route headroom/* models through the authenticated GitHub Copilot subscription",)+ "--openai-api-url",+ default=None,+ envvar="OPENAI_TARGET_API_URL",+ help=(+ "Upstream base URL for OpenAI-compatible traffic, e.g. "+ "https://api.deepseek.com/v1. Without it the proxy forwards to "+ "https://api.openai.com/v1 (env: OPENAI_TARGET_API_URL)."+ ),+)@click.option("--learn", is_flag=True, help="Enable live traffic learning")@click.option("--memory", is_flag=True, help="Enable persistent cross-session memory")@click.option(@@ -8187,6 +8246,7 @@ def opencode(code_graph: bool,no_proxy: bool,copilot_subscription: bool,+ openai_api_url: str | None,learn: bool,memory: bool,backend: str | None,@@ -8212,9 +8272,25 @@ def opencode(headroom wrap opencode --port 9999 # Custom proxy portheadroom wrap opencode --backend anyllm --anyllm-provider groqheadroom wrap opencode --copilot-subscription # Use a GitHub Copilot subscription+ headroom wrap opencode --openai-api-url https://api.deepseek.com/v1++ \b+ Without --openai-api-url the proxy forwards OpenAI-compatible traffic to+ https://api.openai.com/v1, so a third-party key (DeepSeek, Together,+ OpenRouter, ...) is rejected upstream with OpenAI's 401 "Incorrect API key+ provided". Point the proxy at the real upstream instead:++ \b+ headroom wrap opencode --openai-api-url https://api.deepseek.com/v1+ OPENAI_TARGET_API_URL=https://api.deepseek.com/v1 headroom wrap opencode"""subscription_resolution = Noneif copilot_subscription:+ if openai_api_url:+ raise click.ClickException(+ "--openai-api-url cannot be combined with --copilot-subscription; "+ "the subscription resolves its own upstream."+ )effective_backend = backend or os.environ.get("HEADROOM_BACKEND")if effective_backend not in (None, "", "anthropic"):raise click.ClickException(@@ -8247,6 +8323,12 @@ def opencode(click.echo("Install OpenCode: https://opencode.ai")raise SystemExit(1)+ # Likewise refuse a reused proxy that cannot honor --openai-api-url before+ # touching OpenCode's config or registering a client marker; the same check+ # inside _ensure_proxy would only fire after those edits.+ if not prepare_only and no_proxy and openai_api_url:+ _require_no_proxy_openai_upstream(port, openai_api_url)+# Snapshot OpenCode config.json BEFORE any wrap-time mutation so# `headroom unwrap opencode` can restore the user's pre-wrap state._opencode_config_file, _opencode_backup_file = opencode_config_paths()@@ -8284,7 +8366,7 @@ def opencode(_inject_memory_agents_md(agents_md)if prepare_only:- inject_opencode_provider_config(port)+ inject_opencode_provider_config(port, keep_user_entries=bool(openai_api_url))return# Past the prepare-only return the launch path always ran the binary check@@ -8308,7 +8390,10 @@ def opencode(backend=backend,anyllm_provider=anyllm_provider,region=region,- openai_api_url=(subscription_resolution.api_url if subscription_resolution else None),+ openai_api_url=(+ subscription_resolution.api_url if subscription_resolution else openai_api_url+ ),+ require_openai_api_url=bool(openai_api_url),copilot_api_token=(subscription_resolution.token if subscription_resolution else None),copilot_refresh_oauth_token=(subscription_resolution.refresh_oauth_token if subscription_resolution else None@@ -8338,7 +8423,7 @@ def opencode()# Inject Headroom provider into OpenCode config so traffic routes through proxy.- inject_opencode_provider_config(actual_port)+ inject_opencode_provider_config(actual_port, keep_user_entries=bool(openai_api_url))if memory:mem_dir = Path.cwd() / ".headroom"_inject_memory_mcp_config(diff --git a/headroom/providers/opencode/config.py b/headroom/providers/opencode/config.pyindex 08a6f5748..4a0194d01 100644--- a/headroom/providers/opencode/config.py+++ b/headroom/providers/opencode/config.py@@ -178,11 +178,14 @@ def append_headroom_plugin(config: dict[str, object]) -> bool:return True-def inject_opencode_provider_config(port: int) -> None:+def inject_opencode_provider_config(port: int, *, keep_user_entries: bool = False) -> None:"""Inject a Headroom model provider into OpenCode's config file.- Safe to call multiple times — the injected block is fully replaced on- each call, so re-running with a different ``port`` updates the config.+ Safe to call multiple times — the injected block is replaced on each call,+ so re-running with a different ``port`` updates the config. With+ ``keep_user_entries`` the model ids and options the user added under the+ ``headroom`` provider are kept; callers pass it only when they have pointed+ the proxy at an explicit upstream.Before the first injection, the pre-wrap file is snapshotted to``opencode.json.headroom-backup`` so ``headroom unwrap opencode``can restore it byte-for-byte.@@ -207,7 +210,21 @@ def inject_opencode_provider_config(port: int) -> None:data = _parse_json_loose(content)# Merge provider into the JSON data structure.- provider = {"headroom": headroom_provider_entry(port)}+ entry = headroom_provider_entry(port)+ # Keep the user's own model ids and options (an apiKey, say) under the+ # headroom provider: OpenCode only resolves `headroom/<id>` for listed+ # ids, so a third-party upstream needs them. Only when the caller named+ # that upstream, though: otherwise the proxy forwards to OpenAI, and a+ # kept third-party key would be sent there. Headroom still owns npm,+ # name and baseURL.+ providers = data.get("provider")+ existing = providers.get("headroom") if isinstance(providers, dict) else None+ if keep_user_entries and isinstance(existing, dict):+ if isinstance(existing.get("options"), dict):+ entry["options"] = {**existing["options"], **entry["options"]}+ if isinstance(existing.get("models"), dict):+ entry["models"] = {**entry["models"], **existing["models"]}+ provider = {"headroom": entry}data = _inject_key_into_json(data, "provider", provider)# Write back as formatted JSON (opencode uses standard JSON with comments).diff --git a/tests/test_cli/test_wrap_opencode.py b/tests/test_cli/test_wrap_opencode.pyindex 94c51725d..0c49887d7 100644--- a/tests/test_cli/test_wrap_opencode.py+++ b/tests/test_cli/test_wrap_opencode.py@@ -6,6 +6,7 @@ import jsonfrom pathlib import Pathfrom unittest.mock import patch+import clickimport pytestfrom click.testing import CliRunner@@ -1232,3 +1233,440 @@ def test_unwrap_opencode_preserves_utf8_user_content(assert "“smart quotes”" in contentassert "—" in contentassert wrap_mod._PROVIDER_MARKER_START not in content+++def _capture_ensure_proxy_kwargs(+ runner: CliRunner,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ argv: list[str],+) -> dict[str, object]:+ """Run `wrap opencode` with a stubbed proxy/launch and return _ensure_proxy kwargs."""+ monkeypatch.chdir(tmp_path)+ _set_test_home(monkeypatch, tmp_path)+ captured: dict[str, object] = {}++ def fake_ensure_proxy(port: int, no_proxy: bool, **kwargs): # noqa: ANN003+ captured.update(kwargs, no_proxy=no_proxy)+ return None, port++ with (+ patch.object(wrap_mod.shutil, "which", return_value="opencode"),+ patch.object(wrap_mod, "_ensure_proxy", side_effect=fake_ensure_proxy),+ patch.object(wrap_mod, "_launch_tool"),+ ):+ result = runner.invoke(main, argv)++ assert result.exit_code == 0, result.output+ return captured+++def test_wrap_opencode_forwards_openai_api_url_to_proxy(+ runner: CliRunner,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """--openai-api-url points the proxy at a third-party OpenAI-compatible upstream (#3107)."""+ monkeypatch.delenv("OPENAI_TARGET_API_URL", raising=False)+ captured = _capture_ensure_proxy_kwargs(+ runner,+ monkeypatch,+ tmp_path,+ [+ "wrap",+ "opencode",+ "--port",+ "9000",+ "--no-mcp",+ "--no-serena",+ "--openai-api-url",+ "https://api.deepseek.com/v1",+ ],+ )++ assert captured["openai_api_url"] == "https://api.deepseek.com/v1"+++def test_wrap_opencode_honors_openai_target_api_url_env(+ runner: CliRunner,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """OPENAI_TARGET_API_URL is honored without the flag, matching `headroom proxy`."""+ monkeypatch.setenv("OPENAI_TARGET_API_URL", "https://api.deepseek.com/v1")+ captured = _capture_ensure_proxy_kwargs(+ runner,+ monkeypatch,+ tmp_path,+ ["wrap", "opencode", "--port", "9000", "--no-mcp", "--no-serena"],+ )++ assert captured["openai_api_url"] == "https://api.deepseek.com/v1"+++def test_wrap_opencode_without_openai_api_url_leaves_upstream_unset(+ runner: CliRunner,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """No override means the proxy keeps its own default upstream resolution."""+ monkeypatch.delenv("OPENAI_TARGET_API_URL", raising=False)+ captured = _capture_ensure_proxy_kwargs(+ runner,+ monkeypatch,+ tmp_path,+ ["wrap", "opencode", "--port", "9000", "--no-mcp", "--no-serena"],+ )++ assert captured["openai_api_url"] is None+++def test_wrap_opencode_rejects_openai_api_url_with_copilot_subscription(+ runner: CliRunner,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The Copilot subscription resolves its own upstream; a manual override would fight it."""+ monkeypatch.chdir(tmp_path)+ _set_test_home(monkeypatch, tmp_path)+ _clear_copilot_route_config(monkeypatch)+ monkeypatch.delenv("OPENAI_TARGET_API_URL", raising=False)++ with patch.object(wrap_mod, "_ensure_proxy", side_effect=AssertionError("proxy launched")):+ result = runner.invoke(+ main,+ [+ "wrap",+ "opencode",+ "--copilot-subscription",+ "--openai-api-url",+ "https://api.deepseek.com/v1",+ ],+ )++ assert result.exit_code != 0+ assert "cannot be combined with --copilot-subscription" in result.output+++def _no_proxy_health(openai_api_url: str | None) -> dict[str, object]:+ """A /health payload from a Headroom listener advertising ``openai_api_url``."""+ return {+ "version": wrap_mod._HEADROOM_VERSION,+ "config": {+ "pid": "12345",+ "memory": False,+ "learn": False,+ "code_graph": False,+ "openai_api_url": openai_api_url,+ },+ }+++def test_no_proxy_with_openai_api_url_rejects_absent_listener(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """--no-proxy cannot honor an upstream override when nothing is listening."""+ monkeypatch.setattr(wrap_mod, "_check_proxy", lambda _port: False)+ monkeypatch.setattr(wrap_mod, "_query_proxy_health", lambda _port: None)+ monkeypatch.setattr(wrap_mod, "_query_proxy_config", lambda _port: None)++ with pytest.raises(click.ClickException) as excinfo:+ wrap_mod._ensure_proxy_unlocked(+ 8787,+ True,+ openai_api_url="https://api.deepseek.com/v1",+ require_openai_api_url=True,+ )++ message = str(excinfo.value)+ assert "No Headroom proxy" in message+ assert "headroom proxy --port 8787 --openai-api-url https://api.deepseek.com/v1" in message+++def test_no_proxy_with_openai_api_url_rejects_non_headroom_listener(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A port that accepts connections but exposes no Headroom config is not trusted."""+ monkeypatch.setattr(wrap_mod, "_check_proxy", lambda _port: True)+ monkeypatch.setattr(wrap_mod, "_query_proxy_health", lambda _port: None)+ monkeypatch.setattr(wrap_mod, "_query_proxy_config", lambda _port: None)++ with pytest.raises(click.ClickException) as excinfo:+ wrap_mod._ensure_proxy_unlocked(+ 8787,+ True,+ openai_api_url="https://api.deepseek.com/v1",+ require_openai_api_url=True,+ )++ message = str(excinfo.value)+ assert "did not report a Headroom config" in message+ assert "headroom proxy --port 8787 --openai-api-url https://api.deepseek.com/v1" in message+++def test_no_proxy_with_openai_api_url_reuses_matching_listener(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A running proxy already pointed at the requested upstream is reused as-is."""+ monkeypatch.setattr(wrap_mod, "_check_proxy", lambda _port: True)+ # Trailing slash on the advertised URL: the comparison must be normalized.+ monkeypatch.setattr(+ wrap_mod,+ "_query_proxy_health",+ lambda _port: _no_proxy_health("https://api.deepseek.com/v1/"),+ )+ monkeypatch.setattr(+ wrap_mod,+ "_query_proxy_config",+ lambda _port: pytest.fail("config must come from the /health payload"),+ )++ assert wrap_mod._ensure_proxy_unlocked(+ 8787,+ True,+ openai_api_url="https://api.deepseek.com/v1",+ require_openai_api_url=True,+ ) == (None, 8787)+++def test_no_proxy_with_openai_api_url_still_warns_about_a_mode_mismatch(+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+) -> None:+ """Reusing a matching upstream keeps the mode warning every other reuse path gives."""+ health = _no_proxy_health("https://api.deepseek.com/v1")+ health["config"]["mode"] = "cache" # type: ignore[index]+ monkeypatch.setenv("HEADROOM_MODE", "token")+ monkeypatch.setattr(wrap_mod, "_check_proxy", lambda _port: True)+ monkeypatch.setattr(wrap_mod, "_query_proxy_health", lambda _port: health)++ wrap_mod._ensure_proxy_unlocked(+ 8787,+ True,+ openai_api_url="https://api.deepseek.com/v1",+ require_openai_api_url=True,+ )++ out = capsys.readouterr().out+ assert "requested 'token' mode but the running proxy is in 'cache' mode" in out+++def test_no_proxy_with_openai_api_url_rejects_mismatched_listener(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A proxy on the default OpenAI upstream must not receive a DeepSeek-bound key (#3107)."""+ monkeypatch.setattr(wrap_mod, "_check_proxy", lambda _port: True)+ monkeypatch.setattr(wrap_mod, "_query_proxy_health", lambda _port: _no_proxy_health(None))+ monkeypatch.setattr(wrap_mod, "_query_proxy_config", lambda _port: None)++ with pytest.raises(click.ClickException) as excinfo:+ wrap_mod._ensure_proxy_unlocked(+ 8787,+ True,+ openai_api_url="https://api.deepseek.com/v1",+ require_openai_api_url=True,+ )++ message = str(excinfo.value)+ assert "https://api.openai.com/v1" in message+ assert "https://api.deepseek.com/v1" in message+ assert "headroom proxy --port 8787 --openai-api-url https://api.deepseek.com/v1" in message+++def test_no_proxy_without_required_openai_api_url_keeps_lenient_reuse(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Wrappers with a built-in upstream (grok, kimi, ...) keep the historical warn-and-reuse."""+ monkeypatch.setattr(wrap_mod, "_check_proxy", lambda _port: False)+ monkeypatch.setattr(+ wrap_mod,+ "_query_proxy_health",+ lambda _port: pytest.fail("no upstream check without require_openai_api_url"),+ )++ assert wrap_mod._ensure_proxy_unlocked(8787, True, openai_api_url="https://api.x.ai/v1") == (+ None,+ 8787,+ )+++def test_wrap_opencode_no_proxy_requires_openai_api_url_match(+ runner: CliRunner,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """--no-proxy with an upstream override asks _ensure_proxy to fail closed on a mismatch."""+ monkeypatch.delenv("OPENAI_TARGET_API_URL", raising=False)+ # A listener that already matches, so the up-front check lets the wrap through.+ monkeypatch.setattr(wrap_mod, "_check_proxy", lambda _port: True)+ monkeypatch.setattr(+ wrap_mod,+ "_query_proxy_health",+ lambda _port: _no_proxy_health("https://api.deepseek.com/v1"),+ )+ captured = _capture_ensure_proxy_kwargs(+ runner,+ monkeypatch,+ tmp_path,+ [+ "wrap",+ "opencode",+ "--port",+ "9000",+ "--no-mcp",+ "--no-serena",+ "--no-proxy",+ "--openai-api-url",+ "https://api.deepseek.com/v1",+ ],+ )++ assert captured["no_proxy"] is True+ assert captured["openai_api_url"] == "https://api.deepseek.com/v1"+ assert captured["require_openai_api_url"] is True+++def test_wrap_opencode_no_proxy_rejects_a_mismatched_upstream_before_editing_config(+ runner: CliRunner,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A refused --no-proxy upstream leaves OpenCode's config and the client markers alone."""+ monkeypatch.delenv("OPENAI_TARGET_API_URL", raising=False)+ monkeypatch.chdir(tmp_path)+ _set_test_home(monkeypatch, tmp_path)+ monkeypatch.setattr(wrap_mod, "_check_proxy", lambda _port: True)+ monkeypatch.setattr(wrap_mod, "_query_proxy_health", lambda _port: _no_proxy_health(None))+ registered: list[int] = []+ monkeypatch.setattr(wrap_mod, "_register_proxy_client", registered.append)++ with (+ patch.object(wrap_mod.shutil, "which", return_value="opencode"),+ patch.object(wrap_mod, "_ensure_proxy", side_effect=AssertionError("must not be reached")),+ patch.object(wrap_mod, "_launch_tool"),+ ):+ result = runner.invoke(+ main,+ [+ "wrap",+ "opencode",+ "--port",+ "9000",+ "--no-proxy",+ "--openai-api-url",+ "https://api.deepseek.com/v1",+ ],+ )++ assert result.exit_code != 0+ assert "not https://api.deepseek.com/v1" in result.output+ assert not (tmp_path / ".config" / "opencode").exists()+ assert registered == []+++def _write_user_headroom_provider(tmp_path: Path) -> Path:+ config_file = tmp_path / ".config" / "opencode" / "opencode.json"+ config_file.parent.mkdir(parents=True, exist_ok=True)+ config_file.write_text(+ json.dumps(+ {+ "provider": {+ "headroom": {+ "options": {"apiKey": "{env:DEEPSEEK_API_KEY}"},+ "models": {"deepseek-chat": {"name": "DeepSeek Chat"}},+ }+ }+ }+ ),+ encoding="utf-8",+ )+ return config_file+++ ("extra_args", "kept"),+ [(["--openai-api-url", "https://api.deepseek.com/v1"], True), ([], False)],+)+def test_wrap_opencode_keeps_the_users_headroom_key_only_for_an_explicit_upstream(+ runner: CliRunner,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ extra_args: list[str],+ kept: bool,+) -> None:+ """Without --openai-api-url the proxy forwards to OpenAI, so a third-party key must not be kept."""+ monkeypatch.delenv("OPENAI_TARGET_API_URL", raising=False)+ config_file = _write_user_headroom_provider(tmp_path)++ _capture_ensure_proxy_kwargs(+ runner,+ monkeypatch,+ tmp_path,+ ["wrap", "opencode", "--port", "9000", "--no-mcp", "--no-serena", *extra_args],+ )++ headroom = json.loads(config_file.read_text(encoding="utf-8"))["provider"]["headroom"]+ assert ("apiKey" in headroom["options"]) is kept+ assert ("deepseek-chat" in headroom["models"]) is kept+ assert headroom["options"]["baseURL"] == "http://127.0.0.1:9000/v1"+++def test_wrap_opencode_prepare_only_does_not_need_the_no_proxy_listener(+ runner: CliRunner,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """--prepare-only never uses a proxy, so it must not insist one is already running."""+ monkeypatch.delenv("OPENAI_TARGET_API_URL", raising=False)+ monkeypatch.chdir(tmp_path)+ _set_test_home(monkeypatch, tmp_path)+ config_file = _write_user_headroom_provider(tmp_path)+ monkeypatch.setattr(wrap_mod, "_check_proxy", lambda _port: False)++ result = runner.invoke(+ main,+ [+ "wrap",+ "opencode",+ "--port",+ "9000",+ "--no-mcp",+ "--no-serena",+ "--prepare-only",+ "--no-proxy",+ "--openai-api-url",+ "https://api.deepseek.com/v1",+ ],+ )++ assert result.exit_code == 0, result.output+ headroom = json.loads(config_file.read_text(encoding="utf-8"))["provider"]["headroom"]+ assert headroom["options"]["apiKey"] == "{env:DEEPSEEK_API_KEY}"+++def _has_control_chars(text: str) -> list[str]:+ return sorted({hex(ord(ch)) for ch in text if ord(ch) < 0x20 and ch not in "\n\t"})+++def test_opencode_help_keeps_its_unwrapped_examples(runner: CliRunner) -> None:+ # Wide enough that a paragraph Click reflows would join these commands; at+ # the default 80 columns the reflow can happen to break at the same places.+ result = runner.invoke(+ main, ["wrap", "opencode", "--help"], terminal_width=200, max_content_width=200+ )++ assert result.exit_code == 0, result.output+ assert _has_control_chars(result.output) == []+ lines = [line.strip() for line in result.output.splitlines()]+ # Click's no-rewrap marker must keep each example on its own line; without it+ # the paragraph is reflowed and these commands are joined into prose.+ assert "headroom wrap opencode --openai-api-url https://api.deepseek.com/v1" in lines+ assert "OPENAI_TARGET_API_URL=https://api.deepseek.com/v1 headroom wrap opencode" in lines+ assert "headroom wrap opencode --backend anyllm --anyllm-provider groq" in lines+ assert 'provided". Point the proxy at the real upstream instead:' in lines+++def test_wrap_source_has_no_raw_control_bytes() -> None:+ # In a normal docstring "\b" already becomes 0x08 at runtime, so --help cannot+ # tell the escape from a raw 0x08 byte typed into the file. Check the bytes.+ source = Path(wrap_mod.__file__).read_bytes().decode("utf-8")+ assert _has_control_chars(source.replace("\r", "")) == []diff --git a/tests/test_providers_opencode_config.py b/tests/test_providers_opencode_config.pyindex aec387013..eb50813fe 100644--- a/tests/test_providers_opencode_config.py+++ b/tests/test_providers_opencode_config.py@@ -218,6 +218,84 @@ def test_inject_provider_config_idempotent(tmp_path: Path, monkeypatch: pytest.Massert config["provider"]["headroom"]["options"]["baseURL"] == "http://127.0.0.1:9999/v1"+def test_inject_provider_config_keeps_the_users_models_and_options(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A third-party upstream needs its own model ids and key under `headroom`.++ OpenCode only resolves `headroom/<id>` for listed ids, so wiping the user's+ entries made `wrap opencode --openai-api-url ...` unusable for DeepSeek.+ """+ _set_test_home(monkeypatch, tmp_path)+ config_file = tmp_path / ".config" / "opencode" / "opencode.json"+ config_file.parent.mkdir(parents=True)+ config_file.write_text(+ json.dumps(+ {+ "provider": {+ "headroom": {+ "npm": "something-else",+ "options": {+ "apiKey": "{env:DEEPSEEK_API_KEY}",+ "baseURL": "https://api.deepseek.com/v1",+ },+ "models": {"deepseek-chat": {"name": "DeepSeek Chat"}},+ },+ "anthropic": {"options": {"timeout": 5}},+ }+ }+ ),+ encoding="utf-8",+ )++ inject_opencode_provider_config(port=8787, keep_user_entries=True)+ inject_opencode_provider_config(port=9999, keep_user_entries=True)++ config = _parse_json_loose(config_file.read_text())+ headroom = config["provider"]["headroom"]+ # Headroom still owns how the provider reaches the proxy.+ assert headroom["npm"] == "@ai-sdk/openai-compatible"+ assert headroom["options"]["baseURL"] == "http://127.0.0.1:9999/v1"+ # The user's key and model ids survive alongside Headroom's defaults.+ assert headroom["options"]["apiKey"] == "{env:DEEPSEEK_API_KEY}"+ assert set(headroom["models"]) == {"deepseek-chat", "gpt-4o", "gpt-4.1"}+ assert headroom["models"]["deepseek-chat"] == {"name": "DeepSeek Chat"}+ assert config["provider"]["anthropic"] == {"options": {"timeout": 5}}+++def test_inject_provider_config_drops_user_entries_without_an_explicit_upstream(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Without a named upstream the proxy forwards to OpenAI, so a kept key would go there."""+ _set_test_home(monkeypatch, tmp_path)+ config_file = tmp_path / ".config" / "opencode" / "opencode.json"+ config_file.parent.mkdir(parents=True)+ config_file.write_text(+ json.dumps(+ {+ "provider": {+ "headroom": {+ "npm": "something-else",+ "options": {+ "apiKey": "{env:DEEPSEEK_API_KEY}",+ "baseURL": "https://api.deepseek.com/v1",+ },+ "models": {"deepseek-chat": {"name": "DeepSeek Chat"}},+ },+ "anthropic": {"options": {"timeout": 5}},+ }+ }+ ),+ encoding="utf-8",+ )++ inject_opencode_provider_config(port=8787)++ headroom = _parse_json_loose(config_file.read_text())["provider"]["headroom"]+ assert "apiKey" not in headroom["options"]+ assert set(headroom["models"]) == {"gpt-4o", "gpt-4.1"}++# ---------------------------------------------------------------------------# Edge cases — JSON parsing# ---------------------------------------------------------------------------