Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

feat(opencode): exclude hosts from transport plugin routing (#3668)

Ayush Kumar Jha0024b57405ee
diff --git a/docs/content/docs/opencode.mdx b/docs/content/docs/opencode.mdx
index 6c71d27ff..7ce257f88 100644
--- a/docs/content/docs/opencode.mdx
+++ b/docs/content/docs/opencode.mdx
@@ -69,6 +69,7 @@ The default model is `headroom/claude-sonnet-4-6`. Change it in `opencode.json`
|---|---|
| `OPENCODE_CONFIG_CONTENT` | JSON payload with provider, plugin, and optional local MCP config injected by `wrap` |
| `HEADROOM_PROXY_URL` | Proxy URL passed to Headroom MCP when a non-default port is used, and to the native plugin when configured |
+| `HEADROOM_OPENCODE_EXCLUDE_HOSTS` | Comma-separated hosts (and their subdomains) the native plugin sends straight upstream instead of through the proxy, for example `opencode.ai,.corp.internal` |
## Failure Learning
@@ -110,6 +111,15 @@ export default async function plugin(input) {
Use this plugin when OpenCode should intercept provider traffic in-process. Use `headroom wrap opencode` when you want the CLI to manage the proxy, config injection, MCP registration, backups, and unwrap behavior.
+The plugin routes every external HTTP(S) request through the proxy. To keep a provider or gateway off the proxy while leaving the plugin loaded, pass `excludeHosts` in the plugin options or set `HEADROOM_OPENCODE_EXCLUDE_HOSTS` before launching OpenCode. An entry matches the host and all of its subdomains; excluded requests are sent as-is, with no compression or telemetry.
+
+```jsonc
+// opencode.json
+{
+ "plugin": [["/path/to/headroom/providers/opencode/_dist/entry.opencode.js", { "excludeHosts": ["opencode.ai"] }]]
+}
+```
+
## Programmatic Config Helpers
The package also exports helpers for custom integrations:
@@ -149,6 +159,10 @@ Check that `OPENCODE_CONFIG_CONTENT` is set and contains the `provider.headroom`
Set `HEADROOM_PROXY_URL` to the running proxy URL, for example `http://127.0.0.1:8787`.
+**One provider rejects requests only while the plugin is loaded.**
+
+Some gateways validate the client on the wire and reject the proxy hop. Exclude that host with `HEADROOM_OPENCODE_EXCLUDE_HOSTS=<host>` (or the `excludeHosts` plugin option); Headroom keeps routing every other provider.
+
**Provider not found after unwrap.**
If unwrap left the provider configured, run `headroom unwrap opencode` again, or manually restore from `~/.config/opencode/opencode.json.headroom-backup`.
diff --git a/headroom/providers/opencode/_dist/entry.opencode.js b/headroom/providers/opencode/_dist/entry.opencode.js
index fcc5943bb..3e5057294 100644
--- a/headroom/providers/opencode/_dist/entry.opencode.js
+++ b/headroom/providers/opencode/_dist/entry.opencode.js
@@ -12489,6 +12489,7 @@ var BASE_URL_HEADER = "x-headroom-base-url";
var ORIGINAL_PATH_HEADER = "x-headroom-original-path";
var PROJECT_HEADER = "x-headroom-project";
var PROXY_ENV = "HEADROOM_OPENCODE_TRANSPORT_PROXY_URL";
+var EXCLUDE_HOSTS_ENV = "HEADROOM_OPENCODE_EXCLUDE_HOSTS";
var STATE_KEY = /* @__PURE__ */ Symbol.for("headroom.opencode.transport");
function getState() {
return globalThis[STATE_KEY];
@@ -12510,17 +12511,26 @@ function withNodeImportOption(existing, shim) {
}
return parts.join(" ");
}
-function withShimEnv(env, proxyUrl) {
+function withExcludeHostsEnv(env, excludeHosts) {
+ if (excludeHosts.length > 0) {
+ env[EXCLUDE_HOSTS_ENV] = excludeHosts.join(",");
+ } else {
+ delete env[EXCLUDE_HOSTS_ENV];
+ }
+}
+function withShimEnv(env, proxyUrl, excludeHosts) {
const nextEnv = { ...env ?? process.env };
nextEnv[PROXY_ENV] = proxyUrl;
+ withExcludeHostsEnv(nextEnv, excludeHosts);
const shim = shimImportSpecifier();
if (shim) {
nextEnv.NODE_OPTIONS = withNodeImportOption(nextEnv.NODE_OPTIONS, shim);
}
return nextEnv;
}
-function installProcessEnv(proxyUrl) {
+function installProcessEnv(proxyUrl, excludeHosts) {
process.env[PROXY_ENV] = proxyUrl;
+ withExcludeHostsEnv(process.env, excludeHosts);
const shim = shimImportSpecifier();
if (shim) {
process.env.NODE_OPTIONS = withNodeImportOption(process.env.NODE_OPTIONS, shim);
@@ -12529,11 +12539,11 @@ function installProcessEnv(proxyUrl) {
function isOptions(value) {
return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof URL);
}
-function injectOptionsEnv(args, optionIndex, proxyUrl) {
+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, proxyUrl);
+ existing.env = withShimEnv(existing.env, state.proxyUrl, state.excludeHosts);
if (isOptions(nextArgs[optionIndex])) {
nextArgs[optionIndex] = existing;
} else {
@@ -12551,7 +12561,7 @@ function wrapSpawn(originalSpawn) {
return Reflect.apply(originalSpawn, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
- return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
+ return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state));
};
}
function wrapExec(originalExec) {
@@ -12560,7 +12570,7 @@ function wrapExec(originalExec) {
if (!state) {
return Reflect.apply(originalExec, this, args);
}
- return Reflect.apply(originalExec, this, injectOptionsEnv(args, 1, state.proxyUrl));
+ return Reflect.apply(originalExec, this, injectOptionsEnv(args, 1, state));
};
}
function wrapExecFile(originalExecFile) {
@@ -12570,7 +12580,7 @@ function wrapExecFile(originalExecFile) {
return Reflect.apply(originalExecFile, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
- return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
+ return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state));
};
}
function wrapFork(originalFork) {
@@ -12580,7 +12590,7 @@ function wrapFork(originalFork) {
return Reflect.apply(originalFork, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
- return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
+ return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state));
};
}
function normalizeProxyUrl(proxyUrl) {
@@ -12590,7 +12600,21 @@ function isLoopback(hostname3) {
const normalized = hostname3.toLowerCase().replace(/^\[|\]$/g, "");
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
}
-function shouldRoute(url2, proxy) {
+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(/^(\*\.|\.)/, "");
+ if (host) {
+ hosts.add(host);
+ }
+ }
+ return [...hosts];
+}
+function isExcludedHost(hostname3, excludeHosts) {
+ const normalized = hostname3.toLowerCase().replace(/^\[|\]$/g, "");
+ return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
+}
+function shouldRoute(url2, proxy, excludeHosts) {
if (url2.protocol !== "http:" && url2.protocol !== "https:") {
return false;
}
@@ -12600,6 +12624,9 @@ function shouldRoute(url2, proxy) {
if (url2.origin === proxy.origin) {
return false;
}
+ if (isExcludedHost(url2.hostname, excludeHosts)) {
+ return false;
+ }
return true;
}
function routedUrl(upstream, proxy) {
@@ -12653,9 +12680,9 @@ function mergeFetchHeaders(input, init, upstream, originalPath = void 0, project
}
return headers;
}
-function withRoutedFetchInput(input, init, proxy, project) {
+function withRoutedFetchInput(input, init, proxy, project, excludeHosts) {
const upstream = requestUrl(input);
- if (!shouldRoute(upstream, proxy)) {
+ if (!shouldRoute(upstream, proxy, excludeHosts)) {
return [input, init];
}
const { url: nextUrl, originalPath } = routedUrlForOpenCode(upstream, proxy);
@@ -12723,8 +12750,8 @@ function headersForNodeRequest(options, upstream, originalPath, project) {
});
return result;
}
-function routedNodeOptions(parts, proxy, project) {
- if (!parts.url || !shouldRoute(parts.url, proxy)) {
+function routedNodeOptions(parts, proxy, project, excludeHosts) {
+ if (!parts.url || !shouldRoute(parts.url, proxy, excludeHosts)) {
return void 0;
}
const { url: nextUrl, originalPath } = routedUrlForOpenCode(parts.url, proxy);
@@ -12765,7 +12792,7 @@ function wrapRequest(originalHttpRequest, originalHttpsRequest, originalRequest)
}
const proxy = normalizeProxyUrl(state.proxyUrl);
const parts = splitNodeArgs(args);
- const nextOptions = routedNodeOptions(parts, proxy, state.project);
+ const nextOptions = routedNodeOptions(parts, proxy, state.project, state.excludeHosts);
if (!nextOptions) {
return Reflect.apply(originalRequest, this, args);
}
@@ -12787,7 +12814,7 @@ function wrapHttp2Connect(originalConnect) {
if (state) {
const proxy = normalizeProxyUrl(state.proxyUrl);
const upstream = authority instanceof URL ? authority : new URL(String(authority));
- if (shouldRoute(upstream, proxy)) {
+ if (shouldRoute(upstream, proxy, state.excludeHosts)) {
throw new Error(
`Headroom OpenCode wrap blocked direct HTTP/2 connection to ${upstream.origin}. Use fetch, http, or https so traffic can be routed through Headroom.`
);
@@ -12797,19 +12824,22 @@ function wrapHttp2Connect(originalConnect) {
};
}
function installHeadroomTransport(options) {
+ const excludeHosts = normalizeExcludeHosts(options.excludeHosts ?? process.env[EXCLUDE_HOSTS_ENV] ?? "");
const existing = getState();
if (existing) {
existing.refs += 1;
existing.proxyUrl = options.proxyUrl;
existing.project = options.project;
+ existing.excludeHosts = excludeHosts;
existing.debug = Boolean(options.debug);
- installProcessEnv(options.proxyUrl);
+ installProcessEnv(options.proxyUrl, excludeHosts);
return () => uninstallHeadroomTransport();
}
const state = {
refs: 1,
proxyUrl: options.proxyUrl,
project: options.project,
+ excludeHosts,
debug: Boolean(options.debug),
originalFetch: globalThis.fetch,
originalHttpRequest: http.request,
@@ -12823,14 +12853,14 @@ function installHeadroomTransport(options) {
originalChildFork: childProcess.fork
};
setState(state);
- installProcessEnv(options.proxyUrl);
+ installProcessEnv(options.proxyUrl, excludeHosts);
globalThis.fetch = async (...args) => {
const current = getState();
if (!current) {
return state.originalFetch(...args);
}
const proxy = normalizeProxyUrl(current.proxyUrl);
- const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project);
+ const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project, current.excludeHosts);
return state.originalFetch(nextInput, nextInit);
};
http.request = wrapRequest(state.originalHttpRequest, state.originalHttpsRequest, state.originalHttpRequest);
@@ -12885,6 +12915,7 @@ var HeadroomPlugin = async (input, options = {}) => {
const uninstallTransport = installHeadroomTransport({
proxyUrl,
project,
+ excludeHosts: pluginOptions.excludeHosts,
debug: pluginOptions.debug
});
return {
diff --git a/headroom/providers/opencode/hook-shim/handler.js b/headroom/providers/opencode/hook-shim/handler.js
index e4e0d7d12..c549f220c 100644
--- a/headroom/providers/opencode/hook-shim/handler.js
+++ b/headroom/providers/opencode/hook-shim/handler.js
@@ -10,6 +10,7 @@ var BASE_URL_HEADER = "x-headroom-base-url";
var ORIGINAL_PATH_HEADER = "x-headroom-original-path";
var PROJECT_HEADER = "x-headroom-project";
var PROXY_ENV = "HEADROOM_OPENCODE_TRANSPORT_PROXY_URL";
+var EXCLUDE_HOSTS_ENV = "HEADROOM_OPENCODE_EXCLUDE_HOSTS";
var STATE_KEY = /* @__PURE__ */ Symbol.for("headroom.opencode.transport");
function getState() {
return globalThis[STATE_KEY];
@@ -31,17 +32,26 @@ function withNodeImportOption(existing, shim) {
}
return parts.join(" ");
}
-function withShimEnv(env, proxyUrl2) {
+function withExcludeHostsEnv(env, excludeHosts) {
+ if (excludeHosts.length > 0) {
+ env[EXCLUDE_HOSTS_ENV] = excludeHosts.join(",");
+ } else {
+ delete env[EXCLUDE_HOSTS_ENV];
+ }
+}
+function withShimEnv(env, proxyUrl2, excludeHosts) {
const nextEnv = { ...env ?? process.env };
nextEnv[PROXY_ENV] = proxyUrl2;
+ withExcludeHostsEnv(nextEnv, excludeHosts);
const shim = shimImportSpecifier();
if (shim) {
nextEnv.NODE_OPTIONS = withNodeImportOption(nextEnv.NODE_OPTIONS, shim);
}
return nextEnv;
}
-function installProcessEnv(proxyUrl2) {
+function installProcessEnv(proxyUrl2, excludeHosts) {
process.env[PROXY_ENV] = proxyUrl2;
+ withExcludeHostsEnv(process.env, excludeHosts);
const shim = shimImportSpecifier();
if (shim) {
process.env.NODE_OPTIONS = withNodeImportOption(process.env.NODE_OPTIONS, shim);
@@ -50,11 +60,11 @@ function installProcessEnv(proxyUrl2) {
function isOptions(value) {
return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof URL);
}
-function injectOptionsEnv(args, optionIndex, proxyUrl2) {
+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, proxyUrl2);
+ existing.env = withShimEnv(existing.env, state.proxyUrl, state.excludeHosts);
if (isOptions(nextArgs[optionIndex])) {
nextArgs[optionIndex] = existing;
} else {
@@ -72,7 +82,7 @@ function wrapSpawn(originalSpawn) {
return Reflect.apply(originalSpawn, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
- return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
+ return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state));
};
}
function wrapExec(originalExec) {
@@ -81,7 +91,7 @@ function wrapExec(originalExec) {
if (!state) {
return Reflect.apply(originalExec, this, args);
}
- return Reflect.apply(originalExec, this, injectOptionsEnv(args, 1, state.proxyUrl));
+ return Reflect.apply(originalExec, this, injectOptionsEnv(args, 1, state));
};
}
function wrapExecFile(originalExecFile) {
@@ -91,7 +101,7 @@ function wrapExecFile(originalExecFile) {
return Reflect.apply(originalExecFile, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
- return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
+ return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state));
};
}
function wrapFork(originalFork) {
@@ -101,7 +111,7 @@ function wrapFork(originalFork) {
return Reflect.apply(originalFork, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
- return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
+ return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state));
};
}
function normalizeProxyUrl(proxyUrl2) {
@@ -111,7 +121,21 @@ function isLoopback(hostname) {
const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
}
-function shouldRoute(url, proxy) {
+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(/^(\*\.|\.)/, "");
+ if (host) {
+ hosts.add(host);
+ }
+ }
+ return [...hosts];
+}
+function isExcludedHost(hostname, excludeHosts) {
+ const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
+ return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
+}
+function shouldRoute(url, proxy, excludeHosts) {
if (url.protocol !== "http:" && url.protocol !== "https:") {
return false;
}
@@ -121,6 +145,9 @@ function shouldRoute(url, proxy) {
if (url.origin === proxy.origin) {
return false;
}
+ if (isExcludedHost(url.hostname, excludeHosts)) {
+ return false;
+ }
return true;
}
function routedUrl(upstream, proxy) {
@@ -174,9 +201,9 @@ function mergeFetchHeaders(input, init, upstream, originalPath = void 0, project
}
return headers;
}
-function withRoutedFetchInput(input, init, proxy, project) {
+function withRoutedFetchInput(input, init, proxy, project, excludeHosts) {
const upstream = requestUrl(input);
- if (!shouldRoute(upstream, proxy)) {
+ if (!shouldRoute(upstream, proxy, excludeHosts)) {
return [input, init];
}
const { url: nextUrl, originalPath } = routedUrlForOpenCode(upstream, proxy);
@@ -244,8 +271,8 @@ function headersForNodeRequest(options, upstream, originalPath, project) {
});
return result;
}
-function routedNodeOptions(parts, proxy, project) {
- if (!parts.url || !shouldRoute(parts.url, proxy)) {
+function routedNodeOptions(parts, proxy, project, excludeHosts) {
+ if (!parts.url || !shouldRoute(parts.url, proxy, excludeHosts)) {
return void 0;
}
const { url: nextUrl, originalPath } = routedUrlForOpenCode(parts.url, proxy);
@@ -286,7 +313,7 @@ function wrapRequest(originalHttpRequest, originalHttpsRequest, originalRequest)
}
const proxy = normalizeProxyUrl(state.proxyUrl);
const parts = splitNodeArgs(args);
- const nextOptions = routedNodeOptions(parts, proxy, state.project);
+ const nextOptions = routedNodeOptions(parts, proxy, state.project, state.excludeHosts);
if (!nextOptions) {
return Reflect.apply(originalRequest, this, args);
}
@@ -308,7 +335,7 @@ function wrapHttp2Connect(originalConnect) {
if (state) {
const proxy = normalizeProxyUrl(state.proxyUrl);
const upstream = authority instanceof URL ? authority : new URL(String(authority));
- if (shouldRoute(upstream, proxy)) {
+ if (shouldRoute(upstream, proxy, state.excludeHosts)) {
throw new Error(
`Headroom OpenCode wrap blocked direct HTTP/2 connection to ${upstream.origin}. Use fetch, http, or https so traffic can be routed through Headroom.`
);
@@ -318,19 +345,22 @@ function wrapHttp2Connect(originalConnect) {
};
}
function installHeadroomTransport(options) {
+ const excludeHosts = normalizeExcludeHosts(options.excludeHosts ?? process.env[EXCLUDE_HOSTS_ENV] ?? "");
const existing = getState();
if (existing) {
existing.refs += 1;
existing.proxyUrl = options.proxyUrl;
existing.project = options.project;
+ existing.excludeHosts = excludeHosts;
existing.debug = Boolean(options.debug);
- installProcessEnv(options.proxyUrl);
+ installProcessEnv(options.proxyUrl, excludeHosts);
return () => uninstallHeadroomTransport();
}
const state = {
refs: 1,
proxyUrl: options.proxyUrl,
project: options.project,
+ excludeHosts,
debug: Boolean(options.debug),
originalFetch: globalThis.fetch,
originalHttpRequest: http.request,
@@ -344,14 +374,14 @@ function installHeadroomTransport(options) {
originalChildFork: childProcess.fork
};
setState(state);
- installProcessEnv(options.proxyUrl);
+ installProcessEnv(options.proxyUrl, excludeHosts);
globalThis.fetch = async (...args) => {
const current = getState();
if (!current) {
return state.originalFetch(...args);
}
const proxy = normalizeProxyUrl(current.proxyUrl);
- const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project);
+ const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project, current.excludeHosts);
return state.originalFetch(nextInput, nextInit);
};
http.request = wrapRequest(state.originalHttpRequest, state.originalHttpsRequest, state.originalHttpRequest);
diff --git a/plugins/opencode/README.md b/plugins/opencode/README.md
index 6d30ac982..0527bc22c 100644
--- a/plugins/opencode/README.md
+++ b/plugins/opencode/README.md
@@ -53,6 +53,22 @@ export default async function plugin(input) {
- exposes the `headroom_retrieve` tool.
- publishes `HEADROOM_PROXY_URL` in the plugin output env.
- defaults to `http://127.0.0.1:8787` when no proxy URL is supplied.
+- skips routing for hosts listed in `excludeHosts` (or `HEADROOM_OPENCODE_EXCLUDE_HOSTS`); those requests go straight upstream with no compression or telemetry.
+
+To keep a provider off the proxy, list its host. An entry matches the host and all of its subdomains, and `.example.com` / `*.example.com` are accepted as spellings of `example.com`:
+
+```jsonc
+// opencode.json
+{
+ "plugin": [["/path/to/headroom/providers/opencode/_dist/entry.opencode.js", { "excludeHosts": ["opencode.ai"] }]]
+}
+```
+
+or, for `headroom wrap opencode` and spawned Node child processes, set the environment variable before launching:
+
+```bash
+HEADROOM_OPENCODE_EXCLUDE_HOSTS="opencode.ai,.corp.internal" headroom wrap opencode
+```
## Retrieve Tool
@@ -100,6 +116,7 @@ The provider config exposes these as `headroom/<model>` and defaults to `headroo
| Variable | Used by | Description |
|---|---|---|
| `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 |
| `OPENCODE_CONFIG_CONTENT` | OpenCode wrapper | Generated OpenCode provider, model, and MCP config |
## License
diff --git a/plugins/opencode/src/plugin.ts b/plugins/opencode/src/plugin.ts
index e9d62fa3f..a9fd39bf4 100644
--- a/plugins/opencode/src/plugin.ts
+++ b/plugins/opencode/src/plugin.ts
@@ -8,6 +8,7 @@ import { installHeadroomTransport } from "./transport.js";
export interface HeadroomOpenCodePluginOptions {
proxyUrl?: string;
project?: string;
+ excludeHosts?: string[];
backend?: string;
debug?: boolean;
}
@@ -36,6 +37,7 @@ export const HeadroomPlugin: Plugin = async (input, options = {}) => {
const uninstallTransport = installHeadroomTransport({
proxyUrl,
project,
+ excludeHosts: pluginOptions.excludeHosts,
debug: pluginOptions.debug,
});
diff --git a/plugins/opencode/src/transport.test.ts b/plugins/opencode/src/transport.test.ts
index f6b2cfff4..ef5ca961c 100644
--- a/plugins/opencode/src/transport.test.ts
+++ b/plugins/opencode/src/transport.test.ts
@@ -438,6 +438,201 @@ describe("Headroom OpenCode transport", () => {
await proxy.close();
});
+ it("keeps HEADROOM_OPENCODE_EXCLUDE_HOSTS hosts and their subdomains off the proxy (#3657)", async () => {
+ const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
+ const originalFetch = globalThis.fetch;
+ const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+
+ try {
+ process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = " opencode.ai, .corp.internal ,, *.Gateway.Example ";
+ installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1" });
+
+ const init = { method: "POST", headers: { authorization: "Bearer test" } };
+ await fetch("https://opencode.ai/zen/v1/responses", init);
+ await fetch("https://API.OpenCode.AI/zen/v1/chat/completions", init);
+ await fetch("https://llm.corp.internal/v1/chat/completions", init);
+ await fetch("https://gateway.example/v1/responses", init);
+ await fetch("https://notopencode.ai/v1/responses", init);
+ await fetch("https://api.anthropic.com/v1/messages", init);
+
+ for (const index of [0, 1, 2, 3]) {
+ expect(typeof fetchMock.mock.calls[index][0]).toBe("string");
+ expect(fetchMock.mock.calls[index][1]).toBe(init);
+ }
+ expect(fetchMock.mock.calls[0][0]).toBe("https://opencode.ai/zen/v1/responses");
+ expect(fetchMock.mock.calls[4][0]).toEqual(new URL("http://127.0.0.1:8787/v1/responses"));
+ expect(new Headers(fetchMock.mock.calls[4][1]?.headers).get("x-headroom-base-url")).toBe(
+ "https://notopencode.ai",
+ );
+ expect(fetchMock.mock.calls[5][0]).toEqual(new URL("http://127.0.0.1:8787/v1/messages"));
+ expect(new Headers(fetchMock.mock.calls[5][1]?.headers).get("x-headroom-base-url")).toBe(
+ "https://api.anthropic.com",
+ );
+ } finally {
+ globalThis.fetch = originalFetch;
+ if (originalExclude === undefined) {
+ delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
+ } else {
+ process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
+ }
+ }
+ });
+
+ it("prefers the excludeHosts option over HEADROOM_OPENCODE_EXCLUDE_HOSTS", async () => {
+ const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
+ const originalFetch = globalThis.fetch;
+ const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+
+ try {
+ process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = "api.anthropic.com";
+ installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["opencode.ai"] });
+
+ await fetch("https://opencode.ai/zen/v1/responses", { method: "POST" });
+ await fetch("https://api.anthropic.com/v1/messages", { method: "POST" });
+
+ expect(fetchMock.mock.calls[0][0]).toBe("https://opencode.ai/zen/v1/responses");
+ expect(fetchMock.mock.calls[1][0]).toEqual(new URL("http://127.0.0.1:8787/v1/messages"));
+ expect(process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBe("opencode.ai");
+ } finally {
+ globalThis.fetch = originalFetch;
+ if (originalExclude === undefined) {
+ delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
+ } else {
+ process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
+ }
+ }
+ });
+
+ it("leaves excluded hosts alone for Node https.request and http2.connect", () => {
+ const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
+ const fakeRequest = { on: vi.fn(), end: vi.fn() };
+ const requestSpy = vi.spyOn(https, "request").mockImplementation(() => fakeRequest as never);
+ const connectSpy = vi.spyOn(http2, "connect").mockImplementation(() => ({}) as never);
+
+ try {
+ installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["opencode.ai"] });
+
+ const options = { method: "POST", headers: { authorization: "Bearer test" } };
+ expect(https.request("https://opencode.ai/zen/v1/responses", options)).toBe(fakeRequest);
+ expect(requestSpy).toHaveBeenCalledWith("https://opencode.ai/zen/v1/responses", options);
+
+ expect(() => http2.connect("https://opencode.ai")).not.toThrow();
+ expect(connectSpy).toHaveBeenCalledWith("https://opencode.ai");
+ expect(() => http2.connect("https://api.openai.com")).toThrow(/blocked direct HTTP\/2 connection/);
+ } finally {
+ uninstallHeadroomTransport();
+ if (originalExclude === undefined) {
+ delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
+ } else {
+ process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
+ }
+ }
+ });
+
+ it("propagates excluded hosts into child process env so the hook-shim matches", () => {
+ const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
+ const originalSpawn = childProcess.spawn;
+ const spawnMock = vi.fn(() => ({ on: vi.fn(), kill: vi.fn(), pid: 123 }));
+ childProcess.spawn = spawnMock as unknown as typeof childProcess.spawn;
+
+ try {
+ delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
+ installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1" });
+ childProcess.spawn("node", ["agent.js"], { env: { PATH: "/bin" } });
+ uninstallHeadroomTransport();
+
+ installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["*.opencode.ai", "corp.internal"] });
+ childProcess.spawn("node", ["agent.js"], { env: { PATH: "/bin" } });
+
+ const plain = (spawnMock.mock.calls[0] as unknown[])[2] as { env: NodeJS.ProcessEnv };
+ const excluded = (spawnMock.mock.calls[1] as unknown[])[2] as { env: NodeJS.ProcessEnv };
+ expect(plain.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBeUndefined();
+ expect(excluded.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBe("opencode.ai,corp.internal");
+ expect(excluded.env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL).toBe("http://127.0.0.1:8787/v1");
+ } finally {
+ uninstallHeadroomTransport();
+ childProcess.spawn = originalSpawn;
+ if (originalExclude === undefined) {
+ delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
+ } else {
+ process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
+ }
+ }
+ });
+
+ it("clears a pre-existing HEADROOM_OPENCODE_EXCLUDE_HOSTS when excludeHosts is explicitly empty", async () => {
+ const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
+ const originalFetch = globalThis.fetch;
+ const originalSpawn = childProcess.spawn;
+ const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+ const spawnMock = vi.fn(() => ({ on: vi.fn(), kill: vi.fn(), pid: 123 }));
+ childProcess.spawn = spawnMock as unknown as typeof childProcess.spawn;
+
+ try {
+ process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = "api.anthropic.com";
+ installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: [] });
+
+ // The option wins in-process: the host is routed, not excluded.
+ await fetch("https://api.anthropic.com/v1/messages", { method: "POST" });
+ expect(fetchMock.mock.calls[0][0]).toEqual(new URL("http://127.0.0.1:8787/v1/messages"));
+
+ // ...and the exported variable mirrors that, so the hook-shim in a child
+ // (default env, custom env, or a custom env carrying the stale value)
+ // resolves the same empty list instead of the pre-existing one.
+ expect(process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBeUndefined();
+ childProcess.spawn("node", ["agent.js"]);
+ childProcess.spawn("node", ["agent.js"], { env: { PATH: "/bin" } });
+ childProcess.spawn("node", ["agent.js"], {
+ env: { PATH: "/bin", HEADROOM_OPENCODE_EXCLUDE_HOSTS: "api.anthropic.com" },
+ });
+ for (const call of spawnMock.mock.calls as unknown[][]) {
+ const options = call[2] as { env: NodeJS.ProcessEnv };
+ expect(options.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBeUndefined();
+ expect(options.env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL).toBe("http://127.0.0.1:8787/v1");
+ }
+ } finally {
+ globalThis.fetch = originalFetch;
+ childProcess.spawn = originalSpawn;
+ if (originalExclude === undefined) {
+ delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
+ } else {
+ process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
+ }
+ }
+ });
+
+ it("keeps the exported variable in step with each re-install's resolved list", () => {
+ const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
+
+ try {
+ delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
+ const first = installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["opencode.ai"] });
+ expect(process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBe("opencode.ai");
+
+ // A second install (refs = 2) that resolves to an empty list clears it...
+ const second = installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: [] });
+ expect(process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBeUndefined();
+
+ // ...and one that resolves to a list sets it again.
+ const third = installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["corp.internal"] });
+ expect(process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBe("corp.internal");
+
+ third();
+ second();
+ first();
+ } finally {
+ uninstallHeadroomTransport();
+ if (originalExclude === undefined) {
+ delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
+ } else {
+ process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
+ }
+ }
+ });
+
it("restores patched transports only after the final disposer", () => {
const originalFetch = globalThis.fetch;
const originalHttpRequest = http.request;
diff --git a/plugins/opencode/src/transport.ts b/plugins/opencode/src/transport.ts
index b4f768eec..5ba85c9a7 100644
--- a/plugins/opencode/src/transport.ts
+++ b/plugins/opencode/src/transport.ts
@@ -11,6 +11,7 @@ const BASE_URL_HEADER = "x-headroom-base-url";
const ORIGINAL_PATH_HEADER = "x-headroom-original-path";
const PROJECT_HEADER = "x-headroom-project";
const PROXY_ENV = "HEADROOM_OPENCODE_TRANSPORT_PROXY_URL";
+const EXCLUDE_HOSTS_ENV = "HEADROOM_OPENCODE_EXCLUDE_HOSTS";
const STATE_KEY = Symbol.for("headroom.opencode.transport");
type FetchArgs = Parameters<typeof fetch>;
@@ -27,6 +28,7 @@ type ChildFork = typeof childProcess.fork;
interface InstallOptions {
proxyUrl: string;
project?: string;
+ excludeHosts?: string[];
debug?: boolean;
}
@@ -34,6 +36,7 @@ interface TransportState {
refs: number;
proxyUrl: string;
project: string | undefined;
+ excludeHosts: string[];
debug: boolean;
originalFetch: typeof fetch;
originalHttpRequest: HttpRequest;
@@ -87,9 +90,26 @@ function withNodeImportOption(existing: string | undefined, shim: string): strin
return parts.join(" ");
}
-function withShimEnv(env: NodeJS.ProcessEnv | Record<string, unknown> | undefined, proxyUrl: string): NodeJS.ProcessEnv {
+// The exported variable mirrors the EFFECTIVE list, not merely a non-empty
+// one: an explicit `excludeHosts: []` overrides a pre-existing variable for
+// this process, so a child that inherited the stale value would bypass hosts
+// the parent routes. Delete it when the resolved list is empty.
+function withExcludeHostsEnv(env: NodeJS.ProcessEnv, excludeHosts: string[]): void {
+ if (excludeHosts.length > 0) {
+ env[EXCLUDE_HOSTS_ENV] = excludeHosts.join(",");
+ } else {
+ delete env[EXCLUDE_HOSTS_ENV];
+ }
+}
+
+function withShimEnv(
+ env: NodeJS.ProcessEnv | Record<string, unknown> | undefined,
+ proxyUrl: string,
+ excludeHosts: string[],
+): NodeJS.ProcessEnv {
const nextEnv = { ...(env ?? process.env) } as NodeJS.ProcessEnv;
nextEnv[PROXY_ENV] = proxyUrl;
+ withExcludeHostsEnv(nextEnv, excludeHosts);
const shim = shimImportSpecifier();
if (shim) {
nextEnv.NODE_OPTIONS = withNodeImportOption(nextEnv.NODE_OPTIONS, shim);
@@ -97,8 +117,9 @@ function withShimEnv(env: NodeJS.ProcessEnv | Record<string, unknown> | undefine
return nextEnv;
}
-function installProcessEnv(proxyUrl: string): void {
+function installProcessEnv(proxyUrl: string, excludeHosts: string[]): void {
process.env[PROXY_ENV] = proxyUrl;
+ withExcludeHostsEnv(process.env, excludeHosts);
const shim = shimImportSpecifier();
if (shim) {
process.env.NODE_OPTIONS = withNodeImportOption(process.env.NODE_OPTIONS, shim);
@@ -109,11 +130,11 @@ function isOptions(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof URL);
}
-function injectOptionsEnv(args: unknown[], optionIndex: number, proxyUrl: string): unknown[] {
+function injectOptionsEnv(args: unknown[], optionIndex: number, state: TransportState): unknown[] {
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, proxyUrl);
+ existing.env = withShimEnv(existing.env as NodeJS.ProcessEnv | undefined, state.proxyUrl, state.excludeHosts);
if (isOptions(nextArgs[optionIndex])) {
nextArgs[optionIndex] = existing;
@@ -134,7 +155,7 @@ function wrapSpawn(originalSpawn: ChildSpawn): ChildSpawn {
return Reflect.apply(originalSpawn, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
- return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
+ return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state));
} as ChildSpawn;
}
@@ -144,7 +165,7 @@ function wrapExec(originalExec: ChildExec): ChildExec {
if (!state) {
return Reflect.apply(originalExec, this, args);
}
- return Reflect.apply(originalExec, this, injectOptionsEnv(args, 1, state.proxyUrl));
+ return Reflect.apply(originalExec, this, injectOptionsEnv(args, 1, state));
} as ChildExec;
}
@@ -155,7 +176,7 @@ function wrapExecFile(originalExecFile: ChildExecFile): ChildExecFile {
return Reflect.apply(originalExecFile, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
- return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
+ return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state));
} as ChildExecFile;
}
@@ -166,7 +187,7 @@ function wrapFork(originalFork: ChildFork): ChildFork {
return Reflect.apply(originalFork, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
- return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
+ return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state));
} as ChildFork;
}
@@ -179,7 +200,28 @@ function isLoopback(hostname: string): boolean {
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
}
-function shouldRoute(url: URL, proxy: URL): boolean {
+// "example.com", ".example.com" and "*.example.com" all mean the host itself
+// plus every subdomain. Entries are bare hosts: no scheme, port, or path. A
+// string is the comma-separated env form; plugin options arrive from untyped
+// JSON, so a lone string there is treated the same way instead of iterated
+// character by character.
+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(/^(\*\.|\.)/, "");
+ if (host) {
+ hosts.add(host);
+ }
+ }
+ return [...hosts];
+}
+
+function isExcludedHost(hostname: string, excludeHosts: string[]): boolean {
+ const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
+ return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
+}
+
+function shouldRoute(url: URL, proxy: URL, excludeHosts: string[]): boolean {
if (url.protocol !== "http:" && url.protocol !== "https:") {
return false;
}
@@ -189,6 +231,9 @@ function shouldRoute(url: URL, proxy: URL): boolean {
if (url.origin === proxy.origin) {
return false;
}
+ if (isExcludedHost(url.hostname, excludeHosts)) {
+ return false;
+ }
return true;
}
@@ -255,9 +300,15 @@ function mergeFetchHeaders(
return headers;
}
-function withRoutedFetchInput(input: RequestInfo | URL, init: RequestInit | undefined, proxy: URL, project: string | undefined): FetchArgs {
+function withRoutedFetchInput(
+ input: RequestInfo | URL,
+ init: RequestInit | undefined,
+ proxy: URL,
+ project: string | undefined,
+ excludeHosts: string[],
+): FetchArgs {
const upstream = requestUrl(input);
- if (!shouldRoute(upstream, proxy)) {
+ if (!shouldRoute(upstream, proxy, excludeHosts)) {
return [input, init];
}
@@ -340,8 +391,13 @@ function headersForNodeRequest(
return result;
}
-function routedNodeOptions(parts: NodeRequestParts, proxy: URL, project: string | undefined): Record<string, unknown> | undefined {
- if (!parts.url || !shouldRoute(parts.url, proxy)) {
+function routedNodeOptions(
+ parts: NodeRequestParts,
+ proxy: URL,
+ project: string | undefined,
+ excludeHosts: string[],
+): Record<string, unknown> | undefined {
+ if (!parts.url || !shouldRoute(parts.url, proxy, excludeHosts)) {
return undefined;
}
@@ -390,7 +446,7 @@ function wrapRequest(
const proxy = normalizeProxyUrl(state.proxyUrl);
const parts = splitNodeArgs(args);
- const nextOptions = routedNodeOptions(parts, proxy, state.project);
+ const nextOptions = routedNodeOptions(parts, proxy, state.project, state.excludeHosts);
if (!nextOptions) {
return Reflect.apply(originalRequest, this, args);
}
@@ -415,7 +471,7 @@ function wrapHttp2Connect(originalConnect: Http2Connect): Http2Connect {
if (state) {
const proxy = normalizeProxyUrl(state.proxyUrl);
const upstream = authority instanceof URL ? authority : new URL(String(authority));
- if (shouldRoute(upstream, proxy)) {
+ if (shouldRoute(upstream, proxy, state.excludeHosts)) {
throw new Error(
`Headroom OpenCode wrap blocked direct HTTP/2 connection to ${upstream.origin}. ` +
"Use fetch, http, or https so traffic can be routed through Headroom.",
@@ -427,13 +483,15 @@ function wrapHttp2Connect(originalConnect: Http2Connect): Http2Connect {
}
export function installHeadroomTransport(options: InstallOptions): () => void {
+ const excludeHosts = normalizeExcludeHosts(options.excludeHosts ?? process.env[EXCLUDE_HOSTS_ENV] ?? "");
const existing = getState();
if (existing) {
existing.refs += 1;
existing.proxyUrl = options.proxyUrl;
existing.project = options.project;
+ existing.excludeHosts = excludeHosts;
existing.debug = Boolean(options.debug);
- installProcessEnv(options.proxyUrl);
+ installProcessEnv(options.proxyUrl, excludeHosts);
return () => uninstallHeadroomTransport();
}
@@ -441,6 +499,7 @@ export function installHeadroomTransport(options: InstallOptions): () => void {
refs: 1,
proxyUrl: options.proxyUrl,
project: options.project,
+ excludeHosts,
debug: Boolean(options.debug),
originalFetch: globalThis.fetch,
originalHttpRequest: http.request,
@@ -455,14 +514,14 @@ export function installHeadroomTransport(options: InstallOptions): () => void {
};
setState(state);
- installProcessEnv(options.proxyUrl);
+ installProcessEnv(options.proxyUrl, excludeHosts);
globalThis.fetch = async (...args: FetchArgs) => {
const current = getState();
if (!current) {
return state.originalFetch(...args);
}
const proxy = normalizeProxyUrl(current.proxyUrl);
- const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project);
+ const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project, current.excludeHosts);
return state.originalFetch(nextInput, nextInit);
};