Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 36 additions & 8 deletions src/launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3868,10 +3868,38 @@ const INHERITED_PROXY_VARS = [
"NO_PROXY",
];

/** #3521: internal launcher→child channels carrying THIS launch's options into
* the spawned proxy child. They are not user configuration (CONFIGURATION.md:
* "Only the launcher sets it — no user configuration") and only the proxy
* child reads them (server.ts / context-window.ts). A value left in the parent
* env by an earlier spawn (long-lived desktop hosts, test harnesses, nested
* launches) must not ride along: the child would record it in its instance
* file, later launches with different options fail attach
* (model-windows-mismatch / lane-mismatch), and the replacement dies on the
* twin-collision path. Stripped from every child env here; the spawn site
* re-injects exactly what the current options supply. */
const INTERNAL_LAUNCHER_CHANNEL_VARS = [
"BILI_LAUNCHER_LANE",
"BILI_LAUNCHER_MODEL_WINDOWS",
"BILI_LAUNCHER_MODEL_MAX_OUTPUTS",
"BILI_STRICT_PORT",
];

/** #3521: remove ONLY the internal launcher channels, keeping everything else
* (including the user's own proxy vars) intact. For the client lanes whose
* base env is passed through verbatim because bili does not route them via
* proxy envs (dsh/kimi/mcode/aider with no routable providers, codex and
* claude direct-URL mode) — the channels must still never cross the boundary. */
export function stripInternalLauncherChannels(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
const cleaned: NodeJS.ProcessEnv = { ...env };
for (const key of INTERNAL_LAUNCHER_CHANNEL_VARS) delete cleaned[key];
return cleaned;
}

export function stripInheritedProxy(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
const cleaned: NodeJS.ProcessEnv = { ...env };
for (const key of INHERITED_PROXY_VARS) delete cleaned[key];
return cleaned;
return stripInternalLauncherChannels(cleaned);
}

