fix(opencode): route configured compatible provider bases

The #4747 fix decided whether to send an LLM call to Headroom from the
request path alone, so it could only recognise wire roots it had names for
(a version segment, `api`, a short list of provider roots). An OpenAI-
compatible provider configured at `https://gateway.invalid/tenant/acme` has
no such segment, so OpenCode 1.x sent its `/tenant/acme/chat/completions`
through the patched fetch straight to the gateway: no compression, no
telemetry, silently. That also disagreed with the plugin's own
`modelBaseRoutesThroughProxy`, which already accepts that base.

OpenCode's configuration is the real authority on where a provider mounts
its wire, so the transport now learns the configured base URLs instead of
guessing from the path:

- `installHeadroomTransport` takes `wireRoots`, exported to children through
  `HEADROOM_OPENCODE_WIRE_ROOTS` so the `--import` shim routes the same bases.
- `setHeadroomWireRoots` widens a live transport when the bases arrive later.
  The plugin does not block startup on them: 1.x reads `client.config.get()` /
  `client.provider.list()` without awaiting and widens on resolve, 2.x reads
  the bases its own model transform already sees.
- A configured base is matched by origin plus path prefix and still requires a
  wire endpoint, so an unrelated path on that host (`/tenant/acme/files/1`)
  passes through, and Discord's `/api/v10/.../messages` and a forms API's
  `/forms/123/responses` stay out.
- The path heuristics from the earlier fix remain the fallback for when no
  configuration is available.

Tests cover the fetch and Node request paths for `/tenant/acme`, the
non-endpoint pass-through on the same host, a same-path different-origin
negative, and the plugin wiring the resolved config into the transport. The
committed standalone bundles are rebuilt byte-identically.
This commit is contained in:
Parideboy
2026-11-10 19:40:35 +01:00
parent b695e69744
commit 98b5ba2aa9
7 changed files with 554 additions and 50 deletions
+149 -19
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;
}
@@ -19975,6 +19990,30 @@ function isExcludedHost(hostname3, excludeHosts) {
const normalized = canonicalHostname(hostname3);
return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
}
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) {
@@ -19985,14 +20024,18 @@ function hasWireRootBefore(body) {
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) {
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)) {
return hasWireRootBefore(pathname.slice(0, -suffix.length));
if (!pathname.endsWith(suffix)) {
continue;
}
if (isConfiguredWireRoot(origin, pathname, wireRoots)) {
return true;
}
return hasWireRootBefore(pathname.slice(0, -suffix.length));
}
return false;
}
@@ -20014,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 {
@@ -20078,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);
@@ -20152,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);
@@ -20197,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);
}
@@ -20220,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 = {
@@ -20236,6 +20291,7 @@ function installHeadroomTransport(options) {
proxyUrl: options.proxyUrl,
project: options.project,
excludeHosts,
wireRoots,
debug: Boolean(options.debug),
sessionToken: options.sessionToken,
originalFetch: globalThis.fetch,
@@ -20251,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) {
@@ -20261,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);
@@ -20276,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) {
@@ -20302,6 +20379,37 @@ 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 settled = [client.config?.get?.(), client.provider?.list?.()];
void Promise.allSettled(settled).then(([configResult, providerResult]) => {
const config2 = configResult?.status === "fulfilled" ? configResult.value : void 0;
const providers = providerResult?.status === "fulfilled" ? providerResult.value : void 0;
onResolved(
collectBaseUrls(config2?.data ?? config2, providers?.data ?? providers)
);
}).catch(() => {
});
}
function normalizeProxyUrl2(url2) {
return trimTrailingSlashes(url2);
}
@@ -20366,6 +20474,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);
@@ -20376,7 +20495,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 () => {
@@ -20410,10 +20535,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) => {
@@ -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;
}
@@ -190,6 +205,30 @@ function isExcludedHost(hostname, excludeHosts) {
const normalized = canonicalHostname(hostname);
return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
}
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) {
@@ -200,14 +239,18 @@ function hasWireRootBefore(body) {
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) {
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)) {
return hasWireRootBefore(pathname.slice(0, -suffix.length));
if (!pathname.endsWith(suffix)) {
continue;
}
if (isConfiguredWireRoot(origin, pathname, wireRoots)) {
return true;
}
return hasWireRootBefore(pathname.slice(0, -suffix.length));
}
return false;
}
@@ -229,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);
@@ -286,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);
@@ -360,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);
@@ -405,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);
}
@@ -428,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 = {
@@ -444,6 +499,7 @@ function installHeadroomTransport(options) {
proxyUrl: options.proxyUrl,
project: options.project,
excludeHosts,
wireRoots,
debug: Boolean(options.debug),
sessionToken: options.sessionToken,
originalFetch: globalThis.fetch,
@@ -459,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) {
@@ -469,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
+43
View File
@@ -85,6 +85,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 +123,42 @@ 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("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");
+87
View File
@@ -17,6 +17,7 @@ import {
installHeadroomTransport,
modelBaseRoutesThroughProxy,
normalizeExcludeHosts,
setHeadroomWireRoots,
} from "./transport.js";
export interface HeadroomOpenCodePluginOptions {
@@ -26,10 +27,70 @@ 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.
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 settled = [client.config?.get?.(), client.provider?.list?.()];
void Promise.allSettled(settled)
.then(([configResult, providerResult]) => {
const config = configResult?.status === "fulfilled" ? configResult.value : undefined;
const providers = providerResult?.status === "fulfilled" ? providerResult.value : undefined;
onResolved(
collectBaseUrls((config as { data?: unknown })?.data ?? config, (providers as { data?: unknown })?.data ?? providers),
);
})
.catch(() => {
// Routing stays on the path heuristics; not worth failing a session for.
});
}
function normalizeProxyUrl(url: string): string {
return trimTrailingSlashes(url);
}
@@ -144,6 +205,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 +235,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 +283,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) => {
+58
View File
@@ -345,6 +345,64 @@ describe("Headroom OpenCode transport", () => {
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);
+134 -14
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;
}
@@ -302,6 +323,52 @@ function isExcludedHost(hostname: string, excludeHosts: string[]): boolean {
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.
@@ -359,14 +426,21 @@ function hasWireRootBefore(body: string): boolean {
// suffix so that lookalike paths containing the marker but not ending with it
// (e.g. /v1/models/gemini:generateContent/status) remain unrouted. They are
// specific enough to need no wire root.
function isLlmEndpointPath(pathname: string): boolean {
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)) {
return hasWireRootBefore(pathname.slice(0, -suffix.length));
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;
}
@@ -395,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.
@@ -490,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];
}
@@ -586,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;
}
@@ -639,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);
}
@@ -670,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();
}
@@ -687,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,
@@ -703,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) {
@@ -713,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);
};
@@ -731,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) {