Commit Graph
14 Commits
Author SHA1 Message Date
66e0086952 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>
2026-11-17 02:38:10 +05:30
0fe0a597c1 fix(opencode): do not rewrite an OpenCode config that fails to parse (#4424)
## Description

`_parse_json_loose` returned `{}` for any parse failure, and
`inject_opencode_provider_config` / `apply_provider_scope` then wrote
the whole file back with only the Headroom provider, dropping every user
key. A leading UTF-8 BOM was one trigger, a syntax error another. This
PR ignores a leading BOM when parsing, and raises a `ClickException` for
a non-empty config that still cannot be parsed instead of overwriting
it. A file holding only a BOM (or a BOM and whitespace) counts as empty.

Fixes #4415

## Type of Change

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

## Changes Made

- `headroom/providers/opencode/config.py`: new `_try_parse_json_loose`
(strips a leading U+FEFF, returns `None` on failure);
`_parse_json_loose` keeps its `{}` contract on top of it; new
`load_user_opencode_config` raises `click.ClickException` for non-empty
unparseable text; `inject_opencode_provider_config` uses it for both
parse sites.
- `headroom/providers/opencode/install.py`: `apply_provider_scope` uses
`load_user_opencode_config`.
- Tests: BOM config keeps user keys, BOM-only and BOM-plus-whitespace
configs are treated as empty, unparseable config is left byte-identical
(config and install paths).
- Second commit (`ffef07a7`) addresses a review comment: the emptiness
check in `load_user_opencode_config` now runs after the BOM is removed.

## Testing

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

### Test Output

With only the source change reverted (new tests kept),
`tests/test_providers_opencode_config.py
tests/test_providers_opencode_install.py`:

```text
FAILED tests/test_providers_opencode_config.py::test_inject_provider_config_keeps_user_keys_with_bom
FAILED tests/test_providers_opencode_config.py::test_inject_provider_config_leaves_unparseable_config_untouched
FAILED tests/test_providers_opencode_install.py::test_apply_provider_scope_leaves_unparseable_config_untouched
======================== 3 failed, 102 passed in 1.81s ========================
```

With only the second commit's source change reverted
(`tests/test_providers_opencode_config.py`):

```text
FAILED tests/test_providers_opencode_config.py::test_inject_provider_config_treats_bom_only_config_as_empty[]
FAILED tests/test_providers_opencode_config.py::test_inject_provider_config_treats_bom_only_config_as_empty[ 
]
========================= 2 failed, 68 passed in 1.15s =========================
```

With the fix, plus the neighbouring files
(`tests/test_providers_opencode_config.py
tests/test_providers_opencode_install.py
tests/test_providers_opencode_plugin_path.py
tests/test_mcp_registry_opencode.py`):

```text
============================= 155 passed in 1.94s ==============================
```

```text
$ ruff check headroom/providers/opencode tests/test_providers_opencode_config.py tests/test_providers_opencode_install.py
All checks passed!
$ ruff format --check headroom/providers/opencode tests/test_providers_opencode_config.py tests/test_providers_opencode_install.py
6 files already formatted
```

`mypy headroom/providers/opencode` reports one error, in
`headroom/providers/model_metadata.py:79`, which this PR does not touch;
nothing in the changed files.

## Real Behavior Proof

- Environment: WSL2 Ubuntu on Windows 11, Python 3.12.15, branch based
on upstream/main `e995eb9f`; `headroom/_core.abi3.so` taken from the
official headroom-ai 0.41.0 wheel (untracked, not committed). Throwaway
HOME under `/var/tmp`, never a real user config.
- Exact command / steps: write `opencode.json` into the throwaway HOME,
then run the real CLI `headroom wrap opencode --prepare-only --no-mcp
--no-serena --port 18900` (entry `from headroom.cli import main`), then
read the file. Case A: BOM + `{"model": "gpt-4o", "keybinds": {"leader":
"ctrl+x"}}`. Case B: `{"model": "gpt-4o" "oops": 1}`. Case C: the file
holds only the three BOM bytes `ef bb bf`. Each run on the code without
the fix, then with it (case C: without the second commit's change, then
with it).
- Observed result: Case A without the fix: exit 0, file holds only
`provider.headroom`; `model` and `keybinds` are gone. Case A with the
fix: exit 0, `model` and `keybinds` kept, `provider.headroom` added (the
file is written without the BOM). Case B without the fix: exit 0, file
replaced by the Headroom-only block. Case C without the second commit:
exit 1, `Error: could not parse OpenCode config at <path>; leaving it
unchanged.`, file still the three BOM bytes. Case C with it: exit 0,
`provider.headroom` written (same as a zero-byte file). Case B with the
fix: exit 1, `Error: could not parse OpenCode config at <path>; leaving
it unchanged. Fix the JSON/JSONC syntax and retry.`, file still
`{"model": "gpt-4o" "oops": 1}`.
- Not tested: the MCP registrar (`mcp_registry/opencode.py`), which has
its own parser and still reports a BOM config as not valid JSON (it
refuses to write and leaves the file unchanged; checked by calling
`register_server` directly, so the default `wrap opencode` run without
`--no-mcp` was not run); a real `opencode` binary reading the result;
Windows paths or a real Windows editor producing the BOM; JSONC comments
combined with a BOM (comment stripping runs after the BOM strip, only
unit-level reasoning); the `headroom install` flow end to end (only
`apply_provider_scope` via a unit test); the MCP registry parser in
`mcp_registry/opencode.py` (unchanged).

Output, case A (stderr line about the retired MCP cleanup is from the
unchanged registry code):

```text
without the fix:
  "provider": { "headroom": { ... } }          # only key in the file
with the fix:
  "model": "gpt-4o", "keybinds": { "leader": "ctrl+x" }, "provider": { "headroom": { ... } }
```

Output, case B with the fix:

```text
exit: 1
Error: could not parse OpenCode config at .../.config/opencode/opencode.json; leaving it unchanged. Fix the JSON/JSONC syntax and retry.
--- after wrap
{"model": "gpt-4o" "oops": 1}
```

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: yes, narrowly: `wrap opencode` and
the OpenCode provider-scope install now stop with an error on an
unparseable non-empty config instead of overwriting it; a BOM config is
now merged instead of replaced
- Kill switch / disable path: none; fix the config file syntax, or
remove the file
- Unsafe override required: no
- Qualification impact: none expected
- Rollback path: revert this commit

## Review Readiness

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

## Checklist

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

## Screenshots (if applicable)

N/A

## Additional Notes

N/A items: documentation (no user-facing doc describes this failure
mode), mypy (one existing error elsewhere, see above). Behavior change
to review: refusing to write is stricter than before; a file that was
silently replaced earlier now needs a manual syntax fix.

Produced with AI assistance (Claude Code) operated by me (HetCreep); the
reproduction was run on my machine on a clone of the repository.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-10-24 08:38:33 -07:00
Tejas ChopraandClaude Opus 5.5 688b327039 chore(providers): remove dead provider and model helpers (#4078)
## Description

This PR removes provider and model helpers that nothing calls. Two of
them were reached only by tests. For one of those, the test is pointed
at the function production actually uses, so the code path keeps its
coverage.

Refs #4136
## Type of Change

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

## Changes Made

- `headroom/models/config.py`: remove `get_default_embedding_model`,
`get_default_embedding_dim`, `get_default_spacy_model`,
`get_default_siglip_model` and `MLModelConfig.total_memory_estimate`.
Callers read `ML_MODEL_DEFAULTS.<field>` directly, and none of these is
in the `headroom.models` lazy export map.
- `headroom/providers/opencode/config.py`:
  - Remove `_render_provider_block`.
- Remove `_opencode_home_dir`. `OPENCODE_HOME` is resolved by
`headroom.install.paths.opencode_config_path` and by
`context_tool_cleanup._opencode_home`.
- Remove `append_headroom_plugin` and its two tests. The live plugin
wiring is in `opencode/runtime.py`.
- `headroom/providers/litellm.py`: drop the unused `from litellm import
model_cost as litellm_model_cost` and its `None` fallback.
- `headroom/providers/codex/model_metadata.py`: remove the test-only
`fetch_chatgpt_codex_model_ids` wrapper. Its test now calls
`fetch_chatgpt_codex_model_entries`, which is what production uses, and
checks the same slugs and the same request.
- Evidence: a word search (`rg -c -w <name>`) across the repo (code,
tests, docs, wiki, CI, pyproject) and the private consumer repos finds
only each definition, plus tests for the two test-only helpers.

## Testing

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

### Test Output

```text
$ pytest -q tests/test_providers_opencode_config.py tests/test_cli/test_wrap_opencode.py tests/test_providers_opencode_install.py tests/test_provider_codex_model_metadata.py tests/test_providers/test_universal.py tests/test_ml_model_registry_lifecycle.py tests/test_startup_log_noise.py tests/test_install/test_paths.py
239 passed, 1 warning in 14.22s
$ pytest -q tests/test_paths_backward_compat.py tests/test_paths.py tests/test_provider_codex_runtime.py tests/test_models.py
120 passed in 5.38s
$ ruff check (touched files)
All checks passed!
$ mypy headroom/models/config.py headroom/providers/opencode/config.py headroom/providers/codex/model_metadata.py headroom/providers/litellm.py --ignore-missing-imports
Success: no issues found in 4 source files
```

## Real Behavior Proof

- Environment: macOS, repo venv, branch checkout at 91e11e40, temp HOME
/ HEADROOM_WORKSPACE_DIR / CODEX_HOME, offline.
- Exact command / steps: (1) shared smoke harness: start a real proxy
from this checkout against a local fake upstream and send one Anthropic
and one OpenAI request with a compressible tool result; (2) under a temp
HOME, run the OpenCode config injection that `headroom wrap opencode`
uses (the live code left in `opencode/config.py`) and print the written
config, plus the `ML_MODEL_DEFAULTS` fields that replace the removed
`get_default_*` accessors.
- Observed result: smoke requests return HTTP 200 with savings; the
injection writes `~/.config/opencode/opencode.json` (the
`OPENCODE_HOME`/default path resolved by `install.paths`) with the
Headroom provider at `http://127.0.0.1:8787/v1`; `ML_MODEL_DEFAULTS`
reports the default embedding model and dimension.
- Not tested: launching the real OpenCode binary (not installed here)
and a live ChatGPT Codex model-registry fetch.

```text
$ bash smoke.sh <worktree>
branch: cleanup/providers-evals-dead-provider-helpers @ 91e11e40
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines:
   2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you configured, operator-configured local endpoints, loopback health probes.
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.

$ HOME=$(mktemp -d) python -c "inject_opencode_provider_config(8787); print(opencode_config_path().read_text()); print(ML_MODEL_DEFAULTS...)"
.config/opencode/opencode.json
{
  "provider": {
    "headroom": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Headroom Proxy",
      "options": {
        "baseURL": "http://127.0.0.1:8787/v1"
      },
      "models": { "gpt-4o": {...}, "gpt-4.1": {...} }
    }
  }
}
embedding model: all-MiniLM-L6-v2 384
```

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A, dead code only.
- Stable/default behavior changed: No.
- Kill switch / disable path: N/A.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert this commit.

## Review Readiness

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

## Checklist

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

## Screenshots (if applicable)

N/A

## Additional Notes

Part of maintainer-requested cleanup #4136 (dead code, duplication,
debuggability), split into small PRs for review.

A second, equally unused `_opencode_home_dir` in `headroom/cli/wrap.py`
is being removed in a separate CLI cleanup branch. Neither copy had a
caller. No documentation referenced any removed name.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 08:57:09 -07:00
1fb4cbaea0 fix(proxy): astgrep disk verify truncation (#3192)
## Description

`_detect_truncation()` currently relies on client-specific truncation
banners in `tool_result` text. This works for clients that emit a
recognizable line-count banner, but not for clients such as Cursor
(byte-based, direction-reversed truncation) and OpenCode (placeholder +
external file pointer).

Because `headroom proxy` runs alongside the client it wraps, it can
optionally verify the returned content against the actual file on disk.
If the `tool_result` is a strict prefix of the file, we can identify
truncation without depending on client-specific output formatting.

This adds disk verification as an opt-in fallback: the existing
banner-based detection always runs first, and disk verification is only
attempted when no banner is found. All disk-verification failures or
ambiguous cases return `UNKNOWN` rather than guessing.

Following review, the verifier is also constrained to a trusted,
confined workspace root rather than trusting caller-supplied input
directly — see the last four bullets under Changes Made.

**Current scope:** the session-token workspace binding this fallback
requires is wired for `headroom wrap claude` and plugin-loaded `headroom
wrap opencode` only. Cursor remains unsupported/not tested — it has no
header-injection surface today to transmit an authoritative session
token, so disk verification stays `UNKNOWN` for it; extending Cursor
support needs a separate, safe transport design.

Related to #2430
Closes #2421

## Type of Change

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

## Changes Made
- Added optional disk-based Read truncation verification behind
`HEADROOM_VERIFY_TRUNCATION_ON_DISK`.
- Disk verification compares the visible `tool_result` against the file
on disk and distinguishes `COMPLETE`, `TRUNCATED`, and `UNKNOWN`.
- Disk verification only runs when the existing `_detect_truncation()`
banner check finds no truncation marker, avoiding unnecessary file I/O
when the client already provides a signal.
- Added a `current_cwd` contextvar populated from `x-headroom-cwd` so
relative Read paths can be resolved against the client's working
directory.
- Registered `HEADROOM_VERIFY_TRUNCATION_ON_DISK` as a hot-reloadable
runtime setting.
- Gated verification on a new `is_current_request_trusted` contextvar,
set from `is_loopback_host(request.client.host)` — a server-observed
fact, not the caller-supplied header — so `x-headroom-cwd` is never
sufficient authority on its own.
- Confined all path resolution strictly under the canonicalized `cwd`
(`.resolve()` + `relative_to()`), rejecting `..` traversal,
absolute-path escapes, and post-resolution symlink escapes.
- Required the resolved target to be a regular file and under a byte cap
(new `HEADROOM_VERIFY_TRUNCATION_MAX_BYTES` knob, default 5MB), both
checked via `fstat` on the open fd before any read.
- Opened with `O_NONBLOCK` so a non-regular/special file can't park the
read indefinitely; disk I/O already runs off the event loop via the
existing compression thread pool.
- Added unit and integration tests covering successful verification,
missing/unreadable paths, relative paths, content races, feature gating,
banner precedence, and the adversarial cases below.

## Testing

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

### Test Output

```text
$ pytest tests/test_tool_result_interceptors.py -v
51 passed in 2.21s
(includes TestVerifyReadAgainstDisk::* [14 cases, incl. absolute-path escape, `..`
traversal, symlink escape, sibling-prefix boundary, non-regular file, oversized
file, and untrusted-request-touches-no-disk], plus the end-to-end disk-verification
and banner-precedence cases)

$ pytest tests/test_proxy_loopback_gating.py -k trusted
16 passed
(includes test_record_headroom_stack_binds_trusted_true_for_loopback_client and
..._false_for_non_loopback_client — proves a spoofed x-headroom-cwd from a
non-loopback peer does not bind trust)

$ ruff check headroom/proxy/interceptors/astgrep.py headroom/proxy/project_context.py \
    headroom/proxy/server.py headroom/proxy/runtime_env.py \
    tests/test_tool_result_interceptors.py tests/test_proxy_loopback_gating.py
All checks passed!

$ mypy headroom/proxy/interceptors/astgrep.py headroom/proxy/project_context.py \
    headroom/proxy/server.py headroom/proxy/runtime_env.py
Success: no issues found in 4 source files
```

## Real Behavior Proof

- Environment: Mac OS local dev machine, no live proxy/network involved.
Exercised the real interceptor pipeline (`apply_to_messages`) directly
against an actual file on disk, using the same fixture and cwd-binding
path a live proxy request would use.
- Exact command / steps: wrote a 9-function Python fixture to a temp
file, built a client-truncated `tool_result` (first 8 functions, cut
mid-file, **no truncation banner text anywhere**), bound
`x-headroom-cwd` to the temp directory via `set_current_cwd()`, then
called `apply_to_messages()` once with
`HEADROOM_VERIFY_TRUNCATION_ON_DISK` unset and once with it set to `1`.
- Observed result: With disk verification disabled, the existing
ast-grep interceptor produced its normal header without indicating that
the input was truncated. With HEADROOM_VERIFY_TRUNCATION_ON_DISK=1, disk
verification detected that the 50-line tool_result was a strict prefix
of the 59-line file and produced:
 ```text
=== HEADROOM_VERIFY_TRUNCATION_ON_DISK unset (default) ===
[headroom: outlined by ast-grep — 8 definition(s); bodies elided.
Re-read the file with a line range to see a specific body.]

=== HEADROOM_VERIFY_TRUNCATION_ON_DISK=1, x-headroom-cwd bound to the
real directory ===
[headroom: outlined by ast-grep — 8 definition(s) in the visible
portion; input was truncated upstream (showing through line 50 of 59
total). Bodies elided. Re-read remaining lines to see more.]
```

**Trust-gate behavior:** same fixture and disk layout, `HEADROOM_VERIFY_TRUNCATION_ON_DISK=1`, but the request context's trust flag left at its default (`False`, simulating a non-loopback caller) instead of being marked trusted.

```text
=== trusted context (loopback) ===
[headroom: outlined by ast-grep — 8 definition(s) in the visible
portion; input was truncated upstream ...]

=== untrusted context (non-loopback) — same file, same cwd header, same
tool_result ===
[headroom: outlined by ast-grep — 8 definition(s); bodies elided.
Re-read the file with a line range to see a specific body.]
(no disk read attempted — verified via a call-recording wrapper around
os.open asserting zero invocations)
```
Also verified at the HTTP-middleware level with `TestClient(..., client=("100.90.0.5", 12345))`: a request carrying a spoofed `x-headroom-cwd` header from a non-loopback client IP does not bind trust, regardless of header content.

- Not tested: a live `headroom proxy` session with a real coding-agent client; the WebSocket/Codex responses-WS path.

## Runtime Rollout Safety

- Rollout-managed feature(s): None. The feature is gated by `HEADROOM_VERIFY_TRUNCATION_ON_DISK`
- Minimum rollout channel: N/A. `--intercept-tool-results` must already be enabled for the ast-grep interceptor to run.
- Stable/default behavior changed: no
- Kill switch / disable path: Unset `HEADROOM_VERIFY_TRUNCATION_ON_DISK`; the setting is hot-reloadable and does not require a restart.
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert the commit, or unset the env var on a running proxy (takes effect immediately, no restart).

## Review Readiness

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

## Checklist

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

## Additional Notes

this branch is based on `fix/astgrep-truncation-marker` #2430 not main


<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3192" 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 Sonnet 5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-10-08 10:52:09 -05:00
1d4b357ca7 feat(opencode): support the OpenCode 2.x plugin API (#3999)
## Description

Takeover of #3719 by @laurence-diack-pk, who has been unavailable since
Sep 23 and whose branch was left conflicted with `main`. The original
commit is preserved and @laurence-diack-pk remains its author; this
branch adds follow-up commits addressing @JerrettDavis's review and the
findings from live OpenCode 2.x testing.

It makes the OpenCode plugin and `headroom wrap opencode` work on both
OpenCode 1.x and 2.x. On 2.x the 1.x function plugin was silently
dropped (the loader requires a `{ id, setup }` default export loaded
from a directory), and Effect's `FetchHttpClient` keeps its own `fetch`
reference from before plugins load — so `wrap opencode` loaded no plugin
and routed nothing.

Closes #3669. Supersedes #3719.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)

## Changes Made

Carried from #3719:
- One plugin for both versions: default export `{ id: "headroom",
server, setup }`; 1.x calls `server`, 2.x calls `setup`.
- 2.x `setup`: registers `headroom_retrieve` via `ctx.tool.transform`
(`codemode: false`), sets `HEADROOM_*` shell env through the
`create.before` hook, and returns a cleanup that releases the refcounted
transport so hot reloads do not stack interceptors.
- 2.x model routing: `ctx.model.transform` points remote OpenAI-wire
models at the proxy with `x-headroom-base-url` /
`x-headroom-original-path` headers, since 2.x keeps its own `fetch`
reference and the transport patch alone misses model traffic.
- Wheel ships the bundle as `_dist/index.js`;
`headroom_opencode_plugin_path()` returns the directory; `wrap opencode`
adds `--standalone` on 2.x so the private server sees
`OPENCODE_CONFIG_CONTENT`.

Follow-up commits (review from #3719 + live testing):
- Rebased on current `main` (0.40.0). Fixed the routing-contract
conflict: replaced `routesThroughProxy` (TS2554 against `shouldRoute`'s
3-arg signature) with `modelBaseRoutesThroughProxy`, a deliberate
model-base eligibility check that keeps the shared protocol / loopback /
proxy-origin / excluded-host contract but drops the endpoint-suffix
requirement, since 2.x hands us model base URLs (e.g. `/v1`), not
inference endpoints.
- `setup` now resolves the effective `excludeHosts` once (option over
`HEADROOM_OPENCODE_EXCLUDE_HOSTS`) and applies it to both the transport
install and the model rewrite, with new tests for both paths.
- Fixed `test_build_launch_env_with_project` to decode
`OPENCODE_CONFIG_CONTENT` instead of substring-matching the raw path,
which JSON backslash escaping makes impossible on Windows.
- `opencode_major_version` now reads the `v2` channel marker in dev
builds (`opencode v0.0.0-v2-<stamp>`), which previously parsed as major
0, so `wrap` skips `--standalone` and the private server never loads
Headroom's config.
- Rebuilt `_dist/index.js` and `hook-shim/handler.js`; drift check
clean.

## Testing

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

### Test Output

```text
# plugins/opencode
$ npm ci && npm run typecheck && npm run build:standalone && npm test
tsc: clean (no TS2554)
vitest: Test Files 3 passed (3) | Tests 45 passed (45)
$ cmp dist-standalone/index.js ../../headroom/providers/opencode/_dist/index.js          # identical
$ cmp dist-standalone/hook-shim/handler.js ../../headroom/providers/opencode/hook-shim/handler.js  # identical

# focused Python suites (same set as #3719, plus the 2.x dev-build version case)
$ pytest tests/test_providers_opencode_plugin_path.py tests/test_providers_opencode_config.py \
    tests/test_providers_opencode_install.py tests/test_cli/test_wrap_opencode.py \
    tests/test_mcp_registry_opencode.py tests/test_learn/test_opencode_scanner.py -q
193 passed in 1.10s

$ ruff check / ruff format --check on changed paths: clean
$ mypy headroom/providers/opencode headroom/cli/wrap.py: Success: no issues found
```

## Real Behavior Proof

- Environment: macOS arm64, Node v26.10.0, Python 3.13, headroom from
this branch (0.41.0-dev). Tested against two real OpenCode 2.x clients,
each in throwaway XDG dirs with its own proxy port:
  - `opencode 2.0.19` (official 2.x binary);
- OpenCode 2.x head built from `anomalyco/opencode@v2`
(`0.0.0-v2-202610061051`, Bun 1.4.2, `bun run script/build.ts --single`
in `packages/cli`).
- Exact command / steps: throwaway XDG dirs and a dedicated proxy port;
fake key first (routing proof), then the real key (end-to-end proof):
  ```bash
  # fake key first (routing proof), then the real key (end-to-end proof)
OPENCODE_API_KEY=<key> headroom wrap opencode --port 8799 --no-serena --
\
run -m opencode-go/deepseek-v4.1-flash "reply with the single word ok"
  # exclusion check
HEADROOM_OPENCODE_EXCLUDE_HOSTS=opencode.ai OPENCODE_API_KEY=<key>
headroom wrap opencode ...
  ```
(`opencode-go` declares `OPENCODE_API_KEY` as its env credential in the
catalog, so no interactive login is needed.)
- Observed result: routed 401 with the fake key and 200 with the real
key through the proxy, `--standalone` added automatically, exclusion
honored — details:
- **Fake key** — proxy log: `proxy_inbound_request POST
/v1/chat/completions` with `user-agent: opencode/latest/2.0.19/cli` (and
`opencode/v2/0.0.0-v2-202610061051/cli` for the head), headers
`x-headroom-base-url: https://opencode.ai` and
`x-headroom-original-path: /zen/go/v1/chat/completions`; forwarded
upstream, `401` from the fake key — routed through Headroom.
- **Real key** — the model answered `ok`; proxy `status=200` with
upstream `https://opencode.ai/inference/go/openai/v1/chat/completions`.
- `wrap` added `--standalone` automatically on 2.0.19, and again on the
v2 head after the dev-build version fix (explicit `--standalone` also
works, per the kill-switch path).
- **Exclusion** — with `HEADROOM_OPENCODE_EXCLUDE_HOSTS=opencode.ai` the
model still answered while the proxy saw **zero** new chat requests: the
2.x model transform honors the exclusion list.
- Not tested: Windows; OpenAI "responses"-wire against a live 2.x
server; Anthropic-wire custom providers on 2.x; loading the plugin by
npm name (`headroom-opencode`), which needs a published release;
OpenCode 1.x older than 1.2.20.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: on OpenCode 2.x, `wrap opencode`
launches with `--standalone` (a private server per session); on 1.x
behaviour is unchanged apart from the plugin path now being a directory.
- Kill switch / disable path: pass `--server <url>` or `--standalone`
explicitly; `HEADROOM_OPENCODE_PLUGIN_PATH` still overrides the plugin
location.
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this PR; the wheel bundle and plugin path revert
with it.

## Review Readiness

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

## Checklist

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

## Additional Notes

@laurence-diack-pk — thank you for the original implementation; the
commit is preserved verbatim at the base of this branch. @JerrettDavis —
this addresses the routing-contract conflict you described in #3719 (the
missing `excludeHosts` argument and the model-base vs endpoint
mismatch), the Windows assertion, and a dev-build version-detection gap
found while validating on macOS. Live 2.x validation is done on both
2.0.19 and today's `v2` head; details above.

---------

Co-authored-by: laurence <laurence.diack@peekrobotics.co.nz>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-10-07 20:52:53 -05:00
Mansurshakh JaparovandJD Davis 40955b0eef fix(install): preserve OpenCode edits during reactivation (#4022)
## Description

Reapply, restart, and automatic recovery temporarily remove the Headroom
provider before reactivating it. They must not restore the original
backup and erase user configuration added after installation. Final
removal must still restore the original snapshot.

Closes #4016.

## Type of Change

- [x] Bug fix
- [x] Documentation update

## Changes Made

- Separate transient provider deactivation from final backup
restoration, and propagate the intent through the existing install
registry/manifest lifecycle.
- During reactivation and activation rollback, remove only Headroom's
provider; retain unrelated providers, MCP settings, theme, and the
original backup.
- On true removal, restore and delete the original backup as before.
- Associate backups with the actual selected `opencode.json` or
`opencode.jsonc` filename, and pin edited writes to LF.
- Persist snapshot ownership independently of active mutations,
including activation persistence failures and stop/reload/final-remove.
- Migrate historical JSONC backup names (including custom config names)
before snapshotting/restoration in installer and wrapper callers; do not
claim a sibling JSON installation's backup.
- Accept JSONC comments/trailing commas without erasing user settings;
retain quoted URLs and delimiters.
- Restore the snapshot when a successful replacement drops OpenCode, but
retain it on replacement failure.
- Document preservation during reapply/restart/recovery and
original-snapshot behavior on final removal.

## Testing

- [x] Unit tests pass (`pytest`), including JSON/JSONC and all three
reactivation paths.
- [x] Changed-file lint, configured pre-commit mypy and manual
real-filesystem checks pass.

### Test Output

Real filesystem smoke output for both config suffixes:

```json
[{"final_removal_deletes_backup": true, "final_removal_restores_original": true, "headroom_reactivated": true, "original_backup_unchanged": true, "suffix": ".json", "theme": "edited-after-install", "user_mcp_preserved": true, "user_provider_preserved": true}, {"final_removal_deletes_backup": true, "final_removal_restores_original": true, "headroom_reactivated": true, "original_backup_unchanged": true, "suffix": ".jsonc", "theme": "edited-after-install", "user_mcp_preserved": true, "user_provider_preserved": true}]
```

The mandatory pre-push `make ci-precheck` passed: workspace Rust
fmt/clippy/tests, native extension build/import verification, the
complete configured Python gate, and Commitlint. The native gate
explicitly used the installed CPU `libonnxruntime.so.1.26.0` via
`ORT_DYLIB_PATH`, with cached-model assertions enabled.

```text
[build_rust_extension] headroom._core build + install + verify: OK
================== 177 passed, 4 skipped, 1 warning in 6.31s ===================
✅ ci-precheck PASSED — safe to push.
```

```sh
python -m pytest -q tests/test_providers_opencode_install.py tests/test_cli/test_install_cli.py tests/test_install/test_providers.py
```

Original lifecycle suite: **121 passed**. After the review corrections,
the combined provider/config/wrapper/install-CLI/recovery suite passed
**240 tests in 8.32s**:

```sh
python -m pytest -q tests/test_providers_opencode_install.py tests/test_providers_opencode_config.py tests/test_cli/test_wrap_opencode.py tests/test_cli/test_install_cli.py tests/test_install/test_providers.py tests/test_install_tool_env_reconcile.py
```

The regression suite checks real original bytes and persisted recovery
ownership, not mocked call order or incidental error wording. The
obsolete JSONC-trailing-comma rejection expectation was removed.

Changed-file Ruff, formatting, installed pre-commit `mypy headroom`, and
Commitlint hooks passed. Full-tree Ruff remains blocked locally by
executable permissions on five unchanged OAuth2 plugin files (tracked
100644). A separate full dev-environment mypy run found an unchanged
optional LangChain `truthy-function` error; the configured isolated
pre-commit hook passed. Unrelated code/permissions were not modified.

## Real Behavior Proof

- Environment: Linux x86_64, CPython 3.13.14; unchanged
`dea9092e19385f286b7f67a64f4d85de2708d756` and this branch, real
temporary config files and real installer mutation helpers, no mocked
file mutation or service installed on the workstation.
- Exact command / steps: for each suffix `.json` and `.jsonc`, write an
original theme/provider/MCP config; activate a provider-scoped OpenCode
manifest with `_activate_deployment_mutations`; edit the theme and add a
user provider plus remote MCP; call `_deactivate_deployment_mutations`
then `_activate_deployment_mutations`; inspect real files and the
original backup; finally invoke `revert_mutations(...,
restore_backup=True)`.
- Before: theme reset to `original`; added provider and MCP disappeared.
JSONC's actual-name backup was absent.
- Observed result: after the fix, theme remains `edited-after-install`;
both user additions survive; Headroom is active again; both actual-name
backups remain byte-identical to the original. Final removal restores
the original bytes and deletes the backup for both suffixes.
- Review correction proof against published head `4bc8e50c`: actual
temporary files and persisted manifests cover stop/reload/final-remove
for JSON and JSONC, legacy backup migration for default and custom
filenames, JSONC trailing commas and quoted `//`/`,}` text, successful
target removal, and activation-persistence failure followed by
reload/removal. All eight scenario outcomes pass after the correction;
the published baseline leaves or consumes the wrong snapshots and loses
JSONC edits. The actual `headroom unwrap opencode --no-stop-proxy`
command also restores the historical JSONC snapshot byte-for-byte and
consumes its backup. Only external process/service management and the
explicit persistence-fault boundary are substituted; config, manifest
and snapshot IO are real.
- Second review correction against `1c0855c4`: all four new findings
reproduced on real temporary config/backup files and persisted
manifests. After the fix, failed addition consumes its newly created
snapshot (a later install restores the later user edit); changed config
selection restores the recorded original path; an existing canonical
JSONC snapshot wins without deleting the ambiguous legacy backup; and
restoration failure retains ownership in the active replacement so a
retry after reload finishes restoration. Seven permanent boundary cases
initially gave **6 failures and 1 passing control**; the complete
affected suite now gives **247 passed**. OS supervisor calls and
explicit persistence/restoration faults are the only substituted
boundaries.
- Not tested: a real launchd/systemd supervisor or Windows process on
this Linux host. CLI regression tests exercise apply/restart/recovery
boundaries while replacing service management; the filesystem mutation
smoke uses real production helpers.

## Runtime Rollout Safety

- Rollout-managed feature(s): none; lifecycle data-preservation fix.
- Minimum rollout channel: stable; no rollout-managed feature is
enabled.
- Stable/default behavior changed: transient reactivation stops
reverting unrelated user edits. Final uninstall still restores the
original snapshot.
- Kill switch / disable path: remove the persistent OpenCode
installation using its existing removal flow; no new flag.
- Unsafe override required: no.
- Qualification impact: provider-scoped OpenCode configuration only;
other providers retain their existing removal semantics.
- Rollback path: revert the commits; no deployment manifest schema
change. Backup ownership uses the existing artifact record, and legacy
JSONC snapshots migrate to the selected config's canonical filename.

## Review Readiness

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

## Checklist

- [x] Existing registry/lifecycle interfaces reused; persistent-install
docs updated.
- [x] Consumer-visible regressions cover edits, original-backup
invariants, both config suffixes, three reactivation paths, and final
removal.
- [x] `CHANGELOG.md` not edited; Conventional Commit title supplied.

Remote CI results are reported by GitHub, not assumed from local tests.

---------

Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-10-07 17:46:39 -05:00
Ayush Kumar JhaandJerrett Davis 0d7d61d5cc fix(wrap): let wrap opencode target a third-party OpenAI-compatible upstream (#3125)
## Description

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

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

Closes #3107

## Type of Change

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

## Changes Made

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

## Testing

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

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

### Test Output

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

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

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

$ python -m ruff check .
All checks passed!

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

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

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

## Real Behavior Proof

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

## Runtime Rollout Safety

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

## Review Readiness

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

## Checklist

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

## Screenshots (if applicable)

n/a — CLI and docs change.

## Additional Notes

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

---------

Co-authored-by: Jerrett Davis <mxjerrett@gmail.com>
2026-10-06 08:45:54 -05:00
Suliman Abdulrazzaq 5e53b8aa0a fix(opencode): keep Claude models off OpenAI provider
## Description

The injected `headroom` OpenCode provider uses
`@ai-sdk/openai-compatible` and the proxy's `/v1/chat/completions`
route. It currently advertises Claude model IDs in that provider, so
OpenCode sends Claude requests to the OpenAI upstream and receives
`invalid_api_key` errors. Keep Claude on OpenCode's native `anthropic`
provider, which Headroom already redirects to the proxy.

Closes #2911

## Type of Change

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

## Changes Made

- Remove Claude IDs from the injected OpenAI-compatible provider model
map.
- Keep GPT models available through the `headroom/<id>` namespace.
- Add regression assertions that generated config never advertises
Claude models on this endpoint.

## Testing

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

### Test Output

```text
python -m pytest tests/test_providers_opencode_config.py -q -k "not build_launch_env_with_project"
40 passed, 1 deselected

python -m ruff check headroom/providers/opencode/config.py tests/test_providers_opencode_config.py
All checks passed!

python -m compileall -q headroom/providers/opencode/config.py tests/test_providers_opencode_config.py
(pass)
```

The full config test module also exposes an unrelated pre-existing
Windows path assertion failure in `test_build_launch_env_with_project`;
the failure is caused by comparing a native `Path` string with
JSON-escaped backslashes and is outside this change.

## Real Behavior Proof

- Environment: Windows 11, Python 3.11; no external API credentials
used.
- Exact command / steps: `python -c "from
headroom.providers.opencode.config import headroom_provider_entry;
print(sorted(headroom_provider_entry(8787)['models']))"`
- Observed result: `['gpt-4.1', 'gpt-4o']`; the generated
OpenAI-compatible provider no longer advertises any `claude-*` IDs.
- Not tested: live OpenCode request routing or a vendor API call,
because they require external credentials. The regression suite verifies
the generated configuration consumed by OpenCode.

## Review Readiness

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

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
(not needed; the provider routing rationale is documented inline)
- [ ] I have made corresponding changes to the documentation (the
generated provider behavior is documented in code; existing docs
describe the separate npm provider)
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective
- [x] New and existing relevant unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

The native `anthropic` and `openai` provider entries both continue to
point at the Headroom proxy, so this change only removes an invalid
duplicate Claude route and does not affect native Claude traffic.
2026-08-11 09:46:03 -07:00
Tanmay Garg 4e2bbfee3f fix(opencode): Use opencode.jsonc when present (#1590)
## Description

Fix OpenCode proxy injection so it respects user configurations that use
the `.jsonc` extension, preventing Headroom from creating a duplicate
`.json` file that overrides it.

Closes #1588

## Type of Change

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

## Changes Made

- Updated `opencode_config_path` in `paths.py` to check for `.jsonc`
- Updated backup creation in `config.py` to preserve the original
extension

## Testing

<!-- Check what you actually ran, then paste the real command output
below. -->

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

### Test Output

```text
N/A
```

## Real Behavior Proof

- Environment: local headroom dev
- Exact command / steps: creating a dummy
`.config/opencode/opencode.jsonc` and running `headroom wrap opencode`.
- Observed result: Headroom successfully injects into `.jsonc` and
creates a backup named `opencode.jsonc.headroom-backup`.
- Not tested: N/A

## Review Readiness

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

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] I have updated the CHANGELOG.md if applicable

## Screenshots (if applicable)

## Additional Notes
2026-07-16 13:51:21 -07:00
ParideboyandClaude Fable 5 e8151f059b fix(opencode): expose headroom/* models in injected provider config (#1716)
## Description

`headroom wrap opencode` (and `headroom install opencode`) injects a
`provider.headroom` block into the OpenCode config, but the block
contained **no `models` map**. OpenCode only resolves
`<provider>/<model>` ids that are listed in a custom provider's `models`
map, so every documented `headroom/*` model (see
`plugins/opencode/README.md`) failed with:

```text
Error: Model not found: headroom/claude-sonnet-4-6.
```

This PR adds the model map (mirroring `DEFAULT_MODELS` in
`plugins/opencode/src/provider.ts` and the README table) via a single
shared `headroom_provider_entry()` helper used by all three injection
sites. It also fixes a latent bug in the TS helper
`createHeadroomProvider`, which prefixed model **keys** with `headroom/`
— OpenCode would have registered them as `headroom/headroom/<id>`.

Not addressed here (flagged for maintainers): the `headroom-opencode`
npm package referenced by the plugin docs is not published to npm
(registry 404), so the transparent-transport interception path (which
would capture `github-copilot/*` traffic in the dashboard) still depends
on a locally built `plugins/opencode/dist/entry.opencode.js`. With this
fix, the documented `headroom/*` provider route works, so wrapped
OpenCode traffic is proxied and recorded when users select `headroom/*`
models.

Closes #1657

## Type of Change

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

## Changes Made

- `headroom/providers/opencode/config.py`: added
`HEADROOM_OPENCODE_MODELS` (claude-sonnet-4-6, claude-opus-4-6,
claude-haiku-4-5-20251001, gpt-4o, gpt-4.1 — same names/limits as the TS
plugin) and a `headroom_provider_entry(port)` helper that includes the
`models` map; `_render_provider_block` and
`inject_opencode_provider_config` now use it instead of duplicating the
provider dict.
- `headroom/providers/opencode/runtime.py`:
`build_opencode_config_content` reuses `headroom_provider_entry()` so
`OPENCODE_CONFIG_CONTENT` exposes the models too.
- `plugins/opencode/src/provider.ts`: `createHeadroomProvider` no longer
prefixes model keys with `headroom/` (OpenCode namespaces model ids by
provider key; keys must be bare ids).
- `tests/test_providers_opencode_config.py`: assertions that the
injected provider block and `build_opencode_config_content` output
contain a `models` map with bare-id keys including `claude-sonnet-4-6`.

## Testing

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

### Test Output

```text
$ python -m pytest tests/test_providers_opencode_config.py -q
1 failed, rest passed — test_build_launch_env_with_project is a pre-existing
Windows-only failure (json.dumps escapes backslashes in the plugin path);
it fails identically on upstream/main without this change and passes on Linux.

$ ruff check headroom/providers/opencode tests/test_providers_opencode_config.py
All checks passed!
$ ruff format --check .
5 files already formatted
$ mypy headroom --ignore-missing-imports
Success (notes only, no errors)

$ cd plugins/opencode && npm run typecheck && npm test
tsc --noEmit: OK
Test Files  2 passed (2)
Tests  13 passed (13)
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.13, Node v26.3.0, this branch with
the Rust core built locally.
- Exact command / steps: `python -c "from
headroom.providers.opencode.runtime import
build_opencode_config_content; import json;
print(json.dumps(build_opencode_config_content(port=8787,
include_mcp=False)['provider']['headroom'], indent=1))"`
- Observed result: the generated `headroom` provider block now contains
`"models"` with bare-id keys (`claude-sonnet-4-6`, `claude-opus-4-6`,
`claude-haiku-4-5-20251001`, `gpt-4o`, `gpt-4.1`), each with name and
context/output limits; previously the block had no `models` key, which
is exactly why OpenCode returned `Model not found:
headroom/claude-sonnet-4-6`.
- Not tested: a live `opencode run` round-trip against a real OpenCode
install (no OpenCode binary in this environment); dashboard event
capture for `github-copilot/*` models via the transport plugin (blocked
on the unpublished `headroom-opencode` artifact, see Description).

## Review Readiness

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

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [ ] I have updated the CHANGELOG.md if applicable

## Additional Notes

- Docs: `plugins/opencode/README.md` already documents these models; no
doc change needed.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 15:20:14 -07:00
Tejas Chopra ad0034f981 fix(opencode): route native providers + load transport plugin, fix Serena context (#1573)
## Description

`headroom wrap opencode` looked like it worked (proxy started, opencode
launched) but **no inference reached the proxy**, so users saw zero
savings (#1572). Root causes:

1. The injected synthetic `headroom` provider
(`@ai-sdk/openai-compatible`) had **no `models` and no `apiKey`** →
opencode raised `ProviderModelNotFoundError`, and it only ever targets
OpenAI.
2. The wrap injected a reference to the **unpublished
`headroom-opencode` npm plugin**, which opencode silently failed to
resolve → the transparent transport never loaded.
3. Serena was launched with `--context opencode`, a context Serena does
not ship → crash on launch (#1549).

This PR makes `headroom wrap opencode` route opencode's traffic through
the proxy with the user's **own API key** (no key written to disk), and
gets the transparent transport plugin actually loading.

Closes #1572
Closes #1549

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- **`runtime.py`** — two complementary routing layers (both verified
against opencode 1.17):
1. Override opencode's native `anthropic`/`openai` provider `baseURL` to
the proxy. Reliable, credential-independent (covers API key **and**
subscription), keeps native model metadata/limits, reuses the user's
existing key. This is the always-on layer and the only one a pip-only
install needs.
2. Load the transport plugin **by absolute path** when it has been built
(`headroom_opencode_plugin_path()`), self-configured via
`HEADROOM_PROXY_URL`. Covers providers we don't name (Gemini, Copilot,
custom gateways) and providers added mid-session. Loopback URLs aren't
double-routed, so the two layers coexist.
- **`wrap.py`** — Serena context `opencode` → `agent` (valid context).
- **`plugins/opencode/`** — new `src/entry.opencode.ts` loader entry
that exports **only** the plugin function (opencode rejects a module
with non-function exports: "Plugin export is not a function"); tsup
builds it as a second entry.
- **tests** — updated `test_providers_opencode_config.py` for path-based
plugin injection + a skip-when-unbuilt case.

## Testing

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

### Test Output

```text
$ python -m pytest tests/test_providers_opencode_config.py tests/test_cli/test_wrap_opencode.py -q
72 passed in 0.59s

$ (cd plugins/opencode && npm test)
Test Files  2 passed (2)
     Tests  9 passed (9)

$ ruff check headroom/providers/opencode/runtime.py headroom/cli/wrap.py tests/test_providers_opencode_config.py
✓ Ruff: No issues found
$ mypy headroom/providers/opencode/runtime.py
Success: no issues found in 1 source file
```

## Real Behavior Proof

- **Environment:** macOS, opencode 1.17.11 (npm), headroom proxy 0.28.0
(local), Anthropic API key from `.env`.
- **Exact command:**
  ```
headroom wrap opencode --no-serena --no-context-tool --no-proxy --port
8787 \
-- run -m anthropic/claude-haiku-4-5-20251001 "Reply with exactly:
WRAPWORKS"
  ```
- **Observed result:** opencode printed `plugin=headroom-opencode`
(loaded, no error) and returned `WRAPWORKS`. The proxy log shows the
request routed through it:
  ```
event=outbound_request method=POST
path=https://api.anthropic.com/v1/messages source=passthrough
  event=proxy_inbound_response path=/v1/messages status=200
  PERF model=claude-haiku-4-5-20251001 cache_hit_pct=97 client=opencode
  ```
  Compression verified on a large tool_result (`client=opencode`):
  ```
Pipeline complete: 170653 -> 77 tokens (saved 170576, 100.0% reduction)
PERF tok_before=151309 tok_after=67 tok_saved=151242
transforms=router:tool_result:log client=opencode
  ```
- **Not tested:** custom OpenAI-compatible gateways (need the proxy to
honor `x-headroom-base-url` in the dedicated OpenAI handler — open PR
#1502); interactive TUI (verified the headless `opencode run` path).

## Review Readiness

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

## Additional Notes

- **Plugin shipping:** the plugin loads by repo-relative path, which
works for source/editable installs. `plugins/opencode/dist/` is
gitignored, so the plugin must be built (`cd plugins/opencode && npm
install && npm run build`) for layer 2 to activate; pip-only installs
gracefully fall back to layer 1 (native baseURL override). Bundling
`dist/` into the package or publishing `headroom-opencode` to npm is a
follow-up for universal shipping.
- **CHANGELOG:** N/A — handled by Release Please from the conventional
commit.
- Custom-gateway support depends on existing PR #1502 (honor
`x-headroom-base-url` in the dedicated OpenAI handlers); not duplicated
here.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-06-29 15:04:56 -07:00
Vinay Gupta 6c83790680 fix(opencode): write local MCP config (#1381)
## Description

Fixes the OpenCode config corruption reported in #1380 for wrap, MCP
registration, and provider-scope install paths.

OpenCode MCP entries are local stdio servers, not remote HTTP endpoints.
This changes Headroom's OpenCode MCP serialization to write `type:
"local"` with `command: ["headroom", "mcp", "serve"]`, uses OpenCode's
`environment` field for MCP env vars, and still reads the older `env`
key for compatibility.

This also stops provider-only OpenCode config injection from creating a
fake `http://127.0.0.1:<port>/mcp` entry, so `headroom wrap opencode
--no-mcp` no longer leaves `mcp.headroom` behind. Finally, the install
CLI/docs now accept and document `--target opencode` with provider
scope.

This does not change the broader `headroom mcp status/uninstall`
behavior from #1380; that looks like a separate follow-up.

## Type of Change

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

## Changes Made

- Write OpenCode MCP entries as local stdio config instead of remote
`/mcp` config.
- Use `environment` for OpenCode MCP env vars while continuing to read
legacy `env` entries.
- Stop OpenCode provider injection/persistent provider install from
adding MCP config.
- Keep `--no-mcp` from writing `mcp.headroom` while preserving other MCP
entries such as Serena.
- Allow `headroom install apply --target opencode` at the CLI layer.
- Update OpenCode docs and changelog.

## Testing

- [x] Focused unit tests pass
- [x] Linting passes (`ruff check .`)
- [x] Formatting passes (`ruff format --check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for the fixed behavior
- [x] Manual testing performed

### Test Output

```text
$ pytest tests/test_mcp_registry_opencode.py tests/test_cli/test_wrap_opencode.py tests/test_providers_opencode_config.py tests/test_providers_opencode_install.py tests/test_cli/test_install_cli.py tests/test_install/test_providers.py
Pytest: 164 passed

$ uvx ruff check .
All checks passed!

$ uvx ruff format --check .
986 files already formatted

$ uvx mypy --config-file pyproject.toml headroom
Success: no issues found in 398 source files
```

## Real Behavior Proof

- Environment: macOS local worktree at
`/Users/vinaygupta/Desktop/git/headroom-fix-opencode-mcp-config`; branch
`fix-opencode-mcp-config`; commit `aea96208`.
- Exact command / steps: ran the focused OpenCode/installer regression
suite plus Ruff lint/format checks and mypy commands shown above.
- Observed result: the focused tests pass and cover OpenCode MCP
serialization as `type: "local"`, `command: ["headroom", "mcp",
"serve"]`, `environment` env vars, `--no-mcp` not writing
`mcp.headroom`, provider-scope install not adding MCP config, and
`install apply --target opencode` being accepted.
- Not tested: full `pytest` locally, because collection requires the
native `headroom._core` extension in this worktree. Attempting the
project runner hit a local native build failure first: `esaxx-rs` failed
compiling `src/esaxx.cpp` with `fatal error: 'cstdint' file not found`.
The broader generic `headroom mcp status/uninstall` behavior from #1380
is intentionally left for a follow-up.

## Review Readiness

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

Scope note: generic `mcp status/uninstall` support from #1380 is
intentionally left as a separate follow-up PR.
2026-06-26 12:23:54 -05:00
ParideboyandClaude Opus 4.8 487aa71a3c ci: restore green lint (reformat for ruff 0.15.17, fix mypy no-any-return, pin linters) (#1295)
## Description

The CI lint job (`ruff check .` → `ruff format --check .` → `mypy
headroom`) was red on `main`
and therefore on every open PR, for two unrelated reasons that the early
ruff failure was masking:

1. **ruff**: the lint job installs `ruff` unpinned, and ruff 0.15.17
began enforcing import-block
sorting (`I001`) and formatting that older ruff accepted → `ruff check
.` / `ruff format --check .`
   fail on files nobody touched.
2. **mypy**: `headroom/providers/opencode/config.py` had two `return
json.loads(...)` statements in
a function declared `-> dict[str, Any]`; `json.loads` is typed `Any`, so
`mypy headroom` fails
with `no-any-return` (reproduced on mypy 1.20.2 — not a version-specific
quirk).

This restores a green lint baseline and pins both linters so a future
release can't silently break
CI again.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- `.github/workflows/ci.yml`: pin `ruff==0.15.17` and `mypy==1.20.2` in
the lint job.
- Applied `ruff check --fix .` (6 `I001` import-sort fixes) and `ruff
format .` (10 files) across
  the repo — import ordering and whitespace only, no behavior change.
- `headroom/providers/opencode/config.py`: narrow both
`_parse_json_loose` return sites with an
`isinstance(parsed, dict)` guard, so the `dict[str, Any]` annotation is
true at runtime
(non-dict JSON falls back to `{}`) and mypy's `no-any-return` is
resolved.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`, `ruff format --check .`, `mypy
headroom --ignore-missing-imports`)

### Test Output

```text
$ python -m ruff check .
All checks passed!

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

$ python -m mypy headroom/providers/opencode/config.py --ignore-missing-imports
Success: no issues found in 1 source file

$ python -m pytest tests/test_providers_opencode_config.py -q
37 passed
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.13, ruff 0.15.17, mypy 1.20.2,
branch ci/fix-ruff-lint off
  headroomlabs-ai/main
- Exact command / steps: reproduced the red lint (latest ruff: 6 `I001`
+ 10 unformatted files;
the mypy failure was read from the #1295 CI lint log —
`config.py:125,133 no-any-return`, and
re-confirmed locally on mypy 1.20.2). Applied the ruff auto-fix/format,
added the dict guard,
  pinned both linters, and re-ran each lint step.
- Observed result: `ruff check .` → "All checks passed!"; `ruff format
--check .` → "913 files
already formatted"; `mypy` on the fixed file → "Success: no issues
found"; full `mypy headroom`
reports only Unix `fcntl` attributes that don't exist on this Windows
box (present on the Linux
CI runner, where the prior run showed exactly the two now-fixed errors).
37 opencode-config
  tests pass.
- Not tested: did not run the full OS/Python test matrix — the change is
formatting + two CI
dependency pins + a two-line type-narrowing guard, with no runtime
behavior change for dict JSON.

## Review Readiness

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 15:14:40 -05:00
Rudimar RonsoniandRudimar Ronsoni b4571cc346 feat: headroom wrap opencode / unwrap opencode CLI (#1105)
## Summary

This PR implements transparent `headroom wrap opencode` support without
asking users to edit OpenCode provider URLs, choose an extra CLI flag,
or maintain a static provider list.

The wrapper now lives at the runtime transport boundary: OpenCode keeps
its user/provider config, while Headroom intercepts outbound provider
traffic in-process and routes it through the local Headroom proxy.

## What changed

### Transparent OpenCode wrapping

- `headroom wrap opencode` injects the `headroom-opencode` plugin
through `OPENCODE_CONFIG_CONTENT`.
- Existing OpenCode provider URLs are preserved. We do not rewrite user
config URLs to point at Headroom.
- Existing `OPENAI_BASE_URL` and `ANTHROPIC_BASE_URL` env vars are
preserved.
- Local OpenCode traffic, localhost traffic, and Headroom proxy traffic
bypass the shim to avoid loops.

### Runtime transport interception

- Added an OpenCode plugin transport shim that wraps:
  - `globalThis.fetch`
  - `http.request` / `http.get`
  - `https.request` / `https.get`
- External provider calls are routed to the local Headroom proxy.
- The original upstream origin is passed through `x-headroom-base-url`,
so the proxy can forward to the real provider without changing OpenCode
config.
- External `http2.connect` is blocked loudly instead of allowing direct
provider traffic to leak outside Headroom.

### Live provider additions

Provider coverage is no longer based on a static config scan. Because
routing happens at outbound request time, providers added mid-session
are routed through Headroom automatically as long as they use the
covered Node transport paths.

### Subagent and child-process coverage

- The parent OpenCode plugin sets a packaged Node preload shim through
`NODE_OPTIONS=--import=.../hook-shim/handler.js`.
- The transport shim patches `child_process.spawn`, `exec`, `execFile`,
and `fork` so child Node processes receive the Headroom preload even
when OpenCode passes a custom `env`.
- The child-process shim fails closed if it loads without
`HEADROOM_OPENCODE_TRANSPORT_PROXY_URL`.
- This closes the subagent leak path where a child Node process could
otherwise start without Headroom transport interception.

## Why this goes beyond PR #1089

PR #1089 improves OpenCode provider registration, but it still focuses
on provider config shape. This PR moves the enforcement boundary to
runtime transport interception.

This PR goes further because:

- No provider URL rewriting is required.
- New providers added mid-session are covered automatically.
- Subagents and child Node processes inherit the Headroom transport
shim.
- Direct external HTTP/2 paths fail loudly instead of leaking.
- The wrap remains transparent to the user's OpenCode provider config.
- The wrapper is fail-closed for unsupported child-process preload
state.

## Additional robustness fixes

While validating the change in Docker, the full Python suite exposed
unrelated Linux/container robustness issues. These are fixed in this PR
so the suite is green:

- Binary cache handling now treats cache paths under a non-writable
existing parent as unavailable, including when tests run as root in
Docker.
- `release_version.py` honors `MANUAL_VER` before git calls so direct
script execution works outside a `.git` checkout.
- Test logger isolation now resets relevant Headroom child loggers so
proxy logging setup cannot poison later `caplog` tests.
- The scanner missing-path test now uses a guaranteed missing `tmp_path`
child instead of relying on `/nonexistent/path`.

## Validation

All implementation validation was run inside Docker.

- Full Python suite from a fresh Docker copy: `6605 passed, 523
skipped`.
- Ruff on changed Python/OpenCode paths: passed.
- OpenCode plugin typecheck: passed.
- OpenCode plugin tests: `9 passed`.
- OpenCode plugin build: passed.
- Hook shim preload smoke test: passed.

## Notes

This PR intentionally does not add a CLI option. `headroom wrap
opencode` means full wrap. Either Headroom wraps OpenCode transparently,
or the path fails loudly instead of silently leaking provider traffic.

---------

Co-authored-by: Rudimar Ronsoni <6081613+rudironsoni@users.noreply.github.com>
2026-06-22 11:07:12 -05:00