mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 12:05:34 +08:00
feat(opencode): add repeatable --extra-model flag for custom wrap-time models (#2364)
## Description
`headroom wrap opencode` injects a hardcoded model list
(`HEADROOM_OPENCODE_MODELS`) into the `headroom` provider block of
`opencode.json`. There's no way to add custom models (for example a
free-tier DeepSeek) at wrap time. Hand-patching `opencode.json` is the
only workaround, and the next wrap overwrites it.
This PR adds a repeatable `--extra-model` flag and a
`HEADROOM_OPENCODE_EXTRA_MODELS` env var. Both take
`id[=name[=context_window[=output_limit]]]` specs. Extra models are
merged into the injected provider block alongside the built-ins, and
flag specs win over env specs on id collision. `name` defaults to the
id, `context_window` to 200000, and `output_limit` to `min(16384,
context_window)`.
Fields are separated by `=` rather than `:` because model ids routinely
contain `:`. Ollama ids are `name:tag` (`qwen2.5-coder:7b`), and
OpenRouter free-tier ids end in `:free`. With a `:` separator those were
silently cut down to a different id (Devin review, 2026-10-03).
The PR also fixes the wrap/unwrap lifecycle the flag depends on. A wrap
that starts without an `opencode.json` used to write the file with no
backup and no record of what Headroom put in it, so `headroom unwrap
opencode` left the injected models and the proxy base URL behind while
reporting that OpenCode was no longer routed through Headroom, and a
re-wrap under `--openai-api-url` kept an extra model Headroom had
injected but no longer advertised. Wrap now records what it owns in
`opencode.json.headroom-managed.json`, and unwrap uses that record: it
removes the model ids and the base URL Headroom wrote, keeps everything
else in the file, drops an extra model that is no longer requested, and
deletes the config file when Headroom created it and nothing else is
left in it.
Closes #2359
## Type of Change
- [x] Bug fix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [x] Documentation update
- [ ] Refactoring (no functional changes)
## Changes Made
- `headroom/providers/opencode/config.py`:
- New `parse_extra_model_spec()`, which splits on `=` with an optional
fourth `output_limit` field and raises `ValueError` on an empty id or a
non-integer / non-positive limit.
- New `extra_models_from_env()`, which reads comma-separated specs from
`HEADROOM_OPENCODE_EXTRA_MODELS`.
- An `extra_models` parameter threaded through
`headroom_provider_entry()`, `_render_provider_block()` and
`inject_opencode_provider_config()`.
- With `keep_user_entries` (#3125's `--openai-api-url` gate),
`--extra-model` entries win over a kept user entry with the same id.
- New managed-state sidecar (`opencode.json.headroom-managed.json`)
recording the model ids and base URL Headroom injected and whether
Headroom created the config file. `inject_opencode_provider_config()`
writes it on every injection; `record_opencode_config_origin()` marks a
config that Headroom creates because none existed.
- `remove_managed_opencode_provider()` drops the recorded model ids, the
recorded base URL, and the provider block once nothing else is left in
it. Entries the user added or edited are preserved.
- `_drop_stale_managed_models()` prunes an extra model Headroom injected
but no longer advertises, including an extra that overrode a built-in id
and is dropped again, so a re-wrap without the flag restores the
built-in defaults rather than keeping the old override.
- `snapshot_opencode_config_if_unwrapped()` no longer snapshots a config
Headroom wrote itself as pre-wrap content.
- `headroom/providers/opencode/runtime.py`: extras also reach the
launch-time `OPENCODE_CONFIG_CONTENT`.
- `headroom/cli/wrap.py`:
- A repeatable `--extra-model` option on `wrap opencode`. Env and flag
specs are parsed up front, and a malformed spec raises
`click.BadParameter`. The merged dict goes to both
`inject_opencode_provider_config` call sites (prepare-only and launch)
and to the launch env. Also adds a help text and docstring example.
- `wrap opencode` records the config origin before the first config
mutation.
- `unwrap opencode` undoes the recorded provider entries when there is
no pre-wrap backup, keeps the rest of the file, and removes a config
Headroom created once nothing Headroom-owned is left in it.
- `docs/content/docs/opencode.mdx`: new "Adding models" subsection
(format, defaults, Ollama/OpenRouter example, built-in id override, the
env var's no-comma limitation) and an env-var table row. The subsection
and the "How It Works Under The Hood" unwrap step now describe the
managed-state record and the automatic cleanup it enables.
- Tests:
- Spec parsing: full spec with output, defaults, the output cap at small
contexts, colon-bearing ids (`qwen2.5-coder:7b`,
`deepseek/deepseek-chat:free`, a name containing `:`), and invalid specs
including a bad output limit.
- Env parsing, provider-entry merge, and end-to-end inject. Also
@JerrettDavis's collision test across both `keep_user_entries` values.
- CLI: the flag reaches `opencode.json`, the env var persists, both
reach `OPENCODE_CONFIG_CONTENT` on launch, the flag wins over a kept
user entry under `--openai-api-url`, and a malformed spec exits with a
usage error.
- Managed state: the sidecar records the injected ids and base URL, a
config the user already had is not marked as Headroom-created, a re-wrap
does not snapshot Headroom's own config, a dropped extra model is pruned
(including an override of a built-in id, which returns to the built-in
defaults), a user model and a user-edited model survive, and the
provider removal keeps unrelated user entries.
- Lifecycle: a fresh wrap followed by an unwrap removes the config file
again (with and without the MCP entry), user content added after a fresh
wrap survives the unwrap, a re-wrap without the extra model drops the
stale one, and a directly injected provider entry is undone by the
unwrap callback as well.
- A user setting that is false, zero or an empty string is content, not
an empty section: such a setting survives the unwrap instead of costing
the user the whole file.
## Testing
- [x] Unit tests pass locally
- [x] Lint/format/type checks pass locally
- [x] New tests added for new functionality
The new parsing tests fail against the previous `:`-based parser:
```text
FAILED tests/test_providers_opencode_config.py::test_parse_extra_model_spec_keeps_colons_in_ids[qwen2.5-coder:7b-...]
FAILED tests/test_providers_opencode_config.py::test_parse_extra_model_spec_keeps_colons_in_ids[deepseek/deepseek-chat:free=DeepSeek Free-...]
FAILED tests/test_providers_opencode_config.py::test_parse_extra_model_spec_full
...
================ 21 failed, 2 passed, 103 deselected in 0.86s =================
```
With this branch (head 6be848942):
```text
$ pytest tests/test_providers_opencode_config.py tests/test_cli/test_wrap_opencode.py -q
179 passed, 2 skipped in 3.31s
$ pytest tests -q -k "opencode"
322 passed, 26 skipped
$ ruff check headroom/providers/opencode/config.py headroom/cli/wrap.py tests/test_providers_opencode_config.py tests/test_cli/test_wrap_opencode.py
All checks passed!
$ ruff format --check (same files)
4 files already formatted
$ mypy headroom --ignore-missing-imports --no-site-packages
headroom\fileperms.py:92: error: Module has no attribute "fchmod"; maybe "chmod"? [attr-defined]
headroom\proxy\interceptors\astgrep.py:220: error: Module has no attribute "O_DIRECTORY" [attr-defined]
...
Found 7 errors in 2 files (checked 561 source files)
```
The mypy errors are the Windows-only `os.fchmod` / `os.O_DIRECTORY`
false positives in files this PR does not touch. The same Windows
path-escaping failures that `test_build_launch_env_with_project` used to
hit (`tests/test_cli/test_unwrap_claude.py`,
`tests/test_wrap_code_memory.py`, `tests/test_install/test_planner.py`,
`tests/test_cli/test_wrap_stale_marker.py`) reproduce on unchanged
`main` and are unrelated to this change. `Dependency audit (pip-audit)`
passes on this head; only `Rust advisories (cargo audit)` fails, on
advisories published after upstream `main`'s last green run (2026-11-13
04:47) — `quinn-udp` `RUSTSEC-2026-0538` and `rustix`
`RUSTSEC-2026-0486`. `Cargo.lock` on this branch is byte-identical to
upstream `main` (`81818d49`), so the PR does not introduce them.
## Real Behavior Proof
- Environment: Windows 11, Python 3.13, this branch vs. the previous
`:`-based parser and vs. the previous unwrap lifecycle,
`HOME`/`USERPROFILE` pointed at a temp dir.
- Exact command / steps: `headroom wrap opencode --prepare-only
--no-serena --extra-model "qwen2.5-coder:7b" --extra-model
"deepseek/deepseek-chat:free=DeepSeek Free=65536"`, then read
`provider.headroom.models` from `~/.config/opencode/opencode.json`; then
`headroom unwrap opencode --no-stop-proxy` against a config that did not
exist before the wrap.
- Observed result: with the old parser the entries were `qwen2.5-coder`
(name `7b`) and `deepseek/deepseek-chat` (name `free=DeepSeek
Free=65536`, context 200000): wrong ids, and the paid DeepSeek model
instead of the free one. With this branch they're `qwen2.5-coder:7b`
(name defaults to the id, context 200000, output 16384) and
`deepseek/deepseek-chat:free` (name `DeepSeek Free`, context 65536,
output 16384), next to the built-in `gpt-4o` / `gpt-4.1`. After the
unwrap of a fresh wrap, `opencode.json` and its managed-state sidecar
are both gone and no `provider.headroom` block is left. After the unwrap
of a fresh wrap the user had added to, the file keeps the user's own
model id, key and `theme`, and only the injected ids and the
`http://127.0.0.1:8787/v1` base URL are gone.
- Not tested: a full (non-prepare-only) wrap launching the real OpenCode
binary against a live upstream; the OpenCode TS plugin side (extras are
user-supplied and intentionally not synced into
`plugins/opencode/src/provider.ts` `DEFAULT_MODELS`).
## Runtime Rollout Safety
- Rollout-managed feature(s): none; CLI-only opt-in flag and env var on
`headroom wrap opencode`, plus a `opencode.json.headroom-managed.json`
sidecar next to the OpenCode config
- Minimum rollout channel: stable
- Stable/default behavior changed: no. Without `--extra-model` or
`HEADROOM_OPENCODE_EXTRA_MODELS` the injected provider block is
unchanged. `unwrap opencode` now also removes the provider entries
Headroom recorded, which is what it already reported doing
- Kill switch / disable path: drop the flag and unset
`HEADROOM_OPENCODE_EXTRA_MODELS`, then re-wrap; delete the sidecar to
stop Headroom from tracking the config
- Unsafe override required: no
- Qualification impact: none; no proxy, compression or request-path code
changed
- Rollback path: revert the PR; `headroom unwrap opencode` restores the
pre-wrap `opencode.json` when a backup exists
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
<!-- devin-review-badge-begin -->
---
<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/2364"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Fable 5
JD Davis
parent
863b3c7cc7
commit
66e0086952
@@ -42,6 +42,7 @@ headroom wrap opencode \
|
||||
--code-graph \
|
||||
--no-proxy \
|
||||
--openai-api-url https://api.deepseek.com/v1 \
|
||||
--extra-model "deepseek-chat=DeepSeek Chat=65536" \
|
||||
--learn \
|
||||
--memory \
|
||||
--backend anthropic \
|
||||
@@ -90,6 +91,38 @@ The generated `headroom` provider exposes these models through the proxy:
|
||||
|
||||
The default model is `headroom/claude-sonnet-4-6`. Change it in `opencode.json` or in the generated `OPENCODE_CONFIG_CONTENT` payload.
|
||||
|
||||
### Adding models
|
||||
|
||||
OpenCode only resolves `headroom/<id>` for ids listed under the `headroom`
|
||||
provider. Add your own with the repeatable `--extra-model` flag, in the format
|
||||
`id[=name[=context_window[=output_limit]]]`:
|
||||
|
||||
```bash
|
||||
headroom wrap opencode \
|
||||
--openai-api-url https://openrouter.ai/api/v1 \
|
||||
--extra-model "deepseek/deepseek-chat:free=DeepSeek Free=65536" \
|
||||
--extra-model "qwen2.5-coder:7b"
|
||||
```
|
||||
|
||||
Fields are separated by `=` because model ids often contain `:` (Ollama
|
||||
`name:tag`, OpenRouter `:free`). `name` defaults to the id, `context_window` to
|
||||
200000, and `output_limit` to 16384 or the context window, whichever is
|
||||
smaller. An id that matches a built-in model replaces its entry.
|
||||
|
||||
To keep the same models on every wrap, set `HEADROOM_OPENCODE_EXTRA_MODELS` to
|
||||
a comma-separated list of specs. Names in the variable can't contain a comma.
|
||||
When both are set, `--extra-model` wins for the same id.
|
||||
|
||||
With `--openai-api-url`, wrap also keeps the model ids already listed under the
|
||||
`headroom` provider in `opencode.json`. Wrap records the ids it added in
|
||||
`opencode.json.headroom-managed.json`, so the next wrap drops an extra model you
|
||||
no longer pass and keeps the ones you added yourself.
|
||||
|
||||
`headroom unwrap opencode` uses the same record: it removes the model ids and
|
||||
the proxy base URL Headroom wrote, keeps everything else in the file, and
|
||||
deletes the config file when Headroom created it and nothing else is left in
|
||||
it.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
| Variable | Description |
|
||||
@@ -97,6 +130,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_EXTRA_MODELS` | Comma-separated `--extra-model` specs added to the `headroom` provider on every wrap |
|
||||
| `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
|
||||
@@ -177,7 +211,7 @@ const retrieve = createHeadroomRetrieveTool({
|
||||
2. **Runtime config**. `OPENCODE_CONFIG_CONTENT` is set as an env var containing provider, plugin, and optional local MCP JSON. OpenCode reads it at startup and merges it with on-disk config.
|
||||
3. **MCP tools**. Headroom registers `headroom_compress`, `headroom_retrieve`, and `headroom_stats` through `headroom mcp serve` unless `--no-mcp` is set.
|
||||
4. **Native plugin path**. `wrap` loads the transport plugin from a local directory (`plugins/opencode/dist/` in a checkout, `headroom/providers/opencode/_dist/` in the wheel), because OpenCode 2.x only accepts local plugins as directories. The plugin uses `HEADROOM_PROXY_URL` or `http://127.0.0.1:8787` to reach the proxy.
|
||||
5. **Unwrap**. `headroom unwrap opencode` restores `opencode.json` from the pre-wrap backup when present, strips Headroom marker blocks when no backup exists, and unregisters Headroom MCP servers.
|
||||
5. **Unwrap**. `headroom unwrap opencode` restores `opencode.json` from the pre-wrap backup when present, removes the provider entries Headroom recorded in `opencode.json.headroom-managed.json` when no backup exists, strips Headroom marker blocks for older configs, and unregisters Headroom MCP servers.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
@@ -199,7 +233,7 @@ Some gateways validate the client on the wire and reject the proxy hop. Exclude
|
||||
|
||||
**Provider not found after unwrap.**
|
||||
|
||||
If unwrap left the provider configured, run `headroom unwrap opencode` again, or manually restore from `~/.config/opencode/opencode.json.headroom-backup`.
|
||||
If unwrap left the provider configured, run `headroom unwrap opencode` again, or manually restore from `~/.config/opencode/opencode.json.headroom-backup`. When there was no config file before the wrap, there is no backup to restore: unwrap removes the provider entries Headroom recorded in `~/.config/opencode/opencode.json.headroom-managed.json` instead.
|
||||
|
||||
**Proxy port conflict.**
|
||||
|
||||
|
||||
+126
-77
@@ -212,9 +212,17 @@ from headroom.providers.opencode.config import (
|
||||
_MCP_MARKER_START,
|
||||
_PROVIDER_MARKER_END, # noqa: F401
|
||||
_PROVIDER_MARKER_START,
|
||||
_parse_json_loose,
|
||||
clear_managed_state,
|
||||
extra_models_from_env,
|
||||
inject_opencode_provider_config,
|
||||
migrate_legacy_opencode_jsonc_backup,
|
||||
opencode_config_is_empty,
|
||||
opencode_config_paths,
|
||||
parse_extra_model_spec,
|
||||
read_managed_state,
|
||||
record_opencode_config_origin,
|
||||
remove_managed_opencode_provider,
|
||||
snapshot_opencode_config_if_unwrapped,
|
||||
strip_opencode_headroom_blocks,
|
||||
)
|
||||
@@ -3127,10 +3135,9 @@ def _disable_serena_mcp(registrar: Any, *, verbose: bool = False, explicit: bool
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# tokensave — retired; Serena replaced it. The helpers below only clean up a
|
||||
# ======================================================================# tokensave — retired; Serena replaced it. The helpers below only clean up a
|
||||
# tokensave entry a prior release installed, so upgrading users stop launching it.
|
||||
# =============================================================================
|
||||
# ======================================================================
|
||||
|
||||
|
||||
def _remove_headroom_installed_tokensave_mcp(registrar: Any) -> str:
|
||||
@@ -6257,10 +6264,8 @@ def wrap_selfheal(marker: str | None) -> None:
|
||||
_selfheal_dead_wrap_base_url()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Claude Code
|
||||
# =============================================================================
|
||||
|
||||
# ======================================================================# Claude Code
|
||||
# ======================================================================
|
||||
# Hostnames that mean "this machine" — used to avoid feeding the proxy its own
|
||||
# URL back as the upstream when the user already had ANTHROPIC_BASE_URL pointed
|
||||
# at a previous Headroom instance.
|
||||
@@ -6855,9 +6860,8 @@ def claude(
|
||||
cleanup()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Claude Code (unwrap)
|
||||
# =============================================================================
|
||||
# ======================================================================# Claude Code (unwrap)
|
||||
# ======================================================================
|
||||
|
||||
|
||||
def _warn_if_proxy_env_leaked(port: int) -> None:
|
||||
@@ -6988,9 +6992,8 @@ def unwrap_claude(
|
||||
click.echo()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# GitHub Copilot CLI
|
||||
# =============================================================================
|
||||
# ======================================================================# GitHub Copilot CLI
|
||||
# ======================================================================
|
||||
|
||||
|
||||
def _require_copilot_subscription_resolution() -> CopilotSubscriptionTokenResolution:
|
||||
@@ -7339,9 +7342,8 @@ def copilot(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# GitHub Copilot CLI (unwrap)
|
||||
# =============================================================================
|
||||
# ======================================================================# GitHub Copilot CLI (unwrap)
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command("vscode")
|
||||
@@ -7428,9 +7430,8 @@ def unwrap_vscode_copilot(settings_file: Path | None) -> None:
|
||||
click.echo(f"No Headroom Copilot proxy settings found in {target_settings}")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Claude Code for VS Code
|
||||
# =============================================================================
|
||||
# ======================================================================# Claude Code for VS Code
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command("vscode-claude")
|
||||
@@ -7533,9 +7534,8 @@ def unwrap_vscode_claude(settings_file: Path | None) -> None:
|
||||
click.echo(f"No Headroom VS Code Claude settings found for {target_settings}")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# GitHub Copilot CLI (unwrap)
|
||||
# =============================================================================
|
||||
# ======================================================================# GitHub Copilot CLI (unwrap)
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@unwrap.command("copilot")
|
||||
@@ -7549,9 +7549,8 @@ def unwrap_copilot(port: int, no_stop_proxy: bool) -> None:
|
||||
_echo_unwrap_proxy_stop_status(_stop_local_proxy_for_unwrap(port), port)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# OpenAI Codex CLI
|
||||
# =============================================================================
|
||||
# ======================================================================# OpenAI Codex CLI
|
||||
# ======================================================================
|
||||
|
||||
|
||||
def _prepare_codex_wrap_state(
|
||||
@@ -7840,9 +7839,8 @@ def codex(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Aider
|
||||
# =============================================================================
|
||||
# ======================================================================# Aider
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@@ -7916,9 +7914,8 @@ def aider(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Mistral Vibe
|
||||
# =============================================================================
|
||||
# ======================================================================# Mistral Vibe
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@@ -7983,9 +7980,8 @@ def vibe(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Kimi CLI
|
||||
# =============================================================================
|
||||
# ======================================================================# Kimi CLI
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@@ -8072,9 +8068,8 @@ def kimi(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Grok CLI
|
||||
# =============================================================================
|
||||
# ======================================================================# Grok CLI
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@@ -8184,9 +8179,8 @@ def grok(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Cursor
|
||||
# =============================================================================
|
||||
# ======================================================================# Cursor
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@@ -8241,9 +8235,8 @@ def cursor(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Antigravity IDE
|
||||
# =============================================================================
|
||||
# ======================================================================# Antigravity IDE
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@@ -8295,9 +8288,8 @@ def antigravity(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Grok Build
|
||||
# =============================================================================
|
||||
# ======================================================================# Grok Build
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command("grok-build", context_settings={"ignore_unknown_options": True})
|
||||
@@ -8363,9 +8355,8 @@ def grok_build(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Cline (VS Code extension)
|
||||
# =============================================================================
|
||||
# ======================================================================# Cline (VS Code extension)
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@@ -8426,9 +8417,8 @@ def cline(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# ZCode (zcode.z.ai desktop app)
|
||||
# =============================================================================
|
||||
# ======================================================================# ZCode (zcode.z.ai desktop app)
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@@ -8498,9 +8488,8 @@ def zcode(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Continue (VS Code / JetBrains extension)
|
||||
# =============================================================================
|
||||
# ======================================================================# Continue (VS Code / JetBrains extension)
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command("continue", context_settings={"ignore_unknown_options": True})
|
||||
@@ -8641,7 +8630,7 @@ def hermes(
|
||||
|
||||
# =============================================================================
|
||||
# OpenClaw
|
||||
# =============================================================================
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command("openclaw")
|
||||
@@ -8902,9 +8891,8 @@ def openclaw(
|
||||
click.echo()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# OpenCode
|
||||
# =============================================================================
|
||||
# ======================================================================# OpenCode
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@@ -8947,6 +8935,16 @@ def openclaw(
|
||||
)
|
||||
@click.option("--anyllm-provider", default=None, help="Provider for any-llm backend")
|
||||
@click.option("--region", default=None, help="Cloud region for Bedrock/Vertex")
|
||||
@click.option(
|
||||
"--extra-model",
|
||||
"extra_model_specs",
|
||||
multiple=True,
|
||||
help=(
|
||||
"Extra model for the headroom provider, format "
|
||||
"id[=name[=context_window[=output_limit]]] (repeatable; "
|
||||
"env: HEADROOM_OPENCODE_EXTRA_MODELS, comma-separated)"
|
||||
),
|
||||
)
|
||||
@click.option("--verbose", "-v", is_flag=True, help="Verbose output")
|
||||
@click.option("--prepare-only", is_flag=True, hidden=True)
|
||||
@click.argument("opencode_args", nargs=-1, type=click.UNPROCESSED)
|
||||
@@ -8963,6 +8961,7 @@ def opencode(
|
||||
backend: str | None,
|
||||
anyllm_provider: str | None,
|
||||
region: str | None,
|
||||
extra_model_specs: tuple,
|
||||
verbose: bool,
|
||||
prepare_only: bool,
|
||||
opencode_args: tuple,
|
||||
@@ -8985,6 +8984,7 @@ 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 --extra-model "qwen2.5-coder:7b=Qwen Coder=32768"
|
||||
headroom wrap opencode --openai-api-url https://api.deepseek.com/v1
|
||||
|
||||
\b
|
||||
@@ -8997,6 +8997,15 @@ def opencode(
|
||||
headroom wrap opencode --openai-api-url https://api.deepseek.com/v1
|
||||
OPENAI_TARGET_API_URL=https://api.deepseek.com/v1 headroom wrap opencode
|
||||
"""
|
||||
# Env-provided extras persist across re-wraps; flag specs win on id collision.
|
||||
try:
|
||||
extra_models = extra_models_from_env()
|
||||
for spec in extra_model_specs:
|
||||
model_id, entry = parse_extra_model_spec(spec)
|
||||
extra_models[model_id] = entry
|
||||
except ValueError as exc:
|
||||
raise click.BadParameter(str(exc), param_hint="--extra-model") from exc
|
||||
|
||||
subscription_resolution = None
|
||||
if copilot_subscription:
|
||||
if openai_api_url:
|
||||
@@ -9044,6 +9053,9 @@ def opencode(
|
||||
# `headroom unwrap opencode` can restore the user's pre-wrap state.
|
||||
_opencode_config_file, _opencode_backup_file = opencode_config_paths()
|
||||
snapshot_opencode_config_if_unwrapped(_opencode_config_file, _opencode_backup_file)
|
||||
# Without a pre-wrap file there is no backup to restore, so record that
|
||||
# Headroom owns the file it is about to create.
|
||||
record_opencode_config_origin(_opencode_config_file)
|
||||
|
||||
# Register headroom MCP server in OpenCode config so OpenCode can
|
||||
# call headroom_retrieve on compression markers from the proxy.
|
||||
@@ -9078,7 +9090,7 @@ def opencode(
|
||||
_inject_memory_agents_md(agents_md)
|
||||
|
||||
if prepare_only:
|
||||
inject_opencode_provider_config(port, keep_user_entries=bool(openai_api_url))
|
||||
inject_opencode_provider_config(port, extra_models, keep_user_entries=bool(openai_api_url))
|
||||
return
|
||||
|
||||
# Past the prepare-only return the launch path always ran the binary check
|
||||
@@ -9139,11 +9151,14 @@ def opencode(
|
||||
launch_environ,
|
||||
project=_project_name_from_cwd(),
|
||||
include_mcp=not no_mcp,
|
||||
extra_models=extra_models,
|
||||
session_token=_session_token,
|
||||
)
|
||||
|
||||
# Inject Headroom provider into OpenCode config so traffic routes through proxy.
|
||||
inject_opencode_provider_config(actual_port, keep_user_entries=bool(openai_api_url))
|
||||
inject_opencode_provider_config(
|
||||
actual_port, extra_models, keep_user_entries=bool(openai_api_url)
|
||||
)
|
||||
if memory:
|
||||
mem_dir = Path.cwd() / ".headroom"
|
||||
_inject_memory_mcp_config(
|
||||
@@ -9213,13 +9228,15 @@ def unwrap_opencode(port: int, no_stop_proxy: bool) -> None:
|
||||
|
||||
* If a pre-wrap backup (``opencode.json.headroom-backup``) exists, the
|
||||
original file is restored byte-for-byte and the backup is removed.
|
||||
* Otherwise, if Headroom recorded what it owns in the config (the
|
||||
``opencode.json.headroom-managed.json`` sidecar), the injected model
|
||||
ids and baseURL are removed and the rest of the file is preserved.
|
||||
* Otherwise, if the config file still contains the Headroom-managed
|
||||
block, that block is stripped out and the rest of the file is
|
||||
preserved.
|
||||
* If the config only ever contained Headroom-written content, the file
|
||||
is removed entirely so OpenCode falls back to its defaults.
|
||||
* If neither a backup nor a Headroom block is present, this is a safe
|
||||
no-op.
|
||||
* If none of the above applies, this is a safe no-op.
|
||||
"""
|
||||
click.echo()
|
||||
click.echo(" ╔═══════════════════════════════════════════════╗")
|
||||
@@ -9229,6 +9246,8 @@ def unwrap_opencode(port: int, no_stop_proxy: bool) -> None:
|
||||
|
||||
config_file, backup_file = opencode_config_paths()
|
||||
migrate_legacy_opencode_jsonc_backup(config_file, backup_file)
|
||||
managed_state = read_managed_state(config_file)
|
||||
removed_managed = False
|
||||
|
||||
if backup_file.exists():
|
||||
try:
|
||||
@@ -9240,6 +9259,28 @@ def unwrap_opencode(port: int, no_stop_proxy: bool) -> None:
|
||||
raise click.ClickException(
|
||||
f"could not restore OpenCode config from backup: {exc}"
|
||||
) from exc
|
||||
clear_managed_state(config_file)
|
||||
elif config_file.exists() and managed_state is not None:
|
||||
# Headroom wrote this file (or part of it) and recorded what it owns:
|
||||
# undo exactly that, and keep everything the user added.
|
||||
content = _read_text(config_file)
|
||||
data = _parse_json_loose(content)
|
||||
if not data and content.strip():
|
||||
# Unparseable config: leave it alone rather than rewrite it.
|
||||
click.echo(f" Nothing to undo: {config_file} is not valid JSON.")
|
||||
status = "noop"
|
||||
elif remove_managed_opencode_provider(data, managed_state):
|
||||
_write_text(config_file, json.dumps(data, indent=2) + "\n")
|
||||
click.echo(
|
||||
f" Removed Headroom's provider entry from {config_file}; other content preserved."
|
||||
)
|
||||
status = "cleaned"
|
||||
removed_managed = True
|
||||
clear_managed_state(config_file)
|
||||
else:
|
||||
click.echo(f" Nothing to undo: {config_file} has no Headroom-managed provider entry.")
|
||||
status = "noop"
|
||||
clear_managed_state(config_file)
|
||||
elif config_file.exists():
|
||||
content = _read_text(config_file)
|
||||
if _PROVIDER_MARKER_START in content or _MCP_MARKER_START in content:
|
||||
@@ -9258,6 +9299,7 @@ def unwrap_opencode(port: int, no_stop_proxy: bool) -> None:
|
||||
else:
|
||||
click.echo(f" Nothing to undo: {config_file} does not exist.")
|
||||
status = "noop"
|
||||
clear_managed_state(config_file)
|
||||
|
||||
# Remove Serena MCP if it was installed by Headroom.
|
||||
# Also remove the headroom MCP server itself.
|
||||
@@ -9273,6 +9315,19 @@ def unwrap_opencode(port: int, no_stop_proxy: bool) -> None:
|
||||
elif serena_status == "failed":
|
||||
click.echo(" Serena MCP server matched Headroom ledger but could not be removed.")
|
||||
|
||||
# A config Headroom created has no pre-wrap content to restore, so it is
|
||||
# removed once the Headroom-owned entries are gone.
|
||||
if (
|
||||
removed_managed
|
||||
and managed_state is not None
|
||||
and managed_state.created_file
|
||||
and config_file.exists()
|
||||
and opencode_config_is_empty(config_file)
|
||||
):
|
||||
config_file.unlink()
|
||||
click.echo(f" Removed {config_file} (contained only Headroom-written config).")
|
||||
status = "removed"
|
||||
|
||||
click.echo()
|
||||
click.echo("✓ OpenCode is no longer routed through the Headroom proxy.")
|
||||
if not no_stop_proxy and status != "noop":
|
||||
@@ -9356,9 +9411,8 @@ def unwrap_openclaw(
|
||||
click.echo()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# OpenAI Codex CLI (unwrap)
|
||||
# =============================================================================
|
||||
# ======================================================================# OpenAI Codex CLI (unwrap)
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@unwrap.command("grok-build")
|
||||
@@ -9485,9 +9539,8 @@ def unwrap_codex(port: int, no_stop_proxy: bool) -> None:
|
||||
click.echo()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Oh My Pi (omp)
|
||||
# =============================================================================
|
||||
# ======================================================================# Oh My Pi (omp)
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@@ -9684,7 +9737,6 @@ def droid(
|
||||
|
||||
# =============================================================================
|
||||
# Grok CLI (unwrap)
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@unwrap.command("grok")
|
||||
@@ -9740,9 +9792,8 @@ def unwrap_grok(port: int, no_stop_proxy: bool) -> None:
|
||||
click.echo()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# ZCode (unwrap)
|
||||
# =============================================================================
|
||||
# ======================================================================# ZCode (unwrap)
|
||||
# ======================================================================
|
||||
|
||||
|
||||
@unwrap.command("zcode")
|
||||
@@ -9829,10 +9880,8 @@ def _warn_proxy_mode_mismatch(running_config: dict[str, Any] | None) -> None:
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Registry-generated wrap commands
|
||||
# =============================================================================
|
||||
# Env-var tools are described declaratively in headroom.providers.wrap_registry;
|
||||
# ======================================================================# Registry-generated wrap commands
|
||||
# ======================================================================# Env-var tools are described declaratively in headroom.providers.wrap_registry;
|
||||
# one click command per WrapTarget is generated here.
|
||||
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -54,13 +55,83 @@ HEADROOM_OPENCODE_MODELS: dict[str, Any] = {
|
||||
}
|
||||
|
||||
|
||||
def headroom_provider_entry(port: int) -> dict[str, Any]:
|
||||
# Env var holding comma-separated extra model specs (same format as the
|
||||
# `--extra-model` flag) so custom models survive re-wraps. Names in it cannot
|
||||
# contain a comma.
|
||||
HEADROOM_OPENCODE_EXTRA_MODELS_ENV = "HEADROOM_OPENCODE_EXTRA_MODELS"
|
||||
|
||||
# The provider identity wrap writes. Kept as constants so unwrap can tell an
|
||||
# untouched descriptor from one the user edited.
|
||||
HEADROOM_OPENCODE_NPM = "@ai-sdk/openai-compatible"
|
||||
HEADROOM_OPENCODE_NAME = "Headroom Proxy"
|
||||
|
||||
# Defaults for extra models when the spec omits limits. The output default is
|
||||
# also capped at the context window.
|
||||
_EXTRA_MODEL_DEFAULT_CONTEXT = 200000
|
||||
_EXTRA_MODEL_DEFAULT_OUTPUT = 16384
|
||||
|
||||
|
||||
def _extra_model_limit(raw: str, label: str, spec: str) -> int:
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
raise ValueError(f"extra model spec has a non-integer {label}: {spec!r}") from None
|
||||
if value <= 0:
|
||||
raise ValueError(f"extra model spec has a non-positive {label}: {spec!r}")
|
||||
return value
|
||||
|
||||
|
||||
def parse_extra_model_spec(spec: str) -> tuple[str, dict[str, Any]]:
|
||||
"""Parse an ``id[=name[=context_window[=output_limit]]]`` extra-model spec.
|
||||
|
||||
Fields are split on ``=`` because model ids routinely contain ``:``
|
||||
(Ollama ``qwen2.5-coder:7b``, OpenRouter ``vendor/model:free``).
|
||||
Returns a ``(model_id, entry)`` pair shaped like the values in
|
||||
``HEADROOM_OPENCODE_MODELS``. ``name`` defaults to the id,
|
||||
``context_window`` to 200000 and ``output_limit`` to
|
||||
``min(16384, context_window)``. Raises ``ValueError`` on an empty id or a
|
||||
non-integer or non-positive limit.
|
||||
"""
|
||||
parts = [part.strip() for part in spec.split("=", 3)]
|
||||
model_id = parts[0]
|
||||
if not model_id:
|
||||
raise ValueError(f"extra model spec has an empty model id: {spec!r}")
|
||||
name = parts[1] if len(parts) > 1 and parts[1] else model_id
|
||||
context = (
|
||||
_extra_model_limit(parts[2], "context window", spec)
|
||||
if len(parts) > 2 and parts[2]
|
||||
else _EXTRA_MODEL_DEFAULT_CONTEXT
|
||||
)
|
||||
output = (
|
||||
_extra_model_limit(parts[3], "output limit", spec)
|
||||
if len(parts) > 3 and parts[3]
|
||||
else min(_EXTRA_MODEL_DEFAULT_OUTPUT, context)
|
||||
)
|
||||
return model_id, {"name": name, "limit": {"context": context, "output": output}}
|
||||
|
||||
|
||||
def extra_models_from_env() -> dict[str, Any]:
|
||||
"""Parse extra models from ``HEADROOM_OPENCODE_EXTRA_MODELS`` (comma-separated)."""
|
||||
raw = os.environ.get(HEADROOM_OPENCODE_EXTRA_MODELS_ENV, "")
|
||||
models: dict[str, Any] = {}
|
||||
for spec in raw.split(","):
|
||||
spec = spec.strip()
|
||||
if not spec:
|
||||
continue
|
||||
model_id, entry = parse_extra_model_spec(spec)
|
||||
models[model_id] = entry
|
||||
return models
|
||||
|
||||
|
||||
def headroom_provider_entry(
|
||||
port: int, extra_models: dict[str, Any] | None = None
|
||||
) -> dict[str, Any]:
|
||||
"""Return the `headroom` provider block pointed at the local proxy."""
|
||||
return {
|
||||
"npm": "@ai-sdk/openai-compatible",
|
||||
"name": "Headroom Proxy",
|
||||
"npm": HEADROOM_OPENCODE_NPM,
|
||||
"name": HEADROOM_OPENCODE_NAME,
|
||||
"options": {"baseURL": f"http://127.0.0.1:{port}/v1"},
|
||||
"models": HEADROOM_OPENCODE_MODELS,
|
||||
"models": {**HEADROOM_OPENCODE_MODELS, **(extra_models or {})},
|
||||
}
|
||||
|
||||
|
||||
@@ -70,6 +141,208 @@ def opencode_config_paths() -> tuple[Path, Path]:
|
||||
return config_file, config_file.with_name(config_file.name + ".headroom-backup")
|
||||
|
||||
|
||||
# The JSON path writes no marker comments, so a sidecar next to the config
|
||||
# records what Headroom owns: the model ids it injected, the baseURL it
|
||||
# pointed the provider at, and whether Headroom created the file (in which
|
||||
# case there is no pre-wrap backup to restore).
|
||||
_MANAGED_STATE_SUFFIX = ".headroom-managed.json"
|
||||
_MANAGED_STATE_VERSION = 1
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OpencodeManagedState:
|
||||
"""What Headroom owns in an OpenCode config file."""
|
||||
|
||||
created_file: bool = False
|
||||
managed_base_url: str = ""
|
||||
managed_models: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
def opencode_managed_state_path(config_file: Path) -> Path:
|
||||
"""Return the sidecar path recording Headroom's ownership of ``config_file``."""
|
||||
return config_file.with_name(config_file.name + _MANAGED_STATE_SUFFIX)
|
||||
|
||||
|
||||
def read_managed_state(config_file: Path) -> OpencodeManagedState | None:
|
||||
"""Read the managed-state sidecar, or ``None`` when it is absent or unreadable."""
|
||||
path = opencode_managed_state_path(config_file)
|
||||
if not path.exists():
|
||||
return None
|
||||
try:
|
||||
content = fsutil.read_text(path)
|
||||
except OSError:
|
||||
return None
|
||||
data = _parse_json_loose(content)
|
||||
if not data:
|
||||
return None
|
||||
version = data.get("version")
|
||||
if version is not None and version != _MANAGED_STATE_VERSION:
|
||||
# A sidecar this build does not understand: treat the config as
|
||||
# unmanaged rather than guess what it owns.
|
||||
return None
|
||||
models = data.get("managed_models")
|
||||
return OpencodeManagedState(
|
||||
created_file=bool(data.get("created_file")),
|
||||
managed_base_url=str(data.get("managed_base_url") or ""),
|
||||
managed_models=dict(models) if isinstance(models, dict) else {},
|
||||
)
|
||||
|
||||
|
||||
def write_managed_state(config_file: Path, state: OpencodeManagedState) -> None:
|
||||
"""Persist the managed-state sidecar next to the config file.
|
||||
|
||||
Best-effort: the sidecar only refines cleanup, so a write failure must
|
||||
not abort a wrap that already updated the config.
|
||||
"""
|
||||
path = opencode_managed_state_path(config_file)
|
||||
payload = {
|
||||
"version": _MANAGED_STATE_VERSION,
|
||||
"created_file": state.created_file,
|
||||
"managed_base_url": state.managed_base_url,
|
||||
"managed_models": state.managed_models,
|
||||
}
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fsutil.write_text(path, json.dumps(payload, indent=2) + "\n")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def clear_managed_state(config_file: Path) -> None:
|
||||
"""Remove the managed-state sidecar, if present."""
|
||||
try:
|
||||
opencode_managed_state_path(config_file).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def record_opencode_config_origin(config_file: Path) -> None:
|
||||
"""Record that Headroom creates the config file when it is absent.
|
||||
|
||||
Called before the first wrap-time mutation. An absent config file means
|
||||
there is no pre-wrap content, so ``headroom unwrap opencode`` has to
|
||||
remove the file it created instead of restoring a backup that was never
|
||||
made.
|
||||
"""
|
||||
if config_file.exists():
|
||||
return
|
||||
state = read_managed_state(config_file)
|
||||
if state is not None and state.created_file:
|
||||
return
|
||||
write_managed_state(config_file, OpencodeManagedState(created_file=True))
|
||||
|
||||
|
||||
def config_is_headroom_managed(config_file: Path, state: OpencodeManagedState) -> bool:
|
||||
"""Return whether the config still holds the provider block Headroom wrote.
|
||||
|
||||
Used to tell a re-wrapped config apart from the user's own file: the
|
||||
latter is worth snapshotting, the former is not.
|
||||
"""
|
||||
try:
|
||||
data = _parse_json_loose(fsutil.read_text(config_file))
|
||||
except OSError:
|
||||
return False
|
||||
providers = data.get("provider")
|
||||
entry = providers.get("headroom") if isinstance(providers, dict) else None
|
||||
if not isinstance(entry, dict):
|
||||
return False
|
||||
options = entry.get("options")
|
||||
base_url = options.get("baseURL") if isinstance(options, dict) else None
|
||||
if base_url != state.managed_base_url:
|
||||
return False
|
||||
models = entry.get("models")
|
||||
if not isinstance(models, dict):
|
||||
return not state.managed_models
|
||||
return all(
|
||||
models.get(model_id) == injected for model_id, injected in state.managed_models.items()
|
||||
)
|
||||
|
||||
|
||||
def remove_managed_opencode_provider(data: dict[str, Any], state: OpencodeManagedState) -> bool:
|
||||
"""Remove Headroom-owned entries from parsed OpenCode config data.
|
||||
|
||||
Drops the injected model ids and the baseURL Headroom pointed the
|
||||
provider at, then the npm/name it injected, then the provider block itself
|
||||
when nothing else is left in it. Anything the user added or edited --
|
||||
including an edited npm or name -- is preserved. Returns whether anything
|
||||
was removed.
|
||||
"""
|
||||
providers = data.get("provider")
|
||||
if not isinstance(providers, dict):
|
||||
return False
|
||||
entry = providers.get("headroom")
|
||||
if not isinstance(entry, dict):
|
||||
return False
|
||||
changed = False
|
||||
|
||||
models = entry.get("models")
|
||||
if isinstance(models, dict):
|
||||
for model_id, injected in state.managed_models.items():
|
||||
if model_id in models and models[model_id] == injected:
|
||||
del models[model_id]
|
||||
changed = True
|
||||
if not models:
|
||||
entry.pop("models", None)
|
||||
options = entry.get("options")
|
||||
if isinstance(options, dict):
|
||||
if state.managed_base_url and options.get("baseURL") == state.managed_base_url:
|
||||
options.pop("baseURL")
|
||||
changed = True
|
||||
if not options:
|
||||
entry.pop("options", None)
|
||||
if not entry.get("models") and not entry.get("options"):
|
||||
# Headroom's npm/name describe the proxy it injected. An edited value is
|
||||
# the user's own now: dropping it would take their provider identity
|
||||
# with it, so only the untouched, injected values go (#2364).
|
||||
if entry.get("npm") == HEADROOM_OPENCODE_NPM:
|
||||
entry.pop("npm")
|
||||
changed = True
|
||||
if entry.get("name") == HEADROOM_OPENCODE_NAME:
|
||||
entry.pop("name")
|
||||
changed = True
|
||||
if not entry:
|
||||
providers.pop("headroom", None)
|
||||
changed = True
|
||||
if not providers:
|
||||
data.pop("provider", None)
|
||||
changed = True
|
||||
return changed
|
||||
|
||||
|
||||
def _is_empty_config_section(value: Any) -> bool:
|
||||
"""Return whether a config value carries no content.
|
||||
|
||||
An empty section (and a section that only holds empty sections) carries
|
||||
nothing. A scalar counts as content even when it is falsy: a user
|
||||
setting such as ``"autoupdate": false`` is a real preference, not an
|
||||
empty section.
|
||||
"""
|
||||
if isinstance(value, dict):
|
||||
return all(_is_empty_config_section(item) for item in value.values())
|
||||
if isinstance(value, list):
|
||||
return not value
|
||||
return False
|
||||
|
||||
|
||||
def opencode_config_is_empty(config_file: Path) -> bool:
|
||||
"""Return whether the config file holds nothing but empty sections.
|
||||
|
||||
Unparseable files count as non-empty: a config Headroom cannot read is
|
||||
never deleted.
|
||||
"""
|
||||
try:
|
||||
content = fsutil.read_text(config_file)
|
||||
except OSError:
|
||||
return False
|
||||
try:
|
||||
data = json.loads(content)
|
||||
except ValueError:
|
||||
return False
|
||||
if not isinstance(data, dict):
|
||||
return False
|
||||
return all(_is_empty_config_section(value) for value in data.values())
|
||||
|
||||
|
||||
def migrate_legacy_opencode_jsonc_backup(config_file: Path, backup_file: Path) -> None:
|
||||
"""Migrate only legacy JSONC snapshots whose ownership is unambiguous.
|
||||
|
||||
@@ -96,13 +369,18 @@ def snapshot_opencode_config_if_unwrapped(config_file: Path, backup_file: Path)
|
||||
"""Snapshot ``opencode.json`` to ``backup_file`` before the first injection.
|
||||
|
||||
Guarantees that ``headroom unwrap opencode`` can restore the user's
|
||||
original file byte-for-byte.
|
||||
original file byte-for-byte. A config Headroom wrote itself is not
|
||||
snapshot material: there is no user content in it to restore.
|
||||
"""
|
||||
migrate_legacy_opencode_jsonc_backup(config_file, backup_file)
|
||||
if backup_file.exists():
|
||||
return
|
||||
if not config_file.exists():
|
||||
return
|
||||
state = read_managed_state(config_file)
|
||||
if state is not None and (state.created_file or config_is_headroom_managed(config_file, state)):
|
||||
# Headroom wrote this file: it holds no user content to restore.
|
||||
return
|
||||
try:
|
||||
content = fsutil.read_text(config_file)
|
||||
except OSError:
|
||||
@@ -251,7 +529,34 @@ def _inject_key_into_json(data: dict[str, Any], key: str, value: Any) -> dict[st
|
||||
return data
|
||||
|
||||
|
||||
def inject_opencode_provider_config(port: int, *, keep_user_entries: bool = False) -> None:
|
||||
def _drop_stale_managed_models(
|
||||
existing_models: dict[str, Any],
|
||||
prior_state: OpencodeManagedState | None,
|
||||
injected_models: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""Drop entries Headroom injected earlier but no longer advertises.
|
||||
|
||||
That is an extra model dropped from the flags, and an extra that overrode
|
||||
a built-in id and is dropped again: the id stays advertised, but what
|
||||
Headroom writes for it differs, so the old override must not win the
|
||||
merge. Only unmodified entries are dropped: a model the user edited after
|
||||
the wrap is their content, not Headroom's.
|
||||
"""
|
||||
if prior_state is None:
|
||||
return existing_models
|
||||
stale = {
|
||||
model_id
|
||||
for model_id, injected in prior_state.managed_models.items()
|
||||
if existing_models.get(model_id) == injected and injected_models.get(model_id) != injected
|
||||
}
|
||||
if not stale:
|
||||
return existing_models
|
||||
return {model_id: entry for model_id, entry in existing_models.items() if model_id not in stale}
|
||||
|
||||
|
||||
def inject_opencode_provider_config(
|
||||
port: int, extra_models: dict[str, Any] | None = None, *, 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 replaced on each call,
|
||||
@@ -261,17 +566,21 @@ def inject_opencode_provider_config(port: int, *, keep_user_entries: bool = Fals
|
||||
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.
|
||||
can restore it byte-for-byte. A sidecar next to it records the model ids
|
||||
and baseURL Headroom owns, so an unwrap can undo them even when no
|
||||
backup exists.
|
||||
"""
|
||||
config_file, backup_file = opencode_config_paths()
|
||||
config_dir = config_file.parent
|
||||
prior_state = read_managed_state(config_file)
|
||||
|
||||
try:
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
migrate_legacy_opencode_jsonc_backup(config_file, backup_file)
|
||||
snapshot_opencode_config_if_unwrapped(config_file, backup_file)
|
||||
|
||||
if config_file.exists():
|
||||
config_existed = config_file.exists()
|
||||
if config_existed:
|
||||
content = fsutil.read_text(config_file)
|
||||
data = load_user_opencode_config(content, config_file)
|
||||
else:
|
||||
@@ -284,7 +593,8 @@ def inject_opencode_provider_config(port: int, *, keep_user_entries: bool = Fals
|
||||
data = load_user_opencode_config(content, config_file)
|
||||
|
||||
# Merge provider into the JSON data structure.
|
||||
entry = headroom_provider_entry(port)
|
||||
entry = headroom_provider_entry(port, extra_models)
|
||||
injected_models = dict(entry["models"])
|
||||
# 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
|
||||
@@ -297,13 +607,24 @@ def inject_opencode_provider_config(port: int, *, keep_user_entries: bool = Fals
|
||||
if isinstance(existing.get("options"), dict):
|
||||
entry["options"] = {**existing["options"], **entry["options"]}
|
||||
if isinstance(existing.get("models"), dict):
|
||||
entry["models"] = {**entry["models"], **existing["models"]}
|
||||
kept_models = _drop_stale_managed_models(
|
||||
existing["models"], prior_state, injected_models
|
||||
)
|
||||
entry["models"] = {**entry["models"], **kept_models, **(extra_models or {})}
|
||||
provider = {"headroom": entry}
|
||||
data = _inject_key_into_json(data, "provider", provider)
|
||||
|
||||
# Write back as formatted JSON (opencode uses standard JSON with comments).
|
||||
output = json.dumps(data, indent=2) + "\n"
|
||||
config_file.write_text(output, encoding="utf-8")
|
||||
write_managed_state(
|
||||
config_file,
|
||||
OpencodeManagedState(
|
||||
created_file=bool(prior_state and prior_state.created_file) or not config_existed,
|
||||
managed_base_url=str(entry["options"].get("baseURL", "")),
|
||||
managed_models=injected_models,
|
||||
),
|
||||
)
|
||||
except OSError as exc:
|
||||
raise click.ClickException(
|
||||
f"could not write OpenCode config at {config_file}: {exc}"
|
||||
|
||||
@@ -8,6 +8,7 @@ import re
|
||||
import subprocess
|
||||
from collections.abc import Mapping, Sequence
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from headroom._subprocess import run
|
||||
from headroom.mcp_registry.install import DEFAULT_PROXY_URL
|
||||
@@ -152,6 +153,7 @@ def build_opencode_config_content(
|
||||
port: int,
|
||||
include_mcp: bool = True,
|
||||
include_plugin: bool = True,
|
||||
extra_models: dict[str, Any] | None = None,
|
||||
) -> dict[str, object]:
|
||||
"""Build JSON payload for ``OPENCODE_CONFIG_CONTENT``.
|
||||
|
||||
@@ -181,7 +183,7 @@ def build_opencode_config_content(
|
||||
"provider": {
|
||||
"anthropic": {"options": {"baseURL": base_url}},
|
||||
"openai": {"options": {"baseURL": base_url}},
|
||||
"headroom": headroom_provider_entry(port),
|
||||
"headroom": headroom_provider_entry(port, extra_models),
|
||||
}
|
||||
}
|
||||
if include_mcp:
|
||||
@@ -212,6 +214,7 @@ def build_launch_env(
|
||||
*,
|
||||
include_mcp: bool = True,
|
||||
include_plugin: bool = True,
|
||||
extra_models: dict[str, Any] | None = None,
|
||||
session_token: str | None = None,
|
||||
) -> tuple[dict[str, str], list[str]]:
|
||||
"""Build environment variables for launching OpenCode through Headroom.
|
||||
@@ -232,6 +235,7 @@ def build_launch_env(
|
||||
port=port,
|
||||
include_mcp=include_mcp,
|
||||
include_plugin=include_plugin,
|
||||
extra_models=extra_models,
|
||||
)
|
||||
env["OPENCODE_CONFIG_CONTENT"] = json.dumps(config_content, separators=(",", ":"))
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ from unittest.mock import patch
|
||||
|
||||
import click
|
||||
import pytest
|
||||
from click.testing import CliRunner
|
||||
from click.testing import CliRunner, Result
|
||||
|
||||
from headroom.cli import wrap as wrap_mod
|
||||
from headroom.cli.main import main
|
||||
@@ -559,6 +559,199 @@ def test_wrap_opencode_prepare_only_injects_config(
|
||||
assert config["provider"]["headroom"]["options"]["baseURL"] == "http://127.0.0.1:9000/v1"
|
||||
|
||||
|
||||
def test_wrap_opencode_extra_model_flag_injects_config(
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""`--extra-model` specs are merged into the injected provider models."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
|
||||
monkeypatch.delenv("HEADROOM_OPENCODE_EXTRA_MODELS", raising=False)
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="opencode"):
|
||||
result = runner.invoke(
|
||||
main,
|
||||
[
|
||||
"wrap",
|
||||
"opencode",
|
||||
"--prepare-only",
|
||||
"--extra-model",
|
||||
"deepseek-chat=DeepSeek Chat=65536",
|
||||
"--extra-model",
|
||||
"qwen2.5-coder:7b",
|
||||
],
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
config = json.loads(config_file.read_text(encoding="utf-8"))
|
||||
models = config["provider"]["headroom"]["models"]
|
||||
assert models["deepseek-chat"]["name"] == "DeepSeek Chat"
|
||||
assert models["deepseek-chat"]["limit"]["context"] == 65536
|
||||
assert models["qwen2.5-coder:7b"]["name"] == "qwen2.5-coder:7b"
|
||||
assert "gpt-4o" in models
|
||||
|
||||
|
||||
def test_wrap_opencode_extra_models_env_var(
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""HEADROOM_OPENCODE_EXTRA_MODELS persists extra models across wraps."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
|
||||
monkeypatch.setenv("HEADROOM_OPENCODE_EXTRA_MODELS", "deepseek-chat=DeepSeek Chat=65536")
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="opencode"):
|
||||
result = runner.invoke(main, ["wrap", "opencode", "--prepare-only"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
config = json.loads(config_file.read_text(encoding="utf-8"))
|
||||
assert config["provider"]["headroom"]["models"]["deepseek-chat"]["limit"]["context"] == 65536
|
||||
|
||||
|
||||
def test_wrap_opencode_extra_model_flag_in_launch_env(
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Extra models reach OPENCODE_CONFIG_CONTENT on the normal launch path."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
|
||||
monkeypatch.delenv("HEADROOM_OPENCODE_EXTRA_MODELS", raising=False)
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def fake_launch_tool(**kwargs): # noqa: ANN003
|
||||
captured.update(kwargs)
|
||||
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="opencode"):
|
||||
with patch.object(wrap_mod, "_launch_tool", side_effect=fake_launch_tool):
|
||||
result = runner.invoke(
|
||||
main,
|
||||
[
|
||||
"wrap",
|
||||
"opencode",
|
||||
"--port",
|
||||
"9000",
|
||||
"--no-mcp",
|
||||
"--extra-model",
|
||||
"deepseek-chat=DeepSeek Chat=65536",
|
||||
],
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
env = captured["env"]
|
||||
assert isinstance(env, dict)
|
||||
config = json.loads(env["OPENCODE_CONFIG_CONTENT"])
|
||||
models = config["provider"]["headroom"]["models"]
|
||||
assert models["deepseek-chat"]["name"] == "DeepSeek Chat"
|
||||
assert models["deepseek-chat"]["limit"]["context"] == 65536
|
||||
assert "gpt-4o" in models
|
||||
|
||||
|
||||
def test_wrap_opencode_extra_models_env_var_in_launch_env(
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Env-sourced extra models reach OPENCODE_CONFIG_CONTENT on launch."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
|
||||
monkeypatch.setenv("HEADROOM_OPENCODE_EXTRA_MODELS", "kimi-k2=Kimi K2")
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def fake_launch_tool(**kwargs): # noqa: ANN003
|
||||
captured.update(kwargs)
|
||||
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="opencode"):
|
||||
with patch.object(wrap_mod, "_launch_tool", side_effect=fake_launch_tool):
|
||||
result = runner.invoke(main, ["wrap", "opencode", "--port", "9000", "--no-mcp"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
env = captured["env"]
|
||||
assert isinstance(env, dict)
|
||||
config = json.loads(env["OPENCODE_CONFIG_CONTENT"])
|
||||
assert config["provider"]["headroom"]["models"]["kimi-k2"]["name"] == "Kimi K2"
|
||||
|
||||
|
||||
def test_wrap_opencode_extra_model_overrides_kept_user_entry(
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""With --openai-api-url the user's headroom models are kept, but an
|
||||
--extra-model for the same id replaces the kept entry."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
|
||||
monkeypatch.delenv("HEADROOM_OPENCODE_EXTRA_MODELS", raising=False)
|
||||
_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": {
|
||||
"models": {
|
||||
"deepseek-chat": {"name": "Stale"},
|
||||
"deepseek-reasoner": {"name": "DeepSeek Reasoner"},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="opencode"):
|
||||
result = runner.invoke(
|
||||
main,
|
||||
[
|
||||
"wrap",
|
||||
"opencode",
|
||||
"--prepare-only",
|
||||
"--openai-api-url",
|
||||
"https://api.deepseek.com/v1",
|
||||
"--extra-model",
|
||||
"deepseek-chat=DeepSeek Chat=65536",
|
||||
],
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
models = json.loads(config_file.read_text(encoding="utf-8"))["provider"]["headroom"]["models"]
|
||||
assert models["deepseek-chat"]["name"] == "DeepSeek Chat"
|
||||
assert models["deepseek-chat"]["limit"]["context"] == 65536
|
||||
assert models["deepseek-reasoner"] == {"name": "DeepSeek Reasoner"}
|
||||
|
||||
|
||||
def test_wrap_opencode_extra_model_invalid_spec_errors(
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""A malformed --extra-model spec fails with a usage error, not a traceback."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="opencode"):
|
||||
result = runner.invoke(
|
||||
main,
|
||||
["wrap", "opencode", "--prepare-only", "--extra-model", "bad=name=abc"],
|
||||
)
|
||||
|
||||
assert result.exit_code != 0
|
||||
assert "non-integer context window" in result.output
|
||||
|
||||
|
||||
def test_wrap_opencode_prepare_only_registers_serena_with_agent_context(
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
@@ -1757,3 +1950,187 @@ def test_wrap_opencode_session_token_matches_registration(
|
||||
# Assumes the plugin resolves (packaged bundle ships in this checkout);
|
||||
# see test_build_launch_env_omits_session_token_when_plugin_absent.
|
||||
assert env.get("HEADROOM_OPENCODE_SESSION_TOKEN") == registered_token
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fresh wrap -> unwrap lifecycle (no pre-wrap config, no backup)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _managed_state_path(config_file: Path) -> Path:
|
||||
return config_file.with_name(config_file.name + ".headroom-managed.json")
|
||||
|
||||
|
||||
def _prepare_only_wrap(runner: CliRunner, extra_args: list[str] | None = None) -> Result:
|
||||
return runner.invoke(
|
||||
main,
|
||||
["wrap", "opencode", "--prepare-only", "--no-mcp", "--no-serena", *(extra_args or [])],
|
||||
)
|
||||
|
||||
|
||||
def test_unwrap_opencode_removes_a_freshly_wrapped_config(
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""A config Headroom created is removed again, backup or not."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
|
||||
monkeypatch.delenv("HEADROOM_OPENCODE_EXTRA_MODELS", raising=False)
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="opencode"):
|
||||
wrapped = _prepare_only_wrap(runner, ["--extra-model", "my-model=My Model"])
|
||||
assert wrapped.exit_code == 0, wrapped.output
|
||||
assert config_file.exists()
|
||||
assert not (tmp_path / ".config" / "opencode" / "opencode.json.headroom-backup").exists()
|
||||
|
||||
with patch.object(wrap_mod, "_stop_local_proxy_for_unwrap", return_value="stopped"):
|
||||
result = runner.invoke(main, ["unwrap", "opencode"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert not config_file.exists(), "the config Headroom created must be removed again"
|
||||
assert not _managed_state_path(config_file).exists()
|
||||
|
||||
|
||||
def test_unwrap_opencode_removes_a_freshly_wrapped_config_with_mcp(
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""The MCP entry Headroom registered goes away with the config it created."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
|
||||
monkeypatch.delenv("HEADROOM_OPENCODE_EXTRA_MODELS", raising=False)
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="opencode"):
|
||||
wrapped = runner.invoke(main, ["wrap", "opencode", "--prepare-only", "--no-serena"])
|
||||
assert wrapped.exit_code == 0, wrapped.output
|
||||
assert "headroom" in json.loads(config_file.read_text(encoding="utf-8"))["mcp"]
|
||||
|
||||
with patch.object(wrap_mod, "_stop_local_proxy_for_unwrap", return_value="stopped"):
|
||||
result = runner.invoke(main, ["unwrap", "opencode"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert not config_file.exists()
|
||||
assert not _managed_state_path(config_file).exists()
|
||||
|
||||
|
||||
def test_unwrap_opencode_removes_a_directly_injected_config(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Injecting the provider directly and then unwrapping leaves no config."""
|
||||
from headroom.providers.opencode.config import inject_opencode_provider_config
|
||||
|
||||
monkeypatch.chdir(tmp_path)
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
inject_opencode_provider_config(
|
||||
port=8787, extra_models={"my-model": {"name": "My Model", "limit": {}}}
|
||||
)
|
||||
assert "my-model" in config_file.read_text(encoding="utf-8")
|
||||
|
||||
with patch.object(wrap_mod, "_stop_local_proxy_for_unwrap", return_value="stopped"):
|
||||
wrap_mod.unwrap_opencode.callback(port=8787, no_stop_proxy=True)
|
||||
|
||||
assert not config_file.exists()
|
||||
assert not _managed_state_path(config_file).exists()
|
||||
|
||||
|
||||
def test_unwrap_opencode_keeps_a_falsy_user_setting(
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""A user setting that is false is content, not an empty section."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
|
||||
monkeypatch.delenv("HEADROOM_OPENCODE_EXTRA_MODELS", raising=False)
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="opencode"):
|
||||
wrapped = _prepare_only_wrap(runner)
|
||||
assert wrapped.exit_code == 0, wrapped.output
|
||||
|
||||
data = json.loads(config_file.read_text(encoding="utf-8"))
|
||||
data["autoupdate"] = False
|
||||
config_file.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
with patch.object(wrap_mod, "_stop_local_proxy_for_unwrap", return_value="stopped"):
|
||||
result = runner.invoke(main, ["unwrap", "opencode"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert config_file.exists(), "the user setting must not cost the user the file"
|
||||
assert json.loads(config_file.read_text(encoding="utf-8"))["autoupdate"] is False
|
||||
|
||||
|
||||
def test_unwrap_opencode_keeps_user_content_added_after_a_fresh_wrap(
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Undoing Headroom's config keeps what the user added to it."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
|
||||
monkeypatch.delenv("HEADROOM_OPENCODE_EXTRA_MODELS", raising=False)
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="opencode"):
|
||||
wrapped = _prepare_only_wrap(runner, ["--extra-model", "my-model=My Model"])
|
||||
assert wrapped.exit_code == 0, wrapped.output
|
||||
|
||||
data = json.loads(config_file.read_text(encoding="utf-8"))
|
||||
data["theme"] = "dark"
|
||||
data["provider"]["headroom"]["models"]["user-model"] = {"name": "User Model"}
|
||||
data["provider"]["headroom"]["options"]["apiKey"] = "{env:MY_KEY}"
|
||||
config_file.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
with patch.object(wrap_mod, "_stop_local_proxy_for_unwrap", return_value="stopped"):
|
||||
result = runner.invoke(main, ["unwrap", "opencode"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
remaining = json.loads(config_file.read_text(encoding="utf-8"))
|
||||
assert remaining["theme"] == "dark"
|
||||
headroom = remaining["provider"]["headroom"]
|
||||
assert headroom["models"] == {"user-model": {"name": "User Model"}}
|
||||
assert headroom["options"] == {"apiKey": "{env:MY_KEY}"}
|
||||
assert "baseURL" not in headroom["options"]
|
||||
|
||||
|
||||
def test_rewrap_without_the_extra_model_drops_the_stale_extra(
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""A model Headroom injected but no longer requested does not linger."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
|
||||
monkeypatch.delenv("HEADROOM_OPENCODE_EXTRA_MODELS", raising=False)
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
upstream = ["--openai-api-url", "https://api.deepseek.com/v1"]
|
||||
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="opencode"):
|
||||
wrapped = _prepare_only_wrap(runner, [*upstream, "--extra-model", "my-model=My Model"])
|
||||
assert wrapped.exit_code == 0, wrapped.output
|
||||
models = json.loads(config_file.read_text(encoding="utf-8"))["provider"]["headroom"]["models"]
|
||||
assert "my-model" in models
|
||||
|
||||
with patch.object(wrap_mod.shutil, "which", return_value="opencode"):
|
||||
rewrapped = _prepare_only_wrap(runner, upstream)
|
||||
assert rewrapped.exit_code == 0, rewrapped.output
|
||||
models = json.loads(config_file.read_text(encoding="utf-8"))["provider"]["headroom"]["models"]
|
||||
assert "my-model" not in models
|
||||
assert set(models) == {"gpt-4o", "gpt-4.1"}
|
||||
|
||||
@@ -9,11 +9,16 @@ import click
|
||||
import pytest
|
||||
|
||||
from headroom.providers.opencode.config import (
|
||||
HEADROOM_OPENCODE_EXTRA_MODELS_ENV,
|
||||
HEADROOM_OPENCODE_MODELS,
|
||||
HEADROOM_OPENCODE_PLUGIN,
|
||||
_inject_key_into_json,
|
||||
_parse_json_loose,
|
||||
extra_models_from_env,
|
||||
headroom_provider_entry,
|
||||
inject_opencode_provider_config,
|
||||
opencode_config_paths,
|
||||
parse_extra_model_spec,
|
||||
snapshot_opencode_config_if_unwrapped,
|
||||
strip_opencode_headroom_blocks,
|
||||
)
|
||||
@@ -296,6 +301,121 @@ def test_inject_provider_config_drops_user_entries_without_an_explicit_upstream(
|
||||
assert set(headroom["models"]) == {"gpt-4o", "gpt-4.1"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Extra models
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_parse_extra_model_spec_full() -> None:
|
||||
"""Full id=name=context=output spec parses into a provider models entry."""
|
||||
model_id, entry = parse_extra_model_spec("deepseek-v4-pro=DeepSeek V4=1000000=384000")
|
||||
assert model_id == "deepseek-v4-pro"
|
||||
assert entry == {"name": "DeepSeek V4", "limit": {"context": 1000000, "output": 384000}}
|
||||
|
||||
|
||||
def test_parse_extra_model_spec_defaults() -> None:
|
||||
"""Name defaults to the id, context to 200000, output to min(16384, context)."""
|
||||
model_id, entry = parse_extra_model_spec("deepseek-chat")
|
||||
assert model_id == "deepseek-chat"
|
||||
assert entry == {"name": "deepseek-chat", "limit": {"context": 200000, "output": 16384}}
|
||||
|
||||
_, named = parse_extra_model_spec("deepseek-chat=DeepSeek Chat=65536")
|
||||
assert named == {"name": "DeepSeek Chat", "limit": {"context": 65536, "output": 16384}}
|
||||
|
||||
# A context window below the default output caps the output, and an empty
|
||||
# name field still falls back to the id.
|
||||
_, small = parse_extra_model_spec("small-model==8192")
|
||||
assert small == {"name": "small-model", "limit": {"context": 8192, "output": 8192}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("spec", "expected_id", "expected_name"),
|
||||
[
|
||||
("qwen2.5-coder:7b", "qwen2.5-coder:7b", "qwen2.5-coder:7b"),
|
||||
(
|
||||
"deepseek/deepseek-chat:free=DeepSeek Free",
|
||||
"deepseek/deepseek-chat:free",
|
||||
"DeepSeek Free",
|
||||
),
|
||||
("deepseek-r1:14b=DeepSeek R1: 14B=65536", "deepseek-r1:14b", "DeepSeek R1: 14B"),
|
||||
],
|
||||
)
|
||||
def test_parse_extra_model_spec_keeps_colons_in_ids(
|
||||
spec: str, expected_id: str, expected_name: str
|
||||
) -> None:
|
||||
"""Ollama (`name:tag`) and OpenRouter (`:free`) ids keep their colons."""
|
||||
model_id, entry = parse_extra_model_spec(spec)
|
||||
assert model_id == expected_id
|
||||
assert entry["name"] == expected_name
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"spec",
|
||||
[
|
||||
"",
|
||||
"=name=1000",
|
||||
"id=name=abc",
|
||||
"id=name=0",
|
||||
"id=name=1000=abc",
|
||||
"id=name=1000=-1",
|
||||
"id=n=1=2=3",
|
||||
],
|
||||
)
|
||||
def test_parse_extra_model_spec_invalid(spec: str) -> None:
|
||||
"""Empty id or a bad context window / output limit raises ValueError."""
|
||||
with pytest.raises(ValueError):
|
||||
parse_extra_model_spec(spec)
|
||||
|
||||
|
||||
def test_extra_models_from_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""HEADROOM_OPENCODE_EXTRA_MODELS parses comma-separated specs."""
|
||||
monkeypatch.setenv(
|
||||
HEADROOM_OPENCODE_EXTRA_MODELS_ENV,
|
||||
"deepseek-chat=DeepSeek Chat=65536, qwen2.5-coder:7b",
|
||||
)
|
||||
models = extra_models_from_env()
|
||||
assert models["deepseek-chat"]["limit"]["context"] == 65536
|
||||
assert models["qwen2.5-coder:7b"]["name"] == "qwen2.5-coder:7b"
|
||||
|
||||
monkeypatch.delenv(HEADROOM_OPENCODE_EXTRA_MODELS_ENV)
|
||||
assert extra_models_from_env() == {}
|
||||
|
||||
|
||||
def test_headroom_provider_entry_merges_extra_models() -> None:
|
||||
"""Extra models are merged alongside the built-in model list."""
|
||||
_, entry = parse_extra_model_spec("deepseek-chat=DeepSeek Chat=65536")
|
||||
provider = headroom_provider_entry(8787, {"deepseek-chat": entry})
|
||||
assert "gpt-4o" in provider["models"]
|
||||
assert provider["models"]["deepseek-chat"]["name"] == "DeepSeek Chat"
|
||||
|
||||
|
||||
def test_inject_provider_config_with_extra_models(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""inject_opencode_provider_config writes extra models into the config."""
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
_, entry = parse_extra_model_spec("deepseek-chat=DeepSeek Chat=65536")
|
||||
inject_opencode_provider_config(port=8787, extra_models={"deepseek-chat": entry})
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
config = _parse_json_loose(config_file.read_text())
|
||||
models = config["provider"]["headroom"]["models"]
|
||||
assert models["deepseek-chat"]["limit"]["context"] == 65536
|
||||
assert "gpt-4o" in models
|
||||
|
||||
|
||||
def test_build_opencode_config_content_with_extra_models() -> None:
|
||||
"""build_opencode_config_content threads extra models into the headroom provider."""
|
||||
from headroom.providers.opencode.runtime import build_opencode_config_content
|
||||
|
||||
_, entry = parse_extra_model_spec("deepseek-chat=DeepSeek Chat=65536")
|
||||
config = build_opencode_config_content(
|
||||
port=8787, include_mcp=False, include_plugin=False, extra_models={"deepseek-chat": entry}
|
||||
)
|
||||
models = config["provider"]["headroom"]["models"]
|
||||
assert models["deepseek-chat"]["name"] == "DeepSeek Chat"
|
||||
assert "gpt-4o" in models
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Edge cases — JSON parsing
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -655,6 +775,45 @@ def test_inject_provider_config_strips_existing_markers(
|
||||
assert second.count("headroom") == first.count("headroom")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("keep_user_entries", [False, True])
|
||||
def test_extra_models_override_persisted_collision_with_upstream_gate(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, keep_user_entries: bool
|
||||
) -> None:
|
||||
_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": {
|
||||
"options": {
|
||||
"apiKey": "third-party-secret",
|
||||
"baseURL": "https://old.invalid",
|
||||
},
|
||||
"models": {
|
||||
"deepseek-chat": {"name": "Old model"},
|
||||
"private-model": {"name": "Private"},
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
_, entry = parse_extra_model_spec("deepseek-chat=DeepSeek Chat=65536")
|
||||
inject_opencode_provider_config(
|
||||
port=8787, extra_models={"deepseek-chat": entry}, keep_user_entries=keep_user_entries
|
||||
)
|
||||
provider = json.loads(config_file.read_text(encoding="utf-8"))["provider"]["headroom"]
|
||||
assert provider["models"]["deepseek-chat"] == entry
|
||||
assert provider["options"]["baseURL"] == "http://127.0.0.1:8787/v1"
|
||||
assert ("private-model" in provider["models"]) is keep_user_entries
|
||||
assert ("apiKey" in provider["options"]) is keep_user_entries
|
||||
if keep_user_entries:
|
||||
assert provider["options"]["apiKey"] == "third-party-secret"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OpenCode 2.x --standalone launch flag
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -752,6 +911,263 @@ def test_jsonc_migration_treats_dangling_conflict_as_ambiguous(
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Managed state (what Headroom owns in the config file)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _managed_state_path(config_file: Path) -> Path:
|
||||
return config_file.with_name(config_file.name + ".headroom-managed.json")
|
||||
|
||||
|
||||
def test_inject_provider_config_records_managed_state(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""The sidecar records the model ids and baseURL Headroom injected."""
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
|
||||
inject_opencode_provider_config(port=8787, extra_models={"my-model": {"name": "My Model"}})
|
||||
|
||||
state = json.loads(_managed_state_path(config_file).read_text(encoding="utf-8"))
|
||||
assert state["created_file"] is True
|
||||
assert state["managed_base_url"] == "http://127.0.0.1:8787/v1"
|
||||
assert set(state["managed_models"]) == {"gpt-4o", "gpt-4.1", "my-model"}
|
||||
|
||||
|
||||
def test_inject_provider_config_keeps_existing_file_out_of_created_file(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A config the user already had is not marked as Headroom-created."""
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
config_file.parent.mkdir(parents=True)
|
||||
config_file.write_text('{"theme": "dark"}', encoding="utf-8")
|
||||
|
||||
inject_opencode_provider_config(port=8787)
|
||||
|
||||
state = json.loads(_managed_state_path(config_file).read_text(encoding="utf-8"))
|
||||
assert state["created_file"] is False
|
||||
|
||||
|
||||
def test_snapshot_skips_a_config_headroom_wrote(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A re-wrap must not snapshot Headroom's own config as pre-wrap content."""
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
|
||||
inject_opencode_provider_config(port=8787)
|
||||
backup_file = config_file.with_name(config_file.name + ".headroom-backup")
|
||||
assert not backup_file.exists()
|
||||
|
||||
inject_opencode_provider_config(port=8787)
|
||||
assert not backup_file.exists()
|
||||
|
||||
|
||||
def test_snapshot_does_not_back_up_a_config_headroom_created(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A config Headroom created holds no pre-wrap content to restore."""
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
|
||||
inject_opencode_provider_config(port=8787)
|
||||
config_file.write_text('{"theme": "dark"}', encoding="utf-8")
|
||||
|
||||
inject_opencode_provider_config(port=8787)
|
||||
backup_file = config_file.with_name(config_file.name + ".headroom-backup")
|
||||
assert not backup_file.exists()
|
||||
|
||||
|
||||
def test_reinject_prunes_a_dropped_extra_model(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A model Headroom injected but no longer advertises is dropped."""
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
extra = {"name": "My Model", "limit": {"context": 200000, "output": 16384}}
|
||||
|
||||
inject_opencode_provider_config(port=8787, extra_models={"my-model": extra})
|
||||
inject_opencode_provider_config(port=8787, keep_user_entries=True)
|
||||
|
||||
models = _parse_json_loose(config_file.read_text(encoding="utf-8"))["provider"]["headroom"][
|
||||
"models"
|
||||
]
|
||||
assert "my-model" not in models
|
||||
assert set(models) == {"gpt-4o", "gpt-4.1"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("keep_user_entries", [False, True])
|
||||
def test_reinject_prunes_a_dropped_override_of_a_builtin_id(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, keep_user_entries: bool
|
||||
) -> None:
|
||||
"""A dropped --extra-model override of a built-in restores the defaults."""
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
override = {"name": "Override", "limit": {"context": 8000, "output": 4000}}
|
||||
|
||||
inject_opencode_provider_config(
|
||||
port=8787, extra_models={"gpt-4o": override}, keep_user_entries=keep_user_entries
|
||||
)
|
||||
inject_opencode_provider_config(port=8787, keep_user_entries=keep_user_entries)
|
||||
|
||||
models = _parse_json_loose(config_file.read_text(encoding="utf-8"))["provider"]["headroom"][
|
||||
"models"
|
||||
]
|
||||
assert models["gpt-4o"] == HEADROOM_OPENCODE_MODELS["gpt-4o"]
|
||||
|
||||
|
||||
def test_reinject_keeps_a_user_model_and_a_edited_extra(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Models the user added or edited survive a re-wrap."""
|
||||
_set_test_home(monkeypatch, tmp_path)
|
||||
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
|
||||
extra = {"name": "My Model", "limit": {"context": 200000, "output": 16384}}
|
||||
|
||||
inject_opencode_provider_config(port=8787, extra_models={"my-model": extra})
|
||||
data = _parse_json_loose(config_file.read_text(encoding="utf-8"))
|
||||
data["provider"]["headroom"]["models"]["user-model"] = {"name": "User Model"}
|
||||
data["provider"]["headroom"]["models"]["my-model"] = {"name": "Renamed by the user"}
|
||||
config_file.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
inject_opencode_provider_config(port=8787, keep_user_entries=True)
|
||||
|
||||
models = _parse_json_loose(config_file.read_text(encoding="utf-8"))["provider"]["headroom"][
|
||||
"models"
|
||||
]
|
||||
assert models["user-model"] == {"name": "User Model"}
|
||||
assert models["my-model"] == {"name": "Renamed by the user"}
|
||||
|
||||
|
||||
def test_remove_managed_opencode_provider_keeps_user_entries() -> None:
|
||||
"""Only the entries Headroom injected are removed."""
|
||||
from headroom.providers.opencode.config import (
|
||||
OpencodeManagedState,
|
||||
remove_managed_opencode_provider,
|
||||
)
|
||||
|
||||
state = OpencodeManagedState(
|
||||
created_file=True,
|
||||
managed_base_url="http://127.0.0.1:8787/v1",
|
||||
managed_models={"gpt-4o": {"name": "GPT-4o"}},
|
||||
)
|
||||
data = {
|
||||
"provider": {
|
||||
"headroom": {
|
||||
"npm": "@ai-sdk/openai-compatible",
|
||||
"name": "Headroom Proxy",
|
||||
"options": {"baseURL": "http://127.0.0.1:8787/v1", "apiKey": "secret"},
|
||||
"models": {"gpt-4o": {"name": "GPT-4o"}, "user-model": {"name": "User"}},
|
||||
},
|
||||
"anthropic": {"options": {"timeout": 5}},
|
||||
},
|
||||
"theme": "dark",
|
||||
}
|
||||
|
||||
assert remove_managed_opencode_provider(data, state) is True
|
||||
headroom = data["provider"]["headroom"]
|
||||
assert headroom["models"] == {"user-model": {"name": "User"}}
|
||||
assert headroom["options"] == {"apiKey": "secret"}
|
||||
assert headroom["npm"] == "@ai-sdk/openai-compatible"
|
||||
assert headroom["name"] == "Headroom Proxy"
|
||||
assert data["provider"]["anthropic"] == {"options": {"timeout": 5}}
|
||||
assert data["theme"] == "dark"
|
||||
|
||||
|
||||
def test_remove_managed_opencode_provider_keeps_an_edited_provider_identity() -> None:
|
||||
"""An npm/name the user edited survives unwrap (#2364).
|
||||
|
||||
The reported case: wrap a config that did not exist, edit only
|
||||
``provider.headroom.npm`` and ``.name``, then unwrap. The edited values are
|
||||
the user's own provider identity, so removing them emptied the config file
|
||||
even though the user had made it theirs.
|
||||
"""
|
||||
from headroom.providers.opencode.config import (
|
||||
OpencodeManagedState,
|
||||
remove_managed_opencode_provider,
|
||||
)
|
||||
|
||||
state = OpencodeManagedState(
|
||||
created_file=True,
|
||||
managed_base_url="http://127.0.0.1:8787/v1",
|
||||
managed_models={"gpt-4o": {"name": "GPT-4o"}},
|
||||
)
|
||||
data = {
|
||||
"provider": {
|
||||
"headroom": {
|
||||
"npm": "@ai-sdk/my-fork",
|
||||
"name": "My Local Gateway",
|
||||
"options": {"baseURL": "http://127.0.0.1:8787/v1"},
|
||||
"models": {"gpt-4o": {"name": "GPT-4o"}},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert remove_managed_opencode_provider(data, state) is True
|
||||
assert data == {
|
||||
"provider": {"headroom": {"npm": "@ai-sdk/my-fork", "name": "My Local Gateway"}}
|
||||
}
|
||||
|
||||
|
||||
def test_remove_managed_opencode_provider_drops_the_empty_provider() -> None:
|
||||
"""A provider block that only held Headroom's entries is removed."""
|
||||
from headroom.providers.opencode.config import (
|
||||
OpencodeManagedState,
|
||||
remove_managed_opencode_provider,
|
||||
)
|
||||
|
||||
state = OpencodeManagedState(
|
||||
created_file=True,
|
||||
managed_base_url="http://127.0.0.1:8787/v1",
|
||||
managed_models={"gpt-4o": {"name": "GPT-4o"}},
|
||||
)
|
||||
data = {
|
||||
"provider": {
|
||||
"headroom": {
|
||||
"npm": "@ai-sdk/openai-compatible",
|
||||
"name": "Headroom Proxy",
|
||||
"options": {"baseURL": "http://127.0.0.1:8787/v1"},
|
||||
"models": {"gpt-4o": {"name": "GPT-4o"}},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert remove_managed_opencode_provider(data, state) is True
|
||||
assert data == {}
|
||||
|
||||
|
||||
def test_opencode_config_is_empty_only_for_empty_configs(tmp_path: Path) -> None:
|
||||
"""A config with content (or with unreadable content) is never empty."""
|
||||
from headroom.providers.opencode.config import opencode_config_is_empty
|
||||
|
||||
config_file = tmp_path / "opencode.json"
|
||||
config_file.write_text("{}", encoding="utf-8")
|
||||
assert opencode_config_is_empty(config_file) is True
|
||||
|
||||
config_file.write_text('{"provider": {}}', encoding="utf-8")
|
||||
assert opencode_config_is_empty(config_file) is True
|
||||
|
||||
config_file.write_text('{"provider": {"headroom": {}}}', encoding="utf-8")
|
||||
assert opencode_config_is_empty(config_file) is True
|
||||
|
||||
config_file.write_text('{"theme": "dark"}', encoding="utf-8")
|
||||
assert opencode_config_is_empty(config_file) is False
|
||||
|
||||
# A falsy user setting is content, not an empty section.
|
||||
config_file.write_text('{"autoupdate": false}', encoding="utf-8")
|
||||
assert opencode_config_is_empty(config_file) is False
|
||||
|
||||
config_file.write_text('{"retries": 0}', encoding="utf-8")
|
||||
assert opencode_config_is_empty(config_file) is False
|
||||
|
||||
config_file.write_text('{"model": ""}', encoding="utf-8")
|
||||
assert opencode_config_is_empty(config_file) is False
|
||||
|
||||
config_file.write_text("not json", encoding="utf-8")
|
||||
assert opencode_config_is_empty(config_file) is False
|
||||
|
||||
|
||||
# Unparseable user config must not be rewritten
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
Reference in New Issue
Block a user