Commit Graph
2 Commits
Author SHA1 Message Date
ParideboyandJerrettDavis 87c12931fb fix(opencode): stop routing a host's bare /messages or /responses to the proxy (#4781) (#4791)
## Description

A `POST` whose path ends in a wire endpoint but that sits at a host's
origin root (`/messages`, `/responses`, `/chat/completions`) is no
longer routed to the proxy unless that origin is a configured provider
base URL.

Closes #4781.

## Type of Change

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

## Changes Made

- `plugins/opencode/src/transport.ts` — `hasWireRootBefore` no longer
treats "no segment before the endpoint" as a wire root, so a bare
`/messages` at an unknown host goes direct.
- `plugins/opencode/src/transport.test.ts` — the bare-endpoint
assertions from #4758 move into a #4781 case that pins both directions:
direct by default, routed once the base is registered; the #4758 case
keeps the prefixes that still route.
- `plugins/opencode/README.md` — states the actual routing rule, and the
two shapes that still route without a configured base.
- `headroom/providers/opencode/_dist/index.js`,
`headroom/providers/opencode/hook-shim/handler.js` — rebuilt, since the
`opencode-plugin` gate compares bytes against `dist-standalone`.
- `plugins/opencode/scripts/live-proof-4781.mjs` — the live proof below,
committed so it can be rerun.

## Why

