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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -746,7 +746,7 @@ Environment variables take precedence over the config file. They are useful for
| `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 — native hooks attach to it by default, so a deliberate resident daemon “just works” without this env; you then own its lifetime and version. 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 (`0`/`false` closes the gate even over a permissive file — including for user-zone daemons, forcing fresh lane spawns). 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). |
| `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 and the settled port is recorded sticky under `<state>/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_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 `<state>/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). |
| `BILI_ZCODE_SIGNING_FIXED` | `1`/`true` = assume your ZCode build fixed ClientRequestSigningV4 (#1621): the per-entry skips for coding-plan accounts on v3.14+ personal stores flip off and they route again. Temporary escape hatch — there is **no** file equivalent. |
| `BILI_CLAUDE_UPSTREAM` | claude direct mode: your relay endpoint, when `ANTHROPIC_BASE_URL` already points at a relay the launcher would otherwise bypass. |
Expand Down
2 changes: 1 addition & 1 deletion CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -742,7 +742,7 @@
| `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)按定义属于用户主权区——原生 hook 默认直接附着,刻意运行的常驻守护进程无需此变量即可被共用;其寿命与版本由你自己负责。设 `1`/`true` 可以连 lane 型未武装监听者也一并附着:任何 code/lane 兼容的监听者无论看门狗状态都可附着(包括根本不报 `watchdog` 字段的 pre-#1330 构建)。配置文件里 `"native": { "attachExternal": true }` 等效;环境变量优先(`0`/`false` 即使文件开着也关门禁——对用户区守护进程同样生效,强制各 lane 自拉新代理)。默认关闭(针对 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 阶梯解决,落定的口记录在 `<state>/port-zone.json` 粘性表里,后续拉起自动跟随漂移。手工 `bili start` 保持自己的默认口(`8787`)——lane 永不碰用户主权区。 |
| `BILI_ZONE_PORT` | 自管端口区基准(#1660,默认 `18787`):所有 lane 拉起的代理(claude/zcode 原生 hook、跑 0 号口的 launcher lane)先试该 lane 的粘性记录,否则这个基准口;端口碰撞由子进程 +1 阶梯解决(例外:占用者是同 lane 的旧版本实例——升级重启重叠时——子进程最多等 5 秒让它释放并复用同一端口,而不是漂移,#1723),落定的口记录在 `<state>/port-zone.json` 粘性表里,后续拉起自动跟随漂移。手工 `bili start` 保持自己的默认口(`8787`)——lane 永不碰用户主权区。 |
| `BILI_ZCODE_PORT` | 为 zcode 原生通道钉死**确切端口**(#1660):启动变为严格端口——占用者被大声拒绝而不是跳口——共享 store 里的包装也因此跨会话重启存活,无需交接。不设则通道骑自管区(`BILI_ZONE_PORT` 基准 + 粘性漂移跟随)。 |
| `BILI_ZCODE_SIGNING_FIXED` | `1`/`true` = 假设你的 ZCode 构建已修复 ClientRequestSigningV4(#1621):v3.14+ personal store 上 coding-plan 账号的逐条跳过关闭,恢复路由。临时逃生舱 —— **没有**文件等效项。 |
| `BILI_CLAUDE_UPSTREAM` | claude 直连模式:当 `ANTHROPIC_BASE_URL` 已指向某个 relay 时,用它指定你的 relay 端点(否则会被旁路)。 |
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,11 @@ Ports, briefly (#1660): `bili start` (manual) owns `8787`. Everything a lane
spawns for you (native hooks, launcher lanes) lives in a separate
self-managed zone starting at `18787` — collisions hop +1 and each lane
remembers its drift, so zero-config installs never fight you for a port,
and a deliberate `bili start` daemon is attached by default.
and a deliberate `bili start` daemon is attached by default. An
upgrade-restart that finds the previous build still draining on the lane's
port waits for it to release (up to 5s) and rebinds the SAME port instead of
drifting (#1723); only a genuinely occupied port hops +1 — and that hop is
now logged loudly.

### Option 1 — Native plugin (`bili plugin install pi` / `omp` / `opencode` / `dsh` / `kimi` / `hermes` / `zcode`)

Expand Down
2 changes: 1 addition & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ npm install -g billion-context

三种方式背后的机制细节(插件生命周期、runtime-info 协议、注入优先级)见 [TECHNICAL-NOTES.zh-CN.md](TECHNICAL-NOTES.zh-CN.md)。

端口,一句话(#1660):`bili start`(手工)拥有 `8787`;lane 替你拉起的一切(原生 hook、启动器 lane)住在独立的自管端口区,从 `18787` 起 —— 碰撞 +1 跳口、每个 lane 记住自己的漂移,零配置安装永不抢端口,刻意常驻的 `bili start` 守护进程则默认被附着。
端口,一句话(#1660):`bili start`(手工)拥有 `8787`;lane 替你拉起的一切(原生 hook、启动器 lane)住在独立的自管端口区,从 `18787` 起 —— 碰撞 +1 跳口、每个 lane 记住自己的漂移,零配置安装永不抢端口,刻意常驻的 `bili start` 守护进程则默认被附着。升级重启时若旧版本还在该 lane 端口上排水,会最多等 5 秒让它释放并复用同一端口,而不是漂移(#1723);只有真正被占用的端口才 +1 跳口 —— 且这种跳口现在会大声打 warn。

### 方式 1 —— 原生插件(native,`bili plugin install pi` / `omp` / `opencode` / `dsh` / `kimi` / `hermes` / `zcode`)

Expand Down
7 changes: 6 additions & 1 deletion TECHNICAL-NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,12 @@ request) resolves its port like every lane (#1660): an explicit pin
**strict-port** on that exact port (a squatter is refused loudly, #964
preserved); otherwise it rides the self-managed zone — the lane's sticky
record else base `18787` — non-strict, with the child's EADDRINUSE +1
ladder resolving collisions and the settled port recorded sticky. After the
ladder resolving collisions and the settled port recorded sticky. One
exception to the ladder (#1723): when the holder of the lane's port is a
same-lane instance running a **different build** (the upgrade-restart
overlap — the old version still draining), the child waits for it to release
(up to 5s) and rebinds the *same* port instead of drifting; a holder that
never leaves exhausts the wait and gets the plain ladder as before. After the
proxy is up the hook re-pins the managed `ANTHROPIC_BASE_URL` to the live
origin each session (`repinClaudeManagedBaseUrl`), so a hopped port
self-heals on the next launch and the baked URL never stays desynced from
Expand Down
2 changes: 1 addition & 1 deletion TECHNICAL-NOTES.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ launcher 环境变量这档覆盖纯代理客户端(无进程内插件):`bili <c

## Claude 原生姿态(#964)

Claude Code 没有进程内扩展点,所以 `bili plugin install claude` 往 `~/.claude/settings.json` 写一个受管块(env `ANTHROPIC_BASE_URL=http://127.0.0.1:<port>/bili/<upstream>`、`DISABLE_AUTO_COMPACT=1`、`SessionStart` hook),外加同样的用户级 MCP shell。hook 在首个模型请求前触发,端口解析与所有 lane 一致(#1660):显式钉死(`BILI_CLAUDE_NATIVE_PORT` > config `claude.nativePort`)→ 该确切端口**严格端口**启动(占用者被大声拒绝,#964 保留);否则骑自管区 —— 该 lane 粘性记录优先,否则基准口 `18787` —— 非严格,子进程 EADDRINUSE +1 阶梯解决碰撞,落定端口粘性记录。代理就绪后 hook 每会话把受管 `ANTHROPIC_BASE_URL` 重钉到存活 origin(`repinClaudeManagedBaseUrl`),跳口后下次启动自愈,烘进 URL 永不与运行中代理失步。上游覆盖:`BILI_CLAUDE_UPSTREAM`(或既有 `claude.anthropicBaseUrl`)。install 不再持久化 `claude.nativePort`。`BILI_NATIVE_CLAUDE=0` 退出 —— hook 改为在同一解析端口上拉起 **passthrough** 代理(原样转发、关闭压缩)。块是纯 JSON merge/strip:外部键从不触碰,`bili plugin remove claude` 精确还原。装有原生块的机器上 `bili claude` 仍可用 —— 它用自身代理覆盖静态 URL,hook 保持休眠。
Claude Code 没有进程内扩展点,所以 `bili plugin install claude` 往 `~/.claude/settings.json` 写一个受管块(env `ANTHROPIC_BASE_URL=http://127.0.0.1:<port>/bili/<upstream>`、`DISABLE_AUTO_COMPACT=1`、`SessionStart` hook),外加同样的用户级 MCP shell。hook 在首个模型请求前触发,端口解析与所有 lane 一致(#1660):显式钉死(`BILI_CLAUDE_NATIVE_PORT` > config `claude.nativePort`)→ 该确切端口**严格端口**启动(占用者被大声拒绝,#964 保留);否则骑自管区 —— 该 lane 粘性记录优先,否则基准口 `18787` —— 非严格,子进程 EADDRINUSE +1 阶梯解决碰撞,落定端口粘性记录。阶梯有一个例外(#1723):lane 端口的持有者是**不同构建**的同 lane 实例(升级重启重叠——旧版本还在排水)时,子进程等它释放(最多 5 秒)后复用*同一*端口,而不是漂移;持有者永不退出则等待预算耗尽,照旧走 +1 阶梯。代理就绪后 hook 每会话把受管 `ANTHROPIC_BASE_URL` 重钉到存活 origin(`repinClaudeManagedBaseUrl`),跳口后下次启动自愈,烘进 URL 永不与运行中代理失步。上游覆盖:`BILI_CLAUDE_UPSTREAM`(或既有 `claude.anthropicBaseUrl`)。install 不再持久化 `claude.nativePort`。`BILI_NATIVE_CLAUDE=0` 退出 —— hook 改为在同一解析端口上拉起 **passthrough** 代理(原样转发、关闭压缩)。块是纯 JSON merge/strip:外部键从不触碰,`bili plugin remove claude` 精确还原。装有原生块的机器上 `bili claude` 仍可用 —— 它用自身代理覆盖静态 URL,hook 保持休眠。

## 注入优先级 —— 能不写文件就不写(#535)

Expand Down
27 changes: 27 additions & 0 deletions src/instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,33 @@ export function lanePreferredPort(lane: string, env: NodeJS.ProcessEnv = process
return readZonePort(lane, file) ?? resolveZonePortBase(env);
}

/** #1723: identify the EADDRINUSE holder BEFORE laddering (#1660 follow-up).
* Upgrade-restart overlap: the new build's child tries the lane's sticky
* port while the OLD build's instance is still draining (its host is
* exiting; the flush frees the port within seconds). The correct response
* is to wait for the release and rebind the SAME port — not to drift +1
* into the monotonic ratchet. Returns the live registry entry holding
* `port` on `lane` when it runs DIFFERENT code than us (a predecessor being
* replaced; missing fingerprints from pre-#1232 markers count as
* "different build"). Never returns: no holder, a different/undeclared
* lane (a manual `bili start` daemon can serve any client — waiting on it
* would stall a launch behind a peer that may never leave), or a live peer
* running OUR build (genuine contention — waiting cannot help). */
export function findSameLanePredecessor(
entries: RegistryEntry[],
port: number,
lane: string | undefined,
ownFingerprint: string | undefined,
): RegistryEntry | undefined {
if (!lane || !ownFingerprint) return undefined;
for (const e of entries) {
if (e.port !== port || e.lane !== lane) continue;
if (!isPidAlive(e.pid)) continue;
if (e.codeFingerprint !== ownFingerprint) return e;
}
return undefined;
}

/** #1225: content identity of a bili entry script (sha256 of its bytes).
* The spawned child records this for ITS script; an attaching launcher
* compares it against the hash of the script it would spawn — so "same
Expand Down
35 changes: 34 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ import { getStore } from "./persist.js";
import { log as loggerLog, configureLogger, getLogPath, closeLogger, isStreamWriteError, enterSessionContext } from "./logger.js";
import { queryLogLines } from "./web/logs-query.js";
import { configFile, defaultLogFile, dumpsDir, stateDir } from "./paths.js";
import { atomicWriteInstanceFile, clearProxyInstanceFile, entryScriptFingerprint, isPidAlive, registerInstanceAndWarn, unregisterInstance, type ProxyInstanceFile } from "./instance.js";
import { atomicWriteInstanceFile, clearProxyInstanceFile, entryScriptFingerprint, findSameLanePredecessor, isPidAlive, listInstances, registerInstanceAndWarn, unregisterInstance, type ProxyInstanceFile } from "./instance.js";
import { compressLoopResponsesJson } from "./compress-loop-responses.js";
import { hoistTrappedToolItems } from "./tool-pair-order.js";
import { runCompressLoop, pickAdapter } from "./loop/index.js";
Expand Down Expand Up @@ -658,6 +658,26 @@ export async function startServer(opts: ProxyOptions): Promise<http.Server> {
const MAX_LISTEN_ATTEMPTS = 17;
let listenAttempts = 0;
let lastTriedPort = opts.port;
// #1723 (#1660 follow-up): the upgrade-restart overlap. The launcher spawns
// this child while the OLD build's instance of the same lane is still
// draining (its host is exiting; the flush frees the port within seconds).
// Laddering +1 there is what ratchets the sticky port up one slot per
// auto-update forever. When EADDRINUSE hits a port held by a same-lane
// predecessor running DIFFERENT code, rebind the SAME port on a tick until
// it releases — bounded, so a holder that never leaves falls through to
// the plain ladder (today's behavior) after the budget is spent.
const PREDECESSOR_WAIT_TICKS = 10;
const PREDECESSOR_WAIT_MS = 500;
let predecessorTicksLeft = PREDECESSOR_WAIT_TICKS;
let predecessorWaitAnnounced = false;
const sameLanePredecessorHolds = (port: number): boolean => {
const pred = findSameLanePredecessor(listInstances(), port, launcherLane, ownFingerprint);
if (pred && !predecessorWaitAnnounced) {
predecessorWaitAnnounced = true;
log("warn", `port ${port} held by a same-lane predecessor (pid ${pred.pid}, different build) — waiting up to ${Math.round((PREDECESSOR_WAIT_TICKS * PREDECESSOR_WAIT_MS) / 1000)}s for it to release instead of drifting`);
}
return pred !== undefined;
};
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);
Expand Down Expand Up @@ -720,6 +740,14 @@ export async function startServer(opts: ProxyOptions): Promise<http.Server> {
: "Clear it in the web UI (概览 page) or remove \"passthrough\": true from the config file to re-enable compression."),
);
}
// #1723: residual zone drift is now an exception, not the norm — a
// lane'd launch landing ABOVE its preferred port means that port was
// held by something we must not wait on (foreign squatter, same-code
// peer). Clients pinned to the old port (lane wrappers, firewall
// rules, docs) point at air until they re-resolve; say so loudly.
if (launcherLane && actualPort > opts.port) {
log("warn", `[zone] lane "${launcherLane}" drifted ${opts.port} → ${actualPort} — the preferred port is still occupied by something else; anything pinned to ${opts.port} must re-resolve`);
}
const envKnobs: string[] = [];
if (process.env.ACP_PASSTHROUGH !== undefined) envKnobs.push(`ACP_PASSTHROUGH=${process.env.ACP_PASSTHROUGH}`);
if (process.env.ACP_MODEL_CONTEXT_LIMIT !== undefined) envKnobs.push(`ACP_MODEL_CONTEXT_LIMIT=${process.env.ACP_MODEL_CONTEXT_LIMIT}`);
Expand Down Expand Up @@ -751,6 +779,11 @@ export async function startServer(opts: ProxyOptions): Promise<http.Server> {
// flush sessions, and exit cleanly (exit code 1 so callers/scripts notice).
server.on("error", (err: NodeJS.ErrnoException) => {
if (err.code === "EADDRINUSE" && launchToken && !strictPort && listenAttempts < MAX_LISTEN_ATTEMPTS) {
if (predecessorTicksLeft > 0 && sameLanePredecessorHolds(lastTriedPort)) {
predecessorTicksLeft -= 1;
setTimeout(() => attemptListen(lastTriedPort), PREDECESSOR_WAIT_MS);
return;
}
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}`}`);
Expand Down
Loading
Loading