fix(opencode): stop routing non-LLM hosts and paths to the proxy (#4747) (#4758)

Closes #4747.

## Description

The OpenCode transport shim decides whether to reroute a request from
the URL string alone. That decision had three blind spots: two too
literal, one too narrow.

**Hosts.** `isLoopback` compared the raw hostname against exactly
`"127.0.0.1"` and `"::1"`, so every other spelling of loopback counted
as remote and its request — with the caller's `Authorization` header —
went to the proxy:

| URL host | `URL.hostname` | old check | new check |
| --- | --- | --- | --- |
| `127.0.0.2` | `127.0.0.2` | remote | loopback |
| `127.1.2.3` | `127.1.2.3` | remote | loopback |
| `[::ffff:127.0.0.2]` | `[::ffff:7f00:2]` | remote | loopback |
| `localhost.` | `localhost.` | remote | loopback |
| `api.x.example.` | `api.x.example.` | not excluded | excluded |

The trailing-dot row is the same bug on the `excludeHosts` path:
`example.com.` is the fully qualified spelling of `example.com`, so an
excluded host was routed anyway.

**Paths.** Any path ending in `/messages` or `/responses` was treated as
an LLM endpoint, so Discord's `/api/v10/channels/123/messages` and a
forms API's `/forms/123/responses` were rerouted. That needs a wire root
in front of the endpoint.

**Configured bases.** The first version of that wire-root rule could
only recognise root names it knew (`v1`, `api`, `openai`, …), so a
compatible gateway configured at `https://gateway.invalid/tenant/acme`
lost its routing entirely: OpenCode 1.x sent
`/tenant/acme/chat/completions` through the patched `fetch` straight
upstream, with no compression and no telemetry. The plugin's own
`modelBaseRoutesThroughProxy` still accepted that base, so the transport
disagreed with the plugin. Provider base URLs from OpenCode's
configuration are now authoritative, matched by origin and path prefix
rather than by root name, and the path heuristics stay as the fallback
when no configuration is available.

## 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
- [ ] Refactoring (no functional changes)
- [ ] Tests only

## Reproduction

On `main`, with the plugin's transport installed:

```js
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["api.x.example"] });
await fetch("http://127.0.0.2:11434/v1/chat/completions", { method: "POST" });   // routed to proxy
await fetch("http://localhost./v1/chat/completions", { method: "POST" });        // routed to proxy
await fetch("https://api.x.example./v1/chat/completions", { method: "POST" });   // routed to proxy
await fetch("https://discord.com/api/v10/channels/123/messages", { method: "POST" }); // routed to proxy
```

A local provider on `127.0.0.2` or `[::ffff:127.0.0.2]`, a `.internal`
host spelled with a trailing dot, and a non-LLM `POST` all ended up at
the Headroom proxy instead of their own server.

For the configured-base half, on the previous head `b695e697` with a
provider base URL of `https://gateway.invalid/tenant/acme`:

```js
await fetch("https://gateway.invalid/tenant/acme/chat/completions", { method: "POST" });
// main: proxy. b695e697: gateway, with no x-headroom-base-url, so no compression.
```

## Changes Made

`plugins/opencode/src/transport.ts`:

- Added `canonicalHostname()` — lowercase, strip IPv6 brackets, strip
trailing dots — and used it in `isLoopback`, `isExcludedHost`, and
`normalizeExcludeHosts`, so all three agree on what a host *is*.
- `isLoopback` now covers all of `127.0.0.0/8` (not just `.0.1`),
`0.0.0.0`, `localhost`, `::1`, and IPv4-mapped IPv6. The mapped form is
tested as a full 32-bit address, because `URL` canonicalizes it to hex
(`127.1.2.3` → `::ffff:7f01:203`) and the last two octets share the low
16-bit group.
- `isLlmEndpointPath` now requires a *wire root* before the endpoint
suffix:
  - the URL is under a **configured provider base** (see below), **or**
- the segment immediately before the suffix is a version (`v1`,
`v1beta`, `v4`) or a base a compatible gateway mounts the wire directly
under (`api`), which keeps prefixed gateways working
(`/api/coding/paas/v4/chat/completions`, `/base/v1/messages`,
`/zen/v1/responses`, and a provider base URL of
`https://gateway.example/api`), **or**
- the path contains a named root (`openai`, `anthropic`, `zen`, `codex`,
`backend-api`) anywhere, which is what Azure OpenAI needs — its
deployment name sits between `/openai/` and the endpoint
(`/openai/deployments/{name}/chat/completions`).
- A bare `/messages` or `/responses` (no preceding segment) still
routes.
- Position matters for the version/`api` branch: `api` counts only when
it abuts the endpoint, so `/api/chat/completions` routes while Discord's
`/api/v10/channels/123/messages` (immediate segment `123`) does not. The
same is true of the version branch — a version segment *anywhere* would
be too weak.
- Gemini's `:generateContent` / `:streamGenerateContent` suffixes are
unchanged and still need no wire root.
- Added `WireRoot` / `normalizeWireRoots` / `isConfiguredWireRoot`: a
configured base is matched by **origin plus path prefix**, and only when
the URL also ends in a wire endpoint. So an OpenAI-compatible provider
at `/tenant/acme` routes its `/tenant/acme/chat/completions`, while
`/tenant/acme/files/1` on the same host passes through, and a different
origin sharing that path prefix does not match at all. Malformed entries
are skipped rather than disabling the set.
- `installHeadroomTransport` takes `wireRoots` and exports the effective
set to child processes as `HEADROOM_OPENCODE_WIRE_ROOTS`, so the
`--import` hook shim routes the same bases; it is removed from the
environment when empty, like `HEADROOM_OPENCODE_EXCLUDE_HOSTS`.
- `setHeadroomWireRoots()` widens a live transport when configured bases
are discovered later, so routing can start before OpenCode answers.
- Regenerated `headroom/providers/opencode/_dist/index.js` and
`headroom/providers/opencode/hook-shim/handler.js` from `npm run
build:standalone` (CI `cmp`s them).

`plugins/opencode/src/plugin.ts`:

- 1.x reads `client.config.get()` and `client.provider.list()` **without
awaiting them**, and applies **each response as it arrives**: the two
reads are independent, so a fulfilled `config.get()` widens routing even
while `provider.list()` is still pending. A round trip to the server
that is loading the plugin cannot be allowed to gate plugin startup, a
server that is not answering yet must not disable routing, and a stalled
`/provider` call must not suppress a base the config already reported. A
failed read costs only its own bases; requests before either answer use
the path heuristics.
- 2.x reads the base URLs its own `ctx.model.transform` already sees, so
no extra round trip is needed.
- `HeadroomOpenCodePluginOptions.wireRoots` lets a user supply a base
the plugin cannot see; normally it is unused.

The residual over-match is `/api/v2/messages`, which still routes;
distinguishing it from a provider needs the host or the body, and
`excludeHosts` already covers any host a user controls. That trade-off
is recorded in the code comment rather than left implicit.

## Testing

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

Six new tests, all tagged `#4747`:

1. non-LLM `POST` paths that merely end in an endpoint
(`discord.com/api/v10/channels/123/messages`, `discord.com/api/v9/...`,
`forms.example.com/forms/123/responses`,
`chat.example.com/rooms/42/chat/completions`) pass through untouched,
with no `x-headroom-base-url` and no session token added.
2. provider-rooted wire paths still route: bare `/messages`,
`/responses`, `/api/chat/completions` (a gateway base URL of `.../api`),
`/api/v2/chat/completions`, `/openai/deployments/x/chat/completions`,
`/zen/v1/responses`, `/backend-api/codex/responses`.
3. every loopback spelling (`127.0.0.1`, `127.0.0.2`, `127.1.2.3`,
`127.255.255.254`, `localhost.`, `[::1]`, `[::ffff:127.0.0.1]`,
`[::ffff:127.1.2.3]`) and a trailing-dot excluded host stay off the
proxy for `fetch`.
4. the same failures stay off the proxy for Node's `http.request`
(`http://` loopbacks) and `https.request` (the excluded and
Discord-shaped `https://` cases). This one spies on both, because real
`https.request` rejects an `http://` URL — asserting one against the
https spy would have proved nothing.
5. a configured base with no version or reserved prefix
(`https://gateway.invalid/tenant/acme`) routes
`/tenant/acme/chat/completions` in **both** the fetch and the Node
request paths, with the right `x-headroom-base-url`;
`/tenant/acme/files/1` on the same host and origin stays unrouted; and
the same path on a different origin stays unrouted. A separate plugin
test asserts that a base URL returned by `client.config.get()` reaches
the transport.
6. a config response applies while `provider.list()` **never settles**:
the configured fetch and Node paths already route, and a non-endpoint
path on the same base still passes through. This is the
partial-availability case from review, and it fails on the previous head
(`expected [] to include 'https://gateway.invalid/tenant/acme'`).

Red/green check for test 5 against the previous head `b695e697`:

```
$ git checkout b695e697 -- plugins/opencode/src/transport.ts
$ npx vitest run src/transport.test.ts
 Test Files  1 failed (1)
      Tests  1 failed | 45 passed (46)

AssertionError: expected 'https://gateway.invalid/tenant/acme/c…' to be an instance of URL
```

The fetch assertion is where it fails first: on `b695e697` the request
passes through untouched, so the recorded first argument is still the
original URL string. Restore the branch sources and all 78 pass.

Earlier red/green, still true: tests 1, 3 and 4 fail before the first
fix; the `/api/chat/completions` assertion fails against the first
commit's rule; test 4 fails against `upstream/main`'s `transport.ts`
(`127.0.0.2` was proxied).

```
$ npm test          → Test Files 4 passed (4) | Tests 78 passed (78)
$ npm run typecheck → clean
$ npm run build     → success
$ npm run build:standalone → success
```

## Real Behavior Proof

- Environment: Windows 11, Node v26.10.0, npm 11. The probe loads the
*built* `dist-standalone/index.js` bundle (before = the committed `HEAD`
bundle, after = this branch), wires the plugin's `server` hook exactly
as OpenCode does, points `proxyUrl` at a real `http.createServer`
listener on `127.0.0.1:19400`, and starts real target servers on
`127.0.0.1:19401`, `127.0.0.2:19401`, `[::1]:19401`, plus the machine's
LAN IPv4 on `:19401`. Every request is a real `fetch` over the stack —
no mocks. Two non-loopback cases use `.invalid` hosts so they cannot
leave the machine; they only need to be *classified*, and the shim drops
the response on the floor. The configured-base rows run on the LAN
address, because loopback is deliberately never routed.
- Exact command / steps: `node proof4747.mjs file:///<abs path to
bundle>` (10-row probe); `node proof4747-shim.mjs <hook-shim/handler.js>
<child>` (child `--import` shim probe); `node proof4747-partial.mjs
file:///<bundle>` (stalled discovery probe)

**Before (committed `HEAD` bundle):**

```
┌──────────────────────────────────────┬──────────┬──────────┬─────────┬──────────────┐
│ label                                │ landed   │ expect   │ verdict │ outcome      │
├──────────────────────────────────────┼──────────┼──────────┼─────────┼──────────────┤
│ loopback 127.0.0.2                   │ target   │ target   │ ok      │ 200 target   │
│ loopback mapped v6                   │ target   │ target   │ ok      │ 200 target   │
│ loopback trailing dot                │ target   │ target   │ ok      │ 200 target   │
│ non-LLM path (Discord shape)         │ target   │ target   │ ok      │ 200 target   │
│ bare loopback endpoint               │ target   │ target   │ ok      │ 200 target   │
│ custom gateway base /api             │ proxy    │ proxy    │ ok      │ 200 proxy    │
│ configured base /tenant/acme         │ target   │ proxy    │ WRONG   │ 200 target   │
│ configured base, non-endpoint path   │ target   │ target   │ ok      │ 200 target   │
│ real provider endpoint               │ proxy    │ proxy    │ ok      │ 200 proxy    │
│ Azure-style endpoint                 │ proxy    │ proxy    │ ok      │ 200 proxy    │
└──────────────────────────────────────┴──────────┴──────────┴─────────┴──────────────┘
proxy saw: ['/v1/chat/completions', '/v1/messages', '/v1/chat/completions']
target saw: ['/v1/chat/completions', '/v1/chat/completions', '/v1/chat/completions',
             '/api/v10/channels/123/messages', '/chat/completions',
             '/tenant/acme/chat/completions', '/tenant/acme/files/1']
```

**After (this branch):**

```
┌──────────────────────────────────────┬──────────┬──────────┬─────────┬──────────────┐
│ label                                │ landed   │ expect   │ verdict │ outcome      │
├──────────────────────────────────────┼──────────┼──────────┼─────────┼──────────────┤
│ loopback 127.0.0.2                   │ target   │ target   │ ok      │ 200 target   │
│ loopback mapped v6                   │ target   │ target   │ ok      │ 200 target   │
│ loopback trailing dot                │ target   │ target   │ ok      │ 200 target   │
│ non-LLM path (Discord shape)         │ target   │ target   │ ok      │ 200 target   │
│ bare loopback endpoint               │ target   │ target   │ ok      │ 200 target   │
│ custom gateway base /api             │ proxy    │ proxy    │ ok      │ 200 proxy    │
│ configured base /tenant/acme         │ proxy    │ proxy    │ ok      │ 200 proxy    │
│ configured base, non-endpoint path   │ target   │ target   │ ok      │ 200 target   │
│ real provider endpoint               │ proxy    │ proxy    │ ok      │ 200 proxy    │
│ Azure-style endpoint                 │ proxy    │ proxy    │ ok      │ 200 proxy    │
└──────────────────────────────────────┴──────────┴──────────┴─────────┴──────────────┘
proxy saw: ['/v1/chat/completions', '/v1/chat/completions', '/v1/messages',
            '/v1/chat/completions']
target saw: ['/v1/chat/completions', '/v1/chat/completions', '/v1/chat/completions',
             '/api/v10/channels/123/messages', '/chat/completions', '/tenant/acme/files/1']
```

All ten rows correct after the patch. The configured base routes; the
unrelated path on that same host still reaches the target; the three
pre-existing provider cases still reach the proxy — so the fix redirects
false positives without disarming the shim.

- Observed result: all ten rows `ok` after the patch; inside the before
bundle the same probe reports `configured base /tenant/acme → target,
WRONG`, and the same two rows for the child `--import` shim (`shim:
WRONG` before, `shim: ok` after), and for the stalled discovery probe
(both wire calls `WRONG` before, all `ok` after). Full tables above.

**Child process (the `--import` hook shim), before and after.** A real
Node child loads the shipped `hook-shim/handler.js` with the env the
plugin exports, then makes two wire calls and one non-endpoint call
against the configured base:

```
before:  /tenant/acme/chat/completions -> target   /tenant/acme/messages -> target
         proxy saw: []                              shim: WRONG
after:   /tenant/acme/chat/completions -> proxy    /tenant/acme/messages -> proxy
         /tenant/acme/files/1 -> target             proxy saw: ['/v1/chat/completions', '/tenant/acme/messages']
                                                    shim: ok
```

**Partial availability (`config.get()` answers, `/provider` stalls),
before and after.** Real built bundle, real listeners, `provider.list()`
returns a promise that never settles:

```
┌──────────────────────────────────────────────────┬────────┬────────┬─────────┐
│ label                                            │ landed │ expect │ verdict │
├──────────────────────────────────────────────────┼────────┼────────┼─────────┤
│ fetch: configured base, provider.list pending    │ target │ proxy  │ WRONG   │   before
│ fetch: non-endpoint path on that base            │ target │ target │ ok      │
│ node http: configured base, provider.list pending│ target │ proxy  │ WRONG   │
└──────────────────────────────────────────────────┴────────┴────────┴─────────┘

after: all three ok — both wire calls reach the proxy, the non-endpoint path does not.
```

- Not tested: no live provider traffic (no API keys were used); a real
`headroom wrap opencode` session against a hosted provider; macOS/Linux.
The loopback and LAN target servers are local stand-ins for a
self-hosted or gateway OpenAI-compatible endpoint (Ollama, LM Studio,
vLLM, a proxy at `/tenant/acme`), which is the shape from the issue. The
config-read path is exercised with a stubbed `client` in the unit test,
not inside a running OpenCode server.

## Runtime Rollout Safety

- Rollout-managed feature(s): none — the OpenCode transport shim is not
behind a rollout flag; it ships as the committed wheel bundle.
- Minimum rollout channel: n/a (no rollout-gated behaviour).
- Stable/default behavior changed: yes, deliberately. Loopback spellings
beyond `127.0.0.1`/`::1` and trailing-dot host spellings now stay off
the proxy; non-LLM paths ending in `/messages` or `/responses` (Discord,
forms shapes) stay off the proxy; configured provider bases route again
(they routed on `main`). Traffic that routed before and still must is
asserted by existing tests (`/base/v1/messages`,
`/api/coding/paas/v4/chat/completions`, `opencode.ai/zen/v1/responses`,
Gemini `:generateContent`).
- Kill switch / disable path: uninstall the transport (`headroom.wrap`
without `opencode`, remove the plugin), or add a provider host to the
`excludeHosts` option / `HEADROOM_OPENCODE_EXCLUDE_HOSTS` env;
`HEADROOM_OPENCODE_TRANSPORT_PROXY_URL` unset also disables the shim.
- Unsafe override required: none. One new optional option (`wireRoots`)
and one new environment variable (`HEADROOM_OPENCODE_WIRE_ROOTS`), both
default to unset; existing calls are unaffected. No wire format or
header changes.
- Qualification impact: route classification only; the proxy wire
protocol is unchanged, so qualification suites that talk to the proxy
are unaffected.
- Rollback path: revert the commit; nothing is persisted and no
migration exists. The committed wheel bundles are byte-identical to `npm
run build:standalone` output (CI `cmp` gate).
- A request that stops routing now reaches its original URL with the
caller's own headers intact — a failure there is a normal provider
error, not a dropped request. Configured-base routing never widens an
arbitrary path: it still requires a wire endpoint, so WebFetch-style
traffic on a provider host is unaffected. The config read is
non-blocking and failure-tolerant; each discovery response applies
independently, and a rejected lookup falls back to the path heuristics
without failing a session. The residual over-match (`/api/v2/messages`)
is inherited from `main` and covered by `excludeHosts`.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review
- [x] Follows `CONTRIBUTING.md` (reproduction + failing-before test +
real behavior proof)
- [x] No `CHANGELOG.md` edit
- [x] Typecheck, tests, both builds run locally
- [x] Behaviour that must be preserved is covered by pre-existing tests

Note for reviewers: #4748 and #4749 are open against the same file
(`transport.ts`) and the same committed bundles. Whichever lands first,
the others will need a rebase and a `build:standalone` refresh; the
conflicts are all in disjoint functions.

Review findings from #4758 addressed in b695e697: `api` is now an
accepted immediate wire root (a provider base URL of
`https://gateway.example/api` routes again, while Discord's
`/api/v10/...` stays out), and the Node test spies on both
`http.request` and `https.request` instead of asserting an `http://` URL
against the https spy, which real Node rejects.

Addressed in 98b5ba2a: configured compatible provider bases are
preserved rather than dropped. Provider base URLs from OpenCode's
configuration are authoritative and matched by origin plus path prefix,
so `/tenant/acme/chat/completions` routes again while Discord and forms
paths stay out; the root-name allowlist remains only as the fallback for
when no configuration is available. Covered in both the fetch and Node
request paths, plus the child-process shim.

Addressed in 3e84b5f2: the two discovery reads no longer gate each
other. Each fulfilled response applies its bases immediately, so a
successful `config.get()` routes the configured wire while
`provider.list()` is still pending; a stalled `/provider` no longer
leaves a known base bypassing Headroom. Startup still never awaits
discovery, and a failed read costs only its own bases.

## Checklist

- [x] My code follows the style of this project
- [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 added tests that prove my fix is effective
- [x] New and existing unit tests pass locally

---------

Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
Parideboy
2026-11-10 23:49:30 -06:00
committed by GitHub
co-authored by JD Davis
parent a91c48a3a4
commit c48778c4ab
7 changed files with 929 additions and 68 deletions
+205 -22
View File
@@ -19797,6 +19797,7 @@ var PROJECT_HEADER = "x-headroom-project";
var SESSION_TOKEN_HEADER = "x-headroom-session-token";
var PROXY_ENV = "HEADROOM_OPENCODE_TRANSPORT_PROXY_URL";
var EXCLUDE_HOSTS_ENV = "HEADROOM_OPENCODE_EXCLUDE_HOSTS";
var WIRE_ROOTS_ENV = "HEADROOM_OPENCODE_WIRE_ROOTS";
var STATE_KEY = /* @__PURE__ */ Symbol.for("headroom.opencode.transport");
function getState() {
return globalThis[STATE_KEY];
@@ -19825,17 +19826,25 @@ function withExcludeHostsEnv(env, excludeHosts) {
delete env[EXCLUDE_HOSTS_ENV];
}
}
function withShimEnv(env, proxyUrl, excludeHosts) {
function withWireRootsEnv(env, wireRoots) {
if (wireRoots.length > 0) {
env[WIRE_ROOTS_ENV] = wireRoots.map((root) => `${root.origin}${root.path}`).join(",");
} else {
delete env[WIRE_ROOTS_ENV];
}
}
function withShimEnv(env, proxyUrl, excludeHosts, wireRoots) {
const nextEnv = { ...env ?? process.env };
nextEnv[PROXY_ENV] = proxyUrl;
withExcludeHostsEnv(nextEnv, excludeHosts);
withWireRootsEnv(nextEnv, wireRoots);
const shim = shimImportSpecifier();
if (shim) {
nextEnv.NODE_OPTIONS = withNodeImportOption(nextEnv.NODE_OPTIONS, shim);
}
return nextEnv;
}
var PROCESS_ENV_KEYS = [PROXY_ENV, EXCLUDE_HOSTS_ENV, "NODE_OPTIONS"];
var PROCESS_ENV_KEYS = [PROXY_ENV, EXCLUDE_HOSTS_ENV, WIRE_ROOTS_ENV, "NODE_OPTIONS"];
function snapshotProcessEnv() {
return Object.fromEntries(PROCESS_ENV_KEYS.map((key) => [key, process.env[key]]));
}
@@ -19848,9 +19857,10 @@ function restoreProcessEnv(saved) {
}
}
}
function installProcessEnv(proxyUrl, excludeHosts) {
function installProcessEnv(proxyUrl, excludeHosts, wireRoots) {
process.env[PROXY_ENV] = proxyUrl;
withExcludeHostsEnv(process.env, excludeHosts);
withWireRootsEnv(process.env, wireRoots);
const shim = shimImportSpecifier();
if (shim) {
process.env.NODE_OPTIONS = withNodeImportOption(process.env.NODE_OPTIONS, shim);
@@ -19863,7 +19873,12 @@ function injectOptionsEnv(args, optionIndex, state) {
const nextArgs = [...args];
const callback = typeof nextArgs.at(-1) === "function" ? nextArgs.pop() : void 0;
const existing = isOptions(nextArgs[optionIndex]) ? { ...nextArgs[optionIndex] } : {};
existing.env = withShimEnv(existing.env, state.proxyUrl, state.excludeHosts);
existing.env = withShimEnv(
existing.env,
state.proxyUrl,
state.excludeHosts,
state.wireRoots
);
if (process.platform === "win32" && existing.windowsHide === void 0) {
existing.windowsHide = true;
}
@@ -19933,14 +19948,38 @@ function usableProxyUrl(proxyUrl) {
return void 0;
}
}
function canonicalHostname(hostname3) {
return hostname3.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.+$/, "");
}
function isLoopback(hostname3) {
const normalized = hostname3.toLowerCase().replace(/^\[|\]$/g, "");
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
const normalized = canonicalHostname(hostname3);
if (normalized === "localhost" || normalized === "::1" || normalized === "0.0.0.0") {
return true;
}
if (isLoopbackIpv4(normalized)) {
return true;
}
const mapped = /^::ffff:(.+)$/.exec(normalized)?.[1];
if (!mapped) {
return false;
}
if (isLoopbackIpv4(mapped)) {
return true;
}
const groups = /^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(mapped);
if (!groups) {
return false;
}
const address = parseInt(groups[1], 16) << 16 | parseInt(groups[2], 16);
return address >>> 24 === 127;
}
function isLoopbackIpv4(host) {
return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host);
}
function normalizeExcludeHosts(entries) {
const hosts = /* @__PURE__ */ new Set();
for (const entry of typeof entries === "string" ? entries.split(",") : entries) {
const host = String(entry).trim().toLowerCase().replace(/^(\*\.|\.)/, "");
const host = canonicalHostname(String(entry).trim()).replace(/^(?:\*\.|\.)/, "");
if (host) {
hosts.add(host);
}
@@ -19948,11 +19987,57 @@ function normalizeExcludeHosts(entries) {
return [...hosts];
}
function isExcludedHost(hostname3, excludeHosts) {
const normalized = hostname3.toLowerCase().replace(/^\[|\]$/g, "");
const normalized = canonicalHostname(hostname3);
return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
}
function isLlmEndpointPath(pathname) {
return pathname.endsWith("/chat/completions") || pathname.endsWith("/responses") || pathname.endsWith("/messages") || pathname.endsWith(":generateContent") || pathname.endsWith(":streamGenerateContent");
function normalizeWireRoots(entries) {
const roots = /* @__PURE__ */ new Map();
for (const entry of typeof entries === "string" ? entries.split(",") : entries) {
const raw = String(entry).trim();
if (!raw) {
continue;
}
try {
const url2 = new URL(raw);
if (url2.protocol !== "http:" && url2.protocol !== "https:") {
continue;
}
const path = url2.pathname.replace(/\/+$/, "");
roots.set(`${url2.origin}${path}`, { origin: url2.origin, path });
} catch {
}
}
return [...roots.values()];
}
function isConfiguredWireRoot(origin, pathname, wireRoots) {
return wireRoots.some(
(root) => root.origin === origin && (root.path === "" ? pathname.startsWith("/") : pathname === root.path || pathname.startsWith(`${root.path}/`))
);
}
var NAMED_WIRE_ROOTS = /* @__PURE__ */ new Set(["backend-api", "codex", "openai", "anthropic", "zen"]);
var IMMEDIATE_WIRE_ROOTS = /* @__PURE__ */ new Set(["api"]);
function isVersionSegment(segment) {
return /^v\d+[a-z0-9]*$/i.test(segment);
}
function hasWireRootBefore(body) {
const segments = body.split("/").filter(Boolean);
const last = segments.at(-1);
return last === void 0 || isVersionSegment(last) || IMMEDIATE_WIRE_ROOTS.has(last) || segments.some((s) => NAMED_WIRE_ROOTS.has(s));
}
function isLlmEndpointPath(pathname, origin = "", wireRoots = []) {
if (pathname.endsWith(":generateContent") || pathname.endsWith(":streamGenerateContent")) {
return true;
}
for (const suffix of ["/chat/completions", "/responses", "/messages"]) {
if (!pathname.endsWith(suffix)) {
continue;
}
if (isConfiguredWireRoot(origin, pathname, wireRoots)) {
return true;
}
return hasWireRootBefore(pathname.slice(0, -suffix.length));
}
return false;
}
function isRoutableUpstream(url2, proxy, excludeHosts) {
if (url2.protocol !== "http:" && url2.protocol !== "https:") {
@@ -19972,8 +20057,11 @@ function isRoutableUpstream(url2, proxy, excludeHosts) {
function isLlmMethod(method) {
return typeof method === "string" && method.toUpperCase() === "POST";
}
function shouldRoute(url2, proxy, excludeHosts, method) {
return isLlmMethod(method) && isRoutableUpstream(url2, proxy, excludeHosts) && isLlmEndpointPath(url2.pathname);
function shouldRoute(url2, proxy, excludeHosts, method, wireRoots = []) {
if (!isLlmMethod(method) || !isRoutableUpstream(url2, proxy, excludeHosts)) {
return false;
}
return isLlmEndpointPath(url2.pathname, url2.origin, wireRoots);
}
function modelBaseRoutesThroughProxy(baseUrl, proxyUrl, excludeHosts = []) {
try {
@@ -20036,10 +20124,10 @@ function mergeFetchHeaders(input2, init, upstream, originalPath = void 0, projec
}
return headers;
}
function withRoutedFetchInput(input2, init, proxy, project, excludeHosts, sessionToken) {
function withRoutedFetchInput(input2, init, proxy, project, excludeHosts, sessionToken, wireRoots = []) {
const upstream = requestUrl(input2);
const method = init?.method ?? (input2 instanceof Request ? input2.method : "GET");
if (!shouldRoute(upstream, proxy, excludeHosts, method)) {
if (!shouldRoute(upstream, proxy, excludeHosts, method, wireRoots)) {
return [input2, init];
}
const { url: nextUrl, originalPath } = routedUrlForOpenCode(upstream, proxy);
@@ -20110,8 +20198,8 @@ function headersForNodeRequest(options, upstream, originalPath, project, session
});
return result;
}
function routedNodeOptions(parts, proxy, project, excludeHosts, sessionToken) {
if (!parts.url || !shouldRoute(parts.url, proxy, excludeHosts, parts.options.method ?? "GET")) {
function routedNodeOptions(parts, proxy, project, excludeHosts, sessionToken, wireRoots = []) {
if (!parts.url || !shouldRoute(parts.url, proxy, excludeHosts, parts.options.method ?? "GET", wireRoots)) {
return void 0;
}
const { url: nextUrl, originalPath } = routedUrlForOpenCode(parts.url, proxy);
@@ -20155,7 +20243,14 @@ function wrapRequest(originalHttpRequest, originalHttpsRequest, originalRequest)
return Reflect.apply(originalRequest, this, args);
}
const parts = splitNodeArgs(args);
const nextOptions = routedNodeOptions(parts, proxy, state.project, state.excludeHosts, state.sessionToken);
const nextOptions = routedNodeOptions(
parts,
proxy,
state.project,
state.excludeHosts,
state.sessionToken,
state.wireRoots
);
if (!nextOptions) {
return Reflect.apply(originalRequest, this, args);
}
@@ -20178,15 +20273,17 @@ function wrapHttp2Connect(originalConnect) {
}
function installHeadroomTransport(options) {
const excludeHosts = normalizeExcludeHosts(options.excludeHosts ?? process.env[EXCLUDE_HOSTS_ENV] ?? "");
const wireRoots = normalizeWireRoots(options.wireRoots ?? process.env[WIRE_ROOTS_ENV] ?? "");
const existing = getState();
if (existing) {
existing.refs += 1;
existing.proxyUrl = options.proxyUrl;
existing.project = options.project;
existing.excludeHosts = excludeHosts;
existing.wireRoots = wireRoots;
existing.debug = Boolean(options.debug);
existing.sessionToken = options.sessionToken;
installProcessEnv(options.proxyUrl, excludeHosts);
installProcessEnv(options.proxyUrl, excludeHosts, wireRoots);
return () => uninstallHeadroomTransport();
}
const state = {
@@ -20194,6 +20291,7 @@ function installHeadroomTransport(options) {
proxyUrl: options.proxyUrl,
project: options.project,
excludeHosts,
wireRoots,
debug: Boolean(options.debug),
sessionToken: options.sessionToken,
originalFetch: globalThis.fetch,
@@ -20209,7 +20307,7 @@ function installHeadroomTransport(options) {
originalEnv: snapshotProcessEnv()
};
setState(state);
installProcessEnv(options.proxyUrl, excludeHosts);
installProcessEnv(options.proxyUrl, excludeHosts, wireRoots);
globalThis.fetch = async (...args) => {
const current = getState();
if (!current) {
@@ -20219,7 +20317,15 @@ function installHeadroomTransport(options) {
if (!proxy) {
return state.originalFetch(...args);
}
const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project, current.excludeHosts, current.sessionToken);
const [nextInput, nextInit] = withRoutedFetchInput(
args[0],
args[1],
proxy,
current.project,
current.excludeHosts,
current.sessionToken,
current.wireRoots
);
return state.originalFetch(nextInput, nextInit);
};
http.request = wrapRequest(state.originalHttpRequest, state.originalHttpsRequest, state.originalHttpRequest);
@@ -20234,6 +20340,19 @@ function installHeadroomTransport(options) {
syncBuiltinESMExports();
return () => uninstallHeadroomTransport();
}
function setHeadroomWireRoots(wireRoots) {
const state = getState();
if (!state) {
return;
}
const existing = new Set(state.wireRoots.map((root) => `${root.origin}${root.path}`));
const added = normalizeWireRoots(wireRoots).filter((root) => !existing.has(`${root.origin}${root.path}`));
if (added.length === 0) {
return;
}
state.wireRoots = [...state.wireRoots, ...added];
withWireRootsEnv(process.env, state.wireRoots);
}
function uninstallHeadroomTransport() {
const state = getState();
if (!state) {
@@ -20260,6 +20379,48 @@ function uninstallHeadroomTransport() {
// src/plugin.ts
var HEADROOM_PLUGIN_ID = "headroom";
function collectBaseUrls(config2, providers) {
const urls = /* @__PURE__ */ new Set();
const add = (value) => {
if (typeof value === "string" && value.trim()) {
urls.add(value.trim());
}
};
const configProviders = config2?.provider;
for (const entry of Object.values(configProviders ?? {})) {
add(entry?.options?.baseURL);
}
const list = Array.isArray(providers) ? providers : providers?.all;
for (const entry of Array.isArray(list) ? list : []) {
add(entry?.options?.baseURL);
}
return [...urls];
}
function resolveConfiguredWireRoots(client, onResolved) {
if (!client?.config?.get && !client?.provider?.list) {
return;
}
const apply = (read, pick2) => {
if (!read) {
return;
}
void Promise.resolve().then(read).then((value) => {
const urls = pick2(value);
if (urls.length > 0) {
onResolved(urls);
}
}).catch(() => {
});
};
apply(
client.config?.get?.bind(client.config),
(config2) => collectBaseUrls(config2?.data ?? config2, void 0)
);
apply(
client.provider?.list?.bind(client.provider),
(providers) => collectBaseUrls(void 0, providers?.data ?? providers)
);
}
function normalizeProxyUrl2(url2) {
return trimTrailingSlashes(url2);
}
@@ -20324,6 +20485,17 @@ function routeModelsThroughProxy(models, proxyUrl, project, excludeHosts, sessio
});
}
}
function modelBaseUrls(models) {
const urls = /* @__PURE__ */ new Set();
for (const model of models.list()) {
const provider = models.provider.get(String(model.providerID))?.provider;
const baseURL = model.settings?.baseURL ?? provider?.settings?.baseURL;
if (typeof baseURL === "string" && baseURL.trim()) {
urls.add(baseURL.trim());
}
}
return [...urls];
}
var HeadroomPlugin = async (input2, options = {}) => {
const pluginOptions = options;
const proxyUrl = resolveProxyUrl(pluginOptions);
@@ -20334,7 +20506,13 @@ var HeadroomPlugin = async (input2, options = {}) => {
project,
excludeHosts: pluginOptions.excludeHosts,
debug: pluginOptions.debug,
sessionToken: resolveSessionToken(pluginOptions)
sessionToken: resolveSessionToken(pluginOptions),
wireRoots: pluginOptions.wireRoots
});
resolveConfiguredWireRoots(input2.client, (urls) => {
if (urls.length > 0) {
setHeadroomWireRoots(urls.join(","));
}
});
return {
dispose: async () => {
@@ -20368,10 +20546,15 @@ var headroomSetup = async (ctx) => {
project,
excludeHosts,
debug: pluginOptions.debug,
sessionToken
sessionToken,
wireRoots: pluginOptions.wireRoots
});
try {
await ctx.model.transform((models) => {
const wireRoots = modelBaseUrls(models);
if (wireRoots.length > 0) {
setHeadroomWireRoots(wireRoots.join(","));
}
routeModelsThroughProxy(models, proxyUrl, project, excludeHosts, sessionToken);
});
await ctx.tool.transform((editor) => {
+126 -20
View File
@@ -12,6 +12,7 @@ var PROJECT_HEADER = "x-headroom-project";
var SESSION_TOKEN_HEADER = "x-headroom-session-token";
var PROXY_ENV = "HEADROOM_OPENCODE_TRANSPORT_PROXY_URL";
var EXCLUDE_HOSTS_ENV = "HEADROOM_OPENCODE_EXCLUDE_HOSTS";
var WIRE_ROOTS_ENV = "HEADROOM_OPENCODE_WIRE_ROOTS";
var STATE_KEY = /* @__PURE__ */ Symbol.for("headroom.opencode.transport");
function getState() {
return globalThis[STATE_KEY];
@@ -40,17 +41,25 @@ function withExcludeHostsEnv(env, excludeHosts) {
delete env[EXCLUDE_HOSTS_ENV];
}
}
function withShimEnv(env, proxyUrl2, excludeHosts) {
function withWireRootsEnv(env, wireRoots) {
if (wireRoots.length > 0) {
env[WIRE_ROOTS_ENV] = wireRoots.map((root) => `${root.origin}${root.path}`).join(",");
} else {
delete env[WIRE_ROOTS_ENV];
}
}
function withShimEnv(env, proxyUrl2, excludeHosts, wireRoots) {
const nextEnv = { ...env ?? process.env };
nextEnv[PROXY_ENV] = proxyUrl2;
withExcludeHostsEnv(nextEnv, excludeHosts);
withWireRootsEnv(nextEnv, wireRoots);
const shim = shimImportSpecifier();
if (shim) {
nextEnv.NODE_OPTIONS = withNodeImportOption(nextEnv.NODE_OPTIONS, shim);
}
return nextEnv;
}
var PROCESS_ENV_KEYS = [PROXY_ENV, EXCLUDE_HOSTS_ENV, "NODE_OPTIONS"];
var PROCESS_ENV_KEYS = [PROXY_ENV, EXCLUDE_HOSTS_ENV, WIRE_ROOTS_ENV, "NODE_OPTIONS"];
function snapshotProcessEnv() {
return Object.fromEntries(PROCESS_ENV_KEYS.map((key) => [key, process.env[key]]));
}
@@ -63,9 +72,10 @@ function restoreProcessEnv(saved) {
}
}
}
function installProcessEnv(proxyUrl2, excludeHosts) {
function installProcessEnv(proxyUrl2, excludeHosts, wireRoots) {
process.env[PROXY_ENV] = proxyUrl2;
withExcludeHostsEnv(process.env, excludeHosts);
withWireRootsEnv(process.env, wireRoots);
const shim = shimImportSpecifier();
if (shim) {
process.env.NODE_OPTIONS = withNodeImportOption(process.env.NODE_OPTIONS, shim);
@@ -78,7 +88,12 @@ function injectOptionsEnv(args, optionIndex, state) {
const nextArgs = [...args];
const callback = typeof nextArgs.at(-1) === "function" ? nextArgs.pop() : void 0;
const existing = isOptions(nextArgs[optionIndex]) ? { ...nextArgs[optionIndex] } : {};
existing.env = withShimEnv(existing.env, state.proxyUrl, state.excludeHosts);
existing.env = withShimEnv(
existing.env,
state.proxyUrl,
state.excludeHosts,
state.wireRoots
);
if (process.platform === "win32" && existing.windowsHide === void 0) {
existing.windowsHide = true;
}
@@ -148,14 +163,38 @@ function usableProxyUrl(proxyUrl2) {
return void 0;
}
}
function canonicalHostname(hostname) {
return hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.+$/, "");
}
function isLoopback(hostname) {
const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
const normalized = canonicalHostname(hostname);
if (normalized === "localhost" || normalized === "::1" || normalized === "0.0.0.0") {
return true;
}
if (isLoopbackIpv4(normalized)) {
return true;
}
const mapped = /^::ffff:(.+)$/.exec(normalized)?.[1];
if (!mapped) {
return false;
}
if (isLoopbackIpv4(mapped)) {
return true;
}
const groups = /^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(mapped);
if (!groups) {
return false;
}
const address = parseInt(groups[1], 16) << 16 | parseInt(groups[2], 16);
return address >>> 24 === 127;
}
function isLoopbackIpv4(host) {
return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host);
}
function normalizeExcludeHosts(entries) {
const hosts = /* @__PURE__ */ new Set();
for (const entry of typeof entries === "string" ? entries.split(",") : entries) {
const host = String(entry).trim().toLowerCase().replace(/^(\*\.|\.)/, "");
const host = canonicalHostname(String(entry).trim()).replace(/^(?:\*\.|\.)/, "");
if (host) {
hosts.add(host);
}
@@ -163,11 +202,57 @@ function normalizeExcludeHosts(entries) {
return [...hosts];
}
function isExcludedHost(hostname, excludeHosts) {
const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
const normalized = canonicalHostname(hostname);
return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
}
function isLlmEndpointPath(pathname) {
return pathname.endsWith("/chat/completions") || pathname.endsWith("/responses") || pathname.endsWith("/messages") || pathname.endsWith(":generateContent") || pathname.endsWith(":streamGenerateContent");
function normalizeWireRoots(entries) {
const roots = /* @__PURE__ */ new Map();
for (const entry of typeof entries === "string" ? entries.split(",") : entries) {
const raw = String(entry).trim();
if (!raw) {
continue;
}
try {
const url = new URL(raw);
if (url.protocol !== "http:" && url.protocol !== "https:") {
continue;
}
const path = url.pathname.replace(/\/+$/, "");
roots.set(`${url.origin}${path}`, { origin: url.origin, path });
} catch {
}
}
return [...roots.values()];
}
function isConfiguredWireRoot(origin, pathname, wireRoots) {
return wireRoots.some(
(root) => root.origin === origin && (root.path === "" ? pathname.startsWith("/") : pathname === root.path || pathname.startsWith(`${root.path}/`))
);
}
var NAMED_WIRE_ROOTS = /* @__PURE__ */ new Set(["backend-api", "codex", "openai", "anthropic", "zen"]);
var IMMEDIATE_WIRE_ROOTS = /* @__PURE__ */ new Set(["api"]);
function isVersionSegment(segment) {
return /^v\d+[a-z0-9]*$/i.test(segment);
}
function hasWireRootBefore(body) {
const segments = body.split("/").filter(Boolean);
const last = segments.at(-1);
return last === void 0 || isVersionSegment(last) || IMMEDIATE_WIRE_ROOTS.has(last) || segments.some((s) => NAMED_WIRE_ROOTS.has(s));
}
function isLlmEndpointPath(pathname, origin = "", wireRoots = []) {
if (pathname.endsWith(":generateContent") || pathname.endsWith(":streamGenerateContent")) {
return true;
}
for (const suffix of ["/chat/completions", "/responses", "/messages"]) {
if (!pathname.endsWith(suffix)) {
continue;
}
if (isConfiguredWireRoot(origin, pathname, wireRoots)) {
return true;
}
return hasWireRootBefore(pathname.slice(0, -suffix.length));
}
return false;
}
function isRoutableUpstream(url, proxy, excludeHosts) {
if (url.protocol !== "http:" && url.protocol !== "https:") {
@@ -187,8 +272,11 @@ function isRoutableUpstream(url, proxy, excludeHosts) {
function isLlmMethod(method) {
return typeof method === "string" && method.toUpperCase() === "POST";
}
function shouldRoute(url, proxy, excludeHosts, method) {
return isLlmMethod(method) && isRoutableUpstream(url, proxy, excludeHosts) && isLlmEndpointPath(url.pathname);
function shouldRoute(url, proxy, excludeHosts, method, wireRoots = []) {
if (!isLlmMethod(method) || !isRoutableUpstream(url, proxy, excludeHosts)) {
return false;
}
return isLlmEndpointPath(url.pathname, url.origin, wireRoots);
}
function routedUrl(upstream, proxy) {
return new URL(`${upstream.pathname}${upstream.search}`, proxy.origin);
@@ -244,10 +332,10 @@ function mergeFetchHeaders(input, init, upstream, originalPath = void 0, project
}
return headers;
}
function withRoutedFetchInput(input, init, proxy, project, excludeHosts, sessionToken) {
function withRoutedFetchInput(input, init, proxy, project, excludeHosts, sessionToken, wireRoots = []) {
const upstream = requestUrl(input);
const method = init?.method ?? (input instanceof Request ? input.method : "GET");
if (!shouldRoute(upstream, proxy, excludeHosts, method)) {
if (!shouldRoute(upstream, proxy, excludeHosts, method, wireRoots)) {
return [input, init];
}
const { url: nextUrl, originalPath } = routedUrlForOpenCode(upstream, proxy);
@@ -318,8 +406,8 @@ function headersForNodeRequest(options, upstream, originalPath, project, session
});
return result;
}
function routedNodeOptions(parts, proxy, project, excludeHosts, sessionToken) {
if (!parts.url || !shouldRoute(parts.url, proxy, excludeHosts, parts.options.method ?? "GET")) {
function routedNodeOptions(parts, proxy, project, excludeHosts, sessionToken, wireRoots = []) {
if (!parts.url || !shouldRoute(parts.url, proxy, excludeHosts, parts.options.method ?? "GET", wireRoots)) {
return void 0;
}
const { url: nextUrl, originalPath } = routedUrlForOpenCode(parts.url, proxy);
@@ -363,7 +451,14 @@ function wrapRequest(originalHttpRequest, originalHttpsRequest, originalRequest)
return Reflect.apply(originalRequest, this, args);
}
const parts = splitNodeArgs(args);
const nextOptions = routedNodeOptions(parts, proxy, state.project, state.excludeHosts, state.sessionToken);
const nextOptions = routedNodeOptions(
parts,
proxy,
state.project,
state.excludeHosts,
state.sessionToken,
state.wireRoots
);
if (!nextOptions) {
return Reflect.apply(originalRequest, this, args);
}
@@ -386,15 +481,17 @@ function wrapHttp2Connect(originalConnect) {
}
function installHeadroomTransport(options) {
const excludeHosts = normalizeExcludeHosts(options.excludeHosts ?? process.env[EXCLUDE_HOSTS_ENV] ?? "");
const wireRoots = normalizeWireRoots(options.wireRoots ?? process.env[WIRE_ROOTS_ENV] ?? "");
const existing = getState();
if (existing) {
existing.refs += 1;
existing.proxyUrl = options.proxyUrl;
existing.project = options.project;
existing.excludeHosts = excludeHosts;
existing.wireRoots = wireRoots;
existing.debug = Boolean(options.debug);
existing.sessionToken = options.sessionToken;
installProcessEnv(options.proxyUrl, excludeHosts);
installProcessEnv(options.proxyUrl, excludeHosts, wireRoots);
return () => uninstallHeadroomTransport();
}
const state = {
@@ -402,6 +499,7 @@ function installHeadroomTransport(options) {
proxyUrl: options.proxyUrl,
project: options.project,
excludeHosts,
wireRoots,
debug: Boolean(options.debug),
sessionToken: options.sessionToken,
originalFetch: globalThis.fetch,
@@ -417,7 +515,7 @@ function installHeadroomTransport(options) {
originalEnv: snapshotProcessEnv()
};
setState(state);
installProcessEnv(options.proxyUrl, excludeHosts);
installProcessEnv(options.proxyUrl, excludeHosts, wireRoots);
globalThis.fetch = async (...args) => {
const current = getState();
if (!current) {
@@ -427,7 +525,15 @@ function installHeadroomTransport(options) {
if (!proxy) {
return state.originalFetch(...args);
}
const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project, current.excludeHosts, current.sessionToken);
const [nextInput, nextInit] = withRoutedFetchInput(
args[0],
args[1],
proxy,
current.project,
current.excludeHosts,
current.sessionToken,
current.wireRoots
);
return state.originalFetch(nextInput, nextInit);
};
http.request = wrapRequest(state.originalHttpRequest, state.originalHttpsRequest, state.originalHttpRequest);
+2
View File
@@ -73,6 +73,7 @@ The default export is `{ id: "headroom", server, setup }`. OpenCode 1.x calls `s
- add `HEADROOM_ACTIVE`, `HEADROOM_PROXY_URL`, `HEADROOM_PROJECT` (and `HEADROOM_BACKEND` when set) to shell command environments.
- default to `HEADROOM_PROXY_URL`, then `http://127.0.0.1:8787`, when no `proxyUrl` option is supplied.
- skip routing for hosts listed in `excludeHosts` (or `HEADROOM_OPENCODE_EXCLUDE_HOSTS`); those requests go straight upstream with no compression or telemetry.
- route the provider base URLs configured in OpenCode, so a compatible gateway with an arbitrary path prefix is still compressed. Only wire endpoints (`/chat/completions`, `/responses`, `/messages`) under a configured base route; other paths on that host pass through.
On 2.x, setup returns a cleanup that releases the transport, so hot reloads do not stack interceptors.
@@ -140,6 +141,7 @@ The provider config exposes these as `headroom/<model>` and defaults to `headroo
|---|---|---|
| `HEADROOM_PROXY_URL` | Native plugin | Proxy URL used by `HeadroomPlugin` |
| `HEADROOM_OPENCODE_EXCLUDE_HOSTS` | Native plugin | Comma-separated hosts (and their subdomains) that bypass the proxy; the `excludeHosts` plugin option takes precedence |
| `HEADROOM_OPENCODE_WIRE_ROOTS` | Native plugin | Set from OpenCode's configured provider base URLs so spawned Node processes route the same bases; rarely set by hand |
| `OPENCODE_CONFIG_CONTENT` | OpenCode wrapper | Generated OpenCode provider, model, and MCP config |
## License
+95
View File
@@ -1,3 +1,5 @@
import http from "node:http";
import https from "node:https";
import { afterEach, describe, expect, it, vi } from "vitest";
import HeadroomOpenCodePlugin, { HeadroomPlugin, headroomSetup } from "./plugin.js";
@@ -85,6 +87,13 @@ function transportState(): { refs: number } | undefined {
return (globalThis as Record<symbol, { refs: number } | undefined>)[TRANSPORT_STATE];
}
function transportWireRoots(): string[] {
const state = (globalThis as Record<symbol, { wireRoots?: Array<{ origin: string; path: string }> }>)[
TRANSPORT_STATE
];
return (state?.wireRoots ?? []).map((root) => `${root.origin}${root.path}`);
}
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
@@ -116,6 +125,92 @@ describe("HeadroomPlugin", () => {
});
});
it("widens transport routing to base URLs from OpenCode's config (#4747)", async () => {
const fetchMock = vi.fn(async (..._args: unknown[]) => new Response("ok"));
vi.stubGlobal("fetch", fetchMock);
const client = {
config: {
get: async () => ({
data: {
provider: {
acme: { options: { baseURL: "https://gateway.invalid/tenant/acme" } },
},
},
}),
},
provider: { list: async () => ({ data: { all: [] } }) },
};
const plugin = await HeadroomPlugin(
{ ...(pluginInput() as Record<string, unknown>), client } as never,
{ proxyUrl: "http://127.0.0.1:8787" },
);
try {
// The config read is deliberately not awaited by the plugin, so let it land.
await vi.waitFor(() => {
expect(transportWireRoots()).toContain("https://gateway.invalid/tenant/acme");
});
await fetch("https://gateway.invalid/tenant/acme/chat/completions", { method: "POST" });
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(String(fetchMock.mock.calls[0][0])).toBe("http://127.0.0.1:8787/v1/chat/completions");
} finally {
await plugin.dispose?.();
}
});
it("applies a config result without waiting for a pending provider listing (#4747)", async () => {
const fetchMock = vi.fn(async (..._args: unknown[]) => new Response("ok"));
vi.stubGlobal("fetch", fetchMock);
const fakeRequest = { on: vi.fn(), end: vi.fn(), destroy: vi.fn() };
const httpSpy = vi.spyOn(http, "request").mockImplementation(() => fakeRequest as never);
const httpsSpy = vi.spyOn(https, "request").mockImplementation(() => fakeRequest as never);
// The provider listing never settles: a stalled server must not hold back a
// base the config already reported.
const client = {
config: {
get: async () => ({
data: {
provider: {
acme: { options: { baseURL: "https://gateway.invalid/tenant/acme" } },
},
},
}),
},
provider: { list: () => new Promise<never>(() => {}) },
};
const plugin = await HeadroomPlugin(
{ ...(pluginInput() as Record<string, unknown>), client } as never,
{ proxyUrl: "http://127.0.0.1:8787" },
);
try {
// The read is still not awaited by the plugin, but nothing else blocks it.
await vi.waitFor(() => {
expect(transportWireRoots()).toContain("https://gateway.invalid/tenant/acme");
});
await fetch("https://gateway.invalid/tenant/acme/chat/completions", { method: "POST" });
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(String(fetchMock.mock.calls[0][0])).toBe("http://127.0.0.1:8787/v1/chat/completions");
https.request("https://gateway.invalid/tenant/acme/chat/completions", { method: "POST" });
expect(httpSpy).toHaveBeenCalledTimes(1);
expect(httpsSpy).not.toHaveBeenCalled();
// Still a root, not a blanket route for the host.
await fetch("https://gateway.invalid/tenant/acme/files/1", { method: "POST" });
expect(String(fetchMock.mock.calls[1][0])).toBe("https://gateway.invalid/tenant/acme/files/1");
} finally {
await plugin.dispose?.();
httpSpy.mockRestore();
httpsSpy.mockRestore();
}
});
it("treats an empty HEADROOM_PROXY_URL as unset and falls through to HEADROOM_BASE_URL", async () => {
vi.stubEnv("HEADROOM_PROXY_URL", "");
vi.stubEnv("HEADROOM_BASE_URL", "http://127.0.0.1:9999");
+106
View File
@@ -17,6 +17,7 @@ import {
installHeadroomTransport,
modelBaseRoutesThroughProxy,
normalizeExcludeHosts,
setHeadroomWireRoots,
} from "./transport.js";
export interface HeadroomOpenCodePluginOptions {
@@ -26,10 +27,89 @@ export interface HeadroomOpenCodePluginOptions {
backend?: string;
debug?: boolean;
sessionToken?: string;
/**
* Provider base URLs whose wire the transport must route. Normally read from
* OpenCode's own configuration, so this is only needed when that is
* unavailable (or to cover a base the plugin cannot see).
*/
wireRoots?: string[];
}
export const HEADROOM_PLUGIN_ID = "headroom";
// OpenCode's own configuration is the authority on where a provider mounts its
// wire: `provider.<id>.options.baseURL` in the config, or the runtime list with
// injective defaults resolved. A base URL the user configured must route, even
// when its path has no version segment and no recognisable root name
// (/tenant/acme), because OpenCode 1.x sends those calls through the patched
// fetch and would otherwise bypass Headroom silently (#4747 review).
function collectBaseUrls(config: unknown, providers: unknown): string[] {
const urls = new Set<string>();
const add = (value: unknown) => {
if (typeof value === "string" && value.trim()) {
urls.add(value.trim());
}
};
const configProviders = (config as { provider?: Record<string, { options?: { baseURL?: unknown } }> })
?.provider;
for (const entry of Object.values(configProviders ?? {})) {
add(entry?.options?.baseURL);
}
// /provider returns { all: [...] } in the generated API and the bare list in
// older servers; handle both rather than depending on one version.
const list = Array.isArray(providers) ? providers : (providers as { all?: unknown })?.all;
for (const entry of Array.isArray(list) ? list : []) {
add((entry as { options?: { baseURL?: unknown } })?.options?.baseURL);
}
return [...urls];
}
// The plugin must not block startup on a round trip to the server that is
// loading it, and a server that is not serving yet must not disable routing.
// So install first with whatever is known, then widen the rule when the answer
// arrives. Requests that land in between fall back to the path heuristics.
//
// Each endpoint is applied on its own: keeping a base back because the other
// request is still pending would leave a configured wire bypassing Headroom for
// as long as that request stalls (#4747 review). A failed or missing read only
// costs its own bases, never the other's.
function resolveConfiguredWireRoots(
client: { config?: { get?: () => Promise<unknown> }; provider?: { list?: () => Promise<unknown> } } | undefined,
onResolved: (urls: string[]) => void,
): void {
if (!client?.config?.get && !client?.provider?.list) {
return;
}
const apply = (read: (() => Promise<unknown>) | undefined, pick: (value: unknown) => string[]) => {
if (!read) {
return;
}
// Promise.resolve() turns a synchronous throw into a rejection, and the
// catch keeps a failing read on the path heuristics instead of surfacing.
void Promise.resolve()
.then(read)
.then((value) => {
const urls = pick(value);
if (urls.length > 0) {
onResolved(urls);
}
})
.catch(() => {
// Routing stays on the path heuristics; not worth failing a session for.
});
};
apply(client.config?.get?.bind(client.config), (config) =>
collectBaseUrls((config as { data?: unknown })?.data ?? config, undefined),
);
apply(client.provider?.list?.bind(client.provider), (providers) =>
collectBaseUrls(undefined, (providers as { data?: unknown })?.data ?? providers),
);
}
function normalizeProxyUrl(url: string): string {
return trimTrailingSlashes(url);
}
@@ -144,6 +224,21 @@ function routeModelsThroughProxy(
}
}
// Every base URL the 2.x transform can see. The transport only needs the ones
// it must keep routing, but passing them all is harmless: it ignores entries it
// cannot parse and bases it would not route anyway.
function modelBaseUrls(models: ModelEditor): string[] {
const urls = new Set<string>();
for (const model of models.list()) {
const provider = models.provider.get(String(model.providerID))?.provider;
const baseURL = model.settings?.baseURL ?? provider?.settings?.baseURL;
if (typeof baseURL === "string" && baseURL.trim()) {
urls.add(baseURL.trim());
}
}
return [...urls];
}
// OpenCode 1.x: a factory returning a hooks object.
export const HeadroomPlugin: Plugin = async (input, options = {}) => {
const pluginOptions = options as HeadroomOpenCodePluginOptions;
@@ -159,6 +254,12 @@ export const HeadroomPlugin: Plugin = async (input, options = {}) => {
excludeHosts: pluginOptions.excludeHosts,
debug: pluginOptions.debug,
sessionToken: resolveSessionToken(pluginOptions),
wireRoots: pluginOptions.wireRoots,
});
resolveConfiguredWireRoots(input.client, (urls) => {
if (urls.length > 0) {
setHeadroomWireRoots(urls.join(","));
}
});
return {
@@ -201,10 +302,15 @@ export const headroomSetup: PluginV2.Plugin["setup"] = async (ctx) => {
excludeHosts,
debug: pluginOptions.debug,
sessionToken,
wireRoots: pluginOptions.wireRoots,
});
try {
await ctx.model.transform((models) => {
const wireRoots = modelBaseUrls(models);
if (wireRoots.length > 0) {
setHeadroomWireRoots(wireRoots.join(","));
}
routeModelsThroughProxy(models, proxyUrl, project, excludeHosts, sessionToken);
});
await ctx.tool.transform((editor) => {
+163
View File
@@ -267,6 +267,169 @@ describe("Headroom OpenCode transport", () => {
req2.destroy();
});
it("passes a non-LLM POST whose path merely ends in an LLM endpoint through unchanged (#4747)", async () => {
const originalFetch = globalThis.fetch;
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
globalThis.fetch = fetchMock as unknown as typeof fetch;
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", sessionToken: "SESSION-TOKEN" });
const init = { method: "POST", headers: { authorization: "Bearer SECRET" }, body: "{}" };
await fetch("https://discord.com/api/v10/channels/123/messages", init);
await fetch("https://discord.com/api/v9/channels/123/messages", init);
await fetch("https://forms.example.com/forms/123/responses", init);
await fetch("https://chat.example.com/rooms/42/chat/completions", init);
expect(fetchMock).toHaveBeenCalledTimes(4);
for (const call of fetchMock.mock.calls as FetchCall[]) {
expect(typeof call[0]).toBe("string");
expect(call[1]).toBe(init);
const headers = new Headers(call[1]?.headers);
expect(headers.get("x-headroom-base-url")).toBeNull();
expect(headers.get("x-headroom-session-token")).toBeNull();
}
globalThis.fetch = originalFetch;
});
it("still routes provider-rooted wire paths, including a bare endpoint and other version prefixes (#4747)", async () => {
const originalFetch = globalThis.fetch;
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
globalThis.fetch = fetchMock as unknown as typeof fetch;
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1" });
const init = { method: "POST" };
await fetch("https://api.example.com/messages", init);
await fetch("https://api.example.com/responses", init);
await fetch("https://gateway.example.com/api/chat/completions", init);
await fetch("https://gateway.example.com/api/v2/chat/completions", init);
await fetch("https://gateway.example.com/openai/deployments/x/chat/completions", init);
await fetch("https://opencode.ai/zen/v1/responses", init);
await fetch("https://cloud.example.com/backend-api/codex/responses", init);
expect(fetchMock).toHaveBeenCalledTimes(7);
for (const call of fetchMock.mock.calls as FetchCall[]) {
expect(call[0]).toBeInstanceOf(URL);
expect(new Headers(call[1]?.headers).get("x-headroom-base-url")).not.toBeNull();
}
globalThis.fetch = originalFetch;
});
it("keeps every loopback spelling and a trailing-dot excluded host off the proxy (#4747)", async () => {
const originalFetch = globalThis.fetch;
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
globalThis.fetch = fetchMock as unknown as typeof fetch;
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["api.x.example"] });
const init = { method: "POST" };
await fetch("http://127.0.0.1:11434/v1/chat/completions", init);
await fetch("http://127.0.0.2:11434/v1/chat/completions", init);
await fetch("http://127.1.2.3:11434/v1/chat/completions", init);
await fetch("http://127.255.255.254:11434/v1/chat/completions", init);
await fetch("http://localhost./v1/chat/completions", init);
await fetch("http://[::1]:11434/v1/chat/completions", init);
await fetch("http://[::ffff:127.0.0.1]:11434/v1/chat/completions", init);
await fetch("http://[::ffff:127.1.2.3]:11434/v1/chat/completions", init);
await fetch("https://api.x.example./v1/chat/completions", init);
expect(fetchMock).toHaveBeenCalledTimes(9);
for (const call of fetchMock.mock.calls as FetchCall[]) {
expect(typeof call[0]).toBe("string");
expect(call[1]).toBe(init);
expect(new Headers(call[1]?.headers).get("x-headroom-base-url")).toBeNull();
}
globalThis.fetch = originalFetch;
});
it("routes a configured compatible base with no version or reserved prefix, in fetch and Node requests (#4747)", async () => {
const originalFetch = globalThis.fetch;
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
globalThis.fetch = fetchMock as unknown as typeof fetch;
const fakeRequest = { on: vi.fn(), end: vi.fn(), destroy: vi.fn() };
const httpsSpy = vi.spyOn(https, "request").mockImplementation(() => fakeRequest as never);
const httpSpy = vi.spyOn(http, "request").mockImplementation(() => fakeRequest as never);
// The base the user configured for an OpenAI-compatible provider. Its path
// has no version segment and no reserved root name, so only knowing the
// configured base can route it.
installHeadroomTransport({
proxyUrl: "http://127.0.0.1:8787/v1",
wireRoots: ["https://gateway.invalid/tenant/acme"],
});
const init = { method: "POST" };
try {
await fetch("https://gateway.invalid/tenant/acme/chat/completions", init);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][0]).toBeInstanceOf(URL);
expect(new Headers(fetchMock.mock.calls[0][1]?.headers).get("x-headroom-base-url")).toBe(
"https://gateway.invalid",
);
// The configured base is a root, not a blanket route for its host: an
// unrelated path on that host still passes through untouched.
await fetch("https://gateway.invalid/tenant/acme/files/1", init);
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(fetchMock.mock.calls[1][0]).toBe("https://gateway.invalid/tenant/acme/files/1");
https.request("https://gateway.invalid/tenant/acme/chat/completions", init);
// The proxy is http://, so a routed request is re-issued through
// http.request; https.request keeps only the untouched pass-through.
expect(httpSpy).toHaveBeenCalledTimes(1);
const routed = httpSpy.mock.calls[0][0] as { headers?: Record<string, string>; hostname?: string; path?: string };
expect(routed).toMatchObject({
hostname: "127.0.0.1",
path: "/v1/chat/completions",
});
expect(new Headers(routed.headers).get("x-headroom-base-url")).toBe("https://gateway.invalid");
https.request("https://gateway.invalid/tenant/acme/files/1", init);
expect(httpSpy).toHaveBeenCalledTimes(1);
expect(httpsSpy).toHaveBeenCalledTimes(1);
expect(httpsSpy.mock.calls[0][0]).toBe("https://gateway.invalid/tenant/acme/files/1");
// A different origin that merely shares a path prefix must not match.
await fetch("https://other.invalid/tenant/acme/chat/completions", init);
expect(fetchMock).toHaveBeenCalledTimes(3);
expect(fetchMock.mock.calls[2][0]).toBe("https://other.invalid/tenant/acme/chat/completions");
} finally {
uninstallHeadroomTransport();
globalThis.fetch = originalFetch;
httpsSpy.mockRestore();
httpSpy.mockRestore();
}
});
it("keeps loopback spellings and a trailing-dot excluded host off the proxy for Node http/https.request (#4747)", () => {
const fakeRequest = { on: vi.fn(), end: vi.fn(), destroy: vi.fn() };
const httpsSpy = vi.spyOn(https, "request").mockImplementation(() => fakeRequest as never);
const httpSpy = vi.spyOn(http, "request").mockImplementation(() => fakeRequest as never);
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["api.x.example"] });
const options = { method: "POST" };
try {
// http:// goes through http.request: real https.request rejects that
// protocol, so asserting it against the https spy would prove nothing.
http.request("http://127.0.0.2:11434/v1/chat/completions", options);
http.request("http://[::ffff:127.0.0.2]:11434/v1/chat/completions", options);
https.request("https://api.x.example./v1/chat/completions", options);
https.request("https://discord.com/api/v10/channels/123/messages", options);
expect(httpSpy.mock.calls[0][0]).toBe("http://127.0.0.2:11434/v1/chat/completions");
expect(httpSpy.mock.calls[1][0]).toBe("http://[::ffff:127.0.0.2]:11434/v1/chat/completions");
expect(httpsSpy.mock.calls[0][0]).toBe("https://api.x.example./v1/chat/completions");
expect(httpsSpy.mock.calls[1][0]).toBe("https://discord.com/api/v10/channels/123/messages");
} finally {
uninstallHeadroomTransport();
httpsSpy.mockRestore();
httpSpy.mockRestore();
}
});
it("routes Gemini native :generateContent and :streamGenerateContent through the proxy", async () => {
const originalFetch = globalThis.fetch;
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
+232 -26
View File
@@ -13,6 +13,7 @@ export const PROJECT_HEADER = "x-headroom-project";
export const SESSION_TOKEN_HEADER = "x-headroom-session-token";
const PROXY_ENV = "HEADROOM_OPENCODE_TRANSPORT_PROXY_URL";
export const EXCLUDE_HOSTS_ENV = "HEADROOM_OPENCODE_EXCLUDE_HOSTS";
export const WIRE_ROOTS_ENV = "HEADROOM_OPENCODE_WIRE_ROOTS";
const STATE_KEY = Symbol.for("headroom.opencode.transport");
type FetchArgs = Parameters<typeof fetch>;
@@ -32,6 +33,7 @@ interface InstallOptions {
excludeHosts?: string[];
debug?: boolean;
sessionToken?: string;
wireRoots?: string | Iterable<unknown>;
}
interface TransportState {
@@ -39,6 +41,7 @@ interface TransportState {
proxyUrl: string;
project: string | undefined;
excludeHosts: string[];
wireRoots: WireRoot[];
debug: boolean;
sessionToken: string | undefined;
originalFetch: typeof fetch;
@@ -106,14 +109,26 @@ function withExcludeHostsEnv(env: NodeJS.ProcessEnv, excludeHosts: string[]): vo
}
}
// Same rule as excludeHosts: the child must inherit this process's roots, so
// the variable always mirrors the effective set and is removed when empty.
function withWireRootsEnv(env: NodeJS.ProcessEnv, wireRoots: WireRoot[]): void {
if (wireRoots.length > 0) {
env[WIRE_ROOTS_ENV] = wireRoots.map((root) => `${root.origin}${root.path}`).join(",");
} else {
delete env[WIRE_ROOTS_ENV];
}
}
function withShimEnv(
env: NodeJS.ProcessEnv | Record<string, unknown> | undefined,
proxyUrl: string,
excludeHosts: string[],
wireRoots: WireRoot[],
): NodeJS.ProcessEnv {
const nextEnv = { ...(env ?? process.env) } as NodeJS.ProcessEnv;
nextEnv[PROXY_ENV] = proxyUrl;
withExcludeHostsEnv(nextEnv, excludeHosts);
withWireRootsEnv(nextEnv, wireRoots);
const shim = shimImportSpecifier();
if (shim) {
nextEnv.NODE_OPTIONS = withNodeImportOption(nextEnv.NODE_OPTIONS, shim);
@@ -122,7 +137,7 @@ function withShimEnv(
}
// installProcessEnv writes these process-wide keys; uninstall puts them back.
const PROCESS_ENV_KEYS = [PROXY_ENV, EXCLUDE_HOSTS_ENV, "NODE_OPTIONS"] as const;
const PROCESS_ENV_KEYS = [PROXY_ENV, EXCLUDE_HOSTS_ENV, WIRE_ROOTS_ENV, "NODE_OPTIONS"] as const;
function snapshotProcessEnv(): Record<string, string | undefined> {
return Object.fromEntries(PROCESS_ENV_KEYS.map((key) => [key, process.env[key]]));
@@ -138,9 +153,10 @@ function restoreProcessEnv(saved: Record<string, string | undefined>): void {
}
}
function installProcessEnv(proxyUrl: string, excludeHosts: string[]): void {
function installProcessEnv(proxyUrl: string, excludeHosts: string[], wireRoots: WireRoot[]): void {
process.env[PROXY_ENV] = proxyUrl;
withExcludeHostsEnv(process.env, excludeHosts);
withWireRootsEnv(process.env, wireRoots);
const shim = shimImportSpecifier();
if (shim) {
process.env.NODE_OPTIONS = withNodeImportOption(process.env.NODE_OPTIONS, shim);
@@ -155,7 +171,12 @@ function injectOptionsEnv(args: unknown[], optionIndex: number, state: Transport
const nextArgs = [...args];
const callback = typeof nextArgs.at(-1) === "function" ? nextArgs.pop() : undefined;
const existing = isOptions(nextArgs[optionIndex]) ? { ...(nextArgs[optionIndex] as Record<string, unknown>) } : {};
existing.env = withShimEnv(existing.env as NodeJS.ProcessEnv | undefined, state.proxyUrl, state.excludeHosts);
existing.env = withShimEnv(
existing.env as NodeJS.ProcessEnv | undefined,
state.proxyUrl,
state.excludeHosts,
state.wireRoots,
);
if (process.platform === "win32" && existing.windowsHide === undefined) {
existing.windowsHide = true;
}
@@ -240,9 +261,45 @@ function usableProxyUrl(proxyUrl: string): URL | undefined {
}
}
// A hostname reaches this module as WHATWG `URL.hostname`, so a few spellings of
// the same host are still distinct strings: "example.com." is the same name as
// "example.com" (a fully qualified name), and an IPv4-mapped IPv6 loopback
// arrives canonicalized as "[::ffff:7f00:1]" - never as "127.0.0.1" or "::1".
// Compare canonical forms, or the loopback and exclude checks miss (#4747).
function canonicalHostname(hostname: string): string {
return hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.+$/, "");
}
function isLoopback(hostname: string): boolean {
const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
const normalized = canonicalHostname(hostname);
if (normalized === "localhost" || normalized === "::1" || normalized === "0.0.0.0") {
return true;
}
// 127.0.0.0/8 is entirely loopback, not just 127.0.0.1.
if (isLoopbackIpv4(normalized)) {
return true;
}
const mapped = /^::ffff:(.+)$/.exec(normalized)?.[1];
if (!mapped) {
return false;
}
// URL canonicalization writes the embedded IPv4 in hex ("::ffff:7f00:1"),
// but accept the dotted form too, which some non-WHATWG callers pass through.
if (isLoopbackIpv4(mapped)) {
return true;
}
// Two remaining groups are the full 32-bit address: 127.1.2.3 is
// "::ffff:7f01:203", so the last two octets share the low group.
const groups = /^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(mapped);
if (!groups) {
return false;
}
const address = (parseInt(groups[1], 16) << 16) | parseInt(groups[2], 16);
return address >>> 24 === 127;
}
function isLoopbackIpv4(host: string): boolean {
return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host);
}
// "example.com", ".example.com" and "*.example.com" all mean the host itself
@@ -253,7 +310,7 @@ function isLoopback(hostname: string): boolean {
export function normalizeExcludeHosts(entries: string | Iterable<unknown>): string[] {
const hosts = new Set<string>();
for (const entry of typeof entries === "string" ? entries.split(",") : entries) {
const host = String(entry).trim().toLowerCase().replace(/^(\*\.|\.)/, "");
const host = canonicalHostname(String(entry).trim()).replace(/^(?:\*\.|\.)/, "");
if (host) {
hosts.add(host);
}
@@ -262,27 +319,130 @@ export function normalizeExcludeHosts(entries: string | Iterable<unknown>): stri
}
function isExcludedHost(hostname: string, excludeHosts: string[]): boolean {
const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
const normalized = canonicalHostname(hostname);
return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
}
// A provider base URL the user configured (for example
// https://gateway.invalid/tenant/acme) says where that provider mounts its
// wire: the client appends /chat/completions to exactly that path. These are
// facts about the configuration, not guesses from a path's shape, so they are
// matched by origin and path prefix instead of by root name (#4747 review).
//
// This is what keeps arbitrary compatible gateways routable. A root-name
// allowlist can only ever recognise the names we thought of, so
// /tenant/acme/chat/completions fell through while OpenCode 1.x still sent it
// through the patched fetch - silently disabling compression for a base that
// modelBaseRoutesThroughProxy accepts.
interface WireRoot {
origin: string;
path: string;
}
function normalizeWireRoots(entries: string | Iterable<unknown>): WireRoot[] {
const roots = new Map<string, WireRoot>();
for (const entry of typeof entries === "string" ? entries.split(",") : entries) {
const raw = String(entry).trim();
if (!raw) {
continue;
}
try {
const url = new URL(raw);
if (url.protocol !== "http:" && url.protocol !== "https:") {
continue;
}
const path = url.pathname.replace(/\/+$/, "");
roots.set(`${url.origin}${path}`, { origin: url.origin, path });
} catch {
// Not a URL: nothing to match against. A bad entry must not disable the
// root set, so skip it rather than throwing.
}
}
return [...roots.values()];
}
function isConfiguredWireRoot(origin: string, pathname: string, wireRoots: WireRoot[]): boolean {
return wireRoots.some(
(root) =>
root.origin === origin &&
(root.path === "" ? pathname.startsWith("/") : pathname === root.path || pathname.startsWith(`${root.path}/`)),
);
}
// Only recognized LLM API endpoints route through Headroom; any other path
// (WebFetch, registries, GitHub, unknown services) must reach its original URL
// untouched. A bare suffix match keeps provider-prefixed variants working
// (/api/coding/paas/v4/chat/completions, /base/v1/messages, ...).
// untouched.
//
// The endpoint suffix alone cannot decide this. Discord's
// /api/v10/channels/123/messages and a forms API's /forms/123/responses end in
// the same two segments, so a bare suffix match rerouted them - with the
// caller's Authorization header - to the proxy (#4747). A path therefore also
// has to be rooted where providers mount a wire:
//
// * the segment right before the endpoint is a version ("v1", "v1beta", "v4")
// or a base a compatible gateway mounts the wire directly under ("api"),
// which keeps prefixed gateways working (/api/coding/paas/v4/chat/completions,
// /base/v1/messages, /zen/v1/responses, and a custom base URL of
// https://gateway.example/api), or
// * the path contains a named wire root, which is what Azure OpenAI needs: its
// deployment name sits between /openai/ and the endpoint
// (/openai/deployments/{name}/chat/completions).
//
// A bare /messages or /responses on a provider origin still counts: there is no
// segment at all.
//
// The immediate segment is what keeps this tight. "api" is a root only when it
// abuts the endpoint, so /api/chat/completions routes while Discord's
// /api/v10/channels/123/messages (immediate segment "123") does not. For the
// same reason a version segment counts only in that position, not anywhere.
//
// The residual over-match is documented, not solved: /api/v2/messages still
// routes. Telling that apart from a provider needs the host or the body, and
// excludeHosts already covers any host a user controls.
const NAMED_WIRE_ROOTS = new Set(["backend-api", "codex", "openai", "anthropic", "zen"]);
// Custom OpenAI-compatible gateways commonly mount the wire directly under one
// of these, with no version segment: a model base URL of `.../api` plus
// `/chat/completions` is a real configuration (#4747 review).
const IMMEDIATE_WIRE_ROOTS = new Set(["api"]);
function isVersionSegment(segment: string): boolean {
return /^v\d+[a-z0-9]*$/i.test(segment);
}
function hasWireRootBefore(body: string): boolean {
const segments = body.split("/").filter(Boolean);
const last = segments.at(-1);
return (
last === undefined ||
isVersionSegment(last) ||
IMMEDIATE_WIRE_ROOTS.has(last) ||
segments.some((s) => NAMED_WIRE_ROOTS.has(s))
);
}
// Native Gemini model-generation endpoints use colon-action suffixes
// (:generateContent, :streamGenerateContent). These are matched by exact
// suffix so that lookalike paths containing the marker but not ending with it
// (e.g. /v1/models/gemini:generateContent/status) remain unrouted.
function isLlmEndpointPath(pathname: string): boolean {
return (
pathname.endsWith("/chat/completions") ||
pathname.endsWith("/responses") ||
pathname.endsWith("/messages") ||
pathname.endsWith(":generateContent") ||
pathname.endsWith(":streamGenerateContent")
);
// (e.g. /v1/models/gemini:generateContent/status) remain unrouted. They are
// specific enough to need no wire root.
function isLlmEndpointPath(pathname: string, origin = "", wireRoots: WireRoot[] = []): boolean {
if (pathname.endsWith(":generateContent") || pathname.endsWith(":streamGenerateContent")) {
return true;
}
for (const suffix of ["/chat/completions", "/responses", "/messages"]) {
if (!pathname.endsWith(suffix)) {
continue;
}
// A configured base URL is authoritative for its own origin: the client
// appends the endpoint to it. Still require the suffix, so a WebFetch to
// some other path on that host stays out (#4747 review).
if (isConfiguredWireRoot(origin, pathname, wireRoots)) {
return true;
}
return hasWireRootBefore(pathname.slice(0, -suffix.length));
}
return false;
}
function isRoutableUpstream(url: URL, proxy: URL, excludeHosts: string[]): boolean {
@@ -309,8 +469,17 @@ function isLlmMethod(method: unknown): boolean {
return typeof method === "string" && method.toUpperCase() === "POST";
}
function shouldRoute(url: URL, proxy: URL, excludeHosts: string[], method: unknown): boolean {
return isLlmMethod(method) && isRoutableUpstream(url, proxy, excludeHosts) && isLlmEndpointPath(url.pathname);
function shouldRoute(
url: URL,
proxy: URL,
excludeHosts: string[],
method: unknown,
wireRoots: WireRoot[] = [],
): boolean {
if (!isLlmMethod(method) || !isRoutableUpstream(url, proxy, excludeHosts)) {
return false;
}
return isLlmEndpointPath(url.pathname, url.origin, wireRoots);
}
// OpenCode 2.x hands the plugin model base URLs (e.g.
@@ -404,10 +573,11 @@ function withRoutedFetchInput(
project: string | undefined,
excludeHosts: string[],
sessionToken: string | undefined,
wireRoots: WireRoot[] = [],
): FetchArgs {
const upstream = requestUrl(input);
const method = init?.method ?? (input instanceof Request ? input.method : "GET");
if (!shouldRoute(upstream, proxy, excludeHosts, method)) {
if (!shouldRoute(upstream, proxy, excludeHosts, method, wireRoots)) {
return [input, init];
}
@@ -500,8 +670,9 @@ function routedNodeOptions(
project: string | undefined,
excludeHosts: string[],
sessionToken: string | undefined,
wireRoots: WireRoot[] = [],
): Record<string, unknown> | undefined {
if (!parts.url || !shouldRoute(parts.url, proxy, excludeHosts, parts.options.method ?? "GET")) {
if (!parts.url || !shouldRoute(parts.url, proxy, excludeHosts, parts.options.method ?? "GET", wireRoots)) {
return undefined;
}
@@ -553,7 +724,14 @@ function wrapRequest(
return Reflect.apply(originalRequest, this, args);
}
const parts = splitNodeArgs(args);
const nextOptions = routedNodeOptions(parts, proxy, state.project, state.excludeHosts, state.sessionToken);
const nextOptions = routedNodeOptions(
parts,
proxy,
state.project,
state.excludeHosts,
state.sessionToken,
state.wireRoots,
);
if (!nextOptions) {
return Reflect.apply(originalRequest, this, args);
}
@@ -584,15 +762,17 @@ function wrapHttp2Connect(originalConnect: Http2Connect): Http2Connect {
export function installHeadroomTransport(options: InstallOptions): () => void {
const excludeHosts = normalizeExcludeHosts(options.excludeHosts ?? process.env[EXCLUDE_HOSTS_ENV] ?? "");
const wireRoots = normalizeWireRoots(options.wireRoots ?? process.env[WIRE_ROOTS_ENV] ?? "");
const existing = getState();
if (existing) {
existing.refs += 1;
existing.proxyUrl = options.proxyUrl;
existing.project = options.project;
existing.excludeHosts = excludeHosts;
existing.wireRoots = wireRoots;
existing.debug = Boolean(options.debug);
existing.sessionToken = options.sessionToken;
installProcessEnv(options.proxyUrl, excludeHosts);
installProcessEnv(options.proxyUrl, excludeHosts, wireRoots);
return () => uninstallHeadroomTransport();
}
@@ -601,6 +781,7 @@ export function installHeadroomTransport(options: InstallOptions): () => void {
proxyUrl: options.proxyUrl,
project: options.project,
excludeHosts,
wireRoots,
debug: Boolean(options.debug),
sessionToken: options.sessionToken,
originalFetch: globalThis.fetch,
@@ -617,7 +798,7 @@ export function installHeadroomTransport(options: InstallOptions): () => void {
};
setState(state);
installProcessEnv(options.proxyUrl, excludeHosts);
installProcessEnv(options.proxyUrl, excludeHosts, wireRoots);
globalThis.fetch = async (...args: FetchArgs) => {
const current = getState();
if (!current) {
@@ -627,7 +808,15 @@ export function installHeadroomTransport(options: InstallOptions): () => void {
if (!proxy) {
return state.originalFetch(...args);
}
const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project, current.excludeHosts, current.sessionToken);
const [nextInput, nextInit] = withRoutedFetchInput(
args[0],
args[1],
proxy,
current.project,
current.excludeHosts,
current.sessionToken,
current.wireRoots,
);
return state.originalFetch(nextInput, nextInit);
};
@@ -645,6 +834,23 @@ export function installHeadroomTransport(options: InstallOptions): () => void {
return () => uninstallHeadroomTransport();
}
// The configured bases are only known after a round trip to OpenCode's server,
// which may still be starting. Routing must not wait for it, so this widens the
// rule afterwards instead: requests in between use the path heuristics.
export function setHeadroomWireRoots(wireRoots: string): void {
const state = getState();
if (!state) {
return;
}
const existing = new Set(state.wireRoots.map((root) => `${root.origin}${root.path}`));
const added = normalizeWireRoots(wireRoots).filter((root) => !existing.has(`${root.origin}${root.path}`));
if (added.length === 0) {
return;
}
state.wireRoots = [...state.wireRoots, ...added];
withWireRootsEnv(process.env, state.wireRoots);
}
export function uninstallHeadroomTransport(): void {
const state = getState();
if (!state) {