/** #1012: capture the user's proxy vars BEFORE stripping, so the launcher can
Expand Down Expand Up @@ -5101,7 +5129,7 @@ export async function runLaunch(params: RunLaunchParams, deps: LauncherDeps = {}
// through them, so a launch with no non-loopback custom providers behaves
// exactly as before.
const usesProxyEnv = routes.httpsDomains.length > 0 || routes.httpEnvRoutes.length > 0;
env = usesProxyEnv ? stripInheritedProxy(process.env) : { ...process.env };
env = usesProxyEnv ? stripInheritedProxy(process.env) : stripInternalLauncherChannels(process.env);
env.BILLION_CONTEXT_PROXY = origin;
env.DEEPSEEK_BASE_URL = wrapUpstream(origin, "https://api.deepseek.com");
if (usesProxyEnv) {
Expand Down Expand Up @@ -5191,7 +5219,7 @@ export async function runLaunch(params: RunLaunchParams, deps: LauncherDeps = {}
// W − reserved_context_size (~95% of window), which ACP compression
// (~55% once windows align via BILI_LAUNCHER_MODEL_WINDOWS) precedes.
const usesProxyEnv = routes.httpsDomains.length > 0 || routes.httpEnvRoutes.length > 0;
env = usesProxyEnv ? stripInheritedProxy(process.env) : { ...process.env };
env = usesProxyEnv ? stripInheritedProxy(process.env) : stripInternalLauncherChannels(process.env);
if (usesProxyEnv) {
const caBundle = resolveCombinedCaPath(process.env);
env.HTTPS_PROXY = origin;
Expand Down Expand Up @@ -5220,7 +5248,7 @@ export async function runLaunch(params: RunLaunchParams, deps: LauncherDeps = {}
// auto-compaction fires on input-token footprint, which ACP compression
// precedes once windows align via BILI_LAUNCHER_MODEL_WINDOWS.
const usesProxyEnv = routes.httpsDomains.length > 0 || routes.httpEnvRoutes.length > 0;
env = usesProxyEnv ? stripInheritedProxy(process.env) : { ...process.env };
env = usesProxyEnv ? stripInheritedProxy(process.env) : stripInternalLauncherChannels(process.env);
if (usesProxyEnv) {
const caBundle = resolveCombinedCaPath(process.env);
env.HTTPS_PROXY = origin;
Expand Down Expand Up @@ -5320,7 +5348,7 @@ export async function runLaunch(params: RunLaunchParams, deps: LauncherDeps = {}
const usesProxyEnv = routes.httpsDomains.length > 0 || routes.httpEnvRoutes.length > 0;
env = usesProxyEnv
? buildAiderEnv(origin, resolveCombinedCaPath(process.env), stripInheritedProxy(process.env), routes.httpEnvRoutes.length > 0)
: { ...process.env };
: stripInternalLauncherChannels(process.env);
if (routes.httpRewrites.length > 0) {
console.error(
`bili: ${routes.httpRewrites.length} loopback endpoint(s) declared for aider bypass NO_PROXY and will NOT go through the proxy — point their base URL at ${origin}/bili/<url> manually (e.g. via --openai-api-base) to compress them.`,
Expand Down Expand Up @@ -5387,7 +5415,7 @@ export async function runLaunch(params: RunLaunchParams, deps: LauncherDeps = {}
const codexConversationId = injectMcp ? randomUUID() : undefined;
const codexCaPath = resolveCombinedCaPath(process.env);
if (directUrl) {
env = { ...process.env, BILLION_CONTEXT_PROXY: origin };
env = { ...stripInternalLauncherChannels(process.env), BILLION_CONTEXT_PROXY: origin };
} else {
env = buildCodexEnv(origin, codexCaPath, stripInheritedProxy(process.env));
clientArgs = buildCodexArgs(origin, routes.httpRewrites, routes.httpsRewrites, clientArgs);
Expand Down Expand Up @@ -5464,8 +5492,8 @@ export async function runLaunch(params: RunLaunchParams, deps: LauncherDeps = {}
// table in buildClientEnv, per-key).
const claudeVertex = claudeVertexUpstream(config.claude);
env = directUrl
? buildClaudePluginEnv(origin, true, process.env, claudeVertex)
: buildClaudeEnv(origin, ca, routes.httpRewrites, routes.httpsRewrites, process.env);
? buildClaudePluginEnv(origin, true, stripInternalLauncherChannels(process.env), claudeVertex)
: buildClaudeEnv(origin, ca, routes.httpRewrites, routes.httpsRewrites, stripInternalLauncherChannels(process.env));
if (directUrl) env.BILLION_CONTEXT_PROXY = origin;
// An unroutable Vertex lane is a warning, not a silent downgrade: the
// client would call Google directly and bili would see nothing at all.
Expand Down
110 changes: 110 additions & 0 deletions tests/launcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
opencodeMajorVersion,
parseOpencodeMajor,
stripInheritedProxy,
stripInternalLauncherChannels,
resolvePiHome,
resolveOmpHome,
extractDomains,
Expand Down Expand Up @@ -3284,6 +3285,115 @@ test("stripInheritedProxy: removes generic proxy redirector vars, keeps the rest
assert.equal(cleaned.HOME, "/home/dog", "HOME kept");
});

// #3521: the verbatim-passthrough client lanes (no routable providers, direct-URL
// mode) must keep the user's OWN proxy vars while losing every internal channel.
test("stripInternalLauncherChannels: #3521 removes only the internal channels, keeps user proxy vars", () => {
const cleaned = stripInternalLauncherChannels({
BILI_LAUNCHER_LANE: "pi",
BILI_LAUNCHER_MODEL_WINDOWS: JSON.stringify({ "stale-model": 12345 }),
BILI_LAUNCHER_MODEL_MAX_OUTPUTS: JSON.stringify({ "stale-model": 999 }),
BILI_STRICT_PORT: "1",
http_proxy: "http://corp:20172",
HTTPS_PROXY: "http://corp:20172",
PATH: "/usr/bin",
});
for (const k of ["BILI_LAUNCHER_LANE", "BILI_LAUNCHER_MODEL_WINDOWS", "BILI_LAUNCHER_MODEL_MAX_OUTPUTS", "BILI_STRICT_PORT"]) {
assert.equal(cleaned[k], undefined, `${k} should be stripped`);
}
assert.equal(cleaned.http_proxy, "http://corp:20172", "user's own lowercase proxy var survives");
assert.equal(cleaned.HTTPS_PROXY, "http://corp:20172", "user's own uppercase proxy var survives");
assert.equal(cleaned.PATH, "/usr/bin", "PATH kept");
});

// #3521: internal launcher channels are not user configuration — a value left
// behind by an earlier spawn must not survive sanitization, while user-facing
// env (BILI_MITM_DOMAINS is the config twin of mitm.domains) must.
test("stripInheritedProxy: #3521 strips inherited internal launcher channels, keeps user-facing vars", () => {
const cleaned = stripInheritedProxy({
BILI_LAUNCHER_LANE: "pi",
BILI_LAUNCHER_MODEL_WINDOWS: JSON.stringify({ "stale-model": 12345 }),
BILI_LAUNCHER_MODEL_MAX_OUTPUTS: JSON.stringify({ "stale-model": 999 }),
BILI_STRICT_PORT: "1",
BILI_MITM_DOMAINS: "api.example.com",
PATH: "/usr/bin",
});
for (const k of ["BILI_LAUNCHER_LANE", "BILI_LAUNCHER_MODEL_WINDOWS", "BILI_LAUNCHER_MODEL_MAX_OUTPUTS", "BILI_STRICT_PORT"]) {
assert.equal(cleaned[k], undefined, `${k} should be stripped`);
}
assert.equal(cleaned.BILI_MITM_DOMAINS, "api.example.com", "user-facing mitm domains kept");
assert.equal(cleaned.PATH, "/usr/bin", "PATH kept");
});

// #3521: an earlier spawn left its options in THIS process's env (long-lived
// desktop host, test harness). They must not ride into the next proxy child:
// the child records them in its instance file, later launches with different
// options fail attach (model-windows-mismatch) and die on the twin-collision
// path. Current options are still injected fresh on top of the clean env.
test("ensureProxyRunning: #3521 inherited launcher channels never reach the spawned proxy", async () => {
const channelKeys = ["BILI_LAUNCHER_LANE", "BILI_LAUNCHER_MODEL_WINDOWS", "BILI_LAUNCHER_MODEL_MAX_OUTPUTS", "BILI_STRICT_PORT"] as const;
const saved: Record<string, string | undefined> = {};
for (const k of channelKeys) saved[k] = process.env[k];
let liveInst: InstanceFile | undefined;
const spawns: Array<NodeJS.ProcessEnv> = [];
const spawnImpl: SpawnFn = (_cmd, _args, options) => {
const env = options.env ?? {};
spawns.push(env);
const pid = 42900 + spawns.length;
// The child records whatever lane/windows it was handed — here the
// poisoned values, so launch two below cannot attach (lane-mismatch)
// and must spawn, exactly like the real repro.
liveInst = recordedInstance({ pid, lane: env.BILI_LAUNCHER_LANE ?? "stale-lane", modelWindows: { "stale-model": 12345 }, launchToken: env.BILI_LAUNCH_TOKEN });
return makeFakeChild(pid);
};
const deps = {
spawnImpl,
fetchImpl: async () => ({ ok: true }),
fetchHealthInfo: async () => ({ ok: true, instanceId: liveInst?.instanceId ?? "inst-1", pid: liveInst?.pid, watchdog: { armed: true } }),
readInstanceFile: () => liveInst,
sleep: () => Promise.resolve(),
scriptPath: FP_SCRIPT,
};
try {
process.env.BILI_LAUNCHER_LANE = "stale-lane";
process.env.BILI_LAUNCHER_MODEL_WINDOWS = JSON.stringify({ "stale-model": 12345 });
process.env.BILI_LAUNCHER_MODEL_MAX_OUTPUTS = JSON.stringify({ "stale-model": 999 });
process.env.BILI_STRICT_PORT = "1";

await ensureProxyRunning(
{ host: "127.0.0.1", port: 8787, passthrough: false, debug: false },
deps,
);
assert.equal(spawns.length, 1, "first launch spawns");
for (const k of channelKeys) {
assert.equal(spawns[0][k], undefined, `${k} must not ride along from the parent env`);
}

await ensureProxyRunning(
{
host: "127.0.0.1",
port: 8787,
passthrough: false,
debug: false,
lane: "pi",
modelWindows: { "current-model": 200000 },
modelMaxOutputs: { "current-model": 64000 },
strictPort: true,
},
deps,
);
assert.equal(spawns.length, 2, "lane-mismatch against the recorded stale lane forces a fresh spawn");
assert.equal(spawns[1].BILI_LAUNCHER_LANE, "pi", "current lane is injected fresh");
assert.equal(spawns[1].BILI_LAUNCHER_MODEL_WINDOWS, JSON.stringify({ "current-model": 200000 }), "current windows replace, not merge with, stale ones");
assert.equal(spawns[1].BILI_LAUNCHER_MODEL_MAX_OUTPUTS, JSON.stringify({ "current-model": 64000 }), "current max outputs replace, not merge with, stale ones");
assert.equal(spawns[1].BILI_STRICT_PORT, "1", "explicit strict port still crosses the boundary");
} finally {
for (const k of channelKeys) {
if (saved[k] === undefined) delete process.env[k];
else process.env[k] = saved[k];
}
}
});

test("parseOmpYaml: reads providers.<name>.baseUrl (skips non-matching)", () => {
const yml = [
"providers:",
Expand Down
Loading