From c2567cc2b295aa8a845ef83bf21364328166a35c Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Mon, 31 Aug 2026 22:34:27 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20instance=20governance=20=E2=80=94?= =?UTF-8?q?=20attach,=20liveness,=20handshake,=20graceful=20exit,=20atomic?= =?UTF-8?q?=20state=20(#417)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit L1 identity: proxy-origin file upgraded to JSON {origin, instanceId, pid, startedAt, config fingerprint, launchToken} with atomic writes and legacy plain-string read compatibility; /__bili/health echoes instanceId/pid/startedAt (#403 read side). L2 attach-or-spawn (#394): ensureProxyRunning attaches to a healthy, config-compatible instance instead of doubling writers over one sessions dir; stateDir instances.json registry prunes dead pids and warns loudly on dual live instances. L3 handshake (#407): no more probe-release-rebind TOCTOU — the child self- binds, retries EADDRINUSE (+1 up to 16, then ephemeral) when launched with BILI_LAUNCH_TOKEN, and reports the real origin via the instance file; forced --debug on spawned proxies removed (12MB/day logs). L4 graceful exit (#414): launcher children watch BILI_PARENT_PID and run the flush path when the parent dies (Windows TerminateProcess never flushed); stopProxy is a no-op kill on win32 (the watcher owns shutdown) and leaves attached instances alone. L5 state hygiene (#406, #403 write side): plugin-conversations.json gets tmp+rename atomic writes, a dirty flag (dying paths no longer rewrite the table), and corrupt-byte preservation + warning instead of silent zeroing; plugin install refuses to freeze dead/unverifiable origins into client configs (BILI_MCP_PROXY still wins). L6 overlay antidote (#410): mergeOverlayEntry threads the generatedFile exclusion through directory recursion (nested models.yml can no longer be promoted into the real home); dead proxy URLs baked into a real models.yml are unpacked mechanically on launch (live origins kept). --- src/instance.ts | 174 ++++++++++++++++++++ src/launcher.ts | 163 +++++++++++++++++-- src/mcp.ts | 9 +- src/plugin-install.ts | 27 +++- src/plugin.ts | 26 ++- src/server.ts | 99 +++++++++--- tests/instance-governance.test.ts | 257 ++++++++++++++++++++++++++++++ tests/launcher.test.ts | 112 ++++++++++++- 8 files changed, 812 insertions(+), 55 deletions(-) create mode 100644 src/instance.ts create mode 100644 tests/instance-governance.test.ts diff --git a/src/instance.ts b/src/instance.ts new file mode 100644 index 0000000000..9458b5d1bf --- /dev/null +++ b/src/instance.ts @@ -0,0 +1,174 @@ +import { randomUUID } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { stateDir } from "./paths.js"; + +/** Instance registry (#394/#403/#417): the proxy-origin file is upgraded from + * a bare URL string to a JSON record identifying the live instance, so + * readers (launcher attach, plugin install, MCP shells) can verify liveness + * and config compatibility before trusting it. Readers from older builds + * treat a JSON body as unreadable and fall back to their default origin; the + * writer and all in-tree readers ship together, so the skew window is one + * restart. */ +export interface ProxyInstanceFile { + origin: string; + instanceId: string; + pid: number; + startedAt: number; + host: string; + port: number; + passthrough: boolean; + mitmDomains: string[]; + modelWindows: Record; + launchToken?: string; +} + +export function isProxyInstanceFile(v: ProxyInstanceFile | { origin: string } | undefined): v is ProxyInstanceFile { + return v !== undefined && "instanceId" in v; +} + +export function readProxyInstanceFile(file?: string): ProxyInstanceFile | { origin: string } | undefined { + let raw: string; + try { + raw = fs.readFileSync(file ?? instanceFilePath(), "utf8").trim(); + } catch { + return undefined; + } + if (raw.startsWith("{")) { + try { + const parsed = JSON.parse(raw) as Partial; + if (typeof parsed.origin === "string" && /^https?:\/\/\S+$/.test(parsed.origin)) { + const windows: Record = {}; + if (parsed.modelWindows && typeof parsed.modelWindows === "object") { + for (const [k, v] of Object.entries(parsed.modelWindows)) { + const n = Number(v); + if (Number.isFinite(n) && n > 0) windows[k] = n; + } + } + return { + origin: parsed.origin, + instanceId: typeof parsed.instanceId === "string" ? parsed.instanceId : "", + pid: typeof parsed.pid === "number" ? parsed.pid : 0, + startedAt: typeof parsed.startedAt === "number" ? parsed.startedAt : 0, + host: typeof parsed.host === "string" ? parsed.host : "", + port: typeof parsed.port === "number" ? parsed.port : 0, + passthrough: Boolean(parsed.passthrough), + mitmDomains: Array.isArray(parsed.mitmDomains) ? parsed.mitmDomains.map(String) : [], + modelWindows: windows, + launchToken: typeof parsed.launchToken === "string" ? parsed.launchToken : undefined, + }; + } + } catch { + // fall through to legacy plain-string parsing + } + } + if (/^https?:\/\/\S+$/.test(raw)) return { origin: raw }; + return undefined; +} + +export function instanceFilePath(): string { + return path.join(stateDir(), "proxy-origin"); +} + +/** tmp+fsync+rename (same shape as web/api.ts atomicWriteConfig) — a torn + * write must never leave a half-origin behind (#406 family). */ +export function atomicWriteInstanceFile(info: ProxyInstanceFile, file?: string): void { + const filePath = file ?? instanceFilePath(); + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`; + let descriptor: number | undefined; + try { + descriptor = fs.openSync(tempPath, "wx", 0o644); + fs.writeSync(descriptor, JSON.stringify(info) + "\n", null, "utf8"); + fs.fsyncSync(descriptor); + fs.closeSync(descriptor); + descriptor = undefined; + fs.renameSync(tempPath, filePath); + } catch (error) { + if (descriptor !== undefined) { + try { + fs.closeSync(descriptor); + } catch {} + } + try { + fs.unlinkSync(tempPath); + } catch {} + throw error; + } +} + +/** Remove our record on shutdown — but only if the file still carries OUR + * instanceId (a newer instance may have legitimately taken it over). */ +export function clearProxyInstanceFile(instanceId: string, file?: string): void { + const filePath = file ?? instanceFilePath(); + const current = readProxyInstanceFile(filePath); + if (isProxyInstanceFile(current) && current.instanceId === instanceId) { + try { + fs.unlinkSync(filePath); + } catch {} + } +} + +/** pid liveness (kill-0). EPERM means the process exists but is owned by + * another user — still alive. */ +export function isPidAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (err) { + return (err as NodeJS.ErrnoException).code === "EPERM"; + } +} + +interface RegistryEntry { + instanceId: string; + pid: number; + port: number; + origin: string; + startedAt: number; +} + +function registryFilePath(): string { + return path.join(stateDir(), "instances.json"); +} + +/** Cross-instance liveness registry (#394): every proxy registers itself at + * listen time; a second live registrant triggers the dual-writer warning. + * Entries whose pid is dead are pruned on read. Best-effort throughout. */ +export function registerInstanceAndWarn(entry: RegistryEntry, warn: (msg: string) => void): void { + const file = registryFilePath(); + const entries: RegistryEntry[] = []; + try { + const parsed = JSON.parse(fs.readFileSync(file, "utf8")) as { instances?: RegistryEntry[] }; + if (Array.isArray(parsed.instances)) { + for (const e of parsed.instances) { + if (e && typeof e.instanceId === "string" && e.instanceId !== entry.instanceId && isPidAlive(e.pid)) { + entries.push(e); + } + } + } + } catch {} + for (const other of entries) { + warn( + `another bili instance is running (pid ${other.pid}, ${other.origin}) — both processes will write the same sessions directory; stop one to avoid state pollution (#394)`, + ); + } + entries.push(entry); + try { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, JSON.stringify({ instances: entries }) + "\n"); + } catch {} +} + +export function unregisterInstance(instanceId: string): void { + const file = registryFilePath(); + try { + const parsed = JSON.parse(fs.readFileSync(file, "utf8")) as { instances?: RegistryEntry[] }; + if (!Array.isArray(parsed.instances)) return; + const kept = parsed.instances.filter( + (e) => !(e && typeof e.instanceId === "string" && e.instanceId === instanceId) && isPidAlive(e.pid), + ); + fs.writeFileSync(file, JSON.stringify({ instances: kept }) + "\n"); + } catch {} +} diff --git a/src/launcher.ts b/src/launcher.ts index d34e4c6d4f..9ecca8b132 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -33,6 +33,7 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import { spawn, type StdioOptions } from "node:child_process"; import { DEFAULT_MITM_DOMAINS } from "./mitm.js"; +import { isProxyInstanceFile, isPidAlive, readProxyInstanceFile, type ProxyInstanceFile } from "./instance.js"; import { selfPackageRoot, isBiliPiEntry, ompPluginLoadedFrom } from "./plugin-install.js"; /** Absolute path of a file inside our dist/, resolved via the package root @@ -122,12 +123,15 @@ export interface LaunchOptions { export interface ProxyHandle { origin: string; port: number; - child: SpawnChild; + child?: SpawnChild; logPath?: string; + attached?: boolean; } export interface LauncherDeps { fetchImpl?: (url: string) => Promise<{ ok: boolean }>; + fetchHealthInfo?: (origin: string) => Promise<{ ok: boolean; instanceId?: string } | undefined>; + readInstanceFile?: () => ProxyInstanceFile | { origin: string } | undefined; spawnImpl?: SpawnFn; now?: () => number; sleep?: (ms: number) => Promise; @@ -860,7 +864,7 @@ function refreshOverlayHome(realHome: string, overlay: string, generatedFile: st try { fs.unlinkSync(overlayPath); } catch {} - } else if (mergeOverlayEntry(overlayPath, realPath)) { + } else if (mergeOverlayEntry(overlayPath, realPath, generatedFile)) { try { fs.rmSync(overlayPath, { recursive: true, force: true }); } catch {} @@ -921,7 +925,7 @@ function refreshOverlayHome(realHome: string, overlay: string, generatedFile: st return true; } -function mergeOverlayEntry(src: string, dst: string): boolean { +function mergeOverlayEntry(src: string, dst: string, excludedName?: string): boolean { let st: fs.Stats; try { st = fs.lstatSync(src); @@ -954,7 +958,11 @@ function mergeOverlayEntry(src: string, dst: string): boolean { } let ok = true; for (const entry of entries) { - if (!mergeOverlayEntry(path.join(src, entry), path.join(dst, entry))) ok = false; + // #410: generated configs must never merge back into the real + // home, at ANY depth — a nested promote bakes proxy URLs into + // the user's real config. + if (excludedName !== undefined && entry === excludedName) continue; + if (!mergeOverlayEntry(path.join(src, entry), path.join(dst, entry), excludedName)) ok = false; } return ok; } @@ -1084,14 +1092,71 @@ export function preparePiHttpRewrite( * refreshOverlayHome — comments, ordering and formatting are preserved * verbatim, and the real models.yml is never touched. */ +function atomicWriteTextFile(filePath: string, contents: string): void { + const draft = `${filePath}.${process.pid}.bili-tmp`; + try { + fs.writeFileSync(draft, contents); + fs.renameSync(draft, filePath); + } catch { + try { + fs.rmSync(draft, { force: true }); + } catch {} + throw new Error(`bili: could not write ${filePath}`); + } +} + +export function liveProxyPorts(): Set { + const ports = new Set(); + const inst = readProxyInstanceFile(); + if (isProxyInstanceFile(inst)) { + if (isPidAlive(inst.pid)) ports.add(inst.port); + } else if (inst) { + try { + ports.add(new URL(inst.origin).port === "" ? 80 : Number(new URL(inst.origin).port)); + } catch {} + } + return ports; +} + +/** #410: repair a real config that had proxy-prefixed URLs baked in. The + * original upstream is embedded in the /bili/ path, so dead-origin wraps + * unpack mechanically; a LIVE origin is left alone (the user may have + * pointed the config at a running proxy deliberately). */ +export function unpackDeadProxyUrlsInFile(filePath: string, livePorts: Set): number { + let txt: string; + try { + txt = fs.readFileSync(filePath, "utf8"); + } catch { + return 0; + } + const re = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)\/bili\/(https?:\/\/\S+)/g; + let changed = 0; + const out = txt.replace(re, (full, portStr: string, raw: string) => { + if (livePorts.has(Number(portStr))) return full; + changed += 1; + return raw; + }); + if (changed === 0) return 0; + try { + atomicWriteTextFile(filePath, out); + } catch { + return 0; + } + return changed; +} + export function prepareOmpHttpRewrite( ompHome: string, origin: string, httpRewrites: HttpRewrite[], httpsRewrites: HttpRewrite[], ): string | undefined { - if (httpRewrites.length === 0 && httpsRewrites.length === 0) return undefined; const modelsPath = path.join(ompHome, "models.yml"); + const unpacked = unpackDeadProxyUrlsInFile(modelsPath, liveProxyPorts()); + if (unpacked > 0) { + console.error(`bili: unpacked ${unpacked} dead proxy URL(s) from the real ${modelsPath}`); + } + if (httpRewrites.length === 0 && httpsRewrites.length === 0) return undefined; let txt: string; try { txt = fs.readFileSync(modelsPath, "utf8"); @@ -1452,6 +1517,45 @@ async function probeHealth( } } +interface HealthInfo { + ok: boolean; + instanceId?: string; +} + +async function fetchHealthInfoDefault(origin: string): Promise { + try { + const res = await fetch(healthUrl(origin), { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) }); + if (!res.ok) return undefined; + const data = (await res.json()) as { ok?: boolean; instanceId?: string }; + return { ok: Boolean(data.ok), instanceId: typeof data.instanceId === "string" ? data.instanceId : undefined }; + } catch { + return undefined; + } +} + +function instanceCompatible(inst: ProxyInstanceFile, opts: LaunchOptions): boolean { + if (inst.host !== opts.host || inst.passthrough !== opts.passthrough) return false; + const wantDomains = opts.mitmDomains ?? []; + if (inst.mitmDomains.length !== wantDomains.length || inst.mitmDomains.some((d, i) => d !== wantDomains[i])) return false; + const wantWindows = opts.modelWindows ?? {}; + const keys = Object.keys(wantWindows); + if (Object.keys(inst.modelWindows).length !== keys.length) return false; + return keys.every((k) => inst.modelWindows[k] === wantWindows[k]); +} + +async function probeExistingInstance( + readInstance: () => ProxyInstanceFile | { origin: string } | undefined, + fetchHealthInfo: (origin: string) => Promise, +): Promise { + const inst = readInstance(); + if (!isProxyInstanceFile(inst)) return undefined; + if (!isPidAlive(inst.pid)) return undefined; + const health = await fetchHealthInfo(inst.origin); + if (!health || !health.ok) return undefined; + if (health.instanceId !== undefined && health.instanceId !== inst.instanceId) return undefined; + return inst; +} + export function findFreePort(preferred: number, host = LAUNCHER_DEFAULT_HOST): Promise { const tryBind = (port: number): Promise => new Promise((resolve) => { @@ -1496,13 +1600,26 @@ export async function ensureProxyRunning( deps: LauncherDeps = {}, ): Promise { const fetchImpl = deps.fetchImpl ?? defaultFetch; + const fetchHealthInfo = deps.fetchHealthInfo ?? fetchHealthInfoDefault; + const readInstance = deps.readInstanceFile ?? readProxyInstanceFile; const spawnImpl = deps.spawnImpl ?? (spawn as SpawnFn); const now = deps.now ?? Date.now; const sleepImpl = deps.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); - const port = await findFreePort(opts.port, opts.host); - const spawnedOrigin = proxyOrigin(opts.host, port); + // #394/#417: a healthy proxy with a compatible config is SHARED, not + // doubled — two concurrent launches of the same client would otherwise + // spawn two writers over one sessions dir. + const existing = await probeExistingInstance(readInstance, fetchHealthInfo); + if (existing && instanceCompatible(existing, opts)) { + console.error(`bili: attaching to running proxy at ${existing.origin} (pid ${existing.pid})`); + return { origin: existing.origin, port: existing.port, attached: true }; + } + // #407: no probe-release-rebind. The child binds the preferred port + // itself and retries on EADDRINUSE, reporting the real origin through + // the instance file via this launchToken. + const launchToken = randomUUID(); + const port = opts.port; const script = process.argv[1]; if (!script) throw new Error("bili: cannot resolve launcher script path"); const logPath = path.join(os.tmpdir(), `bili-proxy-${port}.log`); @@ -1511,12 +1628,14 @@ export async function ensureProxyRunning( try { child = spawnImpl( process.execPath, - [script, ...proxyStartArgs({ ...opts, port, debug: true })], + [script, ...proxyStartArgs(opts)], { detached: true, stdio: ["ignore", logFd, logFd], env: { ...stripInheritedProxy(process.env), + BILI_LAUNCH_TOKEN: launchToken, + BILI_PARENT_PID: String(process.pid), ...(opts.mitmDomains && opts.mitmDomains.length ? { BILI_MITM_DOMAINS: opts.mitmDomains.join(",") } : {}), @@ -1538,17 +1657,37 @@ export async function ensureProxyRunning( const deadline = now() + SPAWN_WAIT_MS; while (now() < deadline) { await sleepImpl(HEALTH_POLL_INTERVAL_MS); - if (await probeHealth(spawnedOrigin, fetchImpl)) { - return { origin: spawnedOrigin, port, child, logPath }; + const inst = readInstance(); + if (isProxyInstanceFile(inst) && inst.launchToken === launchToken) { + if (await probeHealth(inst.origin, fetchImpl)) { + return { origin: inst.origin, port: inst.port, child, logPath }; + } + continue; + } + // Fallback for a child that cannot write the instance file (broken + // state dir) or an old pre-handshake binary: only trust the preferred + // origin when NO record vouches for it — a LIVE record's owner owns + // the discovery surface and our child is retry-binding elsewhere. + // A stale record (dead pid / legacy plain) cannot vouch for anything. + const stale = !isProxyInstanceFile(inst) || !isPidAlive(inst.pid); + if (stale && (await probeHealth(proxyOrigin(opts.host, port), fetchImpl))) { + return { origin: proxyOrigin(opts.host, port), port, child, logPath }; } } - throw new Error(`bili: proxy did not become healthy at ${spawnedOrigin} within ${SPAWN_WAIT_MS}ms`); + throw new Error(`bili: proxy did not become healthy within ${SPAWN_WAIT_MS}ms (log: ${logPath})`); } export function stopProxy(handle: ProxyHandle): void { + if (handle.attached) return; const child = handle.child; if (!child || child.pid === undefined) return; - if (process.platform !== "win32" && child.pid > 0) { + if (process.platform === "win32") { + // #414: child.kill() on win32 is TerminateProcess — zero flush. + // Launcher children watch BILI_PARENT_PID and run the graceful path + // themselves once this process exits (≤2s later). + return; + } + if (child.pid > 0) { try { process.kill(-child.pid); } catch { diff --git a/src/mcp.ts b/src/mcp.ts index b7d16e07bd..9208580d8e 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -9,7 +9,7 @@ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { proxyOriginFile } from "./paths.js"; +import { readProxyInstanceFile } from "./instance.js"; const VERSION = (() => { try { @@ -37,11 +37,8 @@ const DEFAULT_PROXY_ORIGIN = "http://127.0.0.1:8787"; export function resolveProxyOrigin(): string { const fromEnv = process.env.BILI_MCP_PROXY?.trim(); if (fromEnv && fromEnv.length > 0) return fromEnv; - try { - const discovered = fs.readFileSync(proxyOriginFile(), "utf8").trim(); - if (/^https?:\/\/\S+$/.test(discovered)) return discovered; - } catch { - } + const discovered = readProxyInstanceFile(); + if (discovered && /^https?:\/\/\S+$/.test(discovered.origin)) return discovered.origin; return DEFAULT_PROXY_ORIGIN; } diff --git a/src/plugin-install.ts b/src/plugin-install.ts index 01e362f693..7eacfc5c00 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -17,7 +17,24 @@ import os from "node:os"; import { execFileSync } from "node:child_process"; import { fileURLToPath } from "node:url"; import { resolvePiHome } from "./client-config.js"; -import { resolveProxyOrigin } from "./mcp.js"; +import { isPidAlive, isProxyInstanceFile, readProxyInstanceFile } from "./instance.js"; + +/** #403: never freeze a dead or unverifiable origin into a client's + * persistent config — the MCP shell would dial it forever. An explicit + * BILI_MCP_PROXY env wins (the user said so); otherwise a recorded + * instance must be pid-alive. */ +function proxyOriginForInstall(): string { + const fromEnv = process.env.BILI_MCP_PROXY?.trim(); + if (fromEnv && fromEnv.length > 0) return fromEnv; + const inst = readProxyInstanceFile(); + if (inst === undefined) { + throw new Error("no bili proxy origin found — start bili first (\`bili start\` or \`bili \`), then retry, or set BILI_MCP_PROXY explicitly"); + } + if (isProxyInstanceFile(inst) && !isPidAlive(inst.pid)) { + throw new Error(`the recorded bili proxy (pid ${inst.pid}, ${inst.origin}) is not running — start bili and retry so a dead origin is not frozen into the client config`); + } + return inst.origin; +} export const PLUGIN_AGENTS = ["pi", "omp", "claude", "codex", "opencode"] as const; export type PluginAgent = (typeof PLUGIN_AGENTS)[number]; @@ -250,7 +267,7 @@ function claudeInstall(): string { requireDistFile(mcpJs); const claude = process.env.CLAUDE?.trim() || "claude"; try { - execFileSync(claude, ["mcp", "add", "bili", "--scope", "user", "-e", `BILI_MCP_PROXY=${resolveProxyOrigin()}`, "--", process.execPath, mcpJs], { stdio: ["ignore", "pipe", "pipe"], timeout: CLAUDE_EXEC_TIMEOUT_MS }); + execFileSync(claude, ["mcp", "add", "bili", "--scope", "user", "-e", `BILI_MCP_PROXY=${proxyOriginForInstall()}`, "--", process.execPath, mcpJs], { stdio: ["ignore", "pipe", "pipe"], timeout: CLAUDE_EXEC_TIMEOUT_MS }); return `claude: installed via \`claude mcp add\` (user scope) -> ${claudeMcpJson()}`; } catch (err) { const stderr = err instanceof Error && "stderr" in err ? String((err as { stderr?: Buffer | string }).stderr ?? "") : ""; @@ -283,7 +300,7 @@ function codexToml(): string { } function codexBlock(): string { - return `\n[mcp_servers.bili]\ncommand = ${JSON.stringify(process.execPath)}\nargs = [${JSON.stringify(path.join(selfPackageRoot(), "dist", "mcp.js"))}]\nenv = { BILI_MCP_PROXY = ${JSON.stringify(resolveProxyOrigin())} }\n`; + return `\n[mcp_servers.bili]\ncommand = ${JSON.stringify(process.execPath)}\nargs = [${JSON.stringify(path.join(selfPackageRoot(), "dist", "mcp.js"))}]\nenv = { BILI_MCP_PROXY = ${JSON.stringify(proxyOriginForInstall())} }\n`; } function codexInstall(): string { @@ -292,7 +309,7 @@ function codexInstall(): string { const existing = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(text); if (existing !== null) { const block = text.slice(existing.index, text.indexOf("\n[", existing.index + 1) === -1 ? undefined : text.indexOf("\n[", existing.index + 1)); - if (block.includes(`BILI_MCP_PROXY = ${JSON.stringify(resolveProxyOrigin())}`)) return `codex: already installed (${file})`; + if (block.includes(`BILI_MCP_PROXY = ${JSON.stringify(proxyOriginForInstall())}`)) return `codex: already installed (${file})`; const refreshed = text.slice(0, existing.index) + codexBlock().replace(/^\n/, "") + text.slice(existing.index + block.length); backupOnce(file); fs.writeFileSync(file, refreshed); @@ -346,7 +363,7 @@ function opencodeInstall(): string { const data = readJson(file); const mcp = (data.mcp as Record | undefined) ?? {}; if ("bili" in mcp) return `opencode: already installed (${file})`; - mcp.bili = { type: "local", command: [process.execPath, mcpJs], environment: { BILI_MCP_PROXY: resolveProxyOrigin() }, enabled: true }; + mcp.bili = { type: "local", command: [process.execPath, mcpJs], environment: { BILI_MCP_PROXY: proxyOriginForInstall() }, enabled: true }; data.mcp = mcp; writeJson(file, data); return `opencode: installed -> ${file} mcp.bili`; diff --git a/src/plugin.ts b/src/plugin.ts index 093bdb440e..5da5ee6e19 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -106,13 +106,21 @@ const remembered = new Map(); // before the debounced write just means the next model request repopulates it. const conversationsFile = () => path.join(stateDir(), "plugin-conversations.json"); let conversationsSaveTimer: NodeJS.Timeout | undefined; +let conversationsDirty = false; function writeConversationsFile(): void { + if (!conversationsDirty) return; try { const obj: Record = {}; for (const [k, v] of conversations) obj[k] = v; fs.mkdirSync(stateDir(), { recursive: true }); - fs.writeFileSync(conversationsFile(), JSON.stringify(obj)); + // #406: the only state file that used to be written in place — a + // torn write or a dying dual instance must not zero every route. + const filePath = conversationsFile(); + const draft = `${filePath}.${process.pid}.bili-tmp`; + fs.writeFileSync(draft, JSON.stringify(obj)); + fs.renameSync(draft, filePath); + conversationsDirty = false; } catch { // best-effort persistence; ignore write failures } @@ -138,8 +146,13 @@ export function flushConversations(): void { /** Restore the persisted conversationId → session map. Called at startup, * AFTER initSessions so the referenced sessions are already loaded. */ export function loadConversations(): void { + let raw: string; + try { + raw = fs.readFileSync(conversationsFile(), "utf8"); + } catch { + return; + } try { - const raw = fs.readFileSync(conversationsFile(), "utf8"); const obj = JSON.parse(raw) as Record; for (const [k, v] of Object.entries(obj)) { if (v && typeof v.sessionId === "string" && v.sessionId.length > 0) { @@ -147,8 +160,14 @@ export function loadConversations(): void { } } } catch { - // no file or corrupt — start empty + // #406: preserve the corrupt bytes for forensics instead of + // silently zeroing every route on the next debounced write. + try { + fs.renameSync(conversationsFile(), `${conversationsFile()}.corrupt-${Date.now()}`); + } catch {} + loggerLog("warn", "[plugin] plugin-conversations.json is corrupt — backed up beside the original, starting an empty routing table"); } + conversationsDirty = false; } /** Index a plugin session by its conversation id (the key the plugin uses on @@ -157,6 +176,7 @@ export function loadConversations(): void { export function recordPluginSession(conversationId: string, sessionId: string): void { conversations.delete(conversationId); conversations.set(conversationId, { sessionId, lastSeen: Date.now() }); + conversationsDirty = true; // remembered[sessionId] is intentionally left alone here: this runs OUTSIDE // the session lock. rememberPluginMessages() rewrites it under the lock // after forward(), and the tool API reads it under the lock — so no diff --git a/src/server.ts b/src/server.ts index 351ea5f517..d2200946c3 100644 --- a/src/server.ts +++ b/src/server.ts @@ -50,7 +50,8 @@ import { renderUI, handleConfigGet, handleConfigPut } from "./web/index.js"; import { reapOrphanBlocks } from "./orphan-gc.js"; import { getStore } from "./persist.js"; import { log as loggerLog, configureLogger, getLogPath, closeLogger } from "./logger.js"; -import { defaultLogFile, stateDir, proxyOriginFile } from "./paths.js"; +import { defaultLogFile, stateDir } from "./paths.js"; +import { atomicWriteInstanceFile, clearProxyInstanceFile, isPidAlive, registerInstanceAndWarn, unregisterInstance } from "./instance.js"; import { compressLoopResponsesJson } from "./compress-loop-responses.js"; import { runCompressLoop, pickAdapter } from "./loop/index.js"; import { containsToolCallXmlFragment } from "./loop/tag-echo-filter.js"; @@ -293,6 +294,7 @@ export async function startServer(opts: ProxyOptions): Promise { // (tests) are distinct instances; a restart changing the id is harmless // (the chain check only compares against the other running instance). const instanceId = randomUUID(); + const instanceStartedAt = Date.now(); // Reload persisted compression state before accepting traffic so sessions // that survived a restart keep their folded view (otherwise long sessions // re-send oversized raw history and hang). @@ -308,7 +310,7 @@ export async function startServer(opts: ProxyOptions): Promise { void loadRegistry(); const server = http.createServer(async (req, res) => { try { - await handle(req, res, opts, core, config, log, instanceId); + await handle(req, res, opts, core, config, log, instanceId, instanceStartedAt); } catch (err) { const msg = String(err); log("error", msg); @@ -347,53 +349,89 @@ export async function startServer(opts: ProxyOptions): Promise { const allowRemoteConnect = opts.host === "0.0.0.0" || opts.host === "::" || !isLoopbackAddress(opts.host); setupMitm(server, opts.mitm.domains, (msg) => log("info", msg), (host) => resolveProxy(opts.routes, opts.proxy, `https://${host}`, opts.proxyFallback), allowRemoteConnect); } - server.listen(opts.port, opts.host, () => { + // Launcher mode handshake (#407): the child self-binds and retries on + // EADDRINUSE instead of dying, reporting the real origin via the instance + // file (launchToken match). Manual `bili start` keeps fail-fast semantics. + const launchToken = process.env.BILI_LAUNCH_TOKEN?.trim(); + const MAX_LISTEN_ATTEMPTS = 17; + let listenAttempts = 0; + let lastTriedPort = opts.port; + const announceListening = (): void => { + const actualPort = server.address() === null ? opts.port : (server.address() as { port: number }).port; const nonLoopbackBind = opts.host === "0.0.0.0" || opts.host === "::" || !isLoopbackAddress(opts.host); // Honest bind display: a wildcard bind shows as 0.0.0.0 (the user // chose to expose the proxy — hiding it behind "localhost" made // remote setups look broken in the log, see #240). const displayHost = nonLoopbackBind ? opts.host : opts.host === "0.0.0.0" ? "localhost" : opts.host; + // Discovery origin local MCP shells dial: collapse wildcard + // binds to loopback (localhost may resolve to ::1, where an + // IPv4-only listener is absent) and bracket bare IPv6 literals + // so the file always holds a valid URL. + const originHost = opts.host === "0.0.0.0" || opts.host === "::" || opts.host === "localhost" ? "127.0.0.1" : opts.host.includes(":") && !opts.host.startsWith("[") ? `[${opts.host}]` : opts.host; + const origin = `http://${originHost}:${actualPort}`; try { fs.mkdirSync(stateDir(), { recursive: true }); - // Discovery origin local MCP shells dial: collapse wildcard - // binds to loopback (localhost may resolve to ::1, where an - // IPv4-only listener is absent) and bracket bare IPv6 literals - // so the file always holds a valid URL. - const originHost = opts.host === "0.0.0.0" || opts.host === "::" || opts.host === "localhost" ? "127.0.0.1" : opts.host.includes(":") && !opts.host.startsWith("[") ? `[${opts.host}]` : opts.host; - fs.writeFileSync(proxyOriginFile(), `http://${originHost}:${server.address() === null ? opts.port : (server.address() as { port: number }).port}\n`); + atomicWriteInstanceFile({ + origin, + instanceId, + pid: process.pid, + startedAt: instanceStartedAt, + host: opts.host, + port: actualPort, + passthrough: opts.passthrough, + mitmDomains: opts.mitm.enabled ? opts.mitm.domains : [], + modelWindows: { ...LAUNCHER_MODEL_WINDOWS }, + launchToken: launchToken || undefined, + }); } catch { // best-effort discovery hint for host-spawned MCP shells } + registerInstanceAndWarn( + { instanceId, pid: process.pid, port: actualPort, origin, startedAt: instanceStartedAt }, + (msg) => log("warn", `[instances] ${msg}`), + ); const nOverrides = Object.keys(opts.routes).length; log( "info", - `acp-proxy listening on http://${displayHost}:${opts.port}` + - ` — web UI: http://${displayHost}:${opts.port}/__bili/` + - ` — zero-config: prefix any baseURL with http://${displayHost}:${opts.port}/bili/` + + `acp-proxy listening on http://${displayHost}:${actualPort}` + + ` — web UI: http://${displayHost}:${actualPort}/__bili/` + + ` — zero-config: prefix any baseURL with http://${displayHost}:${actualPort}/bili/` + (nOverrides ? ` — context overrides for ${nOverrides} upstream URL(s)` : "") + (opts.mitm.enabled ? ` — MITM proxy on (whitelist)${opts.mitm.domains.length ? ` +${opts.mitm.domains.join(",")}` : ""}` : ""), ); if (nonLoopbackBind) { log( "warn", - `[security] bound to ${opts.host} — proxy endpoints (/bili/, CONNECT for whitelisted model hosts) are reachable from the network with NO authentication; /__bili/ management endpoints stay loopback-only. Restrict access with a firewall on untrusted networks. Remote agents: point baseURL at http://:${opts.port}/bili/`, + `[security] bound to ${opts.host} — proxy endpoints (/bili/, CONNECT for whitelisted model hosts) are reachable from the network with NO authentication; /__bili/ management endpoints stay loopback-only. Restrict access with a firewall on untrusted networks. Remote agents: point baseURL at http://:${actualPort}/bili/`, ); } if (opts.debug) { log("info", `[debug] build features: raw-HTTP-capture(on) | remote_compaction_v2-strip(on) | cert-MITM-launcher(on) | strip-acp-summary(on) — seeing this line confirms the launcher build (not registry 0.1.34)`); } - }); + }; + const attemptListen = (port: number): void => { + lastTriedPort = port; + server.listen(port, opts.host, announceListening); + }; + attemptListen(opts.port); // Listen errors (EADDRINUSE port taken, EACCES privileged port, EAFNOSUPPORT // bad host) surface as an 'error' event on the server. Without a listener // Node treats it as an unhandled 'error' and throws, aborting before the // graceful-shutdown flush can run. Catch, log a human-readable message, // flush sessions, and exit cleanly (exit code 1 so callers/scripts notice). server.on("error", (err: NodeJS.ErrnoException) => { + if (err.code === "EADDRINUSE" && launchToken && listenAttempts < MAX_LISTEN_ATTEMPTS) { + listenAttempts += 1; + const next = listenAttempts === MAX_LISTEN_ATTEMPTS ? 0 : lastTriedPort + 1; + log("warn", `port ${lastTriedPort} busy — ${next === 0 ? "retrying on an ephemeral port" : `retrying on port ${next}`}`); + attemptListen(next); + return; + } const hint = err.code === "EADDRINUSE" - ? ` — port ${opts.port} is already in use. Stop the other process or use --port .` + ? ` — port ${lastTriedPort} is already in use. Stop the other process or use --port .` : err.code === "EACCES" - ? ` — port ${opts.port} requires privileges. Use a port >= 1024.` + ? ` — port ${lastTriedPort} requires privileges. Use a port >= 1024.` : ""; log("error", `listen failed: ${err.code ?? ""} ${err.message}${hint}`); shuttingDown = true; @@ -417,6 +455,12 @@ export async function startServer(opts: ProxyOptions): Promise { // not lose recent compression state. SIGKILL/power loss cannot flush, but // debounced writes keep disk within ~500ms of in-memory state. let shuttingDown = false; + const finishShutdown = (): void => { + clearProxyInstanceFile(instanceId); + unregisterInstance(instanceId); + closeLogger(); + process.exit(0); + }; const shutdown = (sig: string) => { if (shuttingDown) return; shuttingDown = true; @@ -428,20 +472,14 @@ export async function startServer(opts: ProxyOptions): Promise { // rather than being yanked mid-chunk. server.close(() => { flushConversations(); - void flushAllSessions().finally(() => { - closeLogger(); - process.exit(0); - }); + void flushAllSessions().finally(finishShutdown); }); // Hard fallback: if connections hang (client never closes), don't // block shutdown forever — force-exit after a grace window. setTimeout(() => { log("warn", "shutdown grace window elapsed; forcing exit"); flushConversations(); - void flushAllSessions().finally(() => { - closeLogger(); - process.exit(0); - }); + void flushAllSessions().finally(finishShutdown); }, 10_000).unref?.(); }; process.on("SIGTERM", () => shutdown("SIGTERM")); @@ -452,6 +490,16 @@ export async function startServer(opts: ProxyOptions): Promise { if (process.platform === "win32") { process.on("SIGBREAK", () => shutdown("SIGBREAK")); } + // Launcher children have no console and TerminateProcess leaves no room + // for a flush (#414): they watch the launcher pid and run the graceful + // path themselves when it disappears (≤2s after the parent exits). + const parentPid = Number.parseInt(process.env.BILI_PARENT_PID ?? "", 10); + if (Number.isInteger(parentPid) && parentPid > 0 && parentPid !== process.pid) { + const watcher = setInterval(() => { + if (!isPidAlive(parentPid)) shutdown(`parent-gone (pid ${parentPid})`); + }, 2_000); + watcher.unref?.(); + } return server; } @@ -535,6 +583,7 @@ async function handle( config: Config, log: (level: string, msg: string) => void, instanceId: string, + instanceStartedAt: number, ): Promise { // SECURITY: the /__bili/ management endpoints (config read/write, reload, // session stats) are privileged — a remote caller who can reach them can @@ -574,7 +623,7 @@ async function handle( } if (req.method === "GET" && req.url === "/__bili/health") { res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, upstream: opts.upstream })); + res.end(JSON.stringify({ ok: true, upstream: opts.upstream, instanceId, pid: process.pid, startedAt: instanceStartedAt })); return; } // Web config UI (served as HTML, separate from the JSON health check above). diff --git a/tests/instance-governance.test.ts b/tests/instance-governance.test.ts new file mode 100644 index 0000000000..4f03a734b2 --- /dev/null +++ b/tests/instance-governance.test.ts @@ -0,0 +1,257 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { + atomicWriteInstanceFile, + clearProxyInstanceFile, + instanceFilePath, + isPidAlive, + isProxyInstanceFile, + readProxyInstanceFile, + registerInstanceAndWarn, + unregisterInstance, + type ProxyInstanceFile, +} from "../src/instance.ts"; +import { resolveProxyOrigin } from "../src/mcp.ts"; +import { loadConversations, recordPluginSession, flushConversations } from "../src/plugin.ts"; +import { unpackDeadProxyUrlsInFile, liveProxyPorts, prepareOmpHttpRewrite } from "../src/launcher.ts"; +import { pluginInstall } from "../src/plugin-install.ts"; +import { setLogCapture } from "../src/logger.ts"; + +function tmpStateDir(): { dir: string; restore: () => void } { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-inst-state-")); + const prev = process.env.XDG_STATE_HOME; + process.env.XDG_STATE_HOME = dir; + return { + dir, + restore: () => { + if (prev === undefined) delete process.env.XDG_STATE_HOME; + else process.env.XDG_STATE_HOME = prev; + }, + }; +} + +function sampleInstance(over: Partial = {}): ProxyInstanceFile { + return { + origin: "http://127.0.0.1:8787", + instanceId: "inst-abc", + pid: process.pid, + startedAt: 1_000, + host: "127.0.0.1", + port: 8787, + passthrough: false, + mitmDomains: [], + modelWindows: {}, + ...over, + }; +} + +function deadPid(): number { + return 4_000_000; +} + +test("instance file: JSON round-trip, atomic write, legacy plain-string read", () => { + const st = tmpStateDir(); + try { + atomicWriteInstanceFile(sampleInstance()); + const read = readProxyInstanceFile(); + assert.ok(isProxyInstanceFile(read)); + assert.equal(read.instanceId, "inst-abc"); + assert.equal(read.pid, process.pid); + assert.equal(read.port, 8787); + const raw = fs.readFileSync(instanceFilePath(), "utf8"); + assert.ok(raw.trim().startsWith("{"), "file is JSON"); + assert.equal(fs.readdirSync(st.dir).filter((f) => f.endsWith(".tmp")).length, 0, "no leftover tmp"); + + fs.writeFileSync(instanceFilePath(), "http://127.0.0.1:9999\n"); + const legacy = readProxyInstanceFile(); + assert.ok(!isProxyInstanceFile(legacy) && legacy !== undefined); + assert.equal(legacy.origin, "http://127.0.0.1:9999"); + + fs.writeFileSync(instanceFilePath(), "{{{garbage"); + assert.equal(readProxyInstanceFile(), undefined); + } finally { + st.restore(); + } +}); + +test("clearProxyInstanceFile: only removes its own record", () => { + const st = tmpStateDir(); + try { + atomicWriteInstanceFile(sampleInstance()); + clearProxyInstanceFile("other-instance"); + assert.ok(isProxyInstanceFile(readProxyInstanceFile())); + clearProxyInstanceFile("inst-abc"); + assert.equal(readProxyInstanceFile(), undefined); + } finally { + st.restore(); + } +}); + +test("resolveProxyOrigin: env wins, JSON file parsed, default fallback", () => { + const st = tmpStateDir(); + const prevEnv = process.env.BILI_MCP_PROXY; + try { + process.env.BILI_MCP_PROXY = "http://10.1.1.1:1"; + assert.equal(resolveProxyOrigin(), "http://10.1.1.1:1"); + delete process.env.BILI_MCP_PROXY; + atomicWriteInstanceFile(sampleInstance({ origin: "http://127.0.0.1:4242" })); + assert.equal(resolveProxyOrigin(), "http://127.0.0.1:4242"); + fs.writeFileSync(instanceFilePath(), "http://127.0.0.1:7777"); + assert.equal(resolveProxyOrigin(), "http://127.0.0.1:7777"); + fs.writeFileSync(instanceFilePath(), "garbage"); + assert.equal(resolveProxyOrigin(), "http://127.0.0.1:8787"); + } finally { + if (prevEnv === undefined) delete process.env.BILI_MCP_PROXY; + else process.env.BILI_MCP_PROXY = prevEnv; + st.restore(); + } +}); + +test("isPidAlive: self alive, dead pid not", () => { + assert.equal(isPidAlive(process.pid), true); + assert.equal(isPidAlive(deadPid()), false); + assert.equal(isPidAlive(0), false); + assert.equal(isPidAlive(-1), false); +}); + +test("instance registry: registers, warns on a second live instance, prunes dead, unregisters", () => { + const st = tmpStateDir(); + const warnings: string[] = []; + setLogCapture((_level, msg) => warnings.push(msg)); + try { + registerInstanceAndWarn( + { instanceId: "a", pid: process.pid, port: 1, origin: "http://127.0.0.1:1", startedAt: 1 }, + (msg) => warnings.push(msg), + ); + assert.equal(warnings.length, 0); + registerInstanceAndWarn( + { instanceId: "b", pid: process.pid, port: 2, origin: "http://127.0.0.1:2", startedAt: 2 }, + (msg) => warnings.push(msg), + ); + assert.equal(warnings.length, 1); + assert.match(warnings[0], /another bili instance is running/); + const file = path.join(st.dir, "billion-context", "instances.json"); + const after = JSON.parse(fs.readFileSync(file, "utf8")) as { instances: { instanceId: string }[] }; + assert.equal(after.instances.length, 2); + + unregisterInstance("a"); + const after2 = JSON.parse(fs.readFileSync(file, "utf8")) as { instances: { instanceId: string }[] }; + assert.deepEqual(after2.instances.map((e) => e.instanceId), ["b"]); + } finally { + setLogCapture(null); + st.restore(); + } +}); + +test("plugin-conversations: clean state does not rewrite the file; corrupt file is preserved, not zeroed", () => { + const st = tmpStateDir(); + const logged: string[] = []; + setLogCapture((_level, msg) => logged.push(msg)); + try { + const file = () => path.join(st.dir, "billion-context", "plugin-conversations.json"); + fs.mkdirSync(path.dirname(file()), { recursive: true }); + fs.writeFileSync(file(), JSON.stringify({ "c1": { sessionId: "s1", lastSeen: 5 } })); + loadConversations(); + fs.writeFileSync(file(), "SENTINEL-UNTOUCHED"); + flushConversations(); + assert.equal(fs.readFileSync(file(), "utf8"), "SENTINEL-UNTOUCHED", "no dirty flag → no write"); + + recordPluginSession("c2", "s2"); + flushConversations(); + const obj = JSON.parse(fs.readFileSync(file(), "utf8")) as Record; + assert.equal(obj.c1.sessionId, "s1"); + assert.equal(obj.c2.sessionId, "s2"); + + fs.writeFileSync(file(), "{corrupt-bytes"); + loadConversations(); + const backups = fs.readdirSync(path.dirname(file())).filter((f) => f.startsWith("plugin-conversations.json.corrupt-")); + assert.equal(backups.length, 1, "corrupt bytes preserved beside the original"); + assert.ok(logged.some((m) => m.includes("plugin-conversations.json is corrupt"))); + } finally { + setLogCapture(null); + st.restore(); + } +}); + +test("unpackDeadProxyUrlsInFile: dead-origin wraps unpacked, live-origin wraps kept", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-unpack-")); + const st = tmpStateDir(); + try { + const models = path.join(dir, "models.yml"); + fs.writeFileSync( + models, + [ + "providers:", + " relay:", + " baseUrl: http://127.0.0.1:8787/bili/https://ps.air-outer.com/v1", + " live:", + " baseUrl: http://127.0.0.1:9001/bili/https://keep.example.com/v1", + "", + ].join("\n"), + ); + atomicWriteInstanceFile(sampleInstance({ origin: "http://127.0.0.1:9001", port: 9001 })); + const livePorts = liveProxyPorts(); + assert.ok(livePorts.has(9001)); + assert.equal(livePorts.has(8787), false); + const changed = unpackDeadProxyUrlsInFile(models, livePorts); + assert.equal(changed, 1); + const out = fs.readFileSync(models, "utf8"); + assert.match(out, /baseUrl: https:\/\/ps\.air-outer\.com\/v1/, "dead-origin wrap unpacked"); + assert.match(out, /baseUrl: http:\/\/127\.0\.0\.1:9001\/bili\/https:\/\/keep\.example\.com\/v1/, "live-origin wrap kept"); + } finally { + st.restore(); + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("omp overlay: nested generated models.yml is never promoted into the real home (#410)", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-omp-nest-")); + const overlay = `${home}-bili`; + fs.writeFileSync(path.join(home, "models.yml"), ["providers:", " a:", " baseUrl: http://example.com/v1"].join("\n")); + fs.mkdirSync(path.join(home, "sessions"), { recursive: true }); + fs.mkdirSync(path.join(overlay, "sessions"), { recursive: true }); + fs.writeFileSync(path.join(overlay, "sessions", "models.yml"), "providers:\n poisoned:\n baseUrl: http://127.0.0.1:8787/bili/http://evil.example.com/v1\n"); + let tmp: string | undefined; + try { + tmp = prepareOmpHttpRewrite(home, "http://127.0.0.1:8787", [{ key: "a", realUpstream: "http://example.com/v1" }], []); + assert.ok(tmp); + assert.equal(fs.existsSync(path.join(home, "sessions", "models.yml")), false, "nested generated file NOT promoted"); + const real = fs.readFileSync(path.join(home, "models.yml"), "utf8"); + assert.ok(!real.includes("poisoned"), "real models.yml clean"); + } finally { + if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); + fs.rmSync(home, { recursive: true, force: true }); + try { + fs.rmSync(overlay, { recursive: true, force: true }); + } catch {} + } +}); + +test("plugin install: refuses to freeze a dead or missing proxy origin (#403)", () => { + const st = tmpStateDir(); + const prevCodex = process.env.CODEX_HOME; + const prevEnv = process.env.BILI_MCP_PROXY; + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-codex-home-")); + process.env.CODEX_HOME = home; + delete process.env.BILI_MCP_PROXY; + try { + assert.throws(() => pluginInstall("codex"), /no bili proxy origin found/); + atomicWriteInstanceFile(sampleInstance({ pid: deadPid() })); + assert.throws(() => pluginInstall("codex"), /is not running/); + + atomicWriteInstanceFile(sampleInstance()); + const msg = pluginInstall("codex"); + assert.match(msg, /codex:/); + const toml = fs.readFileSync(path.join(home, "config.toml"), "utf8"); + assert.match(toml, /BILI_MCP_PROXY = "http:\/\/127\.0\.0\.1:8787"/); + } finally { + if (prevCodex === undefined) delete process.env.CODEX_HOME; + else process.env.CODEX_HOME = prevCodex; + if (prevEnv !== undefined) process.env.BILI_MCP_PROXY = prevEnv; + st.restore(); + fs.rmSync(home, { recursive: true, force: true }); + } +}); diff --git a/tests/launcher.test.ts b/tests/launcher.test.ts index 7df4c7840d..f56aba5554 100644 --- a/tests/launcher.test.ts +++ b/tests/launcher.test.ts @@ -5,6 +5,7 @@ import type { PathLike, SymlinkType } from "node:fs"; import net from "node:net"; import os from "node:os"; import path from "node:path"; +import type { ProxyInstanceFile as InstanceFile } from "../src/instance.ts"; import { LAUNCHER_DEFAULT_HOST, isLaunchClient, @@ -516,7 +517,7 @@ function makeFakeChild(pid: number): SpawnChild { }; } -test("ensureProxyRunning: always spawns a fresh proxy, never reuses a listener", async () => { +test("ensureProxyRunning: spawns a fresh proxy when no live instance is recorded", async () => { let spawnCalls = 0; const spawnImpl: SpawnFn = () => { spawnCalls++; @@ -525,7 +526,7 @@ test("ensureProxyRunning: always spawns a fresh proxy, never reuses a listener", const fetchImpl = async () => ({ ok: true }); const handle = await ensureProxyRunning( { host: "127.0.0.1", port: 8787, passthrough: false, debug: false }, - { fetchImpl, spawnImpl }, + { fetchImpl, spawnImpl, readInstanceFile: () => undefined }, ); assert.equal(spawnCalls, 1); assert.ok(handle.child); @@ -546,7 +547,7 @@ test("ensureProxyRunning: spawns when not healthy, polls until healthy", async ( }; const handle = await ensureProxyRunning( { host: "127.0.0.1", port: 8787, passthrough: false, debug: false }, - { fetchImpl, spawnImpl, sleep: () => Promise.resolve() }, + { fetchImpl, spawnImpl, sleep: () => Promise.resolve(), readInstanceFile: () => undefined }, ); assert.equal(handle.child?.pid, 42421); assert.ok(spawnedArgs !== null); @@ -570,12 +571,115 @@ test("ensureProxyRunning: throws when never healthy within deadline", async () = await assert.rejects( ensureProxyRunning( { host: "127.0.0.1", port: 8787, passthrough: false, debug: false }, - { fetchImpl, spawnImpl, now, sleep }, + { fetchImpl, spawnImpl, now, sleep, readInstanceFile: () => undefined }, ), /did not become healthy/, ); }); +function recordedInstance(over: Partial = {}): InstanceFile { + return { + origin: "http://127.0.0.1:8787", + instanceId: "inst-1", + pid: process.pid, + startedAt: Date.now(), + host: "127.0.0.1", + port: 8787, + passthrough: false, + mitmDomains: [], + modelWindows: {}, + ...over, + }; +} + +test("ensureProxyRunning: attaches to a compatible healthy instance instead of doubling (#394)", async () => { + let spawnCalls = 0; + const spawnImpl: SpawnFn = () => { + spawnCalls++; + return makeFakeChild(42431); + }; + const handle = await ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false }, + { + spawnImpl, + fetchImpl: async () => ({ ok: true }), + fetchHealthInfo: async () => ({ ok: true, instanceId: "inst-1" }), + readInstanceFile: () => recordedInstance(), + }, + ); + assert.equal(spawnCalls, 0); + assert.equal(handle.attached, true); + assert.equal(handle.origin, "http://127.0.0.1:8787"); + let killed = false; + stopProxy({ ...handle, child: { pid: 77777, kill: () => { killed = true; return true; } } }); + assert.equal(killed, false); +}); + +test("ensureProxyRunning: incompatible recorded instance (modelWindows) is not attached", async () => { + let spawnCalls = 0; + const spawnImpl: SpawnFn = () => { + spawnCalls++; + return makeFakeChild(42434); + }; + let reads = 0; + const handle = await ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false, modelWindows: { "m1": 100000 } }, + { + spawnImpl, + fetchImpl: async () => ({ ok: true }), + fetchHealthInfo: async () => ({ ok: true, instanceId: "inst-1" }), + readInstanceFile: () => (reads++ === 0 ? recordedInstance() : undefined), + sleep: () => Promise.resolve(), + }, + ); + assert.equal(spawnCalls, 1); + assert.equal(handle.attached, undefined); +}); + +test("ensureProxyRunning: dead recorded pid is ignored (no attach)", async () => { + let spawnCalls = 0; + const spawnImpl: SpawnFn = () => { + spawnCalls++; + return makeFakeChild(42435); + }; + const handle = await ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false }, + { + spawnImpl, + fetchImpl: async () => ({ ok: true }), + fetchHealthInfo: async () => ({ ok: true, instanceId: "inst-1" }), + readInstanceFile: () => recordedInstance({ pid: 99999999 }), + sleep: () => Promise.resolve(), + }, + ); + assert.equal(spawnCalls, 1); +}); + +test("ensureProxyRunning: launchToken handshake returns the child's real port (#407)", async () => { + let handshaked: InstanceFile | undefined; + const spawnImpl: SpawnFn = (_cmd, _args, options) => { + const token = (options.env?.BILI_LAUNCH_TOKEN as string) ?? ""; + const parentPid = Number(options.env?.BILI_PARENT_PID); + assert.ok(token.length > 0, "spawn env carries BILI_LAUNCH_TOKEN"); + assert.equal(parentPid, process.pid); + setImmediate(() => { + handshaked = recordedInstance({ origin: "http://127.0.0.1:8799", port: 8799, launchToken: token }); + }); + return makeFakeChild(42436); + }; + const handle = await ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false }, + { + spawnImpl, + fetchImpl: async (url: string) => ({ ok: url.startsWith("http://127.0.0.1:8799") }), + readInstanceFile: () => handshaked, + sleep: () => new Promise((r) => setTimeout(r, 0)), + }, + ); + assert.equal(handle.port, 8799); + assert.equal(handle.origin, "http://127.0.0.1:8799"); +}); + test("stopProxy: no-op when child missing pid", () => { assert.doesNotThrow(() => stopProxy({ origin: "http://127.0.0.1:8787", port: 8787, child: { pid: 0 } }), From 43cc106fb856cee5b3842722524535319f3df51d Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Mon, 31 Aug 2026 22:46:18 +0800 Subject: [PATCH 2/2] =?UTF-8?q?test:=20stopProxy=20asserts=20the=20per-pla?= =?UTF-8?q?tform=20contract=20(#414)=20=E2=80=94=20win32=20defers=20to=20t?= =?UTF-8?q?he=20parent-gone=20watcher?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI caught the stale assertion: win32 stopProxy is intentionally a no-op (child.kill is TerminateProcess, zero flush); the test now pins that contract on both platforms instead of assuming POSIX behavior. --- tests/launcher.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/launcher.test.ts b/tests/launcher.test.ts index f56aba5554..2a4ac54032 100644 --- a/tests/launcher.test.ts +++ b/tests/launcher.test.ts @@ -686,7 +686,7 @@ test("stopProxy: no-op when child missing pid", () => { ); }); -test("stopProxy: kills the owned child", () => { +test("stopProxy: POSIX kills the owned child, win32 defers to the parent-gone watcher (#414)", () => { let killed = false; const child: SpawnChild = { pid: 77777, @@ -696,7 +696,11 @@ test("stopProxy: kills the owned child", () => { }, }; stopProxy({ origin: "http://127.0.0.1:8787", port: 8787, reused: false, child }); - assert.equal(killed, true); + if (process.platform === "win32") { + assert.equal(killed, false, "win32 child.kill is TerminateProcess (no flush) — shutdown belongs to BILI_PARENT_PID watcher"); + } else { + assert.equal(killed, true); + } }); test("isOnPath: finds a known binary on PATH, misses bogus name", () => {