From 07e4c98ee430ddf9aecfd1511ffc0c5c20fc258f Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 23 Oct 2026 21:28:08 +0800 Subject: [PATCH 1/3] feat: bili start --lane declares the client lane a manual instance serves (#4368) --- README.md | 1 + src/cli.ts | 40 +++++++++++- src/instance.ts | 8 ++- src/launcher.ts | 31 +++++---- src/server.ts | 7 ++ tests/cli-parseargs.test.ts | 49 ++++++++++++++ tests/launcher.test.ts | 124 +++++++++++++++++++++++++++++++----- 7 files changed, 226 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 330df3717e..633855f077 100644 --- a/README.md +++ b/README.md @@ -498,6 +498,7 @@ above. ```bash bili --port 9000 # change listen port bili --host 0.0.0.0 # listen on all interfaces (see host note below) +bili start --lane zcode # declare which client lane a manual instance serves (#4368) bili --debug # verbose logging (also: set "debug": true in config) bili --passthrough # forward without compression (smoke-test mode) bili --config ~/my-bili.json # use a different config file diff --git a/src/cli.ts b/src/cli.ts index c7f2e55286..e7f0b19360 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -49,7 +49,7 @@ import { hydrateAffinityUnified } from "./affinity-persist.js"; import { resolveProxy } from "./upstream-proxy.js"; import { runMcpStdio } from "./mcp.js"; import { PLUGIN_AGENTS, isPluginAgent, pluginInstall, pluginRemove, pluginStatusAll, pluginUpdate, renderPluginList, warnActivePluginSessions, type PluginAgent } from "./plugin-install.js"; -import { runLaunch, runTestPi, isLaunchClient, type ClientName } from "./launcher.js"; +import { runLaunch, runTestPi, isLaunchClient, KNOWN_LANES, type ClientName } from "./launcher.js"; import { exportSession } from "./export.js"; import { runSessionsCommand, runStorageGcCommand } from "./storage-maintenance.js"; import { installPackFromNpm, removePackFile } from "./pack-install.js"; @@ -194,6 +194,9 @@ Options (override config file / env): http://host:port; must precede the client name) --port listen port (start: 8787; launcher default: random free port) --host listen host (default 127.0.0.1) + --lane which client lane a manual 'start' instance serves (attach + identity, #4368; known lanes: all bili client names + zcode — + an unknown name is rejected at startup) --mitm-domain extra MITM domain (repeatable; launcher only) --config path to config JSON (default: XDG location) --debug verbose logging @@ -212,6 +215,8 @@ Docs: https://github.com/ranxianglei/billion-context type Parsed = { command: "start" | "update" | "doctor" | "help" | "version" | "launch" | "test" | "export" | "plugin-register" | "mcp" | "plugin" | "acp-cache" | "sessions" | "storage" | "pack"; client?: ClientName; + /** #4368: client lane a manual `start` instance declares (KNOWN_LANES). */ + lane?: string; clientArgs: string[]; mitmDomains: string[]; overrides: Record; @@ -249,6 +254,7 @@ export function parseArgs(argv: string[]): Parsed { let command: Parsed["command"] = "start"; const positional: string[] = []; let client: ClientName | undefined; + let lane: string | undefined; let clientArgs: string[] = []; let posture: "inline" | "server" | undefined; const mitmDomains: string[] = []; @@ -437,6 +443,22 @@ export function parseArgs(argv: string[]): Parsed { acpCacheSession = val; break; } + case "--lane": { + const val = argv[++i]; + if (val === undefined || val.length === 0) { + console.error(`bili: ${a} requires a non-empty value`); + process.exit(2); + } + // #4368: loud-fail on unknown names — a typo'd lane would be + // recorded in the instance file and silently match no hook, + // re-creating exactly the worst-class misroute this flag fixes. + if (!(KNOWN_LANES as readonly string[]).includes(val)) { + console.error(`bili: unknown lane "${val}" (known lanes: ${KNOWN_LANES.join(", ")})`); + process.exit(2); + } + lane = val; + break; + } case "-F": case "--port": case "--host": @@ -605,11 +627,16 @@ export function parseArgs(argv: string[]): Parsed { } } - return { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, sessionsApply, sessionsRestoreTarget, storageDays, storageVacuum, storageDryRun, jsonOutput, doctorJson, doctorFix, packAction, packSpec, packProject, packForce }; + if (lane !== undefined && command !== "start") { + console.error(`bili: --lane is only valid with 'start' (client launches take their lane from the client itself)`); + process.exit(2); + } + + return { command, client, lane, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, sessionsApply, sessionsRestoreTarget, storageDays, storageVacuum, storageDryRun, jsonOutput, doctorJson, doctorFix, packAction, packSpec, packProject, packForce }; } export async function main(): Promise { - const { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, sessionsApply, sessionsRestoreTarget, storageDays, storageVacuum, storageDryRun, jsonOutput, doctorJson, doctorFix, packAction, packSpec, packProject, packForce } = parseArgs(process.argv.slice(2)); + const { command, client, lane, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, exportJsonl, registerConversationId, pluginAction, pluginAgent, pluginWithMcp, acpCacheDir, acpCacheLog, acpCacheNoLog, acpCacheSession, sessionsSub, sessionsTarget, sessionsNoVacuum, sessionsApply, sessionsRestoreTarget, storageDays, storageVacuum, storageDryRun, jsonOutput, doctorJson, doctorFix, packAction, packSpec, packProject, packForce } = parseArgs(process.argv.slice(2)); if (command === "help") { process.stdout.write(HELP); return; @@ -845,6 +872,13 @@ export async function main(): Promise { return; } + // #4368: a manual instance declares which client lane it serves — the + // server records it in the instance file so same-lane hooks attach + // instead of spawning duplicates. Flag > env: an explicit --lane wins + // over a stale exported BILI_LAUNCHER_LANE (the env var stays as the + // escape hatch for scripts that cannot pass flags). + if (lane !== undefined) process.env.BILI_LAUNCHER_LANE = lane; + for (const [k, v] of Object.entries(overrides)) { if (v !== undefined) process.env[k] = v; } diff --git a/src/instance.ts b/src/instance.ts index 7fa0dd5749..6870be9194 100644 --- a/src/instance.ts +++ b/src/instance.ts @@ -24,9 +24,11 @@ export interface ProxyInstanceFile { modelWindows: Record; modelMaxOutputs?: Record; launchToken?: string; - /** #1225: which client/lane the launcher that spawned this instance - * belongs to (BILI_LAUNCHER_LANE). Absent for manual `bili start` - * daemons and pre-#1225 instances — both stay shareable (wildcard). */ + /** #1225: which client/lane this instance serves (BILI_LAUNCHER_LANE). + * Set by the launcher for spawned proxies, or by `bili start --lane + * ` / BILI_LAUNCHER_LANE for a user-declared manual daemon + * (#4368). Absent for pre-#1225 instances and lane-less manual starts — + * those stay wildcard-compatible. */ lane?: string; /** #1225: sha256 of the entry script this instance is RUNNING. A missing * fingerprint means pre-#1225 code — attaching new code to it would diff --git a/src/launcher.ts b/src/launcher.ts index 285a07a6c6..403c225cb6 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -171,6 +171,11 @@ import { conflictScanEnabled, isDesignBenign, scanClientPlugins } from "./thirdp export const LAUNCHER_DEFAULT_HOST = "127.0.0.1"; export const LAUNCH_CLIENTS = ["pi", "codex", "claude", "omp", "opencode", "hermes", "dsh", "codebuddy", "qoder", "trae", "jcode", "kimi", "gemini", "iflow", "qwen", "mcode", "aider", "copilot", "amp", "crush", "zed", "goose", "antigravity", "kiro", "pi-test", "pi-inline", "opencode-inline"] as const; export type ClientName = (typeof LAUNCH_CLIENTS)[number]; +/** #4368: lane names a manual `bili start --lane ` may declare — every + * built-in client lane plus zcode (native-hook only, never launchable). A + * typo here would silently re-create the worst-class attach misroute, so the + * CLI rejects unknown names at startup instead of recording them. */ +export const KNOWN_LANES = [...LAUNCH_CLIENTS, "zcode"] as const; type BaseClientName = "claude" | "codex" | "pi" | "omp" | "opencode" | "hermes" | "dsh" | "codebuddy" | "qoder" | "trae" | "jcode" | "kimi" | "gemini" | "iflow" | "qwen" | "mcode" | "aider" | "copilot" | "amp" | "crush" | "zed" | "goose" | "antigravity" | "kiro"; const HEALTH_PATH = "/__bili/health"; @@ -4272,27 +4277,31 @@ async function probeLiveInstances( /** #1335: the attach gate — a listener may be attached to only when its * health reports an ARMED session-lifecycle watchdog, or the user explicitly * opted in via native.attachExternal / BILI_NATIVE_ATTACH_EXTERNAL. A missing - * watchdog field (pre-#1330 build) is unverifiable and refused by default: - * those are exactly the stale manually-started daemons behind #1322, and - * riding them pins every session to possibly-old code that outlives it. */ + * watchdog field (pre-#1330 build) is unverifiable and refused by default — + * riding it pins every session to possibly-old code that outlives it (#1322); + * user-zone (token-less manual) instances stay exempt below (#1660/#4368). */ function attachGateAllows(health: HealthInfo | undefined, attachExternal: boolean): boolean { if (attachExternal) return true; return health?.watchdog?.armed === true; } -/** #1660: the user-sovereignty zone marker — neither a declared lane nor a - * launcher launch token exists only for a manually started `bili start` - * daemon. By definition the user maintains it (they typed the command; it - * has no session lifecycle BY DESIGN, not by drift), so lanes may attach to - * it despite the unarmed watchdog — code-fingerprint and config-shape - * compatibility still apply, and an older build stays incompatible. */ +/** #1660/#4368: the user-sovereignty zone marker — a manually started + * `bili start` daemon carries no launcher launch token, with or without a + * declared lane (#4368: `bili start --lane ` marks WHICH client lane + * the user-maintained daemon serves; the env channel is BILI_LAUNCHER_LANE). + * By definition the user maintains it (they typed the command; it has no + * session lifecycle BY DESIGN, not by drift), so lanes may attach to it + * despite the unarmed watchdog — code-fingerprint and config-shape + * compatibility still apply, and an older build stays incompatible. + * Launcher-spawned instances always carry a token and keep the full #1335 + * gate. */ function isUserZoneInstance(inst: ProxyInstanceFile): boolean { - return inst.lane === undefined && inst.launchToken === undefined; + return inst.launchToken === undefined; } function gateRefusalMessage(inst: ProxyInstanceFile, health: HealthInfo): string { const reason = health.watchdog && health.watchdog.armed === false - ? "it reports NO session-lifecycle watchdog (started without BILI_PARENT_PID, e.g. manual `bili start`)" + ? "it reports NO session-lifecycle watchdog (started without BILI_PARENT_PID)" : "it does not report watchdog state (older bili build) — its lifecycle is unverifiable"; return `bili: refusing to attach to ${inst.origin} (pid ${inst.pid}) — ${reason}. It would outlive this session and ignore config edits until killed (#1322/#1335). Starting a session-owned proxy instead; set native.attachExternal=true or BILI_NATIVE_ATTACH_EXTERNAL=1 to attach anyway.`; } diff --git a/src/server.ts b/src/server.ts index f06ee81a2b..f448b8b9bb 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1206,6 +1206,13 @@ export async function startServer(opts: ProxyOptions): Promise { // (hopping strands it serving no client while the old instance keeps the // real port: the orphan leak #3044 reports). const upgradeReplacement = process.env[UPGRADE_REPLACEMENT_ENV] === "1"; + if (launcherLane !== undefined && launchToken === undefined) { + // #4368: user-declared lane on a manual daemon (bili start --lane or + // BILI_LAUNCHER_LANE) — announce it so an operator debugging why no + // client attaches can see the declared identity in the boot log. + log("info", `[start] declaring client lane "${launcherLane}" — same-lane hooks attach to this manual daemon instead of spawning their own (#4368)`); + } + const MAX_LISTEN_ATTEMPTS = 17; let listenAttempts = 0; let lastTriedPort = opts.port; diff --git a/tests/cli-parseargs.test.ts b/tests/cli-parseargs.test.ts index dfb6c0d8d2..6e6e66cac0 100644 --- a/tests/cli-parseargs.test.ts +++ b/tests/cli-parseargs.test.ts @@ -173,3 +173,52 @@ test("parseArgs: launcher flags stay with the client, bili flags stay before it assert.equal(parseArgs(["export", "--output", "--help"]).command, "export"); assert.equal(parseArgs(["export", "--output", "--help"]).exportOutput, "--help"); }); + +// #4368: a manual instance declares which client lane it serves (--lane). +// Unknown names fail loudly at startup — a typo'd lane would be recorded in +// the instance file and silently match no hook; the flag is 'start'-only. + +/** Runs fn, recording any process.exit(code) call instead of dying (parseArgs usage errors). */ +async function captureExit(fn: () => unknown): Promise { + const prevExit = process.exit; + let code: number | undefined; + process.exit = ((c?: number) => { code = c ?? 0; }) as typeof process.exit; + try { + await fn(); + } finally { + process.exit = prevExit; + } + return code; +} + +test("parseArgs: start --lane declares the manual instance's lane (#4368)", () => { + const r = parseArgs(["start", "--lane", "zcode"]); + assert.equal(r.command, "start"); + assert.equal(r.lane, "zcode"); +}); + +test("parseArgs: bare bili --lane defaults to the start command (#4368)", () => { + const r = parseArgs(["--lane", "pi"]); + assert.equal(r.command, "start"); + assert.equal(r.lane, "pi"); +}); + +test("parseArgs: --lane= equals form (#4368)", () => { + const r = parseArgs(["start", "--lane=zcode"]); + assert.equal(r.command, "start"); + assert.equal(r.lane, "zcode"); +}); + +test("parseArgs: --lane without a value or with an empty value exits 2 (#4368)", async () => { + assert.equal(await captureExit(() => parseArgs(["start", "--lane"])), 2); + assert.equal(await captureExit(() => parseArgs(["start", "--lane", ""])), 2); +}); + +test("parseArgs: unknown --lane name exits 2 (#4368)", async () => { + assert.equal(await captureExit(() => parseArgs(["start", "--lane", "zcdoe"])), 2); +}); + +test("parseArgs: --lane is rejected outside 'start' (#4368)", async () => { + assert.equal(await captureExit(() => parseArgs(["update", "--lane", "pi"])), 2); + assert.equal(await captureExit(() => parseArgs(["doctor", "--lane", "pi"])), 2); +}); diff --git a/tests/launcher.test.ts b/tests/launcher.test.ts index b98142051c..99e05800c0 100644 --- a/tests/launcher.test.ts +++ b/tests/launcher.test.ts @@ -1562,15 +1562,15 @@ test("ensureProxyRunning: armed daemon (no lane) stays shareable with any client assert.equal(handle.attached, true); }); -// #1335: the attach gate — an unarmed listener is never attached by +// #1335: the attach gate — an unarmed LAUNCHED listener is never attached by // default; the hook spawns its own session-owned proxy so every session runs // the currently installed bili and the proxy dies with the last session -// (#1186 semantics). #1660 narrows the gate to LANE'D instances: a lane'd -// proxy with a dead/unarmed watchdog is a lifecycle-drift symptom and is -// refused; a USER-ZONE instance (manual `bili start`: no lane, no launch -// token) is deliberately maintained by the user and IS attachable — see the -// dedicated user-zone test below. -test("ensureProxyRunning: unarmed LANE'D listener is not attached by default — self-managed spawn (#1335/#1660)", async () => { +// (#1186 semantics). The exemption is the USER ZONE: token-less manual +// `bili start` daemons — with or WITHOUT a declared lane (#1660/#4368) — are +// deliberately maintained by the user and ARE attachable; see the dedicated +// user-zone tests below. A launch token marks a launcher-spawned child, so +// an orphaned one (dead parent) keeps being refused here. +test("ensureProxyRunning: unarmed SPAWNED lane'd listener (launch token present) is not attached by default — self-managed spawn (#1335)", async () => { let spawnCalls = 0; let registered = 0; let childToken = ""; @@ -1586,7 +1586,7 @@ test("ensureProxyRunning: unarmed LANE'D listener is not attached by default — }, fetchImpl: async () => ({ ok: true }), fetchHealthInfo: async () => ({ ok: true, instanceId: "daemon-1", watchdog: { armed: false } }), - readInstanceFile: () => (spawned ? recordedInstance({ launchToken: childToken }) : recordedInstance({ instanceId: "daemon-1", lane: "claude-native" })), + readInstanceFile: () => (spawned ? recordedInstance({ launchToken: childToken }) : recordedInstance({ instanceId: "daemon-1", lane: "claude-native", launchToken: "orphan-token" })), registerWatcher: async () => { registered++; return "refused"; @@ -1595,7 +1595,7 @@ test("ensureProxyRunning: unarmed LANE'D listener is not attached by default — scriptPath: FP_SCRIPT, }, ); - assert.equal(spawnCalls, 1, "self-managed proxy spawned instead of attaching to the unarmed lane'd daemon"); + assert.equal(spawnCalls, 1, "self-managed proxy spawned instead of attaching to the unarmed launched daemon"); assert.ok(handle.child); assert.equal(handle.attached, undefined); assert.equal(registered, 0, "no watcher registration is attempted against the refused daemon"); @@ -1659,6 +1659,96 @@ test("ensureProxyRunning: unarmed USER-ZONE daemon (manual `bili start`) is atta assert.equal(registered, 1); }); +// #4368: a MANUAL daemon that declares its own lane (`bili start --lane`, +// BILI_LAUNCHER_LANE) keeps the #1660 user-zone exemption — its own-lane hook +// attaches despite the unarmed watchdog instead of spawning a duplicate. +// The manual daemon takes no watchers (no parent pid), so the attach lands +// with refusedWatcher set — the #1322 host-visible warning path stays live. +test("ensureProxyRunning: unarmed LANE'd MANUAL daemon (no launch token) attaches by its own lane (#4368/#1335/#1660)", async () => { + let spawnCalls = 0; + let registered = 0; + const handle = await ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false, lane: "zcode" }, + { + spawnImpl: () => { + spawnCalls++; + return makeFakeChild(42507); + }, + fetchImpl: async () => ({ ok: true }), + fetchHealthInfo: async () => ({ ok: true, instanceId: "manual-lane-1", watchdog: { armed: false } }), + readInstanceFile: () => recordedInstance({ instanceId: "manual-lane-1", lane: "zcode" }), + registerWatcher: async () => { + registered++; + return "refused"; + }, + sleep: () => Promise.resolve(), + scriptPath: FP_SCRIPT, + }, + ); + assert.equal(spawnCalls, 0, "the user-declared lane daemon is reused, not doubled"); + assert.equal(handle.attached, true); + assert.equal(registered, 1); + assert.equal(handle.refusedWatcher, true, "a manual daemon takes no watchers — the #1322 warning path stays live"); +}); + +// Negative twin: the #4368 exemption is MANUAL-only. A launcher-spawned +// instance always carries a launch token, so an unarmed LANE'D spawned proxy +// (a crashed session's orphan) is still refused loudly (#1335). +test("ensureProxyRunning: unarmed LANE'd SPAWNED daemon (launch token present) is still refused (#4368/#1335)", async () => { + let spawnCalls = 0; + let childToken = ""; + let registered = 0; + const handle = await ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false, lane: "claude-native" }, + { + spawnImpl: (_cmd, _args, options) => { + childToken = options.env?.BILI_LAUNCH_TOKEN ?? ""; + spawnCalls++; + return makeFakeChild(42508); + }, + fetchImpl: async () => ({ ok: true }), + fetchHealthInfo: async () => ({ ok: true, instanceId: "orphan-1", watchdog: { armed: false } }), + readInstanceFile: () => (spawnCalls > 0 ? recordedInstance({ launchToken: childToken }) : recordedInstance({ instanceId: "orphan-1", lane: "claude-native", launchToken: "tok-orphan" })), + registerWatcher: async () => { + registered++; + return "ok"; + }, + sleep: () => new Promise((r) => setTimeout(r, 0)), + scriptPath: FP_SCRIPT, + }, + ); + assert.equal(spawnCalls, 1, "the orphan is refused — self-managed spawn instead"); + assert.ok(handle.child); + assert.equal(handle.attached, undefined); + assert.equal(registered, 0, "no watcher registration against the refused orphan"); +}); + +// Cross-lane negative: a lane-tagged manual daemon is NOT ridden by a +// DIFFERENT lane's hook under the default own-lane policy — lane isolation +// holds even though the candidate is user-zone-exempt from the lifecycle gate. +test("ensureProxyRunning: a lane-tagged manual daemon is not ridden by a different lane by default (#4368/#2877)", async () => { + let spawnCalls = 0; + let childToken = ""; + const handle = await ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false, lane: "codex" }, + { + spawnImpl: (_cmd, _args, options) => { + childToken = options.env?.BILI_LAUNCH_TOKEN ?? ""; + spawnCalls++; + return makeFakeChild(42509); + }, + fetchImpl: async () => ({ ok: true }), + fetchHealthInfo: async () => ({ ok: true, instanceId: "manual-zcode-1", watchdog: { armed: false } }), + readInstanceFile: () => (spawnCalls > 0 ? recordedInstance({ launchToken: childToken }) : recordedInstance({ instanceId: "manual-zcode-1", lane: "zcode" })), + registerWatcher: async () => "ok", + sleep: () => new Promise((r) => setTimeout(r, 0)), + scriptPath: FP_SCRIPT, + }, + ); + assert.equal(spawnCalls, 1, "own-lane policy: a different lane's manual daemon is skipped, not ridden"); + assert.ok(handle.child); +}); + test("ensureProxyRunning: a lane'd launch with port 0 binds the zone preference and settles it sticky (#1660)", async () => { let spawnedArgs: string[] | null = null; const preferred: string[] = []; @@ -1720,7 +1810,7 @@ test("ensureProxyRunning: an unlane'd launch keeps the OS ephemeral default — assert.deepEqual(settled, [], "no sticky write without a lane"); }); -test("ensureProxyRunning: unverifiable lane'd listener (no watchdog field, pre-#1330 build) is treated as unarmed (#1335)", async () => { +test("ensureProxyRunning: unverifiable LAUNCHED lane'd listener (missing watchdog field) is treated as unarmed (#1335)", async () => { let spawnCalls = 0; let childToken = ""; let spawned = false; @@ -1735,7 +1825,7 @@ test("ensureProxyRunning: unverifiable lane'd listener (no watchdog field, pre-# }, fetchImpl: async () => ({ ok: true }), fetchHealthInfo: async () => ({ ok: true, instanceId: "stale-daemon" }), - readInstanceFile: () => (spawned ? recordedInstance({ launchToken: childToken }) : recordedInstance({ instanceId: "stale-daemon", lane: "zcode" })), + readInstanceFile: () => (spawned ? recordedInstance({ launchToken: childToken }) : recordedInstance({ instanceId: "stale-daemon", lane: "zcode", launchToken: "orphan-stale" })), sleep: () => new Promise((r) => setTimeout(r, 0)), scriptPath: FP_SCRIPT, }, @@ -1777,7 +1867,7 @@ test("ensureProxyRunning: strictPort launch fails fast when its pinned port is h }, fetchImpl: async () => ({ ok: true }), fetchHealthInfo: async () => ({ ok: true, instanceId: "daemon-1", watchdog: { armed: false } }), - readInstanceFile: () => recordedInstance({ origin: "http://127.0.0.1:8799", port: 8799, instanceId: "daemon-1", lane: "claude-native" }), + readInstanceFile: () => recordedInstance({ origin: "http://127.0.0.1:8799", port: 8799, instanceId: "daemon-1", lane: "claude-native", launchToken: "orphan-strict" }), sleep: () => Promise.resolve(), scriptPath: FP_SCRIPT, }, @@ -8044,13 +8134,13 @@ test("attach diagnostics record a fingerprint-mismatch skip (#1623)", async () = test("attach diagnostics record a lifecycle-gate refusal (#1623)", async () => { const diag: string[] = []; - // #1660: an unarmed instance WITHOUT a lane is a user-zone manual start - // and attaches by default — the refusal path needs a lane'd one. + // #1660/#4368: a token-less manual start attaches by default even WITH a + // declared lane — the refusal path needs a launched (token'd) one. const inst = await findLiveAttachableInstance( { host: "127.0.0.1", port: 0, passthrough: false, debug: false }, { fetchHealthInfo: async () => ({ ok: true, instanceId: "inst-1" }), - readInstanceFile: () => recordedInstance({ lane: "zcode" }), + readInstanceFile: () => recordedInstance({ lane: "zcode", launchToken: "orphan-diag" }), attachDiag: (m) => diag.push(m), scriptPath: FP_SCRIPT, }, @@ -8319,11 +8409,11 @@ test("user-actionable gate refusal stays on the terminal — not hidden with the { host: "127.0.0.1", port: 0, passthrough: false, debug: false }, { fetchHealthInfo: async () => ({ ok: true, instanceId: "inst-1" }), - readInstanceFile: () => recordedInstance({ lane: "opencode" }), + readInstanceFile: () => recordedInstance({ lane: "opencode", launchToken: "orphan-term" }), scriptPath: FP_SCRIPT, }, ); - assert.equal(inst, undefined, "unverifiable-watchdog lane instance is still refused"); + assert.equal(inst, undefined, "unverifiable-watchdog launched lane instance is still refused"); assert.ok(stderrWrites.some((m) => m.includes("refusing to attach")), `stderr was: ${JSON.stringify(stderrWrites)}`); assert.ok(stateLog(home).includes("refusing to attach"), "file record kept as well"); }); From 611f3c368762f8ac7875c36eba758b3308d16d0e Mon Sep 17 00:00:00 2001 From: ci-check Date: Sat, 24 Oct 2026 15:58:24 +0800 Subject: [PATCH 2/3] chore(docs): update BILI_LAUNCHER_LANE seed so the generated env index matches (#4368) Review fix on #4422: the PR hand-edited the generated param-ref table rows in CONFIGURATION.md/.zh-CN.md without updating the website/config-reference seed, so the CI docs-sync drift guard (regenerate + git diff --exit-code) would fail on this head. The row text also used backticks, which the seed validator forbids. This commit updates the seed desc and ships the generator's output verbatim. --- website/config-reference/env-only.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/website/config-reference/env-only.yaml b/website/config-reference/env-only.yaml index a9d12d77d9..e06df7012d 100644 --- a/website/config-reference/env-only.yaml +++ b/website/config-reference/env-only.yaml @@ -323,9 +323,9 @@ entries: kind: env-only audience: internal group: envonly - desc_en: "Launcher channel: lane identity of the spawning bili process." - desc_zh: "启动器通道:派生方 bili 进程的车道身份。" - desc_ja: "ランチャーチャネル:生成元のbiliプロセスのレーンID。" + desc_en: "Launcher channel: lane identity of the spawning bili process; for manual instances, declared via bili start --lane (flag > env, #4368)." + desc_zh: "启动器通道:派生方 bili 进程的车道身份;手动实例可用 bili start --lane 声明(flag > env,#4368)。" + desc_ja: "ランチャーチャネル:生成元のbiliプロセスのレーンID。手動インスタンスは bili start --lane で宣言(フラグ > 環境変数、#4368)。" - key: BILI_LAUNCHER_PLUGIN type: string default: "unset" From 06f97b263c02964e1daef19d562efd821dafb914 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sat, 14 Nov 2026 07:58:02 +0800 Subject: [PATCH 3/3] docs: re-target #4368 --lane docs to docs/ (post #5920 move) The feature commit's docs edits landed on root-level stub files after master moved them to docs/ (#5920). Re-target the BILI_LAUNCHER_LANE and attach-gate content to the new docs/ location. --- docs/configuration.ja.md | 6 +++--- docs/configuration.md | 6 +++--- docs/configuration.zh-CN.md | 5 +++-- docs/lifecycle.md | 2 +- docs/technical-notes.md | 8 ++++---- docs/technical-notes.zh-CN.md | 8 ++++---- 6 files changed, 18 insertions(+), 17 deletions(-) diff --git a/docs/configuration.ja.md b/docs/configuration.ja.md index 80a4e18ec4..51d65e6510 100644 --- a/docs/configuration.ja.md +++ b/docs/configuration.ja.md @@ -416,7 +416,7 @@ | `BILI_UPGRADE_REPLACEMENT` | boolean-ish | unset | — | 生成チャネル:自己再起動による置換をマークする — 解放されたポートを正確に所有するか、ホッピングせずに終了しなければならない(#3044)。 | | `BILI_OPENCODE_ACP_SPEC` | string | unset | — | 生成チャネル:opencodeネイティブレーン用のACP仕様マーカー。 | | `BILI_LAUNCHER_MODEL_WINDOWS` | string | unset | — | ランチャーチャネル:生成されたクライアントに渡されるモデルウィンドウのオーバーライド。 | -| `BILI_LAUNCHER_LANE` | string | unset | — | ランチャーチャネル:生成元のbiliプロセスのレーンID。 | +| `BILI_LAUNCHER_LANE` | string | unset | — | ランチャーチャネル:生成元のbiliプロセスのレーンID。手動インスタンスは bili start --lane で宣言(フラグ > 環境変数、#4368)。 | | `BILI_LAUNCHER_PLUGIN` | string | unset | — | ランチャーチャネル:プラグインモードのハンドオフマーカー。 | | `BILI_LAUNCHER_DIRECT` | boolean-ish | off | — | ランチャーチャネル:この起動において注入されたプロキシをバイパスする。 | | `BILI_INHERITED_HTTP_PROXY` | string | unset | — | Launcher channel: spawn 境界をまたいで継承された http_proxy の値が保持されます。 | @@ -2184,10 +2184,10 @@ ACP ネイティブエージェント(現在は `pi` 拡張機能)は、プ | `PI_PROXY_ANTHROPIC` | `bili omp` ランチャーによってエクスポートされます (ユーザーの環境から `PI_PROXY` も `PI_PROXY_ANTHROPIC` も来ない場合のみ): OMP の Cowork anthropic トランスポートをプロキシに向かせ、それらのリクエストが node:https 直接ではなく圧縮可能レーンに乗るようにします (#2583/#3556)。ユーザー設定の値は常に優先されます。 | | `BILLION_CONTEXT_PLUGIN` | `0` に設定すると、プラグインモードを完全に無効にします (ワイヤレベルのツール注入が再開)。 | | `BILI_LAUNCHER_MODEL_WINDOWS` | 内部: ランチャーはクライアント自身のモデルごとのコンテキストウィンドウ (pi `models.json`、omp `models.yml`、opencode `models..limit`、codex `model_context_window`) を JSON として起動されたプロキシに渡し、セルフホストモデルに対してナッジの分母が実際のウィンドウと一致するようにします。ランチャーのみが設定します — ユーザー設定はありません。 | -| `BILI_LAUNCHER_LANE` | 内部: ランチャーはクライアントのレーン名 (pi / codex / claude / …) を起動されたプロキシに渡し、インスタンスファイルに記録します (#1225)。再利用はアイデンティティベースです: *異なる宣言された* レーンを持つ 2 つのインスタンスは決して互いにアタッチしません; 宣言されたレーンを持たないインスタンスは手動で開始されたユーザーゾーンデーモンです — デフォルトでアタッチ可能 (#1660)。ランチャーのみが設定します — ユーザー設定はありません。 | +| `BILI_LAUNCHER_LANE` | ランチャーはクライアントのレーン名 (pi / codex / claude / …) を起動されたプロキシに渡し、インスタンスファイルに記録します (#1225)。再利用はアイデンティティベースです: *異なる宣言された* レーンを持つ 2 つのインスタンスは決して互いにアタッチしません; 宣言されたレーンを持たないインスタンスは手動で開始されたユーザーゾーンデーモンです (#1660)。手動インスタンスは **`bili start --lane `** で自身のレーンを宣言できます (#4368): フラグはサーバープロセスのためにこの変数を設定します (フラグ > 環境変数)、かつ起動トークンを持たない手動デーモン — 宣言されたレーンの有無に関わらず — はユーザーゾーンのライフサイクルゲート免除を保持するため、同レーンのフックは重複を起動する代わりにそれにアタッチします。既知の名前: すべての `bili ` 名と `zcode` (未知の名前は起動時に拒否されます)。環境変数を直接設定することは、フラグを渡せないスクリプトのエスケープハッチとして引き続き利用可能です。 | | `BILI_LAUNCHER_PLUGIN` | `0` に設定すると、claude/codex に対するランチャーの bili MCP サーバー注入を無効にします (純粋なワイヤモード); `1` でプラグインモードを強制します。デフォルト: 注入 — ただしローカル/プライベートアップストリーム (sglang/vllm/ollama は codex の名前空間ツールタイプを解析できないため、bili はそこで自動的にワイヤツールにフォールバック) を持つ codex を除く。[Launcher Reference](#launcher-reference) を参照。 | | `BILI_LAUNCHER_DIRECT` | `1` に設定すると、ランチャーでの直接 URL ルーティング (MITM/CA 信頼をドロップ) を行います。[Launcher Reference](#launcher-reference) を参照。 | -| `BILI_NATIVE_ATTACH_EXTERNAL` | アタッチゲートエスケープハッチ (#1335)。レーン付きネイティブフックは、アームされたセッションライフサイクルウォッチドッグ (`/__bili/health` で `watchdog.armed == true`) を報告する実行中プロキシにのみアタッチします — アームされていない*レーン付き*プロキシ (クラッシュしたセッションの孤立、またはライフサイクル状態を検証できないインスタンス) は、サイレントに乗る代わりに明確に拒否されます。#1660: **手動で開始された `bili start` デーモン** (レーンなし、起動トークンなし) は定義上ユーザーゾーンです — **アームされた**ユーザーゾーンデーモン (管理された共有プロキシ、#1225) はそれでも互換性のあるクライアントレーンによって乗られますが、**アームされていない**手動デーモンは、デフォルト (`attachPolicy: "own-lane"`, #2877) では、LANEd フックによって乗られず、代わりに自身のものを起動します; #2877 以前のネイティブフックが手動デーモンにデフォルトでアタッチする動作を復元するには `attachPolicy: "global-fallback"` を設定してください。`1`/`true` に設定すると、ウォッチドッグ状態に関係なく、*レーン付き*アームされていないリスナーにもアタッチします (コード/レーン互換のリスナーはすべてアタッチ可能になります。`watchdog` フィールドをまったく報告しない #1330 以前のビルドを含む)。設定ファイルの `"native": { "attachExternal": true }` は同じことをします; 環境変数はファイル値より優先されます。注: `attachExternal` は**レーン付き**デーモンの*ライフサイクルゲート*のみを管理します — ユーザーゾーン (手動) デーモンへのアタッチを開いたり閉じたりしません; その軸は `attachPolicy` / `attachUrl` です。デフォルトは閉じています (レーン付きインスタンスのために)。完全なメカニズム (再利用ルール、リスナートーブル、エスケープハッチ): [technical-notes.md](technical-notes.md#proxy-reuse-and-the-attach-gate-1225-1335-1232-1660)。 | +| `BILI_NATIVE_ATTACH_EXTERNAL` | アタッチゲートエスケープハッチ (#1335)。レーン付きネイティブフックは、アームされたセッションライフサイクルウォッチドッグ (`/__bili/health` で `watchdog.armed == true`) を報告する実行中プロキシにのみアタッチします — アームされていない*レーン付き*プロキシ (クラッシュしたセッションの孤立、またはライフサイクル状態を検証できないインスタンス) は、サイレントに乗る代わりに明確に拒否されます。#1660/#4368: **手動で開始された `bili start` デーモン** (起動トークンなし) は定義上ユーザーゾーンです — **アームされた**ユーザーゾーンデーモン (管理された共有プロキシ、#1225) はそれでも互換性のあるクライアントレーンによって乗られます; フック自身のレーンを宣言した**アームされていない**デーモンは、そのレーンによって乗られます (指定ターゲット、#4368); レーンが一致しない**アームされていない**デーモンは、デフォルト (`attachPolicy: "own-lane"`, #2877) では、LANEd フックによって乗られず、代わりに自身のものを起動します; #2877 以前のネイティブフックが手動デーモンにデフォルトでアタッチする動作を復元するには `attachPolicy: "global-fallback"` を設定してください。`1`/`true` に設定すると、ウォッチドッグ状態に関係なく、*レーン付き*アームされていないリスナーにもアタッチします (コード/レーン互換のリスナーはすべてアタッチ可能になります。`watchdog` フィールドをまったく報告しない #1330 以前のビルドを含む)。設定ファイルの `"native": { "attachExternal": true }` は同じことをします; 環境変数はファイル値より優先されます。注: `attachExternal` は**レーン付き**デーモンの*ライフサイクルゲート*のみを管理します — ユーザーゾーン (手動) デーモンへのアタッチを開いたり閉じたりしません; その軸は `attachPolicy` / `attachUrl` です。デフォルトは閉じています (レーン付きインスタンスのために)。完全なメカニズム (再利用ルール、リスナートーブル、エスケープハッチ): [technical-notes.md](technical-notes.md#proxy-reuse-and-the-attach-gate-1225-1335-1232-1660)。 | | `BILI_ZCODE_ROUTE` | zcode ネイティブプラグインルーティングスコープ (#1622): `all` (デフォルト — 使用可能な http(s) baseURL を持つすべてのプロバイダーエントリが圧縮に乗る、pi/dsh パリティ)、`plans` (#1622 以前の bigmodel コーディングプランホワイトリスト)、`none` (オプトアウト; ブートストラップはストアを直接のままにします)。互換性エスケープハッチ — ファイル同等物は**ありません**; ルーティングはデフォルトでオンです。 | | `BILI_ZONE_PORT` | 自己管理ポートゾーンのベース (#1660、デフォルト `18787`): すべての*レーン起動*プロキシ (claude/zcode ネイティブフック、ポート 0 を乗るランチャーレーン) はまずレーンのスティッキーレコードを試み、それがない場合はこのベースを試みます; ポート競合は子の +1 階段によって解決されます — ただし保持者が異なるビルドを実行している同じレーンの先行者 (アップグレード再起動オーバーラップ) の場合を除き、子はそれを待機 (最大 5 秒) し、ドリフトする代わりに同じポートを再バインドします (#1723) — そして決定されたポートは `/port-zone.json` 下にスティッキーとして記録され、後の起動が自動的にドリフトに従います。手動 `bili start` は独自のデフォルト (`8787`) を保持します — ユーザーゾーンはレーンによって決して触れられません。 | | `BILI_ZCODE_PORT` | zcode ネイティブレーンのプロキシのために**正確な**ポートをピン留めします (#1660): 起動は厳密ポートになります — スクワッターはホッピングする代わりに明確に拒否されます — そして共有ストアに書き込まれたラッパーはハンドオフなしでもセッション再起動を生き残ります。それがない場合、レーンは自己管理ゾーン (`BILI_ZONE_PORT` ベース + スティッキードリフトフォロー) を乗ります。 | diff --git a/docs/configuration.md b/docs/configuration.md index bae6ef4768..5c49047b92 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -417,7 +417,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `BILI_UPGRADE_REPLACEMENT` | boolean-ish | unset | — | Spawn channel: marks a self-restart replacement — it must own exactly the freed port or exit without hopping (#3044). | | `BILI_OPENCODE_ACP_SPEC` | string | unset | — | Spawn channel: ACP spec marker for opencode-native lanes. | | `BILI_LAUNCHER_MODEL_WINDOWS` | string | unset | — | Launcher channel: model-window overrides passed into spawned clients. | -| `BILI_LAUNCHER_LANE` | string | unset | — | Launcher channel: lane identity of the spawning bili process. | +| `BILI_LAUNCHER_LANE` | string | unset | — | Launcher channel: lane identity of the spawning bili process; for manual instances, declared via bili start --lane (flag > env, #4368). | | `BILI_LAUNCHER_PLUGIN` | string | unset | — | Launcher channel: plugin-mode handoff marker. | | `BILI_LAUNCHER_DIRECT` | boolean-ish | off | — | Launcher channel: bypass the injected proxy for this launch. | | `BILI_INHERITED_HTTP_PROXY` | string | unset | — | Launcher channel: inherited http_proxy value preserved across the spawn boundary. | @@ -2195,10 +2195,10 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `PI_PROXY_ANTHROPIC` | Exported by the `bili omp` launcher (only when neither `PI_PROXY` nor `PI_PROXY_ANTHROPIC` comes from the user's environment): points OMP's Cowork anthropic transport at the proxy so those requests ride the compressible lane instead of node:https direct (#2583/#3556). User-set values always win. | | `BILLION_CONTEXT_PLUGIN` | Set `0` to disable plugin mode entirely (wire-level tool injection resumes). | | `BILI_LAUNCHER_MODEL_WINDOWS` | Internal: the launcher hands the client's own per-model context windows (pi `models.json`, omp `models.yml`, opencode `models..limit`, codex `model_context_window`) to the spawned proxy as JSON, so the nudge denominator matches the real window for self-hosted models. Only the launcher sets it — no user configuration. | - | `BILI_LAUNCHER_LANE` | Internal: the launcher hands its client's lane name (pi / codex / claude / …) to the spawned proxy, which records it in the instance file (#1225). Reuse is identity-based: two instances with *different declared* lanes never attach to each other; an instance without a declared lane is a manually-started user-zone daemon — attachable by default (#1660). Only the launcher sets it — no user configuration. | + | `BILI_LAUNCHER_LANE` | The launcher hands its client's lane name (pi / codex / claude / …) to the spawned proxy, which records it in the instance file (#1225). Reuse is identity-based: two instances with *different declared* lanes never attach to each other; an instance without a declared lane is a manually-started user-zone daemon (#1660). Manual instances can declare their own lane with **`bili start --lane `** (#4368): the flag sets this variable for the server process (flag > env), and a token-less manual daemon — with or without a declared lane — keeps the user-zone lifecycle-gate exemption, so same-lane hooks attach to it instead of spawning duplicates. Known names: every `bili ` name plus `zcode` (unknown names are rejected at startup). Setting the env var directly remains available as an escape hatch for scripts that cannot pass flags. | | `BILI_LAUNCHER_PLUGIN` | Set `0` to disable the launcher's bili MCP server injection for claude/codex (pure wire mode); `1` forces plugin mode. Default: injected — except codex with a local/private upstream (sglang/vllm/ollama cannot parse codex's namespace tool type, so bili auto-falls back to wire tools there). See [Launcher Reference](#launcher-reference). | | `BILI_LAUNCHER_DIRECT` | Set `1` for direct-URL routing in the launcher (drop MITM/CA trust). See [Launcher Reference](#launcher-reference). | - | `BILI_NATIVE_ATTACH_EXTERNAL` | Attach-gate escape hatch (#1335). Lane'd native hooks attach to a running proxy only when it reports an armed session-lifecycle watchdog (`watchdog.armed == true` in `/__bili/health`) — an unarmed *lane'd* proxy (a crashed session's orphan, or an instance whose lifecycle state cannot be verified) is refused loudly instead of being silently ridden. #1660: a **manually started `bili start` daemon** (no lane, no launch token) is user-zone by definition — an **armed** user-zone daemon (a managed shared proxy, #1225) is still ridden by any compatible client lane, but an **unarmed** manual daemon is, by default (`attachPolicy: "own-lane"`, #2877), NOT ridden by a LANEd hook, which spawns its own instead; set `attachPolicy: "global-fallback"` to restore the pre-#2877 behavior where native hooks attach to a manual daemon by default. Set `1`/`true` to also attach to *lane'd* unarmed listeners anyway: any code/lane-compatible listener becomes attachable regardless of watchdog state (including pre-#1330 builds that report no `watchdog` field at all). `"native": { "attachExternal": true }` in the config file does the same; the env var wins over the file value. Note: `attachExternal` governs only the *lifecycle gate* for **lane'd** daemons — it does not open or close attachment to a user-zone (manual) daemon; that axis is `attachPolicy` / `attachUrl`. Default is closed (for lane'd instances). Full mechanics (reuse rules, listener table, escape hatch): [technical-notes.md](technical-notes.md#proxy-reuse-and-the-attach-gate-1225-1335-1232-1660). | + | `BILI_NATIVE_ATTACH_EXTERNAL` | Attach-gate escape hatch (#1335). Lane'd native hooks attach to a running proxy only when it reports an armed session-lifecycle watchdog (`watchdog.armed == true` in `/__bili/health`) — an unarmed *lane'd* proxy (a crashed session's orphan, or an instance whose lifecycle state cannot be verified) is refused loudly instead of being silently ridden. #1660/#4368: a **manually started `bili start` daemon** (no launch token) is user-zone by definition — an **armed** user-zone daemon (a managed shared proxy, #1225) is still ridden by any compatible client lane; an **unarmed** one declaring the hook's own lane is ridden by that lane (its designated target, #4368); an **unarmed** one without a matching lane is, by default (`attachPolicy: "own-lane"`, #2877), NOT ridden by a LANEd hook, which spawns its own instead; set `attachPolicy: "global-fallback"` to restore the pre-#2877 behavior where native hooks attach to a manual daemon by default. Set `1`/`true` to also attach to *lane'd* unarmed listeners anyway: any code/lane-compatible listener becomes attachable regardless of watchdog state (including pre-#1330 builds that report no `watchdog` field at all). `"native": { "attachExternal": true }` in the config file does the same; the env var wins over the file value. Note: `attachExternal` governs only the *lifecycle gate* for **lane'd** daemons — it does not open or close attachment to a user-zone (manual) daemon; that axis is `attachPolicy` / `attachUrl`. Default is closed (for lane'd instances). Full mechanics (reuse rules, listener table, escape hatch): [technical-notes.md](technical-notes.md#proxy-reuse-and-the-attach-gate-1225-1335-1232-1660). | | `BILI_ZCODE_ROUTE` | zcode native-plugin routing scope (#1622): `all` (default — every provider entry with a usable http(s) baseURL rides compression, pi/dsh parity), `plans` (pre-#1622 bigmodel coding-plan whitelist), `none` (opt out; the bootstrap leaves the store direct). Compat escape hatch — there is **no** file equivalent; routing is on by default. | | `BILI_ZONE_PORT` | Base of the self-managed port zone (#1660, default `18787`): every *lane-spawned* proxy (claude/zcode native hooks, launcher lanes riding port 0) tries the lane's sticky record first, else this base; port collisions resolve via the child's +1 ladder — except when the holder is a same-lane predecessor running a different build (an upgrade-restart overlap), which the child waits out (up to 5s) and then rebinds the SAME port instead of drifting (#1723) — and the settled port is recorded sticky under `/port-zone.json` so later launches follow drift automatically. Manual `bili start` keeps its own default (`8787`) — the user zone is never touched by lanes. | | `BILI_ZCODE_PORT` | Pin an **exact** port for the zcode native lane's proxy (#1660): the launch becomes strict-port — a squatter is refused loudly instead of hopping — and wrappers written into the shared store survive session restarts even without handoff. Without it the lane rides the self-managed zone (`BILI_ZONE_PORT` base + sticky drift following). | diff --git a/docs/configuration.zh-CN.md b/docs/configuration.zh-CN.md index 45861d8461..9594a0ebd5 100644 --- a/docs/configuration.zh-CN.md +++ b/docs/configuration.zh-CN.md @@ -417,7 +417,7 @@ | `BILI_UPGRADE_REPLACEMENT` | boolean-ish | unset | — | 派生通道:标记自重启替换进程——必须独占被释放的精确端口,否则直接退出而非跳端口(#3044)。 | | `BILI_OPENCODE_ACP_SPEC` | string | unset | — | 派生通道:opencode 原生车道的 ACP 规格标记。 | | `BILI_LAUNCHER_MODEL_WINDOWS` | string | unset | — | 启动器通道:传入被派生客户端的模型窗口覆盖。 | -| `BILI_LAUNCHER_LANE` | string | unset | — | 启动器通道:派生方 bili 进程的车道身份。 | +| `BILI_LAUNCHER_LANE` | string | unset | — | 启动器通道:派生方 bili 进程的车道身份;手动实例可用 bili start --lane 声明(flag > env,#4368)。 | | `BILI_LAUNCHER_PLUGIN` | string | unset | — | 启动器通道:插件模式交接标记。 | | `BILI_LAUNCHER_DIRECT` | boolean-ish | off | — | 启动器通道:本次启动绕过注入的代理。 | | `BILI_INHERITED_HTTP_PROXY` | string | unset | — | 启动器通道:跨派生边界保留的 http_proxy 继承值。 | @@ -2163,9 +2163,10 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 | `PI_PROXY_ANTHROPIC` | 由 `bili omp` launcher 导出(仅当 `PI_PROXY` 与 `PI_PROXY_ANTHROPIC` 均未来自用户环境时):把 OMP 的 Cowork anthropic 传输指向代理,让这些请求走可压缩通道而非 node:https 直连(#2583/#3556)。用户设置的值始终优先。 | | `BILLION_CONTEXT_PLUGIN` | 设 `0` 彻底关闭插件模式(恢复 wire 层工具注入)。 | | `BILI_LAUNCHER_MODEL_WINDOWS` | 内部使用:launcher 把客户端自身配置里的逐模型上下文窗口(pi `models.json`、omp `models.yml`、opencode `models..limit`、codex `model_context_window`)以 JSON 传给自己拉起的代理,让 nudge 分母对自托管模型也用真实窗口。只有 launcher 会设置,无需用户配置。 | +| `BILI_LAUNCHER_LANE` | launcher 把自己客户端的车道名(pi / codex / claude / …)传给派生出的代理,代理记入实例文件(#1225)。复用基于身份:两个*不同声明*车道的实例永不互相附着;未声明车道的实例是手工拉起的用户主权区守护进程(#1660)。手动实例可用 **`bili start --lane `** 声明自己的车道(#4368):flag 为该服务进程设置此变量(flag > env),无 launch token 的手动守护——无论是否声明车道——都保留用户主权区生命周期门禁豁免,因此同车道 hook 会附着到它而不是另起重复实例。合法取值:所有 `bili ` 名加 `zcode`(未知名字启动即报错)。直接设置该环境变量仍可作为无法传 flag 的脚本的逃生舱。 | | `BILI_LAUNCHER_PLUGIN` | 设 `0` 关闭 launcher 为 claude/codex 注入 bili MCP 服务器(退回纯 wire 模式);设 `1` 强制插件模式。默认注入——但 codex 上游为本地/私网地址时自动退回 wire 模式(sglang/vllm/ollama 不解析 codex 的 namespace 工具类型)。见[启动器参考](#启动器参考)。 | | `BILI_LAUNCHER_DIRECT` | 设 `1` 启用 launcher 直连 URL 路由(放弃 MITM/CA 信任)。见[启动器参考](#启动器参考)。 | -| `BILI_NATIVE_ATTACH_EXTERNAL` | 附着门禁逃生舱(#1335)。lane 型原生 hook 只附着于报告了 armed 会话生命周期看门狗(`/__bili/health` 里 `watchdog.armed == true`)的代理——未武装的 lane 型代理(崩溃会话的孤儿、或生命周期状态无法核验的实例)被大声拒绝而不是被静默搭乘。#1660:**手工 `bili start` 守护进程**(无 lane、无 launch token)按定义属于用户主权区——一台**已武装**的用户区守护(受管共享代理,#1225)仍会被任何兼容 client lane 搭车;但一台**未武装**的手动守护在默认(`attachPolicy: "own-lane"`,#2877)下**不会**被 lane 型 hook 搭车 —— 它自行派生;设 `attachPolicy: "global-fallback"` 恢复 #2877 之前「原生 hook 默认附着手动守护」的行为。无论哪种情况,其寿命与版本都由你自己负责。设 `1`/`true` 可以连 lane 型未武装监听者也一并附着:任何 code/lane 兼容的监听者无论看门狗状态都可附着(包括根本不报 `watchdog` 字段的 pre-#1330 构建)。配置文件里 `"native": { "attachExternal": true }` 等效;环境变量优先于文件值。注意:`attachExternal` 只管辖 **lane 型**守护的*生命周期门禁* —— 它并不开/关对 user-zone(手动)守护的附着;那个轴是 `attachPolicy` / `attachUrl`。默认关闭(针对 lane 型实例)。完整机制(复用规则、监听者表、逃生舱)见 [technical-notes.zh-CN.md](technical-notes.zh-CN.md#代理复用与附着门禁122513351232)。 | +| `BILI_NATIVE_ATTACH_EXTERNAL` | 附着门禁逃生舱(#1335)。lane 型原生 hook 只附着于报告了 armed 会话生命周期看门狗(`/__bili/health` 里 `watchdog.armed == true`)的代理——未武装的 lane 型代理(崩溃会话的孤儿、或生命周期状态无法核验的实例)被大声拒绝而不是被静默搭乘。#1660/#4368:**手工 `bili start` 守护进程**(无 launch token)按定义属于用户主权区——一台**已武装**的用户区守护(受管共享代理,#1225)仍会被任何兼容 client lane 搭车;一台**未武装**但声明了 hook 自己车道的会被该车道附着(指定目标,#4368);一台**未武装**且车道不匹配的在默认(`attachPolicy: "own-lane"`,#2877)下**不会**被 lane 型 hook 搭车 —— 它自行派生;设 `attachPolicy: "global-fallback"` 恢复 #2877 之前「原生 hook 默认附着手动守护」的行为。无论哪种情况,其寿命与版本都由你自己负责。设 `1`/`true` 可以连 lane 型未武装监听者也一并附着:任何 code/lane 兼容的监听者无论看门狗状态都可附着(包括根本不报 `watchdog` 字段的 pre-#1330 构建)。配置文件里 `"native": { "attachExternal": true }` 等效;环境变量优先于文件值。注意:`attachExternal` 只管辖 **lane 型**守护的*生命周期门禁* —— 它并不开/关对 user-zone(手动)守护的附着;那个轴是 `attachPolicy` / `attachUrl`。默认关闭(针对 lane 型实例)。完整机制(复用规则、监听者表、逃生舱)见 [technical-notes.zh-CN.md](technical-notes.zh-CN.md#代理复用与附着门禁122513351232)。 | | `BILI_ZCODE_ROUTE` | zcode 原生插件路由范围(#1622):`all`(默认 —— 每个有可用 http(s) baseURL 的 provider 条目都吃压缩,pi/dsh 对齐)、`plans`(#1622 前的 bigmodel coding-plan 白名单)、`none`(整体退出,bootstrap 不碰 store)。兼容逃生舱 —— **没有**文件等效项;路由默认即开启。 | | `BILI_ZONE_PORT` | 自管端口区基准(#1660,默认 `18787`):所有 lane 拉起的代理(claude/zcode 原生 hook、跑 0 号口的 launcher lane)先试该 lane 的粘性记录,否则这个基准口;端口碰撞由子进程 +1 阶梯解决(例外:占用者是同 lane 的旧版本实例——升级重启重叠时——子进程最多等 5 秒让它释放并复用同一端口,而不是漂移,#1723),落定的口记录在 `/port-zone.json` 粘性表里,后续拉起自动跟随漂移。手工 `bili start` 保持自己的默认口(`8787`)——lane 永不碰用户主权区。 | | `BILI_ZCODE_PORT` | 为 zcode 原生通道钉死**确切端口**(#1660):启动变为严格端口——占用者被大声拒绝而不是跳口——共享 store 里的包装也因此跨会话重启存活,无需交接。不设则通道骑自管区(`BILI_ZONE_PORT` 基准 + 粘性漂移跟随)。 | diff --git a/docs/lifecycle.md b/docs/lifecycle.md index 97c4400148..cf2e2f60f9 100644 --- a/docs/lifecycle.md +++ b/docs/lifecycle.md @@ -74,7 +74,7 @@ | `BILI_PARENT_PID` | owner-pid 看门狗(会话生命周期归属) | | `BILI_STRICT_PORT` | `=1` claude SessionStart hook 退出端口重试(#964) | | `BILI_OPENCODE_ACP_SPEC` | 剥离版 ACP spec 临时配置**文件路径**提示 | -| `BILI_LAUNCHER_LANE` | lane 身份戳(attach 时比对归属) | +| `BILI_LAUNCHER_LANE` | lane 身份戳(attach 时比对归属);手动实例可用 `bili start --lane ` 声明(#4368) | | `BILI_LAUNCHER_MODEL_WINDOWS` / `BILI_LAUNCHER_MODEL_MAX_OUTPUTS` | 模型窗口/输出上限 JSON,传给子进程对齐 nudge 分母与输出预留 | | `BILI_INHERITED_HTTP_PROXY` / `BILI_INHERITED_HTTPS_PROXY` / `BILI_INHERITED_ALL_PROXY` / `BILI_INHERITED_NO_PROXY` | 继承调用方代理设置转发给 proxy 子进程 | | `BILI_MITM_HOSTS` / `BILI_MITM_DOMAINS` | MITM 主机/域名单传给子进程 | diff --git a/docs/technical-notes.md b/docs/technical-notes.md index 0e5142f790..52d954c3fd 100644 --- a/docs/technical-notes.md +++ b/docs/technical-notes.md @@ -24,18 +24,18 @@ guess. Opt-out envs: `BILI_NATIVE_PI=0`, `BILI_NATIVE_OMP=0`, `BILI_NATIVE_OPENC ## Proxy reuse and the attach gate (#1225, #1335, #1232, #1660) -A native hook may attach to an already-running proxy instead of spawning its own — only when it passes the lifecycle gate below. Reuse is identity-based (#1225): an existing proxy is attached only when it runs the **same code** (sha256 of the entry script, recorded in the instance file), its **lane is compatible** — each launcher declares its client's lane, two *different declared* lanes never share, and an instance without a declared lane is a manually started user-zone daemon, wildcard-compatible on that axis — **and it passes the lifecycle gate** (§below): an armed parent-pid watchdog (`watchdog.armed == true`), i.e. it was spawned by a launcher with a parent pid and dies when the last attached session dies, **or** it is a user-zone instance (no lane, no launch token), which is exempt by definition (#1660). Instances written before #1225 carry no code fingerprint and are therefore never attached: a rebuilt or updated install always starts a fresh proxy on the next launch, so fixes take effect immediately instead of silently serving stale code. +A native hook may attach to an already-running proxy instead of spawning its own — only when it passes the lifecycle gate below. Reuse is identity-based (#1225): an existing proxy is attached only when it runs the **same code** (sha256 of the entry script, recorded in the instance file), its **lane is compatible** — each launcher declares its client's lane, two *different declared* lanes never share, and an instance without a declared lane is a manually started user-zone daemon, wildcard-compatible on that axis — **and it passes the lifecycle gate** (§below): an armed parent-pid watchdog (`watchdog.armed == true`), i.e. it was spawned by a launcher with a parent pid and dies when the last attached session dies, **or** it is a user-zone instance (no launch token — a manual `bili start`, with or without a declared lane), which is exempt by definition (#1660/#4368). Instances written before #1225 carry no code fingerprint and are therefore never attached: a rebuilt or updated install always starts a fresh proxy on the next launch, so fixes take effect immediately instead of silently serving stale code. | Listener | Attaches? | Why | |---|---|---| | Proxy spawned by this session | ✅ | armed at birth | | Another session's armed shared proxy (watcher set, #1186) | ✅ | sharing is by design | -| Manually started `bili start` daemon (user zone, #1660) | 🔶 conditional | **user-zone** instance (no lane, no launch token): an **armed** one (a managed shared proxy, #1225) is ridden by any compatible client lane; an **unarmed** manual one is, by default (`attachPolicy: own-lane`, #2877), NOT ridden by a LANEd hook — it spawns its own instead. Ridden instead under `attachPolicy: global-fallback` (pre-#2877) or `attachExternal=1`. You own its lifetime and version either way | +| Manually started `bili start` daemon (user zone, #1660) | 🔶 conditional | **user-zone** instance (no launch token — with or without a declared lane, #4368): an **armed** one (a managed shared proxy, #1225) is ridden by any compatible client lane; an **unarmed** one declaring ITS OWN lane is ridden by that lane's hook (its designated target, #4368); an **unarmed** one without a matching lane is, by default (`attachPolicy: own-lane`, #2877), NOT ridden by a LANEd hook — it spawns its own instead. Ridden instead under `attachPolicy: global-fallback` (pre-#2877) or `attachExternal=1`. You own its lifetime and version either way | | Unarmed **lane'd** proxy (crashed-session orphan; pre-#1330 unverifiable) | ❌ loudly refused | lifecycle-drift symptom (#1335): riding it would silently reuse a proxy no live session owns | -The hook probes each candidate's `/__bili/health` before attaching: armed → attach and register a watcher (unchanged); an **armed user-zone** candidate attaches regardless of the lane-affinity policy (a managed shared proxy, #1225); an **unarmed user-zone** (manual) candidate attaches only under `attachPolicy: global-fallback` (pre-#2877) or `attachExternal=1` — by default (`own-lane`) a LANEd hook spawns its own (#2877); an unarmed **lane'd** candidate (a crashed session's orphan, or a pre-#1330 build that reports no `watchdog` field at all — unverifiable, treated as unarmed) is refused **loudly**, and the session spawns its own proxy in the self-managed port zone (base `18787`, or the lane's sticky drift record; armed at birth, dies with the last session, #1186 watcher semantics). Version skew stays fixed: the code-fingerprint check runs first, so a rebuilt or updated install never rides a stale daemon even through the user-zone exemption. Cost: one extra short-lived proxy process per session when nothing attachable exists (session state is shared on disk, so compression continuity is unaffected); the multi-instance warning (#394) becomes correspondingly more common. **Escape hatch:** `native.attachExternal: true` in the config file or `BILI_NATIVE_ATTACH_EXTERNAL=1` extends attaching to *lane'd* listeners regardless of watchdog state (including pre-#1330 builds) — you then own those daemons' lifetimes and versions; `attachExternal` governs only the *lifecycle gate* for **lane'd** daemons (it does not open or close user-zone attachment — that axis is `attachPolicy`); `attachUrl` (env `BILI_MCP_PROXY` / `--origin`) pins an explicit target origin. Explicit user-directed attaches (`BILLION_CONTEXT_ATTACH` / preset `BILLION_CONTEXT_PROXY` for kimi/dsh) bypass discovery entirely and are exempt by construction. +The hook probes each candidate's `/__bili/health` before attaching: armed → attach and register a watcher (unchanged); an **armed user-zone** candidate attaches regardless of the lane-affinity policy (a managed shared proxy, #1225); an **unarmed user-zone** (manual) candidate declaring the hook's own lane attaches directly (its designated target, #4368; watcher registration is refused and the host warns per #1322), while one WITHOUT a matching lane attaches only under `attachPolicy: global-fallback` (pre-#2877) or `attachExternal=1` — by default (`own-lane`) a LANEd hook spawns its own (#2877); an unarmed **lane'd** candidate (a crashed session's orphan, or a pre-#1330 build that reports no `watchdog` field at all — unverifiable, treated as unarmed) is refused **loudly**, and the session spawns its own proxy in the self-managed port zone (base `18787`, or the lane's sticky drift record; armed at birth, dies with the last session, #1186 watcher semantics). Version skew stays fixed: the code-fingerprint check runs first, so a rebuilt or updated install never rides a stale daemon even through the user-zone exemption. Cost: one extra short-lived proxy process per session when nothing attachable exists (session state is shared on disk, so compression continuity is unaffected); the multi-instance warning (#394) becomes correspondingly more common. **Escape hatch:** `native.attachExternal: true` in the config file or `BILI_NATIVE_ATTACH_EXTERNAL=1` extends attaching to *lane'd* listeners regardless of watchdog state (including pre-#1330 builds) — you then own those daemons' lifetimes and versions; `attachExternal` governs only the *lifecycle gate* for **lane'd** daemons (it does not open or close user-zone attachment — that axis is `attachPolicy`); `attachUrl` (env `BILI_MCP_PROXY` / `--origin`) pins an explicit target origin. Explicit user-directed attaches (`BILLION_CONTEXT_ATTACH` / preset `BILLION_CONTEXT_PROXY` for kimi/dsh) bypass discovery entirely and are exempt by construction. -Attach discovery is lane-aware across **all** live instances (#1232): the launcher probes every live entry in the instance registry, not just the single instance file (last-writer-wins — under concurrent multi-client use it can point at another client's proxy), and applies the gate above to every candidate. Among compatible candidates the newest instance with the launcher's own declared lane wins; an instance without a lane (a user-zone daemon) is wildcard-compatible on the lane axis and gate-exempt by default (#1660) — but whether a LANEd hook actually falls back onto it is governed by `attachPolicy`: `own-lane` (default) does not ride an *unarmed* manual daemon (#2877), while `global-fallback` restores the pre-#2877 wildcard ride. The `another bili instance is running` warning (#394) is lane-aware too: it fires for same-lane or lane-less coexistence, but stays silent between two *different* declared lanes, whose session files are disjoint. +Attach discovery is lane-aware across **all** live instances (#1232): the launcher probes every live entry in the instance registry, not just the single instance file (last-writer-wins — under concurrent multi-client use it can point at another client's proxy), and applies the gate above to every candidate. Among compatible candidates the newest instance with the launcher's own declared lane wins; an instance without a lane (a user-zone daemon) is wildcard-compatible on the lane axis and gate-exempt by default (#1660); a lane-TAGGED manual daemon (`bili start --lane`, #4368) is likewise gate-exempt (token-less) but lane-restricted — only its own lane (or an explicit target / listed foreign lane) may ride it; whether a LANEd hook falls back onto a *lane-less* manual daemon is governed by `attachPolicy`: `own-lane` (default) does not ride an *unarmed* manual daemon (#2877), while `global-fallback` restores the pre-#2877 wildcard ride. The `another bili instance is running` warning (#394) is lane-aware too: it fires for same-lane or lane-less coexistence, but stays silent between two *different* declared lanes, whose session files are disjoint. **A reused proxy keeps its own process-local resolver state (#5222).** Attach/reuse hands the session to a *long-lived* process; after an OS-level network change (WSL/VPN switch, MagicDNS takeover) that process's libuv thread pool — the one shared by `dns.lookup` AND undici's default connector for outbound connects — can wedge so every lookup times out inside it while other processes on the same machine resolve fine. Restarting the *host* (e.g. DSH web) does NOT refresh it: the instance registry silently re-adopts the same pid. Remedies: restart the PROXY process (kill the pid recorded in `~/.local/state/billion-context/instances/`), or route egress through an upstream proxy (`-F` / `BILI_UPSTREAM_PROXY`, which skips local-DNS admission entirely). Since #5222 tunnel admission also self-defends: when the main-pool lookups exhaust their retries, ONE probe on a fresh worker-thread pool runs before the `unresolvable` verdict, so a wedged proxy stops false-denying healthy destinations (admitted via the worker result, with a loud warn log telling the operator to restart the proxy for full recovery — outbound connects still share the wedged pool until then). Phase 2 (owner decision 2026-10-31: detect + surface, never self-restart) adds a persistent-wedge detector fed by the admission MAIN-pool outcomes only (the worker probe mitigates admission but does not heal the pool): only THROWING lookups count as failures (an authoritative empty answer proves the resolver reachable), and the gate — at least two distinct hosts this process previously resolved OK, each now failing continuously for ≥5 min (`WEDGE_MIN_HOSTS` / `WEDGE_SUSTAIN_MS` in `src/resolver-wedge.ts`; tracker FIFO-capped at 256 user-supplied hosts) — drives the web panel banner, the additive `resolverWedge` field on `/__bili/status` + `/__bili/overview` (null while healthy), an `acp_status` alarm line, and a warn log line re-logged every 10 min while the episode persists; process behavior is unchanged. diff --git a/docs/technical-notes.zh-CN.md b/docs/technical-notes.zh-CN.md index 89d4515675..2990ce3a63 100644 --- a/docs/technical-notes.zh-CN.md +++ b/docs/technical-notes.zh-CN.md @@ -15,18 +15,18 @@ fork 继承依据子会话重放内容判断保留的压缩块,不直接沿用 ## 代理复用与附着门禁(#1225、#1335、#1232、#1660) -原生 hook 可以附着到已在运行的代理而不自己拉起 —— 仅当通过下面的生命周期门禁。复用基于身份(#1225):只有当既有代理运行的是**同一份代码**(入口脚本 sha256,记录在实例文件里)、**lane 兼容**(每个启动器声明其客户端 lane,两个*不同声明的* lane 永不共享;未声明 lane 的实例是手工拉起的用户主权区守护进程,在该轴上通配)、**且通过生命周期门禁**(见下:armed 父进程 pid 看门狗 `watchdog.armed == true`,即由带父 pid 的启动器拉起、随最后一个附着会话消亡;**或**属用户主权区实例 —— 无 lane、无 launch token —— 按定义豁免,#1660)时才附着。#1225 之前写入的实例没有代码指纹,因此永不附着:重建或更新后的安装下次启动总会拉起新代理,修复立即生效而不是静默服务旧代码。 +原生 hook 可以附着到已在运行的代理而不自己拉起 —— 仅当通过下面的生命周期门禁。复用基于身份(#1225):只有当既有代理运行的是**同一份代码**(入口脚本 sha256,记录在实例文件里)、**lane 兼容**(每个启动器声明其客户端 lane,两个*不同声明的* lane 永不共享;未声明 lane 的实例是手工拉起的用户主权区守护进程,在该轴上通配)、**且通过生命周期门禁**(见下:armed 父进程 pid 看门狗 `watchdog.armed == true`,即由带父 pid 的启动器拉起、随最后一个附着会话消亡;**或**属用户主权区实例(无 launch token —— 手工 `bili start`,无论是否声明 lane)按定义豁免,#1660/#4368)时才附着。#1225 之前写入的实例没有代码指纹,因此永不附着:重建或更新后的安装下次启动总会拉起新代理,修复立即生效而不是静默服务旧代码。 | 监听者 | 附着? | 原因 | |---|---|---| | 本会话拉起的代理 | ✅ | 出生即 armed | | 其他会话的 armed 共享代理(watcher 集,#1186) | ✅ | 共享本就是设计 | -| 手工 `bili start` 常驻守护进程(用户主权区,#1660) | 🔶 视情况 | **用户主权区**实例(无 lane、无 launch token):一台**已武装**的(受管共享代理,#1225)会被任何兼容 client lane 搭车;一台**未武装**的手动守护在默认(`attachPolicy: own-lane`,#2877)下**不会**被 lane 型 hook 搭车 —— 它自行派生。仅在 `attachPolicy: global-fallback`(pre-#2877)或 `attachExternal=1` 下被搭。无论哪种,寿命与版本由你自己负责 | +| 手工 `bili start` 常驻守护进程(用户主权区,#1660) | 🔶 视情况 | **用户主权区**实例(无 launch token——无论是否声明车道,#4368):一台**已武装**的(受管共享代理,#1225)会被任何兼容 client lane 搭车;一台**未武装**但声明了**自己车道**的,会被该车道的 hook 附着(它是该车道指定目标,#4368);一台**未武装**且车道不匹配的手动守护在默认(`attachPolicy: own-lane`,#2877)下**不会**被 lane 型 hook 搭车 —— 它自行派生。仅在 `attachPolicy: global-fallback`(pre-#2877)或 `attachExternal=1` 下被搭。无论哪种,寿命与版本由你自己负责 | | 未武装的 **lane 型**代理(崩溃会话孤儿;pre-#1330 不可验证) | ❌ 大声拒绝 | 生命周期漂移症状(#1335):搭乘等于静默复用无人管理的代理 | -hook 附着前先探测候选者的 `/__bili/health`:armed → 附着并注册 watcher(现状不变);一台**已武装的用户主权区**候选无论 lane 亲和策略都附着(受管共享代理,#1225);一台**未武装的用户主权区**(手动)候选仅在 `attachPolicy: global-fallback`(pre-#2877)或 `attachExternal=1` 下附着 —— 默认(`own-lane`)lane 型 hook 自行派生(#2877);未武装的 **lane 型**候选(崩溃会话孤儿,或 pre-#1330 构建根本不报 `watchdog` 字段 —— 不可验证,按 unarmed 处理)被**大声拒绝**,本会话在自管端口区自拉起代理(基准口 `18787` 或该 lane 粘性漂移记录;出生即 armed、随最后一个会话消亡,#1186 watcher 语义)。版本偏斜仍被修住:代码指纹检查先行,重建/更新后的安装即使经用户主权区豁免也永不搭乘陈旧守护进程。代价:无可附着实例时每会话多一个短命代理进程(会话状态在磁盘上共享,压缩连续性不受影响);多实例告警(#394)相应变多。**逃生舱:** 配置文件 `"native": { "attachExternal": true }` 或 `BILI_NATIVE_ATTACH_EXTERNAL=1` 把附着扩展到 *lane 型*监听者(无论看门狗状态,含 pre-#1330 构建)—— 那些守护进程的寿命与版本由你自己负责;`attachExternal` 只管辖 **lane 型**守护的*生命周期门禁*(它并不开/关对 user-zone 的附着 —— 那个轴是 `attachPolicy`);`attachUrl`(env `BILI_MCP_PROXY` / `--origin`)钉住显式目标 origin。kimi/dsh 的显式用户指定附着(`BILLION_CONTEXT_ATTACH` / 预置 `BILLION_CONTEXT_PROXY`)完全不经过发现路径,构造上豁免。 +hook 附着前先探测候选者的 `/__bili/health`:armed → 附着并注册 watcher(现状不变);一台**已武装的用户主权区**候选无论 lane 亲和策略都附着(受管共享代理,#1225);一台**未武装的用户主权区**(手动)候选若声明了 hook 自己的车道则直接附着(指定目标,#4368;watcher 注册被拒、宿主按 #1322 告警),车道不匹配的则仅在 `attachPolicy: global-fallback`(pre-#2877)或 `attachExternal=1` 下附着 —— 默认(`own-lane`)lane 型 hook 自行派生(#2877);未武装的 **lane 型**候选(崩溃会话孤儿,或 pre-#1330 构建根本不报 `watchdog` 字段 —— 不可验证,按 unarmed 处理)被**大声拒绝**,本会话在自管端口区自拉起代理(基准口 `18787` 或该 lane 粘性漂移记录;出生即 armed、随最后一个会话消亡,#1186 watcher 语义)。版本偏斜仍被修住:代码指纹检查先行,重建/更新后的安装即使经用户主权区豁免也永不搭乘陈旧守护进程。代价:无可附着实例时每会话多一个短命代理进程(会话状态在磁盘上共享,压缩连续性不受影响);多实例告警(#394)相应变多。**逃生舱:** 配置文件 `"native": { "attachExternal": true }` 或 `BILI_NATIVE_ATTACH_EXTERNAL=1` 把附着扩展到 *lane 型*监听者(无论看门狗状态,含 pre-#1330 构建)—— 那些守护进程的寿命与版本由你自己负责;`attachExternal` 只管辖 **lane 型**守护的*生命周期门禁*(它并不开/关对 user-zone 的附着 —— 那个轴是 `attachPolicy`);`attachUrl`(env `BILI_MCP_PROXY` / `--origin`)钉住显式目标 origin。kimi/dsh 的显式用户指定附着(`BILLION_CONTEXT_ATTACH` / 预置 `BILLION_CONTEXT_PROXY`)完全不经过发现路径,构造上豁免。 -附着发现在**所有**存活实例间是 lane 感知的(#1232):启动器探测实例注册表里的每一条存活记录,而不只是单个实例文件(last-writer-wins —— 并发多客户端下它可能指向别的客户端的代理),并对每个候选应用上面的门禁。兼容候选中,lane 与启动器自身声明一致的最新实例胜出;未声明 lane 的实例(用户主权区守护进程)在 lane 轴上通配,且门禁默认豁免(#1660)。`another bili instance is running` 告警(#394)也是 lane 感知的:同 lane 或无 lane 共存时触发,两个*不同声明* lane 之间保持沉默(它们的会话文件互不相交)。 +附着发现在**所有**存活实例间是 lane 感知的(#1232):启动器探测实例注册表里的每一条存活记录,而不只是单个实例文件(last-writer-wins —— 并发多客户端下它可能指向别的客户端的代理),并对每个候选应用上面的门禁。兼容候选中,lane 与启动器自身声明一致的最新实例胜出;未声明 lane 的实例(用户主权区守护进程)在 lane 轴上通配,且门禁默认豁免(#1660);声明了车道的手工守护(`bili start --lane`,#4368)同样门禁豁免(无 launch token),但受车道限制——只有其自己的车道(或显式目标/列出的外来车道)可附着。`another bili instance is running` 告警(#394)也是 lane 感知的:同 lane 或无 lane 共存时触发,两个*不同声明* lane 之间保持沉默(它们的会话文件互不相交)。 ## 共享 state 目录与多实例安全边界(#394、#1724)