Files
headroom/tests/test_providers_opencode_plugin_path.py
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

83 lines
3.9 KiB
Python

"""Resolution of the OpenCode transport-plugin path across install layouts."""
from __future__ import annotations
from pathlib import Path
import pytest
import headroom.providers.opencode.runtime as oc_runtime
from headroom.providers.opencode.runtime import headroom_opencode_plugin_path
# OpenCode 2.x only loads a configured local plugin from a directory, so the
# resolver returns directories; each holds the loadable `index.js`.
_PACKAGED = Path(oc_runtime.__file__).resolve().parent / "_dist"
_REPO_BUILD = Path(oc_runtime.__file__).resolve().parents[3] / "plugins" / "opencode" / "dist"
def test_packaged_bundle_is_committed_and_self_contained() -> None:
# The wheel picks this file up via maturin's python-source packaging; if
# it goes missing, pip installs silently lose all-provider routing again.
bundle = _PACKAGED / "index.js"
assert bundle.is_file(), "committed wheel bundle missing - run npm run build:standalone"
text = bundle.read_text(encoding="utf-8")
assert len(text) > 10_000, "bundle suspiciously small - not the standalone build?"
# Self-contained: no bare npm imports; node builtins are the only imports
# allowed (site-packages has no node_modules to resolve anything else).
assert 'from "headroom-ai"' not in text
assert 'from "@opencode-ai/plugin"' not in text
assert 'from "@opencode/plugin"' not in text
# One default export serves both loaders: 1.x calls `server`, 2.x `setup`.
assert "server: HeadroomPlugin" in text
assert "setup: headroomSetup" in text
def test_packaged_bundle_is_the_only_file_in_its_directory() -> None:
# OpenCode 2.x resolves `<dir>/server.*` before `<dir>/index.*`, and 1.x
# prefers a `package.json` entry — a stray file here would shadow index.js.
assert sorted(p.name for p in _PACKAGED.iterdir()) == ["index.js"]
def test_hook_shim_is_committed_next_to_the_entry_bundle() -> None:
# transport.ts resolves `../hook-shim/handler.js` next to the loaded entry,
# so the shim must ship as a sibling of _dist/. Without it, Node children
# spawned under `headroom wrap opencode` lose fetch/http routing (the
# existsSync guard skips injection), and before that guard they crashed with
# ERR_MODULE_NOT_FOUND on every Node MCP (#2850, #2806).
shim = _PACKAGED.parent / "hook-shim" / "handler.js"
assert shim.is_file(), "committed wheel hook-shim missing - run npm run build:standalone"
text = shim.read_text(encoding="utf-8")
assert len(text) > 5_000, "hook-shim suspiciously small - not the standalone build?"
# Self-contained standalone build, not the checkout dev shim (which imports
# the non-bundled ../dist/index.js that site-packages has no node_modules for).
assert 'from "../dist/index.js"' not in text
assert "installHeadroomTransport" in text
assert "HEADROOM_OPENCODE_TRANSPORT_PROXY_URL" in text
def test_plugin_path_env_override_wins(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
override = tmp_path / "custom"
override.mkdir()
(override / "index.js").write_text("// plugin")
monkeypatch.setenv("HEADROOM_OPENCODE_PLUGIN_PATH", str(override))
assert headroom_opencode_plugin_path() == str(override)
def test_plugin_path_env_override_missing_resolves_none(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("HEADROOM_OPENCODE_PLUGIN_PATH", str(tmp_path / "missing"))
assert headroom_opencode_plugin_path() is None
def test_plugin_path_falls_back_to_packaged_bundle(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("HEADROOM_OPENCODE_PLUGIN_PATH", raising=False)
resolved = headroom_opencode_plugin_path()
assert resolved is not None
# In a repo checkout with a built plugins/opencode/dist the repo build wins
# (fresher during development); otherwise the packaged bundle must resolve.
if (_REPO_BUILD / "index.js").is_file():
assert resolved == str(_REPO_BUILD)
else:
assert resolved == str(_PACKAGED)