fix(wrap): keep OpenCode's headroom key only for an explicit upstream; allow --prepare-only offline

Keeping the user's `provider.headroom` models and `apiKey` is only safe when
`--openai-api-url` names the upstream they belong to. Without it the proxy
forwards to OpenAI, so a kept DeepSeek key would be sent there. Wrap now
keeps them only when the flag (or OPENAI_TARGET_API_URL) is set, and
otherwise writes Headroom's provider entry as before.

The up-front `--no-proxy` upstream check also ran for `--prepare-only`,
which writes config without ever using a proxy, so offline setup failed.
Skip it there.

The DeepSeek guide now says when wrap keeps the entries, and that it adds
its default GPT model ids next to them.

Refs #3107
This commit is contained in:
Ayushraj06-bit
2026-10-06 07:46:05 +05:30
parent bb2d5c6eb6
commit e8754b61f5
5 changed files with 138 additions and 18 deletions
+8 -5
View File
@@ -201,9 +201,10 @@ API key to the proxy, and the proxy forwards it to DeepSeek. Make sure
### Models appear but requests fail
You ran `headroom wrap opencode` without telling it about DeepSeek. Wrap keeps
the `apiKey` and `models` entries from step 4, but the proxy it starts forwards
OpenAI-compatible traffic to OpenAI unless you name another upstream. Pass
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.
@@ -247,8 +248,10 @@ that other clients may be sharing.
- **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}"`).
Wrap keeps both and only rewrites the provider's `npm`, `name` and
`baseURL`.
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
+3 -3
View File
@@ -8309,7 +8309,7 @@ def opencode(
# 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 no_proxy and openai_api_url:
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
@@ -8349,7 +8349,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
@@ -8406,7 +8406,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(
+12 -8
View File
@@ -178,12 +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 — Headroom's fields are rewritten on each call,
so re-running with a different ``port`` updates the config. Model ids and
options the user added under the ``headroom`` provider are kept.
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.
@@ -210,12 +212,14 @@ def inject_opencode_provider_config(port: int) -> None:
# Merge provider into the JSON data structure.
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 dropping them leaves a third-party upstream with no usable
# model. Headroom still owns npm, name and baseURL.
# 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 isinstance(existing, dict):
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):
+80
View File
@@ -1563,6 +1563,86 @@ def test_wrap_opencode_no_proxy_rejects_a_mismatched_upstream_before_editing_con
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"})
+35 -2
View File
@@ -248,8 +248,8 @@ def test_inject_provider_config_keeps_the_users_models_and_options(
encoding="utf-8",
)
inject_opencode_provider_config(port=8787)
inject_opencode_provider_config(port=9999)
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"]
@@ -263,6 +263,39 @@ def test_inject_provider_config_keeps_the_users_models_and_options(
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
# ---------------------------------------------------------------------------