fix(wrap): let wrap opencode target a third-party OpenAI-compatible upstream (#3125)

## Description

`headroom wrap opencode` had no way to say where OpenAI-compatible
traffic should go. `opencode()` forwarded `openai_api_url` to
`_ensure_proxy` only for `--copilot-subscription`; every other run
inherited the proxy default, `https://api.openai.com/v1`. A user
following the README's agent-wrap table with a DeepSeek key therefore
had that key presented to OpenAI, which rejected it with `401 Incorrect
API key provided` and pointed them at a `platform.openai.com` dashboard
for a key they never had. Meanwhile
`docs/content/docs/opencode-deepseek.mdx` said "Do not use `headroom
wrap`", with nothing reconciling the two.

This adds the missing plumbing (`--openai-api-url` /
`OPENAI_TARGET_API_URL`, mirroring `headroom proxy`) and the
documentation the issue asked for.

Closes #3107

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/cli/wrap.py`: `wrap opencode` gains `--openai-api-url`, with
`envvar="OPENAI_TARGET_API_URL"`, mirroring `headroom proxy
--openai-api-url`. It is passed to `_ensure_proxy`, which already knows
how to start the proxy with it and how to report a mismatch against an
already-running proxy.
- `headroom/cli/wrap.py`: combining `--openai-api-url` with
`--copilot-subscription` raises a `ClickException` before anything is
mutated — the subscription resolves its own upstream, so a manual
override would silently fight it.
- `headroom/cli/wrap.py`: the `opencode` docstring documents the default
upstream and both invocation forms.
- `headroom/cli/wrap.py`: `--no-proxy` combined with an upstream
override now fails closed (review). New
`_require_no_proxy_openai_upstream(port, url)` requires a healthy
Headroom listener whose `/health` config advertises the same
`openai_api_url` after `_normalize_proxy_api_url`; an absent listener, a
listener with no Headroom config, or a mismatched upstream each raise a
`ClickException` that names the exact `headroom proxy --port N
--openai-api-url URL` command to run. The check is opted into via a new
`require_openai_api_url` keyword on `_ensure_proxy_unlocked`, set only
by `wrap opencode`, so wrappers that pass a built-in upstream (`vibe`,
`kimi`, `grok`, `zcode`) keep their existing warn-and-reuse `--no-proxy`
behaviour. On a match wrap prints `Proxy on port N already targets URL`,
warns about a proxy-mode mismatch like the other reuse paths, and
continues. `wrap opencode` runs this check before it touches OpenCode's
config or registers a client marker, so a refused upstream leaves
nothing behind. `--prepare-only` skips it, since it never uses a proxy.
- `headroom/providers/opencode/config.py`:
`inject_opencode_provider_config(port, keep_user_entries=...)` keeps the
user's own `models` and `options` (an `apiKey`, say) under
`provider.headroom` instead of replacing the entry; Headroom still owns
`npm`, `name` and `baseURL`. `wrap opencode` passes `keep_user_entries`
only when `--openai-api-url` (or `OPENAI_TARGET_API_URL`) is set.
Without it the proxy forwards to OpenAI, so a kept third-party key would
be sent there, and wrap writes Headroom's entry as before. OpenCode only
resolves `headroom/<id>` for listed ids, so without this a DeepSeek user
had no DeepSeek model to select (`ProviderModelNotFoundError`) and no
key to send.
- `docs/content/docs/opencode.mdx`: `--openai-api-url` documented on the
canonical OpenCode page (Options block, prose, env-var table), with a
two-form example — wrap starts the proxy, or `headroom proxy
--openai-api-url …` then `wrap --no-proxy --openai-api-url …` — and a
paragraph stating that `--no-proxy` verifies and refuses rather than
re-points.
- `docs/content/docs/opencode-deepseek.mdx`: new "Common issues" entry
for the `Incorrect API key provided` 401 (it comes from OpenAI, not
DeepSeek) and a "When is `headroom wrap opencode` safe?" section — safe
as-is for the default OpenAI/Anthropic upstreams, needs
`--openai-api-url` for any third-party OpenAI-compatible provider, and
that wrap keeps the step 4 `models` and `apiKey` under
`provider.headroom` (DeepSeek needs both). The "Models appear but
requests fail" entry and the "What's NOT in this guide" bullet are
reworded to match, replacing the blanket "do not use `headroom wrap`".
- `README.md`: footnote on the OpenCode row of the agent compatibility
matrix naming the default upstream and the flag/env var.
- `tests/test_cli/test_wrap_opencode.py`: ten tests — the flag, the env
var, the unset default, the `--copilot-subscription` rejection; for
`--no-proxy`: absent, non-Headroom, matching (trailing slash, proving
normalization), and mismatched listeners; that wrappers without
`require_openai_api_url` keep lenient reuse; and that the CLI forwards
the flag. With the fix reverted, 5 of the 6 new tests fail. Review
follow-ups add: `wrap opencode --help` keeps its examples unwrapped and
`wrap.py` has no raw control bytes; a refused `--no-proxy` upstream
exits before any OpenCode config edit or client marker; the
matching-upstream path still warns about a mode mismatch.
- `tests/test_providers_opencode_config.py`: with `keep_user_entries`
the user's `headroom` models and `apiKey` survive re-injection, other
providers are untouched, and Headroom's `npm`/`baseURL` win; without it
they are dropped.
- `tests/test_cli/test_wrap_opencode.py` (second round): through the CLI
the key is kept with `--openai-api-url` and dropped without it, and
`--prepare-only --no-proxy --openai-api-url` writes config with no proxy
listening.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

Four failures in the wider `tests/test_cli` run are pre-existing and
Windows-only — they reproduce identically with this branch's changes
stashed: symlink/settings-path issues in `test_recover_codex.py` and
`test_unwrap_claude.py`, and `signal.SIGHUP` (absent on Windows) in
`test_wrap_stale_marker.py`. They are deselected below.
`tests/test_cli_proxy_improvements.py` and
`tests/test_memory/test_learn_flag.py` cannot run from this source
checkout because the Rust `headroom._core` extension is not built here
(same result on the clean branch); CI builds the wheel.

### Test Output

```text
$ python -m pytest tests/test_cli/test_wrap_opencode.py -q
50 passed, 1 warning in 1.96s

$ python -m pytest tests/test_cli -q     --deselect tests/test_cli/test_recover_codex.py     --deselect tests/test_cli/test_unwrap_claude.py     --deselect "tests/test_cli/test_wrap_stale_marker.py::test_signal_handler_unwinds_so_the_restore_can_run"
706 passed, 1 skipped, 46 deselected, 1 warning in 60.41s

$ git stash push -- headroom/cli/wrap.py && python -m pytest tests/test_cli/test_wrap_opencode.py -q -k no_proxy
5 failed, 2 passed   # the new tests fail without the fix; the 2 passing pin unchanged behaviour

$ python -m ruff check .
All checks passed!

$ python -m ruff format --check .
1577 files already formatted

$ python -m mypy headroom
Success: no issues found in 532 source files

$ python -m coverage run --include=headroom/cli/wrap.py -m pytest tests/test_cli/test_wrap_opencode.py -q
50 passed   # 17/17 statements added to wrap.py executed, 0 missing
# Review follow-ups (this branch, with current main merged in)
$ pytest tests/test_cli/test_wrap_opencode.py tests/test_providers_opencode_config.py
102 passed, 1 failed  # test_build_launch_env_with_project: a known Windows-only path-escaping failure, also on main
# each new test fails on the code before its fix:
test_inject_provider_config_keeps_the_users_models_and_options -> KeyError: 'apiKey'
test_no_proxy_with_openai_api_url_still_warns_about_a_mode_mismatch -> warning missing from output
test_wrap_opencode_no_proxy_rejects_a_mismatched_upstream_before_editing_config -> "MCP retrieve tool: registered", then _ensure_proxy reached
test_wrap_opencode_keeps_the_users_headroom_key_only_for_an_explicit_upstream[no flag] -> key kept (would go to OpenAI)
test_wrap_opencode_prepare_only_does_not_need_the_no_proxy_listener -> "No Headroom proxy is listening on port 9000"
# help test: dropping either no-rewrap marker, or writing a raw 0x08 byte, fails a test (3/3)
$ ruff check / ruff format --check (0.16.8): clean
$ mypy headroom/cli/wrap.py headroom/providers/opencode/config.py --ignore-missing-imports --follow-imports=silent
Success: no issues found in 2 source files
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.11.9, headroom 0.35.0 (`rust_core:
loaded`), with a stub `opencode` on `PATH` that curls the proxy's
`/health` — so the wrapped agent reports the upstream the proxy actually
resolved.
- Exact command / steps: (1) baseline against released 0.35.0 without
this fix on `sys.path` — `python -m headroom.cli wrap opencode --port
8799 --no-mcp --no-serena --openai-api-url https://api.deepseek.com/v1`;
(2) same command on this branch, port 8801; (3) env-var form on this
branch — `OPENAI_TARGET_API_URL=https://api.deepseek.com/v1 python -m
headroom.cli wrap opencode --port 8802 --no-mcp --no-serena`. For the
`--no-proxy` review: `python -m headroom.cli wrap opencode --port <P>
--no-proxy --no-mcp --no-serena --openai-api-url
https://api.deepseek.com/v1` on this branch against (4) nothing on 8811;
(5) `python -m http.server 8812`; (6) a real released-0.35.0 `headroom
proxy --port 8813` (default upstream, `/health` reports
`"openai_api_url": null`); (7) a real `headroom proxy --port 8814
--openai-api-url https://api.deepseek.com/v1`.
- Observed result: step 1 reproduces the bug exactly — wrap prints
`Extra args: --openai-api-url https://api.deepseek.com/v1` (the flag is
swallowed by `ignore_unknown_options` and handed to the agent) and the
proxy it started reports `"openai_api_url": null`, i.e. it would forward
to `api.openai.com`. Step 2 prints no `Extra args` line and the proxy
reports `"openai_api_url": "https://api.deepseek.com/v1"`. Step 3
reports the same. All three runs cleaned up their proxy on exit — no
listener left on 8799/8801/8802. Steps 4–6 each exit 1 before `opencode`
is launched, with: (4) `No Headroom proxy is listening on port 8811 …
Start it separately with `headroom proxy --port 8811 --openai-api-url
https://api.deepseek.com/v1`, or drop --no-proxy …`; (5) `The listener
on port 8812 did not report a Headroom config, so wrap cannot confirm it
forwards to https://api.deepseek.com/v1 …`; (6) `The Headroom proxy on
port 8813 forwards OpenAI-compatible traffic to
https://api.openai.com/v1, not https://api.deepseek.com/v1. Restart it
with …` — and the 8813 proxy is left running, still reporting `null`.
Step 7 prints `Proxy on port 8814 already targets
https://api.deepseek.com/v1` and launches the stub (exit 0). Both
proxies were stopped afterwards; 8811–8814 verified free.
- Real OpenCode (review follow-up): OpenCode 1.18.34 installed from npm
into a scratch directory with an isolated `HOME`, and a local fake
OpenAI-compatible "DeepSeek" upstream on 8792 that records each
request's model and `Authorization` header. The global `opencode.json`
declares `provider.headroom.models.deepseek-chat` and `options.apiKey:
"{env:DEEPSEEK_API_KEY}"`. Command: `headroom wrap opencode --port 8796
--openai-api-url http://127.0.0.1:8792/v1 --no-mcp --no-serena -- run
"say hi" -m headroom/deepseek-chat`.
- before this commit: `ProviderModelNotFoundError: Model not found:
headroom/deepseek-chat.` Nothing reached the upstream, and the config
after wrap held only `gpt-4o` and `gpt-4.1` under `headroom`, with no
`apiKey`.
- after (re-run on the final head e8754b61): OpenCode printed `> build ·
deepseek-chat` and `hello from fake deepseek`. The upstream logged
`{"path": "/v1/chat/completions", "model": "deepseek-chat", "auth":
"Bearer sk-fa...", "stream": true}`. The config kept `apiKey` and
`deepseek-chat` alongside Headroom's `baseURL` and defaults.
- Not tested: a live request against `api.deepseek.com` with a real key,
since none is available here. The real-OpenCode run above uses a local
fake upstream instead, so it proves model selection, key forwarding and
routing through Headroom but not DeepSeek's own API. The
`--copilot-subscription` rejection was exercised as a unit test, not
against a real Copilot subscription.

## Runtime Rollout Safety

- Rollout-managed feature(s): none — a CLI option and its plumbing, not
gated by the rollout-channel machinery.
- Minimum rollout channel: n/a, not rollout-gated.
- Stable/default behavior changed: no — without the flag and without
`OPENAI_TARGET_API_URL`, `openai_api_url` stays `None` and the proxy
resolves its upstream exactly as before; a test pins this.
- Kill switch / disable path: omit the flag and leave
`OPENAI_TARGET_API_URL` unset — behavior is identical to the previous
default.
- Unsafe override required: no.
- Qualification impact: none — no change to compression, routing, or the
proxy request path; the option only chooses which upstream URL the proxy
is started with.
- Rollback path: revert this commit — no config, cache, or on-disk state
is written by the new option, so a revert needs no cleanup.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

n/a — CLI and docs change.

## Additional Notes

- The `x-headroom-base-url` header workaround from the issue is
deliberately left out of the DeepSeek guide. With `--openai-api-url` the
proxy targets the right upstream directly, so the header is no longer
needed for this case. It stays documented where it belongs, in
`configuration.mdx` and `pipeline-extensions.mdx`, as a per-request
override.
- Scope is intentionally limited to `wrap opencode`, the command named
in the issue. Other `wrap` subcommands that hardcode an upstream
(`mistral`, `kimi`, `grok`) or detect one (`zcode`) are unaffected;
giving the whole wrap family a uniform upstream override is a reasonable
follow-up, not this fix.

---------

Co-authored-by: Jerrett Davis <mxjerrett@gmail.com>
This commit is contained in:
Ayush Kumar Jha
2026-10-06 08:45:54 -05:00
committed by GitHub
co-authored by Jerrett Davis
parent f37980f7f7
commit 0d7d61d5cc
7 changed files with 708 additions and 13 deletions
+3 -1
View File
@@ -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`,
+51 -4
View File
@@ -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` are
compatibility aliases slated for removal; use `deepseek-v4-pro` and
`deepseek-v4-flash` instead
+28
View File
@@ -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 Mapping
The 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 Learning
+89 -4
View File
@@ -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 e
else:
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",
)
@click.option(
"--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 port
headroom wrap opencode --backend anyllm --anyllm-provider groq
headroom 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 = None
if 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(
+21 -4
View File
@@ -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).
+438
View File
@@ -6,6 +6,7 @@ import json
from pathlib import Path
from unittest.mock import patch
import click
import pytest
from click.testing import CliRunner
@@ -1232,3 +1233,440 @@ def test_unwrap_opencode_preserves_utf8_user_content(
assert "“smart quotes”" in content
assert "—" in content
assert 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
@pytest.mark.parametrize(
("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", "")) == []
+78
View File
@@ -218,6 +218,84 @@ def test_inject_provider_config_idempotent(tmp_path: Path, monkeypatch: pytest.M
assert 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
# ---------------------------------------------------------------------------