#4758 stopped a suffix match from routing non-LLM hosts, but kept bare
endpoints routable "because compatible gateways use those paths". That
left exactly one non-LLM shape still leaking: `POST
https://rest.messagebird.com/messages` with `Authorization: AccessKey
...` went to the proxy, carrying a non-LLM credential (#4781).

Becoming the bare path is not evidence of a provider — it is equally the
shape of a messaging API. A provider mounted at an origin root is still
routed, because its base URL *is* a configured wire root
(`isConfiguredWireRoot` matches every path on that origin when the base
path is empty), which is how OpenCode reports
`provider.<id>.options.baseURL`.

```ts
return (
  last !== undefined &&
  (isVersionSegment(last) || IMMEDIATE_WIRE_ROOTS.has(last) || segments.some((s) => NAMED_WIRE_ROOTS.has(s)))
);
```

Everything else is untouched: version prefixes (`/v1`, `/v1beta`,
`/v4`), immediate `api`, named roots (`backend-api`, `codex`, `openai`,
`anthropic`, `zen`), Gemini colon actions, configured bases,
`excludeHosts`, and the method gate.

## Testing

- [x] New tests added for new functionality
- [x] Manual testing performed

`plugins/opencode` is a TypeScript package, so its gates are npm scripts
rather than `pytest` / `ruff` / `mypy`; `npm audit` and the rest run in
the repo's own CI.

### Test Output

```text
> vitest run
Test Files  4 passed (4)
     Tests  80 passed (80)

> node node_modules/@typescript/native/bin/tsc --noEmit
(clean, no output)

> node scripts/live-proof-4781.mjs
=== decisions (real sockets, real fetch, real built plugin) ===
PASS  MessageBird-shaped  POST /messages             -> left alone
PASS  MessageBird batches  POST /messages/batches    -> left alone
PASS  LLM control         POST /v1/messages          -> REROUTED to proxy
PASS  LLM control         POST /v1/chat/completions  -> REROUTED to proxy

=== what reached the proxy ===
  POST /v1/messages  x-headroom-base-url=http://localtest.me:8899  original-path=null
  POST /v1/chat/completions  x-headroom-base-url=http://localtest.me:8899  original-path=/v1/chat/completions

=== MessageBird-shaped requests that reached the proxy: 0 ===
=== what reached the upstream directly ===
  POST /messages  auth=AccessKey FAKE-TEST-VALUE  (no proxy headers: true)
  POST /messages/batches  auth=AccessKey FAKE-TEST-VALUE  (no proxy headers: true)

ALL CASES PASS
```

Before the fix, same script, source reverted to `HEAD~1` and the bundle
rebuilt:

```text
=== decisions (real sockets, real fetch, real built plugin) ===
FAIL  MessageBird-shaped  POST /messages             -> REROUTED to proxy
PASS  MessageBird batches  POST /messages/batches    -> left alone
PASS  LLM control         POST /v1/messages          -> REROUTED to proxy
PASS  LLM control         POST /v1/chat/completions  -> REROUTED to proxy

=== what reached the proxy ===
  POST /messages  x-headroom-base-url=http://localtest.me:8899  original-path=null
```

Reverting only `src/transport.ts` also fails the unit test (`1 failed |
79 passed`), satisfying "a test that fails before your fix and passes
after".

## Real Behavior Proof

- Environment: Windows 11 (win32), Node v26.10.0, this branch of
`plugins/opencode`, committed wheel bundle
`headroom/providers/opencode/_dist/index.js` loaded via
`plugin.server(...)` as `headroom wrap opencode` does; upstream and
proxy are local HTTP fixtures on real TCP sockets and `globalThis.fetch`
is Node's undici, not a stub.
- Exact command / steps: `cd plugins/opencode && npm ci && npm run
build:standalone && node scripts/live-proof-4781.mjs`, which POSTs a
MessageBird-shaped SMS payload and two LLM control requests to
`http://localtest.me:8899` (resolves to 127.0.0.1 but is not a loopback
spelling, so traffic really leaves the process) and records which server
received each one.
- Observed result: after the patch `POST /messages` and `POST
/messages/batches` reach the upstream directly with no
`x-headroom-base-url` header and the proxy receives zero
MessageBird-shaped requests, while `/v1/messages` and
`/v1/chat/completions` still reach the proxy with the upstream origin
header; with `src/transport.ts` reverted to `HEAD~1` the same run
reroutes `POST /messages` to the proxy, reproducing the reported leak
over a real socket (full output in `Testing` → `Test Output`).
- Not tested: a real MessageBird account and the real
`rest.messagebird.com` host, since the payload and `AccessKey` are fake
and routing is decided before DNS; the proxy's handling of an SMS body,
which never arrives after this change; and a live OpenCode host process,
since the fixture drives the plugin's own `server()` entry rather than
an OpenCode session.

## Runtime Rollout Safety

- Rollout-managed feature(s): none, no feature flag is involved.
- Minimum rollout channel: next released `headroom-opencode` / wheel.
- Stable/default behavior changed: yes, deliberately — a `POST` to
`/messages`, `/responses` or `/chat/completions` at a host's origin root
now goes direct unless that origin is a configured provider base URL;
users whose gateway is configured via `provider.<id>.options.baseURL`
are unaffected.
- Kill switch / disable path: `excludeHosts` /
`HEADROOM_OPENCODE_EXCLUDE_HOSTS` forces a host direct, and configuring
the base URL or listing it in `wireRoots` forces a bare-path provider
through the proxy.
- Unsafe override required: no.
- Qualification impact: none.
- Rollback path: revert the commits; the transport and the committed
bundle revert together.

## 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

## Additional Notes

Residual, deliberately not solved and now stated in the README:
`/api/v2/messages` and `/v2/responses` still route. No path shape
separates those from a gateway rooted at `/api` or `/v2`; only the host
or the request body could, and reading the body inside a sync `fetch`
wrapper buys a new class of failure for a shape `excludeHosts` already
covers. I did not add a known-host allowlist either: it can only
recognise hosts someone already thought of, and it regresses compatible
gateways silently — the failure mode #4747 was filed about.

---------

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-11-17 02:36:58 +05:30
Chen YufeiyangandJD Davis 3d9a6f2cf7 fix(opencode): route Copilot Claude models through the proxy (#4594)
## Description

Closes #4248. The OpenCode 2.x plugin routes models through Headroom by
rewriting model `baseURL`s in `ctx.model.transform`, but it recognized
only the OpenAI wires (`openai-compatible`, `*/chat`, `*/responses`).
Copilot's Claude models use `@opencode/ai/providers/anthropic` (Messages
wire), so they were skipped and their requests never reached the proxy,
while Copilot GPT models kept working.

`modelWireSuffix` now also maps `anthropic`, `anthropic-compatible` and
model-level `*/messages` packages to `/messages`, reusing the existing
rewrite. The config-level `headroom wrap opencode` path cannot cover
Copilot because OpenCode creates that provider dynamically.

## 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

<details>
<summary>changes details</summary>

- `plugins/opencode/src/plugin.ts`: rename `openAiWireSuffix` to
`modelWireSuffix`, map the Anthropic Messages wires to `/messages`.
- `plugins/opencode/README.md`: document that Anthropic Messages models
are rewritten too.
- `plugins/opencode/src/plugin.test.ts`: three new cases plus a narrowed
negative case.
- `headroom/providers/opencode/_dist/index.js`: rebuilt so the wheel
bundle stays byte-identical (CI `cmp` gate).
</details>

## Testing

<details>
<summary>testing details</summary>

- [x] Unit tests pass (`npm test -- --maxWorkers=2`: 66 passed at
current head)
- [x] Type checking passes (`npm run typecheck`)
- [x] Linting: repo lint is Python-only; plugin gates are typecheck,
build, test, bundle `cmp`, all run
- [x] New tests added
- [x] Manual testing performed — actual OpenCode CLI plus real proxy and
controlled upstream; live Copilot not tested

### Test Output

<!-- Paste relevant command output or artifact links here -->

<details><summary>commands and output</summary>

```text
npm test -- --maxWorkers=2 -> 4 files, 66 passed at 95ef917320 | npm run typecheck -> exit 0 | cmp dist-standalone/index.js headroom/providers/opencode/_dist/index.js -> BUNDLE_MATCH
```

The earlier red/green check recorded three new rewrite cases failing
before the fix (`3 failed | 61 passed`). Fresh current-head validation
is 66/66 plugin tests plus a successful no-emit typecheck;
full-repository Python pytest/Ruff were not run for this transport-only
verification.

</details>
</details>

## Real Behavior Proof

- Environment: Current head `95ef9173`, macOS arm64, official OpenCode
2.2.5, Python 3.12.8, Node 26.13.0; real plugin, Anthropic adapter and
Headroom proxy; local SSE upstream; Python-only transport mode.
- Exact command / steps: Build both plugin bundles, then run the runtime
harness with the official CLI in four scenarios. Exact commands, macOS
fixture adaptation, and the committed Linux reproduction are in the
details below.
- Observed result: All four actual CLI scenarios passed; auth retained,
internal headers stripped, streamed text and `step_finish` returned.
Current-head plugin tests 66/66, typecheck and byte-for-byte wheel
bundle comparison pass.
- Not tested: Live Copilot account/discovery or endpoint compatibility,
live z.ai, Rust/compression/cache, TLS, retries, latency, production
rollout, and other OpenCode versions. Full limits are below.

| Actual OpenCode scenario | Plugin | Proxy POSTs | Upstream POSTs |
Observed upstream path |
| --- | --- | --- | --- | --- |
| Baseline | disabled | 0 | 2 | `/messages` |
| Copilot-shaped root URL | enabled | 2 | 2 | `/v1/messages` |
| `/v1` gateway | enabled | 2 | 2 | `/v1/messages` |
| Prefixed gateway | enabled | 0 | 2 | `/api/coding/paas/v4/messages` |

<details>
<summary>Current-head transport evidence and platform-specific harness
setup</summary>

- Environment: Fresh run on 2026-11-04 at 22:10 UTC, PR head
`95ef9173200eb3b0f047e8fe661e1d9924d41c82`; macOS 27.3 arm64, Python
3.12.8, Node 26.13.0, npm 11.20.0, official installed **OpenCode 2.2.5**
CLI, source Headroom 0.42.1-dev, headroom-opencode 0.42.0. OpenCode
loaded the built standalone plugin itself and used its real
`@opencode/ai/providers/anthropic` adapter. Only the upstream API was a
strict-path local SSE fixture. The proxy explicitly ran in **Python-only
degraded mode**, with `HEADROOM_REQUIRE_RUST_CORE=false`, `--no-optimize
--no-cache`; Rust/compression is outside this proof.
- Exact command / steps: Install proxy dependencies with `uv sync
--frozen --extra proxy --no-default-groups --no-install-project --python
<CPython-3.12.8>`. In `plugins/opencode`, run `npm ci --ignore-scripts
--no-audit --no-fund --fetch-timeout=45000`, `npm run build`, and `npm
run build:standalone`. Run `.venv/bin/python
.cache/runtime-proof-macos.py --opencode
/Applications/OpenCode.app/Contents/Resources/opencode-cli --output
.cache/runtime-proof-macos`. This local copy of the checked-in [runtime
harness](https://github.com/headroomlabs-ai/headroom/blob/95ef9173200eb3b0f047e8fe661e1d9924d41c82/plugins/opencode/scripts/runtime-proof.py)
adapts its Linux loopback fixture to macOS as detailed below. For each
scenario the harness starts a real Headroom proxy and upstream, then
executes `opencode-cli run --standalone --print-logs --log-level debug
--format json 'Reply with HEADROOM_RUNTIME_OK.'` with isolated config,
synthetic auth, model-catalog fetching/updates disabled and a 60-second
timeout. It never invokes `headroomSetup` manually or replaces the model
request with `fetch`.
- Observed result: **All four actual CLI scenarios passed in 40.05
seconds.** Both title and user-turn requests traversed the expected
route, preserved the exact synthetic bearer/API-key values, and sent no
internal `x-headroom-*` headers upstream. Every user turn produced the
text event `HEADROOM_RUNTIME_OK` and a completed `step_finish` after
individual SSE events were flushed by the fixture. The rebuilt
standalone bundle matched the checked-in wheel bundle byte-for-byte,
SHA-256
`78fae6e51ef5d1c534a3299216ba3b467131c17594de34f0fe8bb7b5be4b7533`. No
tracked files or lockfiles changed during this run; all eight
proxy/upstream listening ports were closed afterward and no owned
CLI/proxy process remained.
- Not tested: Live GitHub Copilot discovery, subscription auth/token
refresh, Copilot-specific headers, actual model inference, or whether
the live Copilot origin accepts `/v1/messages`. This is a configured
Copilot-shaped provider, **not** native Copilot discovery. The prefix
control uses the real Anthropic adapter, not a live z.ai account or its
specific adapter. Rust core, optimization/compression/cache,
HTTPS/HTTP2, latency/backpressure, retry/rate-limit behavior, production
rollout, and OpenCode versions other than 2.2.5 were not exercised.

The proxied root-URL run recorded the actual OpenCode user agent and
original path at Headroom:

```text
proxy inbound: POST /v1/messages
user-agent: opencode/latest/2.2.5/cli
x-headroom-original-path: /messages
proxy outbound: POST http://[::ffff:7f00:1]:<fixture-port>/v1/messages
upstream: model=claude-sonnet-4-6, stream=true
upstream: authorization and x-api-key exactly matched synthetic fixtures
upstream: anthropic-version=2023-06-01; no x-headroom-* headers
client: text=HEADROOM_RUNTIME_OK; step_finish present
```

The root origin deliberately distinguishes direct `/messages` from
proxied `/v1/messages`. The fixture rejects an unexpected endpoint
rather than answering every path. These observations establish the
plugin/proxy transport boundary; they do **not** establish live Copilot
endpoint compatibility. The `/v1` origin remains `/v1/messages`, and the
prefixed origin remains `/api/coding/paas/v4/messages` with zero model
POSTs reaching Headroom.

The committed harness originally binds `127.0.0.2`, unavailable on this
macOS host (`Errno 49`). The ignored local copy uses an IPv4-mapped
loopback address with an IPv6 HTTP server and WHATWG-normalized fixture
URLs. It also fixes its checkout-relative path after copying, explicitly
allowlists only that fixture origin, sets supported offline/update
flags, creates its isolated proxy cache, accepts an existing isolated
home directory, and bounds each CLI run to 60 seconds. It does not
change production code or the expected endpoint/auth/SSE assertions. No
network interfaces or account settings were changed. All server
processes are scoped to the harness and terminated/waited in cleanup.

For the original independently recorded Linux run, reproducible
commands, and committed machine-readable results, see
[RUNTIME_PROOF.md](https://github.com/headroomlabs-ai/headroom/blob/95ef9173200eb3b0f047e8fe661e1d9924d41c82/plugins/opencode/RUNTIME_PROOF.md)
and
[runtime-proof-result.json](https://github.com/headroomlabs-ai/headroom/blob/95ef9173200eb3b0f047e8fe661e1d9924d41c82/plugins/opencode/scripts/runtime-proof-result.json).
Those artifacts explicitly identify their earlier source revision and
environment; the current-head macOS build hash above is from this fresh
run. Both proofs execute an actual OpenCode 2.x process. The earlier
PR-body experiment that manually supplied a minimal plugin context and
Node `fetch` has been superseded here.

</details>

## Runtime Rollout Safety

- Rollout-managed feature(s): none.
- Minimum rollout channel: n/a.
- Stable/default behavior changed: only previously skipped Anthropic
Messages models are rewritten; the negative test pins the rest.
- Kill switch / disable path: disable the plugin.
- Unsafe override required: no.
- Qualification impact: none expected.
- Rollback path: revert the commit; no state changes.

## 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`

## Screenshots (if applicable)

N/A — no UI change.

## Additional Notes

The rebuilt `_dist` bundle is part of the diff because CI enforces byte
equality with `dist-standalone`. Actual OpenCode transport is now
verified with a controlled upstream. Live provider/account behavior and
the additional limits listed above remain unverified.

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

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4594"
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: JD Davis <mxjerrett@gmail.com>
2026-11-04 23:09:28 -06:00