diff --git a/CLIENTS.md b/CLIENTS.md index bad598dec2..b58e4f53a0 100644 --- a/CLIENTS.md +++ b/CLIENTS.md @@ -230,8 +230,13 @@ two small node scripts that do the work around the client: - **`direct` exemptions:** a provider route declaring `"direct": true` in the `providers` table (keyed by upstream URL — see CONFIGURATION.md) stays direct; the same exemption any lane can honor. - The lane pins its default port (`48789`, `BILI_ZCODE_PORT` to override) so - wrappers survive session restarts even without handoff. `BILI_ZCODE_ROUTE` + The lane launches its proxy in the self-managed port zone (#1660): zone + base `18787`, a per-lane sticky record so a past +1-ladder drift is + followed automatically, collisions resolved by the child's +1 ladder, + and the shared store rewritten to the live origin on drift — wrappers + survive session restarts even without handoff. `BILI_ZCODE_PORT` pins an + exact port instead (strict-port: a squatter is refused loudly, no hop). + `BILI_ZCODE_ROUTE` (`plans`/`none`) is a compat escape hatch, and `BILI_ZCODE_SIGNING_FIXED=1` flips the #1621 skips off once a ZCode build ships the signing fix. - **Watchdog & lifecycle:** the MCP child probes the proxy every 30 s. In @@ -277,6 +282,36 @@ two small node scripts that do the work around the client: `BILLION_CONTEXT_PROXY` is set (attach mode owns the proxy) or `BILI_PROVIDER_REWRITES` is defined. Opt-out: `BILI_NATIVE_ZCODE=0`. +## Codex (OpenAI Codex CLI) + +Codex is the one client a plugin install cannot make self-sufficient. The seam +matrix explains why: claude has a `SessionStart` hook + managed settings block, +zcode has a provider store whose `baseURL` can be rewritten — codex has neither. +Its model traffic routes via environment variables only (`HTTPS_PROXY` / +`SSL_CERT_FILE` — this is how `bili codex` works); the default +ChatGPT-login provider has no config-file routing seam, and a managed +`model_providers` block would force `env_key` API-key auth and **drop the +subscription login**. An MCP server cannot inject env into its parent process, +so the plugin can never route codex's own traffic. Three postures: + +| Posture | What you get | +|---|---| +| `bili codex` (launcher) | Full zero-config: a self-managed lane proxy (#1660 zone, sticky port) + cert-MITM env injected into codex — tools *and* compression | +| `bili plugin install codex` + a running bili + self-exported `HTTPS_PROXY` | Tools + compression for power users who manage their own env | +| `bili plugin install codex` alone | The four tools appear in codex but no conversation is proxied, so there is nothing for them to act on; `tools/list` fails with -32003 (`bili proxy unreachable … — start bili or set BILI_MCP_PROXY`) when nothing is reachable | + +The install writes a single `[mcp_servers.bili]` block into `~/.codex/config.toml` +(command = node, args = dist/mcp.js). #1660 removed the install-time origin bake +(#403: a baked URL went stale after drift/reboot and left the tools pointing at +a dead port); the shell resolves the proxy at session start — env +`BILI_MCP_PROXY` > the live-instance record (any lane's proxy, or a +`bili start` daemon) > the 8787 user-zone default — so a drifted or rebooted +proxy never strands a dead URL, and the shell simply attaches to whatever is +alive. Session binding is headless: the launcher passes +`BILI_CONVERSATION_ID` at spawn time, and the plugin shell binds the next NEW +session otherwise; per-call `conversation_id` overrides work as everywhere +(#760). + ## Gemini family (Gemini CLI / iFlow CLI / Qwen Code) Three launchers for the gemini-cli architecture family (#1043 tier 1). Two of diff --git a/CLIENTS.zh-CN.md b/CLIENTS.zh-CN.md index 8f41e72afc..15ec844b4a 100644 --- a/CLIENTS.zh-CN.md +++ b/CLIENTS.zh-CN.md @@ -73,10 +73,22 @@ fork 继承同一面)。按设计保持 launcher-only。 - **客户端签名账号(#1621):** v3.14+ personal store 上的 coding-plan 账号保持直连(见已知局限);其余 provider 照常路由。 - **环回目标(#809):** http 环回 `baseURL`(localhost / 127.x.x.x / ::1)永不二次代理 —— 包装它会把 bili 叠在自己或你自己的本地中继上。 - **`direct` 豁免:** `providers` 表(以上游 URL 为键,见 CONFIGURATION.zh-CN.md)里声明 `"direct": true` 的路由保持直连 —— 任何 lane 都能遵守的同一套豁免机制。 - 通道默认钉死端口(`48789`,`BILI_ZCODE_PORT` 覆盖),即使没有交接,包装也能跨会话重启存活。`BILI_ZCODE_ROUTE`(`plans`/`none`)是兼容逃生舱;`BILI_ZCODE_SIGNING_FIXED=1` 在 ZCode 发布签名修复后关掉 #1621 跳过。 + 通道把代理拉在自管端口区(#1660):基准口 `18787`,每 lane 粘性记录(自动跟随历史上的 +1 阶梯漂移),碰撞由子进程 +1 阶梯解决,漂移时共享 store 改写到存活 origin —— 即使没有交接,包装也能跨会话重启存活。`BILI_ZCODE_PORT` 钉死一个确切端口(严格模式:占用者被大声拒绝,不跳口)。`BILI_ZCODE_ROUTE`(`plans`/`none`)是兼容逃生舱;`BILI_ZCODE_SIGNING_FIXED=1` 在 ZCode 发布签名修复后关掉 #1621 跳过。 - **看门狗与生命周期:** MCP 子进程每 30 s 探测一次代理。attach 模式下永远等待(绝不碰用户自己的代理);spawn 模式下代理死亡则重新拉起并把路由改写到新 origin。恢复失败时移除受管改写,让流量退回直连上游而不是打到死端口。会话结束时 ZCode 杀掉 MCP 子进程,父进程 pid 看门狗随之收掉拉起的代理;MCP 子进程退出前(SIGTERM/SIGINT/正常退出)在锁下交接:若共享 provider store 仍指向它自己的代理,优先改写到另一个存活兼容实例,没有则移除受管改写退回直连(#1623)——实例死后共享配置不留死端口。看门狗每个 tick 同时检查共享 store:若残留着其他实例的死端口(硬杀场景,上述交接没跑成——如 Windows TerminateProcess 跳过 JS handler),接管修复(优先改到存活实例,否则回退直连);只在 store 指向死端口时动手,绝不从存活实例手里抢路由。多个并发会话共享第一个拉起的代理;它消失后其余会话自动重新拉起并改路。边界:ZCode 按会话缓存 provider baseURL,上述修复只对「之后的新读取」(新会话/新查询)生效,在途会话仍会重试缓存的旧端口直到重读;要结构性规避,把 `BILLION_CONTEXT_PROXY` 钉到一个常驻代理(`bili start`)让所有会话 attach 上去(attach 模式绝不碰用户自己的代理)。 - **已知局限:** ZCode 的反欺诈指纹(#661)作用于 `zcode.z.ai` 登录流量的 MITM 重建 body —— 原生模式不碰那个面(模型流量走 provider store,不走 GUI 代理);若你同时使用 GUI 代理/MITM 配置,请保留 `"mitm://zcode.z.ai": { "passthrough": true }` 路由。v3.14+ 构建上,coding-plan 账号的 ClientRequestSigningV4 在模型创建阶段拒绝非 HTTPS origin,且其握手路径只从 origin 派生(丢弃任何 /bili/ 前缀),因此 /bili/ 包装的 baseURL 会以 "Client signing handshake requires HTTPS." 失败(#1621)。该冲突硬编码在 ZCode 侧,原生模式把这些账号**逐条跳过** —— 记录原因、这些账号保持直连;在这些账号上请用 GUI 证书 MITM 配置获得压缩能力,直到 ZCode 发布签名修复,届时设 `BILI_ZCODE_SIGNING_FIXED=1` 即可恢复路由。默认 `route:"all"` 下只有这些账号被跳过 —— store 上其余 provider 继续路由;整体退场(路由全关)只在 `route:"plans"` 下发生,因为那里 plan 账号本身就是签名账号。pre-3.14 legacy-store 客户端不受影响。`BILLION_CONTEXT_PROXY` 已设置(attach 模式管着代理)或定义了 `BILI_PROVIDER_REWRITES` 时插件整体退场。退出开关:`BILI_NATIVE_ZCODE=0`。 +## Codex(OpenAI Codex CLI) + +Codex 是唯一一个插件安装无法自给自足的客户端。接缝矩阵可以解释:claude 有 SessionStart hook + 受管 settings 块,zcode 有可改写 `baseURL` 的 provider store —— codex 两者都没有。它的模型流量只能经环境变量路由(`HTTPS_PROXY` / `SSL_CERT_FILE` —— `bili codex` 正是这么做的);默认 ChatGPT-登录 provider 没有可改写的配置缝,managed `model_providers` 块会强制 `env_key` API-key 认证、**废掉订阅登录**;而 MCP 子进程无法向父进程注入 env,所以插件永远路由不了 codex 本体流量。三种姿势: + +| 姿势 | 你能得到什么 | +|---|---| +| `bili codex`(启动器) | 全功能零配置:自管 lane 代理(#1660 端口区,粘性口)+ 注入 codex 的证书 MITM env —— 工具与压缩兼得 | +| `bili plugin install codex` + 在跑的 bili + 自行导出 `HTTPS_PROXY` | 自己管 env 的 power user:工具 + 压缩 | +| 只装 `bili plugin install codex` | codex 里出现四个工具但没有对话被代理、无话可操作;全不可达时 `tools/list` 报 -32003(`bili proxy unreachable … — start bili or set BILI_MCP_PROXY`) | + +安装写入 `~/.codex/config.toml` 单个 `[mcp_servers.bili]` 块(command = node,args = dist/mcp.js)。#1660 去掉了安装时烘焙 origin(#403:烘焙的 URL 在漂移/重启后变成死端口,工具永远指向它);shell 在会话启动时解析代理 —— env `BILI_MCP_PROXY` > 活实例登记(任一 lane 的代理,或 `bili start` 守护)> 8787 用户区默认 —— 漂移或重启后绝不残留死 URL,shell 直接附着到活着的那个。会话绑定是 headless 的:启动器在 spawn 时传 `BILI_CONVERSATION_ID`,插件 shell 否则绑定下一个新会话;逐调用的 `conversation_id` 覆盖与其他客户端一致(#760)。 + ## 客户端用 `http.proxy`(CONNECT)接入但从不压缩 部分客户端(VS Code 系 IDE:CodeBuddy、Cursor、Windsurf……)只提供一个 HTTP **代理**设置(`http.proxy`、`codingcopilot.httpProxyURL` 等),没有可改写的模型 base-URL。这类客户端不走普通的 `/bili/…` 请求,而是把 `CONNECT <模型域名>:443` 发给代理。只有当模型域名在 bili 的 **MITM 白名单**里时这条路径才会被解密;否则 bili 只做盲隧道(不透明转发),永远看不到——也就无法压缩——模型请求(#897)。 diff --git a/CONFIGURATION.md b/CONFIGURATION.md index ee7930555a..7e60ec2c0a 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -70,7 +70,7 @@ Top-level keys that control how the proxy listens and behaves globally. - **Type:** `number` - **Default:** `8787` - **Status:** ACTIVE -- **Description:** TCP port the proxy listens on. Must be an integer between 1 and 65535. Overridden by the `ACP_PORT` (or `PORT`) environment variable, or the `--port` CLI flag. An invalid value aborts startup. +- **Description:** TCP port the proxy listens on. Must be an integer between 1 and 65535. Overridden by the `ACP_PORT` (or `PORT`) environment variable, or the `--port` CLI flag. An invalid value aborts startup. This is the **user zone** (`bili start`, default `8787`) — you own this port. Lane-spawned proxies (native hooks, launcher lanes) live in a separate self-managed zone (`BILI_ZONE_PORT`, default `18787`) and never touch this one (#1660). ### `host` @@ -741,14 +741,16 @@ Environment variables take precedence over the config file. They are useful for | `BILLION_CONTEXT_PROXY` | Exported by the launcher; client-side bili plugins/extensions detect it and self-disable their own compression (no double compression). | | `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, while an instance without a declared lane is wildcard-compatible on the lane axis but still subject to the #1335 lifecycle gate (see `BILI_NATIVE_ATTACH_EXTERNAL`). 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_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). Native hooks attach to a running proxy only when it reports an armed session-lifecycle watchdog (`watchdog.armed == true` in `/__bili/health`) — a manually started `bili start` daemon has no lifecycle owner (refuses watcher registration, never dies with sessions, often runs an older build), so by default each session spawns its own ephemeral proxy instead of attaching to one. Set to `1`/`true` when you deliberately run a resident daemon for your native hooks to ride on: any code/lane-compatible listener becomes attachable again regardless of watchdog state (including pre-#1330 builds that report no `watchdog` field at all) — you then own the daemon's lifetime and version yourself. `"native": { "attachExternal": true }` in the config file does the same; the env var wins (`0`/`false` closes the gate even over a permissive file). Default is closed. Full mechanics (reuse rules, listener table, escape hatch): [TECHNICAL-NOTES.md](TECHNICAL-NOTES.md#proxy-reuse-and-the-attach-gate-1225-1335-1232). | + | `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_ZCODE_PORT` | Override the pinned default port (`48789`) of the proxy the zcode native lane spawns; wrappers written into the shared store then survive session restarts even without handoff. | + | `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 `/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. | + | `BILI_CLAUDE_NATIVE_PORT` | Pin an **exact** port for the claude native lane's hook-spawned proxy (#964/#1660): strict-port semantics — a squatter on the port is refused loudly instead of hopping — and the baked managed `ANTHROPIC_BASE_URL` points at it. Without it the hook rides the self-managed zone (`BILI_ZONE_PORT` base + per-lane sticky) and re-pins the managed URL to the live origin each session, so port drift self-heals (#1660). | | `BILI_CODEX_COMPACT` | Codex native-compaction handling. Default `intercept`: bili intercepts codex's compaction requests and forges a local handoff to the ACP state when the safety gate passes (transform ok + steady-state usage < 90% of the window + at least one active compressed block) — trigger form forges a 2-frame SSE, endpoint form forges `{output}` — and never contacts upstream. Forged ACP summaries are re-injected as a history-borne handoff message (developer-message fallback) so compressed content stays visible after codex truncates its history. Set `pass` to opt out and forward codex's compaction requests upstream (native compaction backstops). On any gate failure the request passes through untouched. Codex client detection (which traffic this applies to, also used for window clamping and session-identity fingerprinting): the User-Agent must either start with a registered prefix (`codex_cli_rs/`, `codex_exec/`, `codex desktop/` — matched case-insensitively, since variants like Codex Desktop send an initial capital, #1169) or contain a whitespace-delimited component starting with lowercase `codex` (unknown variants such as `codex_sdk_ts/…`, #645 — narrowed from a bare substring to a token-level prefix in #1641 so non-codex clients whose UAs merely mention "codex" mid-token or in parens are no longer misclassified; the fallback stays case-sensitive on purpose so "Codex"-shaped relays are excluded, #1106). | --- diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 6126c48cbd..e82dda2f26 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -70,7 +70,7 @@ - **类型:** `number` - **默认值:** `8787` - **状态:** ACTIVE -- **说明:** 代理监听的 TCP 端口。必须是 1 到 65535 之间的整数。可由 `ACP_PORT`(或 `PORT`)环境变量或 `--port` CLI 参数覆盖。非法值会导致启动中止。 +- **说明:** 代理监听的 TCP 端口。必须是 1 到 65535 之间的整数。可由 `ACP_PORT`(或 `PORT`)环境变量或 `--port` CLI 参数覆盖。非法值会导致启动中止。这是**用户主权区**(`bili start`,默认 `8787`)——这个口归你管。lane 拉起的代理(原生 hook、launcher lane)住在独立的自管区(`BILI_ZONE_PORT`,默认 `18787`),永不碰这个口(#1660)。 ### `host` @@ -740,11 +740,13 @@ | `BILI_LAUNCHER_MODEL_WINDOWS` | 内部使用:launcher 把客户端自身配置里的逐模型上下文窗口(pi `models.json`、omp `models.yml`、opencode `models..limit`、codex `model_context_window`)以 JSON 传给自己拉起的代理,让 nudge 分母对自托管模型也用真实窗口。只有 launcher 会设置,无需用户配置。 | | `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)。原生 hook 只附着于报告了 armed 会话生命周期看门狗(`/__bili/health` 里 `watchdog.armed == true`)的代理——手工 `bili start` 守护进程没有生命周期属主(拒绝 watcher 注册、不随会话退出、常是旧版本),所以默认每会话自拉起临时代理而不附着它。当你刻意运行常驻守护进程给原生 hook 共用时设 `1`/`true`:任何 code/lane 兼容的监听者重新可附着,无论看门狗状态如何(包括根本不报 `watchdog` 字段的 pre-#1330 构建)——此时守护进程的寿命与版本由你自己负责。配置文件里 `"native": { "attachExternal": true }` 等效;环境变量优先(`0`/`false` 即使文件开着也关门禁)。默认关闭。完整机制(复用规则、监听者表、逃生舱)见 [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:**手工 `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_ZCODE_PORT` | 覆盖 zcode 原生通道拉起代理的钉死默认端口(`48789`);共享 store 里的包装因此跨会话重启存活,无需交接。 | +| `BILI_ZONE_PORT` | 自管端口区基准(#1660,默认 `18787`):所有 lane 拉起的代理(claude/zcode 原生 hook、跑 0 号口的 launcher lane)先试该 lane 的粘性记录,否则这个基准口;端口碰撞由子进程 +1 阶梯解决,落定的口记录在 `/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 端点(否则会被旁路)。 | +| `BILI_CLAUDE_NATIVE_PORT` | 为 claude 原生通道 hook 拉起的代理钉死**确切端口**(#964/#1660):严格端口语义——口上的占用者被大声拒绝而不是跳口——烘进受管 `ANTHROPIC_BASE_URL`。不设则 hook 骑自管区(`BILI_ZONE_PORT` 基准 + 每 lane 粘性),且每次会话把受管 URL 重钉到存活 origin,端口漂移自愈(#1660)。 | | `BILI_CODEX_COMPACT` | codex 原生压缩处理。默认 `intercept`:安全门通过时(transform 成功 + 稳态用量 < 窗口 90% + 至少一个活跃压缩块)拦截 codex 的压缩请求,在本地伪造向 ACP 状态的交接——trigger 形态伪造 2 帧 SSE,endpoint 形态伪造 `{output}`——且不接触上游。伪造的 ACP 摘要经历史承载交接消息注入(缺席时 developer 消息兜底),保证 codex 截断历史后压缩内容仍可见。设为 `pass` 可退出,把 codex 的压缩请求转发给上游(原生压缩兜底)。任一安全门失败则原样透传。codex 客户端判定(本项生效范围,同时用于窗口 clamp 与会话身份指纹):User-Agent 须以已注册前缀开头(`codex_cli_rs/`、`codex_exec/`、`codex desktop/`——大小写不敏感,因 Codex Desktop 等变体首字母大写,#1169),或含某个以**小写** `codex` 开头的空白分隔组件(未知变体如 `codex_sdk_ts/…`,#645——#1641 起从裸子串收窄为 token 级前缀,UA 中仅在括号内/路径段提及 "codex" 的非 codex 客户端不再被误判;兜底有意保持大小写敏感,排除 "Codex"-形中继,#1106)。 | --- diff --git a/README.md b/README.md index 7fd75ad1c1..5b05c73782 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,7 @@ Pick by your client: | **hermes** | `bili plugin install hermes` (self-spawning native, Python plugin #958) or `bili hermes` (cert-MITM) | | **zcode** (Z.ai / bigmodel coding plan) | `bili plugin install zcode` (self-spawning native, #1145) or cert-MITM via the GUI's Settings → Network or `/bili/` prefix — details: [CLIENTS.md](CLIENTS.md) | | **claude** | `bili claude` (launcher) or `bili plugin install claude` (native posture, #964 — managed settings block + session-owned proxy; see the notes below) | +| **codex** | `bili codex` (launcher — the full zero-config posture) or `bili plugin install codex` (MCP-shell tools companion: **start bili first** — the shell never spawns a proxy and never routes codex's own traffic) — details: [CLIENTS.md](CLIENTS.md#codex-openai-codex-cli) | | **jcode** | [`billion-context`](https://github.com/ranxianglei/billion-context) via `bili jcode` (cert-MITM) or `/bili/` prefix — no native mode (compiled Rust binary, no plugin seam, [#962](https://github.com/ranxianglei/billion-context/issues/962)) | | **gemini** (Gemini CLI) | `bili gemini` (launcher, `GOOGLE_GEMINI_BASE_URL` `/bili/` rewrite) or `/bili/` prefix — launcher-only (no in-loop tool seam, #1043) | | **iflow** (iFlow CLI) | `bili iflow` (launcher, `IFLOW_BASE_URL` `/bili/` rewrite) or `/bili/` prefix | @@ -147,6 +148,12 @@ Three ways to use it — pick one: Mechanism details behind these three options (plugin lifecycle, runtime-info protocol, injection priority) live in [TECHNICAL-NOTES.md](TECHNICAL-NOTES.md). +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. + ### Option 1 — Native plugin (`bili plugin install pi` / `omp` / `opencode` / `dsh` / `kimi` / `hermes` / `zcode`) The proxy lives inside the client: install once, then start the client @@ -192,8 +199,8 @@ Notes: - OpenCode legacy sessions, V1/V2 shapes and caveats: [OpenCode](CLIENTS.md#opencode). - `kimi` reports runtime-info at bootstrap only (static headers can't carry per-request window/model values) and binds subagents by per-call `conversation_id`. - `hermes`'s native plugin is Python: it points hermes' httpx stack at the proxy via env vars after a health check and stamps per-request headers through an `llm_request` middleware. -- `codex` has a companion MCP-shell install too, but it needs a running proxy — not native mode. -- `claude` has a native posture (#964): managed settings block + `SessionStart` hook + MCP shell on a stable port; opt out with `BILI_NATIVE_CLAUDE=0` (passthrough). Mechanics: [TECHNICAL-NOTES.md](TECHNICAL-NOTES.md). +- `codex` is the one client a plugin install cannot make self-sufficient: codex routes model traffic via env only (no config-file routing seam for the default ChatGPT-login provider — a managed `model_providers` block would force API-key auth and drop subscription login), and an MCP server cannot inject env into its parent. `bili plugin install codex` writes a single `[mcp_servers.bili]` block into `~/.codex/config.toml` (command = node, args = dist/mcp.js) exposing the four ACP tools; at session start the shell resolves a proxy — env `BILI_MCP_PROXY` > the live-instance record (any lane's proxy or a `bili start` daemon) > the 8787 user-zone default (#1660 removed the install-time origin bake, #403) — nothing reachable → `tools/list` fails with -32003. So: start bili first (`bili start` or any client's lane proxy), export HTTPS_PROXY yourself if you also want compression, or use `bili codex` for the zero-config full posture. Mechanics: [CLIENTS.md](CLIENTS.md#codex-openai-codex-cli). +- `claude` has a native posture (#964): managed settings block + `SessionStart` hook + MCP shell; the hook rides the self-managed port zone (#1660) and re-pins the managed URL to the live origin each session, so port drift self-heals. Opt out with `BILI_NATIVE_CLAUDE=0` (passthrough). Mechanics: [TECHNICAL-NOTES.md](TECHNICAL-NOTES.md). - `zcode` has a native posture (#1145): managed `~/.zcode/cli/config.json` block + per-session provider `baseURL` rewrite. Full mechanics: [CLIENTS.md](CLIENTS.md). - `jcode` and `aider` have no native mode (no plugin/MCP/tool-injection seam: #962, #1048) — use `bili jcode` / `bili aider`. - `copilot`, `amp` and `goose` are launcher-only (#1049); goose cannot be cert-MITMed (rustls trusts no CA file) and rides plain-HTTP base-URL redirects instead. diff --git a/README.zh-CN.md b/README.zh-CN.md index c8ba81cf29..8f2844f125 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -113,6 +113,7 @@ QQ群: | **hermes** | `bili plugin install hermes`(自拉起原生,Python 插件 #958)或 `bili hermes`(证书 MITM) | | **zcode**(Z.ai / bigmodel coding plan) | `bili plugin install zcode`(自拉起原生,#1145)或 GUI「设置 → 网络」证书 MITM 或 `/bili/` 前缀 —— 细节见 [CLIENTS.zh-CN.md](CLIENTS.zh-CN.md) | | **claude** | `bili claude`(启动器)或 `bili plugin install claude`(原生姿态,#964 —— 受管 settings 块 + 会话自管代理;见下方"注意") | +| **codex** | `bili codex`(启动器 —— 全功能零配置姿势)或 `bili plugin install codex`(MCP shell 工具面配套:**先起 bili 再玩** —— shell 不拉代理,也路由不了 codex 本体流量)—— 细节见 [CLIENTS.zh-CN.md](CLIENTS.zh-CN.md#codexopenai-codex-cli) | | **jcode** | [`billion-context`](https://github.com/ranxianglei/billion-context),`bili jcode`(cert-MITM)或 `/bili/` 前缀 —— 无原生模式(编译型 Rust 二进制、无插件接缝,[#962](https://github.com/ranxianglei/billion-context/issues/962)) | | **gemini**(Gemini CLI) | `bili gemini`(启动器,`GOOGLE_GEMINI_BASE_URL` `/bili/` 改写)或 `/bili/` 前缀 —— 仅启动器(无环内工具注入接缝,#1043) | | **iflow**(iFlow CLI) | `bili iflow`(启动器,`IFLOW_BASE_URL` `/bili/` 改写)或 `/bili/` 前缀 | @@ -145,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` 守护进程则默认被附着。 ### 方式 1 —— 原生插件(native,`bili plugin install pi` / `omp` / `opencode` / `dsh` / `kimi` / `hermes` / `zcode`) @@ -175,9 +176,9 @@ pi / omp / kimi / claude 没有客户端侧通道 —— 它们的配置条目 - OpenCode 旧会话、V1/V2 插件形态与全部注意事项:[OpenCode](CLIENTS.zh-CN.md#opencode)。 - `kimi` 仅在自举时上报 runtime-info(静态头无法承载逐请求窗口/模型值),子代理会话按每次调用的 `conversation_id` 绑定。 - `hermes` 的原生插件是 Python:健康检查通过后用环境变量把 hermes 的 httpx 栈指向代理,并经 `llm_request` 中间件打逐请求头。 -- `claude` 有**原生姿态**(#964):受管 settings 块 + `SessionStart` hook + 稳定端口的 MCP shell;`BILI_NATIVE_CLAUDE=0` 退出(passthrough)。机制:[TECHNICAL-NOTES.zh-CN.md](TECHNICAL-NOTES.zh-CN.md)。 +- `claude` 有**原生姿态**(#964):受管 settings 块 + `SessionStart` hook + MCP shell;hook 骑自管端口区(#1660),每会话把受管 URL 重钉到存活 origin,端口漂移自愈。`BILI_NATIVE_CLAUDE=0` 退出(passthrough)。机制:[TECHNICAL-NOTES.zh-CN.md](TECHNICAL-NOTES.zh-CN.md)。 - `zcode` 有**原生姿态**(#1145):受管 `~/.zcode/cli/config.json` 块 + 每会话 provider `baseURL` 改写。完整机制:[CLIENTS.zh-CN.md](CLIENTS.zh-CN.md)。 -- `codex` / `omp` 也有配套安装(MCP shell 与轻量扩展),但需要一个在跑的代理 —— 不属于原生模式。 +- `omp` 是自拉起原生插件;`codex` 性质不同 —— 它是 MCP shell 工具面配套:codex 的模型流量只能经 env 路由(默认 ChatGPT-登录 provider 没有可改写的配置缝 —— managed `model_providers` 块会强制 API-key 认证、废掉订阅登录),而 MCP 子进程无法向父进程注入 env,所以插件安装既不拉代理、也永远路由不了 codex 本体流量。`bili plugin install codex` 在 `~/.codex/config.toml` 写入 `[mcp_servers.bili]`(command = node,args = dist/mcp.js)注册四个 ACP 工具,会话启动时解析代理:env `BILI_MCP_PROXY` > 活实例登记(任一 lane 的代理或 `bili start` 守护)> 8787 用户区默认(#1660 去掉了安装时烘焙 origin,#403)—— 全不可达则 `tools/list` 报 -32003。结论:**先起 bili**(`bili start` 或任一客户端的 lane 代理),想要压缩再自行导出 HTTPS_PROXY;零配置全功能用 `bili codex`。机制:[CLIENTS.zh-CN.md](CLIENTS.zh-CN.md#codexopenai-codex-cli)。 - `jcode`、`aider` 无原生模式(无插件/MCP/工具注入接缝:#962、#1048)—— 用 `bili jcode` / `bili aider`。 - `copilot`、`amp`、`goose` 仅启动器模式(#1049);goose 无法 cert-MITM(rustls 不信任任何 CA 文件),改走纯 HTTP base-URL 重定向。 diff --git a/TECHNICAL-NOTES.md b/TECHNICAL-NOTES.md index 67897d77c7..686277cda0 100644 --- a/TECHNICAL-NOTES.md +++ b/TECHNICAL-NOTES.md @@ -15,19 +15,20 @@ the client's **own model config** to the proxy (runtime-info protocol, #955) so compression budgets use the real window instead of a registry guess. Opt-out envs: `BILI_NATIVE_PI=0`, `BILI_NATIVE_OMP=0`, `BILI_NATIVE_OPENCODE=0`, `BILI_NATIVE_DSH=0`, `BILI_NATIVE_KIMI=0`, `BILI_NATIVE_HERMES=0`, `BILI_NATIVE_ZCODE=0`. -## Proxy reuse and the attach gate (#1225, #1335, #1232) +## 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 wildcard-compatible on that axis — **and it owns a session lifecycle**: its health endpoint reports 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. 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 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. | 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 | ❌ by default | no lifecycle owner (refuses watcher registration, never dies with sessions, often runs an older build — the cause of #1322) | +| Manually started `bili start` daemon (user zone, #1660) | ✅ by default | **user-zone** instance (no lane, no launch token): deliberately maintained by the user — you own its lifetime and version; refused only when `BILI_NATIVE_ATTACH_EXTERNAL=0/false` explicitly closes the gate | +| 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` for `watchdog.armed` before attaching: armed → attach and register a watcher (unchanged); unarmed, or a pre-#1330 build that reports no `watchdog` field at all (unverifiable, treated as unarmed) → do **not** attach; the session spawns its own ephemeral proxy (ephemeral port, armed at birth, dies with the last session, #1186 watcher semantics). This also fixes version skew: every session runs the **currently installed** bili instead of stale daemon code. Cost: one extra short-lived proxy process per session when no armed proxy exists (session state is shared on disk, so compression continuity is unaffected); the multi-instance warning (#394) becomes correspondingly more common. **Escape hatch:** deliberately run a resident daemon for your hooks to ride on → set `native.attachExternal: true` in the config file or `BILI_NATIVE_ATTACH_EXTERNAL=1`. That restores attaching to any compatible listener regardless of watchdog state — you then own the daemon's lifetime and version yourself. 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); a **user-zone** candidate attaches by default regardless of watchdog state (#1660) — the user deliberately maintains that daemon; 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; `0`/`false` closes the gate for everyone, including user-zone daemons, forcing fresh zone spawns. 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 is wildcard-compatible on the lane axis (still subject to the gate). 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). 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. ## Runtime-info protocol (#955) @@ -79,21 +80,27 @@ takes over once traffic lands. Claude Code has no in-process extension point, so `bili plugin install claude` writes a managed block into `~/.claude/settings.json` (env -`ANTHROPIC_BASE_URL=http://127.0.0.1:48787/bili/`, +`ANTHROPIC_BASE_URL=http://127.0.0.1:/bili/`, `DISABLE_AUTO_COMPACT=1`, and a `SessionStart` hook) plus the same -user-scope MCP shell as before, now pinned to that stable port. The hook -(fired before claude's first model request) attaches to a healthy proxy on -the port or spawns one whose pid watchdog tracks claude itself, so the -proxy lives and dies with the session. Port override: -`BILI_CLAUDE_NATIVE_PORT` > config `claude.nativePort` > 48787; upstream -override: `BILI_CLAUDE_UPSTREAM` (or the existing `claude.anthropicBaseUrl` -config). Opt out with `BILI_NATIVE_CLAUDE=0` — the hook then brings up a -**passthrough** proxy on the same port (verbatim forward, compression off) -so claude keeps working. The block is pure JSON merge/strip: foreign keys -are never touched, `bili plugin remove claude` restores exactly. `bili -claude` still works on a machine with the native block installed — it -overrides the static URL with its own ephemeral proxy and the hook stays -dormant. +user-scope MCP shell as before. The hook (fired before claude's first model +request) resolves its port like every lane (#1660): an explicit pin +(`BILI_CLAUDE_NATIVE_PORT` > config `claude.nativePort`) launches +**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 +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 +the running proxy. Upstream override: `BILI_CLAUDE_UPSTREAM` (or the +existing `claude.anthropicBaseUrl` config). Install no longer persists +`claude.nativePort`. Opt out with `BILI_NATIVE_CLAUDE=0` — the hook then +brings up a **passthrough** proxy on the same resolved port (verbatim +forward, compression off) so claude keeps working. The block is pure JSON +merge/strip: foreign keys are never touched, `bili plugin remove claude` +restores exactly. `bili claude` still works on a machine with the native +block installed — it overrides the static URL with its own proxy and the +hook stays dormant. ## Injection priority — no files unless unavoidable (#535) diff --git a/TECHNICAL-NOTES.zh-CN.md b/TECHNICAL-NOTES.zh-CN.md index 2b80f5559b..2d6c4bce94 100644 --- a/TECHNICAL-NOTES.zh-CN.md +++ b/TECHNICAL-NOTES.zh-CN.md @@ -6,19 +6,20 @@ README 三种使用方式背后的机制级说明。README 里每种方式只保 插件加载时**自拉起自己的代理**(已有健康实例则直接复用 —— 父进程 pid 看门狗在客户端退出时收掉它),把模型流量改写到 `/bili/<上游URL>`,把 `compress` / `decompress` / `acp_status` 注册为客户端原生工具(plugin 模式),并把 `/acp` 面板绑定到当前会话。插件还会把客户端**自己的模型配置**上报给代理(runtime-info 协议,#955),压缩预算用真实窗口而不是注册表猜测。退出开关:`BILI_NATIVE_PI=0`、`BILI_NATIVE_OMP=0`、`BILI_NATIVE_OPENCODE=0`、`BILI_NATIVE_DSH=0`、`BILI_NATIVE_KIMI=0`、`BILI_NATIVE_HERMES=0`、`BILI_NATIVE_ZCODE=0`。 -## 代理复用与附着门禁(#1225、#1335、#1232) +## 代理复用与附着门禁(#1225、#1335、#1232、#1660) -原生 hook 可以附着到已在运行的代理而不自己拉起 —— 仅当通过下面的生命周期门禁。复用基于身份(#1225):只有当既有代理运行的是**同一份代码**(入口脚本 sha256,记录在实例文件里)、**lane 兼容**(每个启动器声明其客户端 lane,两个*不同声明的* lane 永不共享;未声明 lane 的实例在该轴上通配)、**且拥有会话生命周期**(健康端点报告 armed 父进程 pid 看门狗 `watchdog.armed == true`,即由带父 pid 的启动器拉起、随最后一个附着会话消亡)时才附着。#1225 之前写入的实例没有代码指纹,因此永不附着:重建或更新后的安装下次启动总会拉起新代理,修复立即生效而不是静默服务旧代码。 +原生 hook 可以附着到已在运行的代理而不自己拉起 —— 仅当通过下面的生命周期门禁。复用基于身份(#1225):只有当既有代理运行的是**同一份代码**(入口脚本 sha256,记录在实例文件里)、**lane 兼容**(每个启动器声明其客户端 lane,两个*不同声明的* lane 永不共享;未声明 lane 的实例是手工拉起的用户主权区守护进程,在该轴上通配)、**且通过生命周期门禁**(见下:armed 父进程 pid 看门狗 `watchdog.armed == true`,即由带父 pid 的启动器拉起、随最后一个附着会话消亡;**或**属用户主权区实例 —— 无 lane、无 launch token —— 按定义豁免,#1660)时才附着。#1225 之前写入的实例没有代码指纹,因此永不附着:重建或更新后的安装下次启动总会拉起新代理,修复立即生效而不是静默服务旧代码。 | 监听者 | 附着? | 原因 | |---|---|---| | 本会话拉起的代理 | ✅ | 出生即 armed | | 其他会话的 armed 共享代理(watcher 集,#1186) | ✅ | 共享本就是设计 | -| 手工 `bili start` 常驻守护进程 | ❌ 默认不附着 | 无生命周期属主(拒绝 watcher 注册、不随会话退出、常是旧版本代码 —— #1322 的成因) | +| 手工 `bili start` 常驻守护进程(用户主权区,#1660) | ✅ 默认附着 | **用户主权区**实例(无 lane、无 launch token):用户刻意维护 —— 其寿命与版本由你自己负责;仅当 `BILI_NATIVE_ATTACH_EXTERNAL=0/false` 显式关门时才拒绝 | +| 未武装的 **lane 型**代理(崩溃会话孤儿;pre-#1330 不可验证) | ❌ 大声拒绝 | 生命周期漂移症状(#1335):搭乘等于静默复用无人管理的代理 | -hook 附着前先探测候选者 `/__bili/health` 里的 `watchdog.armed`:armed → 附着并注册 watcher(现状不变);unarmed、或 pre-#1330 构建根本不报 `watchdog` 字段(不可验证,按 unarmed 处理)→ **不附着**,本会话自拉起一个临时代理(临时端口、出生即 armed、随最后一个会话消亡,#1186 watcher 语义)。顺带修掉版本偏斜:每个会话跑的都是**当前安装的** bili,而不是陈旧守护进程携带的旧代码。代价:无 armed 代理时每会话多一个短命代理进程(会话状态在磁盘上共享,压缩连续性不受影响);多实例告警(#394)相应变多。**逃生舱:** 刻意用常驻守护进程承载原生 hook → 配置文件设 `"native": { "attachExternal": true }` 或 `BILI_NATIVE_ATTACH_EXTERNAL=1`,恢复对任何 code/lane 兼容监听者的附着(守护进程的寿命与版本由你自己负责)。kimi/dsh 的显式用户指定附着(`BILLION_CONTEXT_ATTACH` / 预置 `BILLION_CONTEXT_PROXY`)完全不经过发现路径,构造上豁免。 +hook 附着前先探测候选者的 `/__bili/health`:armed → 附着并注册 watcher(现状不变);**用户主权区**候选无论看门狗状态默认附着(#1660)—— 用户刻意维护该守护进程;未武装的 **lane 型**候选(崩溃会话孤儿,或 pre-#1330 构建根本不报 `watchdog` 字段 —— 不可验证,按 unarmed 处理)被**大声拒绝**,本会话在自管端口区自拉起代理(基准口 `18787` 或该 lane 粘性漂移记录;出生即 armed、随最后一个会话消亡,#1186 watcher 语义)。版本偏斜仍被修住:代码指纹检查先行,重建/更新后的安装即使经用户主权区豁免也永不搭乘陈旧守护进程。代价:无可附着实例时每会话多一个短命代理进程(会话状态在磁盘上共享,压缩连续性不受影响);多实例告警(#394)相应变多。**逃生舱:** 配置文件 `"native": { "attachExternal": true }` 或 `BILI_NATIVE_ATTACH_EXTERNAL=1` 把附着扩展到 *lane 型*监听者(无论看门狗状态,含 pre-#1330 构建)—— 那些守护进程的寿命与版本由你自己负责;`0`/`false` 对所有人关门,包括用户主权区守护进程,强制各 lane 自拉新代理。kimi/dsh 的显式用户指定附着(`BILLION_CONTEXT_ATTACH` / 预置 `BILLION_CONTEXT_PROXY`)完全不经过发现路径,构造上豁免。 -附着发现在**所有**存活实例间是 lane 感知的(#1232):启动器探测实例注册表里的每一条存活记录,而不只是单个实例文件(last-writer-wins —— 并发多客户端下它可能指向别的客户端的代理),并对每个候选应用上面的门禁。兼容候选中,lane 与启动器自身声明一致的最新实例胜出;未声明 lane 的实例在 lane 轴上通配(仍受门禁约束)。`another bili instance is running` 告警(#394)也是 lane 感知的:同 lane 或无 lane 共存时触发,两个*不同声明* lane 之间保持沉默(它们的会话文件互不相交)。 +附着发现在**所有**存活实例间是 lane 感知的(#1232):启动器探测实例注册表里的每一条存活记录,而不只是单个实例文件(last-writer-wins —— 并发多客户端下它可能指向别的客户端的代理),并对每个候选应用上面的门禁。兼容候选中,lane 与启动器自身声明一致的最新实例胜出;未声明 lane 的实例(用户主权区守护进程)在 lane 轴上通配,且门禁默认豁免(#1660)。`another bili instance is running` 告警(#394)也是 lane 感知的:同 lane 或无 lane 共存时触发,两个*不同声明* lane 之间保持沉默(它们的会话文件互不相交)。 ## Runtime-info 协议(#955) @@ -37,7 +38,7 @@ launcher 环境变量这档覆盖纯代理客户端(无进程内插件):`bili `、`DISABLE_AUTO_COMPACT=1`、`SessionStart` hook),外加同样指向该稳定端口的用户级 MCP shell。hook 在首个模型请求前触发:附着到端口上健康的代理,或拉起一个 pid 看门狗追踪 claude 本身的代理 —— 代理随会话生灭。端口覆盖:`BILI_CLAUDE_NATIVE_PORT` > config `claude.nativePort` > 48787;上游覆盖:`BILI_CLAUDE_UPSTREAM`(或既有 `claude.anthropicBaseUrl`)。`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:/bili/`、`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 保持休眠。 ## 注入优先级 —— 能不写文件就不写(#535) diff --git a/src/claude-native-bootstrap.ts b/src/claude-native-bootstrap.ts index 3f42dd2747..498b661795 100644 --- a/src/claude-native-bootstrap.ts +++ b/src/claude-native-bootstrap.ts @@ -33,6 +33,8 @@ import { readFileSync } from "node:fs"; import { execFileSync } from "node:child_process"; import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "./launcher.js"; import { resolveClaudeNativePort } from "./config.js"; +import { lanePreferredPort } from "./instance.js"; +import { repinClaudeManagedBaseUrl } from "./plugin-install.js"; import { nativeBootstrapGate, proxyEnvOrigin } from "./agent/native-bootstrap.js"; /** dist/claude-native-bootstrap.js → sibling dist/index.js (the package @@ -53,12 +55,19 @@ function log(msg: string): void { * - "passthrough": opted out (BILI_NATIVE_CLAUDE=0 / * BILLION_CONTEXT_PLUGIN=0) — serve the static URL verbatim-forward. * - "start": bring up (or attach to) the compression proxy. */ -export function planClaudeNativeBootstrap(env: NodeJS.ProcessEnv): { action: "exit" | "passthrough" | "start"; port: number } { - const port = resolveClaudeNativePort(env); - if (proxyEnvOrigin(env) !== undefined) return { action: "exit", port }; - if (env.BILLION_CONTEXT_PLUGIN === "0" || env.BILI_NATIVE_CLAUDE === "0") return { action: "passthrough", port }; - if (!nativeBootstrapGate(env, "BILI_NATIVE_CLAUDE")) return { action: "exit", port }; - return { action: "start", port }; +export function planClaudeNativeBootstrap(env: NodeJS.ProcessEnv): { action: "exit" | "passthrough" | "start"; port: number; strict: boolean } { + // #1660 zone semantics: an EXPLICIT override (BILI_CLAUDE_NATIVE_PORT / + // claude.nativePort) keeps strict-port behavior (#964 — refuse a squatter + // rather than serve through it); otherwise the claude lane's zone + // preference (sticky record > 18787 base), with the proxy child's + // EADDRINUSE +1 ladder resolving collisions zero-config. + const explicit = resolveClaudeNativePort(env); + const port = explicit ?? lanePreferredPort("claude", env); + const strict = explicit !== undefined; + if (proxyEnvOrigin(env) !== undefined) return { action: "exit", port, strict }; + if (env.BILLION_CONTEXT_PLUGIN === "0" || env.BILI_NATIVE_CLAUDE === "0") return { action: "passthrough", port, strict }; + if (!nativeBootstrapGate(env, "BILI_NATIVE_CLAUDE")) return { action: "exit", port, strict }; + return { action: "start", port, strict }; } // — claude host pid resolution ——————————————————————————————— @@ -309,14 +318,18 @@ async function run(): Promise { // host itself; when the walk cannot find it, chooseWatchdogParentPid // degrades via the wrapper's parent instead of the wrapper. const watchPid = chooseWatchdogParentPid(); + // #1660: an EXPLICIT pin stays exact + strict; otherwise pass port 0 + // so the launcher resolves the zone preference and settles the + // actually-bound port sticky (a pre-resolved port > 0 would skip the + // zone wiring entirely and never write the sticky record). const handle = await ensureProxyRunning( { host: LAUNCHER_DEFAULT_HOST, - port: plan.port, + port: plan.strict ? plan.port : 0, passthrough: plan.action === "passthrough", debug: false, parentPid: watchPid, - strictPort: true, + strictPort: plan.strict, lane: "claude", }, { scriptPath: proxyScriptPath() }, @@ -325,6 +338,18 @@ async function run(): Promise { // (every native client registers there; claude's earlier copy was // redundant once the chokepoint covered all callers). log(`proxy ${handle.attached ? "attached" : "started"} at ${handle.origin}${plan.action === "passthrough" ? " (passthrough — compression off)" : ""}`); + // #1660: the zone port can drift (+1 ladder on EADDRINUSE, sticky + // record). The managed block's baked ANTHROPIC_BASE_URL points at the + // LAST session's port — repin it to the origin we hold so the NEXT + // session dials correctly. The CURRENT session rides whatever base + // URL claude already loaded into its process env, so a failure here + // is non-fatal by construction; still, never let it kill the hook. + try { + const notes = repinClaudeManagedBaseUrl(handle.origin); + if (notes.length > 0) log(`managed settings repinned: ${notes.join("; ")}`); + } catch (err) { + log(`managed settings repin failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`); + } if (handle.refusedWatcher) { // #1322: attach landed on a daemon proxy (no BILI_PARENT_PID) whose // watchdog refused our owner — the README's "lives and dies with the diff --git a/src/config.ts b/src/config.ts index 0905e85d3e..233d63385e 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1054,10 +1054,10 @@ type FileConfig = { * Per-provider `imageBilling` overrides it; env BILI_IMAGE_BILLING wins * over both. See ProviderRoute.imageBilling. */ imageBilling?: string; - /** Claude-native install tuning (#964): the loopback port the managed - * settings block pins ANTHROPIC_BASE_URL at and the SessionStart hook - * brings a proxy up on. Default CLAUDE_NATIVE_DEFAULT_PORT; env - * BILI_CLAUDE_NATIVE_PORT wins over both. */ + /** Claude-native port override (#964/#1660): an explicit port for the + * claude lane — strict-port semantics (EADDRINUSE fails loud). Undefined + * (the default) means the lane's sticky zone port (ZONE_PORT_BASE base). + * Env BILI_CLAUDE_NATIVE_PORT wins over the file. */ claude?: { nativePort?: number }; /** Native-hook attach policy (#1335): set `true` to let native hooks * attach to lifecycle-less listeners (a manually started `bili start` @@ -1101,35 +1101,48 @@ function loadConfigFile(): FileConfig { return {}; } -/** Default loopback port for the claude native install (#964): the value the - * installer bakes into ~/.claude/settings.json's env.ANTHROPIC_BASE_URL and - * the SessionStart hook brings a proxy up on. Documented as reserved. */ -export const CLAUDE_NATIVE_DEFAULT_PORT = 48787; +/** #1660: the self-managed zone port base. Every launcher-spawned lane + * binds here by default instead of an OS-assigned ephemeral port: a stable + * origin survives instance death, and the proxy child's EADDRINUSE ladder + * (+1 per attempt) resolves collisions deterministically with a sticky + * record (instance.ts port-zone.json). 18787 sits below the Linux ephemeral + * range (32768–60999) so the ladder never lands on OS-assigned ports; 8787 + * stays reserved as the USER zone (manual `bili start`). Env BILI_ZONE_PORT + * overrides the base for the whole zone. */ +export const ZONE_PORT_BASE = 18787; -/** The claude-native loopback port, one resolution for installer, hook, and - * launcher: env BILI_CLAUDE_NATIVE_PORT > config `claude.nativePort` > - * CLAUDE_NATIVE_DEFAULT_PORT. */ -export function resolveClaudeNativePort(env: NodeJS.ProcessEnv = process.env): number { +export function resolveZonePortBase(env: NodeJS.ProcessEnv = process.env): number { + const fromEnv = Number.parseInt(env.BILI_ZONE_PORT ?? "", 10); + if (Number.isInteger(fromEnv) && fromEnv > 0 && fromEnv < 65536) return fromEnv; + return ZONE_PORT_BASE; +} + +/** #1660: an explicit user override of the claude lane's port: env + * BILI_CLAUDE_NATIVE_PORT > config `claude.nativePort` > undefined. A + * DEFINED value means a strict-port launch (an EADDRINUSE at bind fails + * loud, #964); undefined means the lane's sticky zone port + * (instance.ts lanePreferredPort) with the +1 ladder absorbing collisions. + * The installer no longer persists this — zone drift is repaired by the + * SessionStart hook rewriting the managed block to the live origin every + * session. */ +export function resolveClaudeNativePort(env: NodeJS.ProcessEnv = process.env): number | undefined { const fromEnv = Number.parseInt(env.BILI_CLAUDE_NATIVE_PORT ?? "", 10); if (Number.isInteger(fromEnv) && fromEnv > 0 && fromEnv < 65536) return fromEnv; const fromFile = loadConfigFile().claude?.nativePort; if (typeof fromFile === "number" && Number.isInteger(fromFile) && fromFile > 0 && fromFile < 65536) return fromFile; - return CLAUDE_NATIVE_DEFAULT_PORT; + return undefined; } -/** ZCode native lane: default pinned port (#1622/#1623) — the same pattern - * as CLAUDE_NATIVE_DEFAULT_PORT. A pinned port means wrappers written into - * the shared provider store stay valid across sessions even when an - * instance dies without handoff: every respawn re-opens the same port (and - * a concurrent compatible listener is attached instead of doubled). Env - * BILI_ZCODE_PORT overrides (validated); no file config — the store is - * re-derived at every bootstrap, so nothing is baked at install time. */ -export const ZCODE_NATIVE_DEFAULT_PORT = 48789; - -export function resolveZcodeNativePort(env: NodeJS.ProcessEnv = process.env): number { +/** #1660: explicit override of the zcode lane's port (env only — the store + * is re-derived at every bootstrap, nothing is baked at install time). + * Defined means a strict-port launch; undefined means the lane's sticky + * zone port. Legacy wrappers pinned to the old 48789 default are migrated + * by the bootstrap's origin-drift repair (routeZcodeConfig rewrites the + * store to the live origin). */ +export function resolveZcodeNativePort(env: NodeJS.ProcessEnv = process.env): number | undefined { const fromEnv = Number.parseInt(env.BILI_ZCODE_PORT ?? "", 10); if (Number.isInteger(fromEnv) && fromEnv > 0 && fromEnv < 65536) return fromEnv; - return ZCODE_NATIVE_DEFAULT_PORT; + return undefined; } /** Client-side routing exemptions (#1622): providers whose route declares @@ -1153,76 +1166,6 @@ export function resolveNativeAttachExternal(env: NodeJS.ProcessEnv = process.env return loadConfigFile().native?.attachExternal === true; } -/** Persist the claude-native port the installer baked into settings.json - * (#964). Without this, an install driven by BILI_CLAUDE_NATIVE_PORT writes - * that port into ~/.claude/settings.json but the SessionStart hook (which - * does NOT inherit claude's settings.env) later resolves the default — - * hooking the wrong port while claude dials the baked one. `claude plugin - * install` calls this; `claude plugin remove` calls clearClaudeNativePort. */ -/** #964: read-modify-write safety for user config files — refuse to write - * over a file that exists but is NOT valid JSON: loadConfigFile() degrades - * malformed input to {}, so an unguarded RMW would replace the user's - * corrupt-but-repairable config with a minimal one (silent clobber). - * Absent / empty / valid files are all safe to write. */ -function configFileRmwSafe(): boolean { - const p = configFile(); - let raw: string; - try { - raw = readFileSync(p, "utf8"); - } catch { - return true; - } - if (!raw.trim()) return true; - try { - JSON.parse(raw.replace(/^\uFEFF/, "")); - return true; - } catch { - return false; - } -} - -export function saveClaudeNativePort(port: number): void { - const p = configFile(); - if (!configFileRmwSafe()) { - loggerLog("warn", `[acp-config] refusing to persist claude.nativePort=${port} — ${p} is not valid JSON; repair it first`); - return; - } - const cur = loadConfigFile() as { claude?: { nativePort?: number } } & Record; - const next: { claude?: { nativePort?: number } } & Record = { ...cur }; - next.claude = { ...(cur.claude ?? {}), nativePort: port }; - try { - mkdirSync(dirname(p), { recursive: true }); - writeFileSync(p, JSON.stringify(next, null, 2) + "\n", "utf8"); - } catch (err) { - loggerLog("warn", `[acp-config] could not persist claude.nativePort=${port} at ${p} — ${err instanceof Error ? err.message : String(err)}`); - } -} - -/** Drop the persisted claude-native port (plugin remove) so a fresh default - * install resolves the default port again. Never throws. */ -export function clearClaudeNativePort(): void { - const p = configFile(); - if (!configFileRmwSafe()) { - loggerLog("warn", `[acp-config] refusing to clear claude.nativePort — ${p} is not valid JSON; repair it first`); - return; - } - const cur = loadConfigFile() as { claude?: { nativePort?: number } } & Record; - if (cur.claude?.nativePort === undefined) return; - const next: Record = { ...cur }; - if (Object.keys(cur.claude).length > 1) { - const claude = { ...cur.claude } as Record; - delete claude.nativePort; - next.claude = claude; - } else { - delete next.claude; - } - try { - mkdirSync(dirname(p), { recursive: true }); - writeFileSync(p, JSON.stringify(next, null, 2) + "\n", "utf8"); - } catch (err) { - loggerLog("warn", `[acp-config] could not clear claude.nativePort at ${p} — ${err instanceof Error ? err.message : String(err)}`); - } -} /** Template written on first run so the user has a file to edit instead * of having to invent the path/schema. Left empty on purpose: the proxy diff --git a/src/instance.ts b/src/instance.ts index 23d27b66b0..c06e6fdb38 100644 --- a/src/instance.ts +++ b/src/instance.ts @@ -1,6 +1,7 @@ import { createHash, randomUUID } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; +import { resolveZonePortBase } from "./config.js"; import { stateDir } from "./paths.js"; /** Instance registry (#394/#403/#417): the proxy-origin file is upgraded from @@ -89,6 +90,54 @@ export function instanceFilePath(): string { return path.join(stateDir(), "proxy-origin"); } +export function portZoneFilePath(): string { + return path.join(stateDir(), "port-zone.json"); +} + +/** #1660: the sticky per-lane port inside the self-managed zone. The +1 + * ladder can drift a lane off its base (EADDRINUSE at 18787 → 18788 → …); + * once a lane runs at a drifted port, every later launch must TRY that + * port first — the lane's persistent wrappers and managed URLs point at + * it. Tolerates a missing/garbage file (undefined → base). */ +export function readZonePort(lane: string, file: string = portZoneFilePath()): number | undefined { + let raw: string; + try { + raw = fs.readFileSync(file, "utf8"); + } catch { + return undefined; + } + try { + const parsed = JSON.parse(raw) as { lanes?: Record }; + const v = parsed?.lanes?.[lane]; + if (typeof v === "number" && Number.isInteger(v) && v > 0 && v < 65536) return v; + return undefined; + } catch { + return undefined; + } +} + +/** #1660: record a lane's settled zone port (the spawn path writes the port + * the child ACTUALLY bound — preferred or laddered). Best-effort RMW via the + * same atomic tmp+rename as every registry marker; never throws. */ +export function writeZonePort(lane: string, port: number, file: string = portZoneFilePath()): void { + if (!Number.isInteger(port) || port <= 0 || port >= 65536) return; + let cur: { lanes?: Record } = {}; + try { + const parsed = JSON.parse(fs.readFileSync(file, "utf8")) as { lanes?: Record }; + if (parsed !== null && typeof parsed === "object" && parsed.lanes !== null && typeof parsed.lanes === "object") cur = parsed; + } catch {} + atomicWriteJson({ lanes: { ...(cur.lanes ?? {}), [lane]: port } }, file); +} + +/** #1660: the port a lane'd launch should TRY to bind — the lane's sticky + * record (a past ladder drift this lane still points at), else the zone + * base (BILI_ZONE_PORT override). Explicit user overrides + * (BILI_CLAUDE_NATIVE_PORT / BILI_ZCODE_PORT) are resolved separately by + * the lanes and imply strict-port launches. */ +export function lanePreferredPort(lane: string, env: NodeJS.ProcessEnv = process.env, file: string = portZoneFilePath()): number { + return readZonePort(lane, file) ?? resolveZonePortBase(env); +} + /** #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 diff --git a/src/launcher.ts b/src/launcher.ts index e9a4ae7d3a..35de4acd9f 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -42,9 +42,11 @@ import { entryScriptFingerprint, isPidAlive, isProxyInstanceFile, + lanePreferredPort, readProxyInstanceFile, readStartingMarker, removeStartingMarker, + writeZonePort, type ProxyInstanceFile, type ProxyStartingMarker, } from "./instance.js"; @@ -252,6 +254,13 @@ export interface LauncherDeps { * construction — tests drive win32 paths from a POSIX host. Defaults * to process.platform. */ platform?: NodeJS.Platform; + /** #1660: zone-port seam for tests. The preferred port a lane'd launch + * tries before the proxy child's +1 ladder (default: the lane's sticky + * record > zone base, instance.ts), and the sticky-settle write + * (default: stateDir()/port-zone.json). Tests inject pure sinks so a + * lane'd fake launch never touches the developer's real zone record. */ + zonePreferredPort?: (lane: string) => number; + writeZonePort?: (lane: string, port: number) => void; } export function isLaunchClient(value: string): value is ClientName { @@ -2538,6 +2547,16 @@ export function attachGateAllows(health: HealthInfo, attachExternal: boolean): b 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. */ +function isUserZoneInstance(inst: ProxyInstanceFile): boolean { + return inst.lane === undefined && 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`)" @@ -2567,7 +2586,9 @@ function pickAttachable( if (opts.strictPort && c.inst.port !== opts.port) { diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): port mismatch`); continue; } // #1335: lifecycle gate — an unarmed (or unverifiable) listener is // never an attach target by default; log the refusal once per origin. - if (!attachGateAllows(c.health, attachExternal)) { + // #1660: a user-zone instance (manual `bili start`) is exempt — the + // missing watchdog is the user's deliberate posture, not drift. + if (!attachGateAllows(c.health, attachExternal) && !isUserZoneInstance(c.inst)) { if (!refusedLog.has(c.inst.origin)) { refusedLog.add(c.inst.origin); console.error(gateRefusalMessage(c.inst, c.health)); @@ -2886,11 +2907,23 @@ export async function ensureProxyRunning( // itself and retries on EADDRINUSE, reporting the real origin through // the instance file via this launchToken. const launchToken = randomUUID(); - // #446: with no explicit --port the launcher binds an OS-assigned - // ephemeral port — its private proxy never squats on 8787, so clients - // pointed there only ever reach an explicitly-started `bili start`. - // The child's EADDRINUSE retry covers the pick/spawn race. - const port = opts.port > 0 ? opts.port : await pickEphemeralPort(opts.host); + // #1660: a lane'd launch with no explicit port binds the SELF-MANAGED + // ZONE — the lane's sticky port (a past ladder drift it still points at) + // else the zone base — instead of an OS-assigned ephemeral. An undeclared + // lane (manual `bili start`, the user zone on 8787) keeps the ephemeral + // default. The child's EADDRINUSE +1 ladder covers the pick/spawn race + // AND a squatted preferred port (zero-config resolution: the lane lands + // on base+1 and records it sticky; #1660). + const zoneLane = opts.lane !== undefined && opts.port <= 0 ? opts.lane : undefined; + const preferredPort = deps?.zonePreferredPort ?? lanePreferredPort; + const port = opts.port > 0 + ? opts.port + : zoneLane !== undefined + ? preferredPort(zoneLane) + : await pickEphemeralPort(opts.host); + const settleZonePort = (settled: number): void => { + if (zoneLane !== undefined) (deps?.writeZonePort ?? writeZonePort)(zoneLane, settled); + }; if (!script) throw new Error("bili: cannot resolve launcher script path"); const logPath = path.join(os.tmpdir(), `bili-proxy-${port}.log`); const logFd = fs.openSync(logPath, "a"); @@ -2992,6 +3025,10 @@ export async function ensureProxyRunning( const inst = readInstance(); if (isProxyInstanceFile(inst) && inst.launchToken === launchToken) { if (await probeHealth(inst.origin, fetchImpl)) { + // #1660: settle the lane's sticky record on the port the + // child actually bound (preferred or laddered) so every + // later launch of this lane tries it first. + settleZonePort(inst.port); return { origin: inst.origin, port: inst.port, child, logPath }; } continue; @@ -3003,6 +3040,7 @@ export async function ensureProxyRunning( // 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))) { + settleZonePort(port); return { origin: proxyOrigin(opts.host, port), port, child, logPath }; } } diff --git a/src/plugin-install.ts b/src/plugin-install.ts index a1b923bf22..a26ffd11b4 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -37,8 +37,8 @@ import { execFileSync, spawnSync } from "node:child_process"; import { fileURLToPath, pathToFileURL } from "node:url"; import { applyEdits, modify as jsoncModify, parse as jsoncParse, type ParseError } from "jsonc-parser"; import { resolveDshHome, resolveHermesHome, resolveKimiHome, resolvePiHome } from "./client-config.js"; -import { clearClaudeNativePort, resolveClaudeNativePort, saveClaudeNativePort } from "./config.js"; -import { isPidAlive, isProxyInstanceFile, readProxyInstanceFile } from "./instance.js"; +import { resolveClaudeNativePort } from "./config.js"; +import { lanePreferredPort } from "./instance.js"; import { DSH_PACKAGE, dshBundleInstalled, dshHasLegacyManagedBlock, dshProfileDependsOnBili, dshProfileDepSpec, dshProfileDirs, isRegistryDepSpec, planDshSpawn, refreshDshProfileBundles, runDshPlugin, stripLegacyManagedBlock } from "./dsh-channel.js"; import { fetchRegistryVersion } from "./update.js"; import { restoreKimiBackup, unrouteKimi } from "./kimi/native.js"; @@ -79,23 +79,6 @@ export function portableHookCommand(exe: string, args: string[] = []): string { return /\s/.test(head) ? [`& "${head}"`, ...tail].join(" ") : [head, ...tail].join(" "); } -/** #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", "dsh", "kimi", "hermes", "zcode"] as const; export type PluginAgent = (typeof PLUGIN_AGENTS)[number]; @@ -499,11 +482,51 @@ export function isBiliClaudeBaseUrl(value: unknown): boolean { } export function claudeNativeBaseUrl(env: NodeJS.ProcessEnv = process.env): string { - const origin = `http://127.0.0.1:${resolveClaudeNativePort(env)}`; + const origin = `http://127.0.0.1:${resolveClaudeNativePort(env) ?? lanePreferredPort("claude", env)}`; + return claudeNativeBaseUrlForOrigin(origin, undefined, env); +} + +/** #1660: the wrapped base URL for an arbitrary live origin — the + * SessionStart hook's drift-repair path (the managed block must follow the + * lane's zone-drifted port). `upstream`, when given, overrides the default + * resolution (BILI_CLAUDE_UPSTREAM > https://api.anthropic.com) — pass the + * UNWRAPPED value of the current settings URL to preserve a relay an + * earlier install baked in. */ +export function claudeNativeBaseUrlForOrigin(origin: string, upstream: string | undefined, env: NodeJS.ProcessEnv = process.env): string { const relay = env.BILI_CLAUDE_UPSTREAM?.trim(); - const upstream = (relay && relay.length > 0 ? relay : "https://api.anthropic.com").replace(/\/+$/, ""); - const prefix = origin + "/bili/"; - return upstream.startsWith(prefix) ? upstream : prefix + upstream; + const base = (upstream !== undefined && upstream.length > 0 + ? upstream + : relay && relay.length > 0 + ? relay + : "https://api.anthropic.com").replace(/\/+$/, ""); + const prefix = origin.replace(/\/+$/, "") + "/bili/"; + return base.startsWith(prefix) ? base : prefix + base; +} + +/** The inverse of the wrap: strip a bili wrapper (any loopback port) from a + * base URL. Returns undefined for anything not written by us. */ +export function unwrapBiliBaseUrl(value: string): string | undefined { + const m = /^http:\/\/127\.0\.0\.1:\d{1,5}\/bili\/(https?:\/\/.+)$/.exec(value); + return m ? m[1] : undefined; +} + +/** #1660: SessionStart drift-repair — repin the managed block's + * ANTHROPIC_BASE_URL to `origin` (the lane's live zone port, which the +1 + * ladder may have drifted off the last install's baked port). The wrapped + * upstream is PRESERVED from the current value unless BILI_CLAUDE_UPSTREAM + * overrides it; a foreign ANTHROPIC_BASE_URL is never touched (same rule as + * install). Also upserts the SessionStart hook, keeping a stale command + * fresh across upgrades. Returns the change notes for the hook's log; + * never throws, and writes only when the file actually changes. */ +export function repinClaudeManagedBaseUrl(origin: string, env: NodeJS.ProcessEnv = process.env): string[] { + const file = claudeSettingsFile(env); + const settings = readJson(file); + const cur = (settings.env as Record | undefined)?.ANTHROPIC_BASE_URL; + const baseUrl = claudeNativeBaseUrlForOrigin(origin, typeof cur === "string" ? unwrapBiliBaseUrl(cur) : undefined, env); + const hookCommand = portableHookCommand(process.execPath, [path.join(selfPackageRoot(), "dist", "claude-native-bootstrap.js")]); + const { data, notes } = applyClaudeManagedBlock(settings, { baseUrl, hookCommand }); + if (JSON.stringify(data) !== JSON.stringify(settings)) writeJson(file, data); + return notes; } /** Pure merge of the #964 managed block into parsed settings (install path). @@ -677,13 +700,14 @@ function claudeInstall(): string { requireDistFile(bootstrapJs); // Managed block first: the static URL + bootstrap hook + compaction off. - // #964: persist the resolved port into the bili config too — the - // SessionStart hook does NOT inherit claude's settings.env, so without a - // persisted copy an env-driven port (BILI_CLAUDE_NATIVE_PORT=48790) - // would live only in settings.json while the hook resolves the default - // and brings the proxy up on the WRONG port. - const nativePort = resolveClaudeNativePort(); - saveClaudeNativePort(nativePort); + // #964/#1660: the baked URL uses the explicit override + // (BILI_CLAUDE_NATIVE_PORT / claude.nativePort) when set — which also + // makes every later hook launch strict-port — else the current zone + // preference (sticky record > 18787 base). An explicit env-driven port + // can no longer desync from the hook: both resolve through + // resolveClaudeNativePort(), and the SessionStart hook's repin pass + // rewrites the baked URL to the live origin anyway (#1660). + const nativePort = resolveClaudeNativePort() ?? lanePreferredPort("claude"); const file = claudeSettingsFile(); const settings = readJson(file); const hookCommand = portableHookCommand(process.execPath, [bootstrapJs]); @@ -724,7 +748,6 @@ function claudeInstall(): string { function claudeRemove(): string { const parts: string[] = []; - clearClaudeNativePort(); const file = claudeSettingsFile(); const settings = readJson(file); const { data, removed } = stripClaudeManagedBlock(settings); @@ -809,7 +832,11 @@ 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(proxyOriginForInstall())} }\n`; + // #1660: no baked origin — the MCP shell discovers the live proxy at + // startup (env > live instance file > 8787 user-zone default), so the + // block never goes stale when the proxy's port drifts or the machine + // reboots. BILI_MCP_PROXY in the user's environment still wins. + return `\n[mcp_servers.bili]\ncommand = ${JSON.stringify(process.execPath)}\nargs = [${JSON.stringify(path.join(selfPackageRoot(), "dist", "mcp.js"))}]\n`; } function malformedCodexArgs(block: string): boolean { @@ -1111,7 +1138,7 @@ export function applyOpencodePluginEntry(args: { data: Record; } // Exactly our one entry, already the right form — nothing to migrate: // leave the key (and the file) untouched. - if (replaced.length === 1 && replaced[0] === entry) return ["plugin present"]; + if (replaced.length === 1 && replaced[0] === entry) return [`${key} present`]; if (Array.isArray(raw)) { data[key] = [...raw.filter((x) => !isOurs(x)), entry]; } else if (raw !== null && typeof raw === "object") { diff --git a/src/zcode/mcp-entry.ts b/src/zcode/mcp-entry.ts index 0db8f2d846..1b06da4819 100644 --- a/src/zcode/mcp-entry.ts +++ b/src/zcode/mcp-entry.ts @@ -54,8 +54,14 @@ function startWatchdog( if (attached) { log(`attached proxy ${state.origin} unhealthy — waiting for it to recover`); } else { + // #1660: same zone semantics as + // zcode/native.ts defaultEnsureProxy — explicit + // BILI_ZCODE_PORT is strict; otherwise port 0 lets the + // launcher resolve the zone preference AND settle the + // actually-bound port sticky (#1660). + const explicit = resolveZcodeNativePort(); const handle = await ensureProxyRunning( - { host: LAUNCHER_DEFAULT_HOST, port: resolveZcodeNativePort(), passthrough: false, debug: false, lane: "zcode" }, + { host: LAUNCHER_DEFAULT_HOST, port: explicit ?? 0, passthrough: false, debug: false, strictPort: explicit !== undefined, lane: "zcode" }, { scriptPath: nativeProxyScriptPath() }, ); if (handle.origin !== state.origin) { diff --git a/src/zcode/native.ts b/src/zcode/native.ts index af37cc85dd..f712b48c28 100644 --- a/src/zcode/native.ts +++ b/src/zcode/native.ts @@ -384,12 +384,16 @@ export async function bootstrapZcodeNative(opts: BootstrapZcodeOptions = {}): Pr async function defaultEnsureProxy(): Promise<{ origin: string; attached: boolean }> { // The spawned proxy's parent-gone watchdog (#server.ts BILI_PARENT_PID) // keys off OUR pid: zcode kills this MCP child when its session ends, so - // the per-session proxy tears itself down with it. The lane pins its - // default port (ZCODE_NATIVE_DEFAULT_PORT, BILI_ZCODE_PORT to override) - // so wrappers written by one session stay valid for the next one even - // when nothing else hands the port off (#1622/#1623). + // the per-session proxy tears itself down with it. #1660 zone semantics: + // BILI_ZCODE_PORT (explicit) keeps strict-port behavior; otherwise the + // zcode lane binds its zone preference (sticky record > 18787 base) and + // the proxy child's EADDRINUSE +1 ladder resolves collisions zero-config + // — wrappers written by one session stay valid for the next one even + // when nothing else hands the port off (#1622/#1623), and the store + // drift-repair below follows any drift. + const explicit = resolveZcodeNativePort(); const handle = await ensureProxyRunning( - { host: LAUNCHER_DEFAULT_HOST, port: resolveZcodeNativePort(), passthrough: false, debug: false, lane: "zcode" }, + { host: LAUNCHER_DEFAULT_HOST, port: explicit ?? 0, passthrough: false, debug: false, strictPort: explicit !== undefined, lane: "zcode" }, { scriptPath: nativeProxyScriptPath() }, ); return { origin: handle.origin, attached: !!handle.attached }; diff --git a/tests/claude-native.test.ts b/tests/claude-native.test.ts index be6b4d4f63..82ec9692a2 100644 --- a/tests/claude-native.test.ts +++ b/tests/claude-native.test.ts @@ -17,13 +17,16 @@ import { claudeNativeBaseUrl, claudeNativeInstalled, claudeSettingsFile, + claudeNativeBaseUrlForOrigin, + unwrapBiliBaseUrl, isBiliClaudeBaseUrl, pluginInstall, pluginRemove, + repinClaudeManagedBaseUrl, resolveClaudeCli, stripClaudeManagedBlock, } from "../src/plugin-install.ts"; -import { CLAUDE_NATIVE_DEFAULT_PORT, clearClaudeNativePort, resolveClaudeNativePort, resolveNativeAttachExternal, saveClaudeNativePort } from "../src/config.ts"; +import { ZONE_PORT_BASE, resolveClaudeNativePort, resolveNativeAttachExternal } from "../src/config.ts"; import { chooseWatchdogParentPid, isClaudeHostArgv, isTransientShArgv, planClaudeNativeBootstrap, readPsProcInfo, readWinProcInfo, resolveClaudeHostPid, splitWindowsCommandLine } from "../src/claude-native-bootstrap.ts"; import { rmrf } from "./tmp-rm.ts"; @@ -148,9 +151,12 @@ test("claudeNativeBaseUrl: default wraps api.anthropic.com; BILI_CLAUDE_UPSTREAM try { delete process.env.BILI_CLAUDE_UPSTREAM; delete process.env.BILI_CLAUDE_NATIVE_PORT; + // #1660: no explicit override → the claude lane's zone preference + // (sticky record > 18787 base) — readZonePort has no record in tests. assert.equal(claudeNativeBaseUrl().includes(`/bili/https://api.anthropic.com`), true); + assert.equal(claudeNativeBaseUrl(), `http://127.0.0.1:${ZONE_PORT_BASE}/bili/https://api.anthropic.com`); process.env.BILI_CLAUDE_UPSTREAM = "https://relay.example/"; - assert.equal(claudeNativeBaseUrl(), `http://127.0.0.1:${CLAUDE_NATIVE_DEFAULT_PORT}/bili/https://relay.example`); + assert.equal(claudeNativeBaseUrl(), `http://127.0.0.1:${ZONE_PORT_BASE}/bili/https://relay.example`); } finally { if (prev === undefined) delete process.env.BILI_CLAUDE_UPSTREAM; else process.env.BILI_CLAUDE_UPSTREAM = prev; @@ -159,11 +165,26 @@ test("claudeNativeBaseUrl: default wraps api.anthropic.com; BILI_CLAUDE_UPSTREAM } }); -test("resolveClaudeNativePort: env > default; rejects junk", () => { - assert.equal(resolveClaudeNativePort({}), CLAUDE_NATIVE_DEFAULT_PORT); +test("claudeNativeBaseUrlForOrigin: wraps an arbitrary origin; explicit upstream preserved (#1660)", () => { + assert.equal(claudeNativeBaseUrlForOrigin("http://127.0.0.1:18788", undefined, {}), "http://127.0.0.1:18788/bili/https://api.anthropic.com"); + assert.equal(claudeNativeBaseUrlForOrigin("http://127.0.0.1:18788/", "https://relay.example/", {}), "http://127.0.0.1:18788/bili/https://relay.example"); + assert.equal(claudeNativeBaseUrlForOrigin("http://127.0.0.1:18788", "https://api.anthropic.com", { BILI_CLAUDE_UPSTREAM: "https://env.example" }), "http://127.0.0.1:18788/bili/https://api.anthropic.com"); + // already-wrapped input is not double-wrapped + assert.equal(claudeNativeBaseUrlForOrigin("http://127.0.0.1:18788", "http://127.0.0.1:18788/bili/https://api.anthropic.com", {}), "http://127.0.0.1:18788/bili/https://api.anthropic.com"); +}); + +test("unwrapBiliBaseUrl: strips any loopback-port wrapper; foreign values untouched (#1660)", () => { + assert.equal(unwrapBiliBaseUrl("http://127.0.0.1:48787/bili/https://api.anthropic.com"), "https://api.anthropic.com"); + assert.equal(unwrapBiliBaseUrl("http://127.0.0.1:18788/bili/https://relay.example"), "https://relay.example"); + assert.equal(unwrapBiliBaseUrl("https://api.anthropic.com"), undefined); + assert.equal(unwrapBiliBaseUrl("http://127.0.0.1:8787/v1"), undefined); +}); + +test("resolveClaudeNativePort: env only, undefined without an explicit override (#1660)", () => { + assert.equal(resolveClaudeNativePort({}), undefined); assert.equal(resolveClaudeNativePort({ BILI_CLAUDE_NATIVE_PORT: "49999" }), 49999); - assert.equal(resolveClaudeNativePort({ BILI_CLAUDE_NATIVE_PORT: "0" }), CLAUDE_NATIVE_DEFAULT_PORT); - assert.equal(resolveClaudeNativePort({ BILI_CLAUDE_NATIVE_PORT: "not-a-number" }), CLAUDE_NATIVE_DEFAULT_PORT); + assert.equal(resolveClaudeNativePort({ BILI_CLAUDE_NATIVE_PORT: "0" }), undefined); + assert.equal(resolveClaudeNativePort({ BILI_CLAUDE_NATIVE_PORT: "not-a-number" }), undefined); }); // #1335: the attach-gate escape hatch — env BILI_NATIVE_ATTACH_EXTERNAL wins @@ -223,9 +244,11 @@ test("planClaudeNativeBootstrap: launcher-owned / opt-out / start", () => { assert.deepEqual(planClaudeNativeBootstrap({ BILI_PROVIDER_REWRITES: "x" }).action, "exit"); assert.deepEqual(planClaudeNativeBootstrap({ BILI_NATIVE_CLAUDE: "0" }).action, "passthrough"); assert.deepEqual(planClaudeNativeBootstrap({ BILLION_CONTEXT_PLUGIN: "0" }).action, "passthrough"); + // #1660: no explicit override → zone preference, non-strict launch. const start = planClaudeNativeBootstrap({}); - assert.deepEqual(start, { action: "start", port: CLAUDE_NATIVE_DEFAULT_PORT }); - assert.equal(planClaudeNativeBootstrap({ BILI_CLAUDE_NATIVE_PORT: "49999" }).port, 49999); + assert.deepEqual(start, { action: "start", port: ZONE_PORT_BASE, strict: false }); + // explicit override → same port, strict-port (#964 preserved). + assert.deepEqual(planClaudeNativeBootstrap({ BILI_CLAUDE_NATIVE_PORT: "49999" }), { action: "start", port: 49999, strict: true }); }); // — claude host pid resolution (parent-gone regression) ————————————————— @@ -530,8 +553,9 @@ function fakeClaude(dir: string): string { function sandbox(): { dir: string; settings: string; mcpJson: string; biliConfig: string } { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-claude-")); process.env.CLAUDE_CONFIG_DIR = dir; - // #964: pluginInstall persists claude.nativePort into the bili config — - // sandbox that too so tests never touch the real user config. + // #1660: install no longer persists claude.nativePort, but the bili + // config path is still sandboxed so tests never touch the real user + // config (loadConfigFile reads it for other keys). const biliConfig = path.join(dir, "billion-context.json"); process.env.BILI_CONFIG_FILE = biliConfig; return { dir, settings: path.join(dir, "settings.json"), mcpJson: path.join(dir, ".claude.json"), biliConfig }; @@ -584,12 +608,14 @@ test("installer round-trip: managed block + MCP face, then removal restores", () assert.ok(note.includes("managed block"), note); assert.ok(fs.existsSync(box.settings)); const after = JSON.parse(fs.readFileSync(box.settings, "utf8")) as { env?: Record; hooks?: unknown }; - assert.equal(after.env?.ANTHROPIC_BASE_URL, baseUrlForPort(CLAUDE_NATIVE_DEFAULT_PORT)); + // #1660: no explicit port → the zone base is baked. + assert.equal(after.env?.ANTHROPIC_BASE_URL, baseUrlForPort(ZONE_PORT_BASE)); assert.equal(after.env?.DISABLE_AUTO_COMPACT, "1"); assert.equal(claudeNativeInstalled(), true); - // #964: the resolved port is persisted so the SessionStart hook (which - // does NOT inherit claude's settings.env) resolves the SAME port. - assert.deepEqual(JSON.parse(fs.readFileSync(box.biliConfig, "utf8")), { claude: { nativePort: CLAUDE_NATIVE_DEFAULT_PORT } }); + // #1660: install no longer persists claude.nativePort — the hook + // resolves the same zone preference, and its repin pass follows any + // drift. The bili config may not even exist. + assert.equal(fs.existsSync(box.biliConfig), false); const removeNote = pluginRemove("claude"); assert.ok(removeNote.includes("managed block removed"), removeNote); @@ -597,7 +623,6 @@ test("installer round-trip: managed block + MCP face, then removal restores", () assert.equal(restored.env, undefined); assert.equal(restored.hooks, undefined); assert.equal(claudeNativeInstalled(), false); - assert.deepEqual(JSON.parse(fs.readFileSync(box.biliConfig, "utf8")), {}, "nativePort cleared on remove"); } finally { unsandbox(prevDir, prevCfg); if (prevClaude === undefined) delete process.env.CLAUDE; @@ -693,7 +718,7 @@ test("installer preserves foreign settings.json keys end-to-end", () => { } }); -test("installer persists an env-driven port so the hook resolves the SAME port", () => { +test("install with an explicit port bakes it; without env the hook rides the zone (#1660)", () => { const prevDir = process.env.CLAUDE_CONFIG_DIR; const prevCfg = process.env.BILI_CONFIG_FILE; const prevClaude = process.env.CLAUDE; @@ -703,20 +728,30 @@ test("installer persists an env-driven port so the hook resolves the SAME port", try { delete process.env.BILI_NATIVE_CLAUDE; process.env.CLAUDE = fakeClaude(box.dir); - // Live failure shape: install with an explicit port, then claude - // later runs the hook WITHOUT that env (claude does not inject its - // settings.env into hook children) — the persisted config keeps - // hook and settings.json on the same port. + // Live failure shape (#964): install with an explicit port, then + // claude later runs the hook WITHOUT that env (claude does not inject + // its settings.env into hook children). #1660: there is no persisted + // copy anymore — without the env the hook resolves the zone + // preference (non-strict), and its SessionStart repin pass rewrites + // the baked URL to the live origin so the two can never stay desynced. process.env.BILI_CLAUDE_NATIVE_PORT = "49999"; pluginInstall("claude"); const settings = JSON.parse(fs.readFileSync(box.settings, "utf8")) as { env?: Record }; assert.equal(settings.env?.ANTHROPIC_BASE_URL, baseUrlForPort(49999)); - assert.deepEqual(JSON.parse(fs.readFileSync(box.biliConfig, "utf8")), { claude: { nativePort: 49999 } }); + assert.equal(fs.existsSync(box.biliConfig), false, "no claude.nativePort persisted anymore"); delete process.env.BILI_CLAUDE_NATIVE_PORT; - assert.equal(resolveClaudeNativePort(), 49999, "hook (no env) resolves the persisted port"); - assert.equal(planClaudeNativeBootstrap(process.env).port, 49999); + // plan on a SANITIZED env copy: the dev/CI harness may itself run under + // a bili proxy (BILLION_CONTEXT_PROXY / BILI_PROVIDER_REWRITES force + // "exit"), and a fresh XDG_STATE_HOME keeps the zone preference at the + // base instead of following this machine's sticky record. + const planEnv: NodeJS.ProcessEnv = { ...process.env, XDG_STATE_HOME: path.join(box.dir, "state") }; + delete planEnv.BILLION_CONTEXT_PROXY; + delete planEnv.BILI_PROVIDER_REWRITES; + delete planEnv.BILI_NATIVE_CLAUDE; + delete planEnv.BILLION_CONTEXT_PLUGIN; + assert.deepEqual(planClaudeNativeBootstrap(planEnv), { action: "start", port: ZONE_PORT_BASE, strict: false }, "hook (no env) rides the zone, non-strict"); pluginRemove("claude"); - assert.equal(resolveClaudeNativePort(), CLAUDE_NATIVE_DEFAULT_PORT, "remove restores the default"); + assert.equal(claudeNativeInstalled(), false); } finally { unsandbox(prevDir, prevCfg); if (prevClaude === undefined) delete process.env.CLAUDE; @@ -728,34 +763,42 @@ test("installer persists an env-driven port so the hook resolves the SAME port", } }); -test("persist/clear refuse to clobber a malformed bili config", () => { - const prevDir = process.env.CLAUDE_CONFIG_DIR; - const prevCfg = process.env.BILI_CONFIG_FILE; - const box = sandbox(); - try { - const corrupt = "{ this is not json"; - fs.writeFileSync(box.biliConfig, corrupt, "utf8"); - assert.doesNotThrow(() => saveClaudeNativePort(49999)); - assert.equal(fs.readFileSync(box.biliConfig, "utf8"), corrupt, "save leaves the corrupt file byte-identical"); - assert.doesNotThrow(() => clearClaudeNativePort()); - assert.equal(fs.readFileSync(box.biliConfig, "utf8"), corrupt, "clear leaves the corrupt file byte-identical"); - } finally { - unsandbox(prevDir, prevCfg); - } -}); - -test("persist preserves foreign config keys; clear drops only the persisted key", () => { +test("repinClaudeManagedBaseUrl: follows a drifted origin, preserves the relay, never touches a foreign URL (#1660)", () => { const prevDir = process.env.CLAUDE_CONFIG_DIR; const prevCfg = process.env.BILI_CONFIG_FILE; + const prevUp = process.env.BILI_CLAUDE_UPSTREAM; const box = sandbox(); try { - fs.writeFileSync(box.biliConfig, JSON.stringify({ port: 9999, claude: { nativePort: 1234 } }), "utf8"); - saveClaudeNativePort(49999); - assert.deepEqual(JSON.parse(fs.readFileSync(box.biliConfig, "utf8")), { port: 9999, claude: { nativePort: 49999 } }); - clearClaudeNativePort(); - assert.deepEqual(JSON.parse(fs.readFileSync(box.biliConfig, "utf8")), { port: 9999 }, "clear drops only nativePort"); + delete process.env.BILI_CLAUDE_UPSTREAM; + // A store left over from an install that baked 48787 + a custom relay. + fs.writeFileSync( + box.settings, + JSON.stringify({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:48787/bili/https://relay.example" } }), + "utf8", + ); + const notes = repinClaudeManagedBaseUrl("http://127.0.0.1:18788"); + const after = JSON.parse(fs.readFileSync(box.settings, "utf8")) as { env?: Record; hooks?: unknown }; + // The relay survives the repin; only the origin moves. + assert.equal(after.env?.ANTHROPIC_BASE_URL, "http://127.0.0.1:18788/bili/https://relay.example"); + assert.ok(Array.isArray(after.hooks?.SessionStart), "the hook is upserted alongside"); + assert.ok(notes.length > 0); + + // Idempotent: a second repin to the same origin changes nothing and + // returns no notes (no write either). + const before = fs.readFileSync(box.settings, "utf8"); + const again = repinClaudeManagedBaseUrl("http://127.0.0.1:18788"); + assert.equal(again.length, 0); + assert.equal(fs.readFileSync(box.settings, "utf8"), before); + + // A foreign base URL is never touched. + fs.writeFileSync(box.settings, JSON.stringify({ env: { ANTHROPIC_BASE_URL: "https://corporate-gateway.example" } }), "utf8"); + repinClaudeManagedBaseUrl("http://127.0.0.1:18788"); + const foreign = JSON.parse(fs.readFileSync(box.settings, "utf8")) as { env?: Record }; + assert.equal(foreign.env?.ANTHROPIC_BASE_URL, "https://corporate-gateway.example"); } finally { unsandbox(prevDir, prevCfg); + if (prevUp === undefined) delete process.env.BILI_CLAUDE_UPSTREAM; + else process.env.BILI_CLAUDE_UPSTREAM = prevUp; } }); @@ -1227,14 +1270,16 @@ test("watcher route: shared proxies take watcher registrations, daemons refuse ( } }); -// #1322 end-to-end: the reported failure shape — a manually started daemon -// squats on the stable port BEFORE any session begins, so every claude -// session attaches to it and its registration is refused (409). Old code -// swallowed that silently: the "lives and dies with the session" contract was -// void with zero signal. Now the hook must WARN loudly on stderr while -// staying non-destructive (the daemon keeps serving; its fate is the -// operator's). Linux-only like the other hook e2es (fake claude walks /proc). -test("hook e2e: unarmed squatter on the pinned port is refused loudly, not silently attached (#1322/#1335)", { timeout: 180_000, skip: LIVE_E2E ? process.platform !== "linux" : liveSkip }, async () => { +// #1322/#1335/#1660 end-to-end: a MANUALLY started `bili start` daemon +// squats on the pinned port BEFORE any session begins. Old world: the hook +// refused it (unarmed) and the strict pinned port then failed fast — the +// operator had to kill their own daemon. #1660 user-zone semantics: a manual +// start is BY DEFINITION user-maintained, so the hook attaches and rides it; +// the daemon's fate stays the operator's. The strict fail-fast still exists +// for lifecycle-less LANE'd squatters (unit-tested in launcher.test.ts) and +// for non-bili listeners (spawn EADDRINUSE). Linux-only like the other hook +// e2es (fake claude walks /proc). +test("hook e2e: manual `bili start` on the pinned port is attached, not refused (#1322/#1335/#1660)", { timeout: 180_000, skip: LIVE_E2E ? process.platform !== "linux" : liveSkip }, async () => { const distCli = path.resolve(import.meta.dirname, "..", "dist", "index.js"); const distScript = path.resolve(import.meta.dirname, "..", "dist", "claude-native-bootstrap.js"); ensureDistBuilt(distCli); @@ -1292,24 +1337,18 @@ test("hook e2e: unarmed squatter on the pinned port is refused loudly, not silen while (!fs.existsSync(doneFile) && Date.now() - t0 < 60_000) await new Promise((r) => setTimeout(r, 250)); assert.ok(fs.existsSync(doneFile), "hook completed"); const stderr = fs.readFileSync(errFile, "utf8"); - // #1335 gate: the hook must REFUSE the lifecycle-less listener and say - // so — the old warn-but-attach behavior is what let #1322 happen. - assert.match(stderr, /refusing to attach/, "hook refused the squatting daemon"); - assert.match(stderr, /NO session-lifecycle watchdog/s, "#1322: refusal surfaced instead of silently voiding the contract"); - assert.match(stderr, /\(#1322\/#1335\)/, "warning cites the issues for operators"); - assert.match(stderr, /native\.attachExternal=true/, "escape hatch surfaced"); - // strictPort launch cannot self-host (the squatter owns the port), so - // bring-up fails fast with an actionable kill/attach-anyway hint. - assert.match(stderr, /bring-up failed.*lifecycle-less/s, "pinned-port fast-fail explains itself"); - assert.match(stderr, /Kill that process \(kill \d+\)/, "actionable kill hint"); + // #1660: the manual daemon is user-zone — attach by default. + assert.match(stderr, /proxy attached at http:\/\/127\.0\.0\.1:\d+/, "hook attached to the user's daemon"); + assert.doesNotMatch(stderr, /refusing to attach/, "no #1335 refusal for a user-maintained daemon"); + assert.doesNotMatch(stderr, /bring-up failed/, "no fail-fast either — the port is owned by the user, not a lane"); // Non-destructive: killing the session must NOT take the daemon down. killPid(claudePid); claudePid = 0; await new Promise((r) => setTimeout(r, 15_000)); assert.ok(await canConnect(port), "daemon survives session end — operator decides its fate"); const h = (await (await fetch(`http://127.0.0.1:${port}/__bili/health`)).json()) as { watchdog?: { armed?: boolean; watchers?: number[] } }; - assert.equal(h.watchdog?.armed, false, "health explains why the warning fired"); - assert.deepEqual(h.watchdog?.watchers, []); + assert.equal(h.watchdog?.armed, false, "health explains the manual start (no session lifecycle)"); + assert.deepEqual(h.watchdog?.watchers, [], "the session's watcher unregistered on exit"); } finally { if (claudePid > 1) killPid(claudePid); if (squatter > 1) killPid(squatter); diff --git a/tests/discover.test.ts b/tests/discover.test.ts index 6f05c9b4a4..4f29f34a13 100644 --- a/tests/discover.test.ts +++ b/tests/discover.test.ts @@ -60,11 +60,21 @@ test("parseZcodeConfig: defensive — non-object / missing provider / non-string function withHome(home: string, fn: () => void): void { const saved = process.env.HOME; process.env.HOME = home; + // Windows os.homedir() resolves through USERPROFILE, not HOME — mirror the + // sandbox there or a real machine's ~/.zcode store leaks into readZcodeConfig + // (zcodeDataRoot falls back to os.homedir()/".zcode"). + const savedProfile = process.env.USERPROFILE; + const mirrorProfile = process.platform === "win32"; + if (mirrorProfile) process.env.USERPROFILE = home; try { fn(); } finally { if (saved === undefined) delete process.env.HOME; else process.env.HOME = saved; + if (mirrorProfile) { + if (savedProfile === undefined) delete process.env.USERPROFILE; + else process.env.USERPROFILE = savedProfile; + } } } diff --git a/tests/doctor.test.ts b/tests/doctor.test.ts index 70b2034653..5933d18deb 100644 --- a/tests/doctor.test.ts +++ b/tests/doctor.test.ts @@ -12,8 +12,15 @@ import { PLUGIN_AGENTS, inspectLanePresence } from "../src/plugin-install.ts"; import { rmrf } from "./tmp-rm.ts"; function withEnv(vars: Record, fn: () => void | Promise): Promise | void { + const effective: Record = { ...vars }; + // Windows os.homedir() resolves through USERPROFILE, not HOME — mirror the + // sandboxed HOME there or real-machine config (~/.dsh, ~/.zcode, …) leaks + // into tests that believe they are running in an empty home. + if (process.platform === "win32" && effective.HOME !== undefined && effective.USERPROFILE === undefined) { + effective.USERPROFILE = effective.HOME; + } const saved: Record = {}; - for (const [k, v] of Object.entries(vars)) { + for (const [k, v] of Object.entries(effective)) { saved[k] = process.env[k]; if (v === undefined) delete process.env[k]; else process.env[k] = v; diff --git a/tests/e2e/e2e-registry.test.ts b/tests/e2e/e2e-registry.test.ts index 0b4e53565c..1ded864e30 100644 --- a/tests/e2e/e2e-registry.test.ts +++ b/tests/e2e/e2e-registry.test.ts @@ -177,6 +177,6 @@ test("hermetic registry e2e", { skip: skipReason }, async (t) => { // entry === `billion-context@${NEW_VERSION}` (the re-pin assertion). assert.deepEqual(cfg.plugins, ["billion-context"]); assert.deepEqual(cfg.compaction, { auto: false }); - assert.match(res.stdout, /plugin present/); + assert.match(res.stdout, /plugins present/); }); }); diff --git a/tests/hermes-native.test.ts b/tests/hermes-native.test.ts index 7b8143143e..5da0490f8b 100644 --- a/tests/hermes-native.test.ts +++ b/tests/hermes-native.test.ts @@ -131,7 +131,11 @@ describe("installer lane (bili plugin install hermes)", () => { const restore = setHermesEnv(home, emptyBin); try { const msg = pluginInstall("hermes"); - assert.match(msg, /the hermes CLI was not found on PATH — enable it manually: hermes plugins enable billion-context/); + // The exact head differs by platform: a POSIX ENOENT prints "the + // hermes CLI was not found on PATH …", while a Windows shell probe + // fails with a localized cmd error and prints "enabling via the + // hermes CLI failed (…) …". Both end in the same manual instruction. + assert.match(msg, /enable it manually: hermes plugins enable billion-context/); assert.equal(hermesStatus(), "installed"); } finally { restore(); diff --git a/tests/hook-command.test.ts b/tests/hook-command.test.ts index ee7e8d49cc..77490be98c 100644 --- a/tests/hook-command.test.ts +++ b/tests/hook-command.test.ts @@ -134,6 +134,12 @@ test("the emitted command really runs: bare token + spaced argument, through eve assert.ok(!command.includes("\\"), command); const ran: string[] = []; for (const shell of platformShells()) { + // `& "spaced head"` is the PowerShell call-operator form. cmd never + // sees it in production (hooks resolve a bare `node`; see the design + // note in plugin-install.ts) and cannot parse `&` — so don't demand + // cmd compatibility for it. The dedicated PowerShell test below + // covers that form where it is actually used. + if (shell.name === "cmd" && command.startsWith("& ")) continue; const r = runInShell(shell, command); if (r.missing) continue; assert.equal(r.status, 0, `${shell.name} exited ${r.status} for: ${command}\n${r.out}`); diff --git a/tests/instance-governance.test.ts b/tests/instance-governance.test.ts index 7b4d411d82..3884cf8d9d 100644 --- a/tests/instance-governance.test.ts +++ b/tests/instance-governance.test.ts @@ -365,7 +365,7 @@ test("dsh overlay: nested generated settings.yaml is never promoted into the rea } }); -test("plugin install: refuses to freeze a dead or missing proxy origin (#403)", () => { +test("plugin install: codex block bakes no origin — nothing to freeze when the proxy is dead or missing (#403/#1660)", () => { const st = tmpStateDir(); const prevCodex = process.env.CODEX_HOME; const prevEnv = process.env.BILI_MCP_PROXY; @@ -373,15 +373,25 @@ test("plugin install: refuses to freeze a dead or missing proxy origin (#403)", process.env.CODEX_HOME = home; delete process.env.BILI_MCP_PROXY; try { - assert.throws(() => pluginInstall("codex"), /no bili proxy origin found/); + // #403 refused to bake a dead origin into the block. #1660 removes the + // baked origin entirely — the MCP shell discovers the live proxy at + // startup (env > instance file > 8787), so install succeeds even with + // no proxy running and freezes nothing. + const msg = pluginInstall("codex"); + assert.match(msg, /codex:/); + let toml = fs.readFileSync(path.join(home, "config.toml"), "utf8"); + assert.doesNotMatch(toml, /BILI_MCP_PROXY/); + atomicWriteInstanceFile(sampleInstance({ pid: deadPid() })); - assert.throws(() => pluginInstall("codex"), /is not running/); + pluginInstall("codex"); + toml = fs.readFileSync(path.join(home, "config.toml"), "utf8"); + assert.doesNotMatch(toml, /BILI_MCP_PROXY/); 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"/); + pluginInstall("codex"); + toml = fs.readFileSync(path.join(home, "config.toml"), "utf8"); + assert.doesNotMatch(toml, /BILI_MCP_PROXY/); + assert.match(toml, /bili/); } finally { if (prevCodex === undefined) delete process.env.CODEX_HOME; else process.env.CODEX_HOME = prevCodex; diff --git a/tests/issue1002-opencode-foreign-entries.test.ts b/tests/issue1002-opencode-foreign-entries.test.ts index 7ec82c1163..4fd3251467 100644 --- a/tests/issue1002-opencode-foreign-entries.test.ts +++ b/tests/issue1002-opencode-foreign-entries.test.ts @@ -66,7 +66,7 @@ test("install and remove preserve foreign object entries in the plugins array (# // "plugin present" re-run: byte-identical file const bytes = fs.readFileSync(file, "utf8"); const again = pluginInstall("opencode"); - assert.match(again, /plugin present/); + assert.match(again, new RegExp(`${ocKey} present`)); assert.equal(fs.readFileSync(file, "utf8"), bytes, "present re-run leaves the file byte-identical"); // remove: only ours goes, the key SURVIVES with all foreign entries diff --git a/tests/issue1086-chain-self-exemption.test.ts b/tests/issue1086-chain-self-exemption.test.ts index d0de78367e..dac34c8546 100644 --- a/tests/issue1086-chain-self-exemption.test.ts +++ b/tests/issue1086-chain-self-exemption.test.ts @@ -725,7 +725,7 @@ test("#1101 T9: BILI_CHAIN_CONTENT env parse — default OFF, 1 enables, env win assert.equal(loadOptions({ BILI_CHAIN_CONTENT: "0" }).chainContentDetection, false, "env =0 wins over file true"); } finally { if (prevFile === undefined) delete process.env.BILI_CONFIG_FILE; else process.env.BILI_CONFIG_FILE = prevFile; - rmSync(root, { recursive: true, force: true }); + rmrf(root); } }); diff --git a/tests/launcher.test.ts b/tests/launcher.test.ts index 260a771a8f..2a5b923378 100644 --- a/tests/launcher.test.ts +++ b/tests/launcher.test.ts @@ -1195,12 +1195,15 @@ test("ensureProxyRunning: armed daemon (no lane) stays shareable with any client assert.equal(handle.attached, true); }); -// #1335: the attach gate — an unarmed listener (a manually started `bili start` -// daemon: no BILI_PARENT_PID, refuses watchers, never dies with its users) 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). -test("ensureProxyRunning: unarmed listener is not attached by default — self-managed spawn (#1335)", async () => { +// #1335: the attach gate — an unarmed 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 () => { let spawnCalls = 0; let registered = 0; let childToken = ""; @@ -1216,7 +1219,7 @@ test("ensureProxyRunning: unarmed listener is not attached by default — self-m }, fetchImpl: async () => ({ ok: true }), fetchHealthInfo: async () => ({ ok: true, instanceId: "daemon-1", watchdog: { armed: false } }), - readInstanceFile: () => (spawned ? recordedInstance({ launchToken: childToken }) : recordedInstance({ instanceId: "daemon-1" })), + readInstanceFile: () => (spawned ? recordedInstance({ launchToken: childToken }) : recordedInstance({ instanceId: "daemon-1", lane: "claude-native" })), registerWatcher: async () => { registered++; return "refused"; @@ -1225,13 +1228,98 @@ test("ensureProxyRunning: unarmed listener is not attached by default — self-m scriptPath: FP_SCRIPT, }, ); - assert.equal(spawnCalls, 1, "self-managed proxy spawned instead of attaching to the unarmed daemon"); + assert.equal(spawnCalls, 1, "self-managed proxy spawned instead of attaching to the unarmed lane'd daemon"); assert.ok(handle.child); assert.equal(handle.attached, undefined); assert.equal(registered, 0, "no watcher registration is attempted against the refused daemon"); }); -test("ensureProxyRunning: unverifiable listener (no watchdog field, pre-#1330 build) is treated as unarmed (#1335)", async () => { +test("ensureProxyRunning: unarmed USER-ZONE daemon (manual `bili start`) is attached by default (#1660)", async () => { + let spawnCalls = 0; + let registered = 0; + const handle = await ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false, lane: "pi" }, + { + spawnImpl: () => { + spawnCalls++; + return makeFakeChild(42505); + }, + fetchImpl: async () => ({ ok: true }), + fetchHealthInfo: async () => ({ ok: true, instanceId: "manual-1", watchdog: { armed: false } }), + readInstanceFile: () => recordedInstance({ instanceId: "manual-1" }), + registerWatcher: async () => { + registered++; + return "ok"; + }, + sleep: () => new Promise((r) => setTimeout(r, 0)), + scriptPath: FP_SCRIPT, + }, + ); + assert.equal(spawnCalls, 0, "the user-maintained daemon is reused, not doubled"); + assert.equal(handle.attached, true); + assert.equal(registered, 1); +}); + +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[] = []; + const settled: Array<[string, number]> = []; + const spawnImpl: SpawnFn = (_cmd, args) => { + spawnedArgs = [...args]; + return makeFakeChild(42441); + }; + const handle = await ensureProxyRunning( + { host: "127.0.0.1", port: 0, passthrough: false, debug: false, lane: "zcode" }, + { + fetchImpl: async () => ({ ok: true }), + spawnImpl, + sleep: () => Promise.resolve(), + readInstanceFile: () => undefined, + zonePreferredPort: (lane) => { + preferred.push(lane); + return 18787; + }, + writeZonePort: (lane, port) => { + settled.push([lane, port]); + }, + }, + ); + assert.deepEqual(preferred, ["zcode"], "the lane's zone preference resolves the spawn port"); + assert.ok(spawnedArgs !== null); + const portIdx = spawnedArgs.indexOf("--port"); + assert.equal(spawnedArgs[portIdx + 1], "18787", "zone base is the spawn port, not an OS ephemeral"); + assert.equal(handle.port, 18787); + assert.deepEqual(settled, [["zcode", 18787]], "the settled port is recorded sticky for later launches"); +}); + +test("ensureProxyRunning: an unlane'd launch keeps the OS ephemeral default — no zone, no sticky (#1660)", async () => { + let spawnedArgs: string[] | null = null; + const settled: Array<[string, number]> = []; + const spawnImpl: SpawnFn = (_cmd, args) => { + spawnedArgs = [...args]; + return makeFakeChild(42442); + }; + const handle = await ensureProxyRunning( + { host: "127.0.0.1", port: 0, passthrough: false, debug: false }, + { + fetchImpl: async () => ({ ok: true }), + spawnImpl, + sleep: () => Promise.resolve(), + readInstanceFile: () => undefined, + writeZonePort: (lane, port) => { + settled.push([lane, port]); + }, + }, + ); + assert.ok(spawnedArgs !== null); + const portIdx = spawnedArgs.indexOf("--port"); + const childPort = Number(spawnedArgs[portIdx + 1]); + assert.ok(Number.isInteger(childPort) && childPort > 0, `ephemeral port assigned, got ${childPort}`); + assert.equal(handle.port, childPort); + 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 () => { let spawnCalls = 0; let childToken = ""; let spawned = false; @@ -1246,7 +1334,7 @@ test("ensureProxyRunning: unverifiable listener (no watchdog field, pre-#1330 bu }, fetchImpl: async () => ({ ok: true }), fetchHealthInfo: async () => ({ ok: true, instanceId: "stale-daemon" }), - readInstanceFile: () => (spawned ? recordedInstance({ launchToken: childToken }) : recordedInstance({ instanceId: "stale-daemon" })), + readInstanceFile: () => (spawned ? recordedInstance({ launchToken: childToken }) : recordedInstance({ instanceId: "stale-daemon", lane: "zcode" })), sleep: () => new Promise((r) => setTimeout(r, 0)), scriptPath: FP_SCRIPT, }, @@ -1276,7 +1364,7 @@ test("ensureProxyRunning: attachExternal escape hatch restores attaching to an u assert.equal(handle.attached, true, "deliberate setups keep the old behavior via the opt-in"); }); -test("ensureProxyRunning: strictPort launch fails fast when its pinned port is held by an unarmed proxy (#1335/#964)", async () => { +test("ensureProxyRunning: strictPort launch fails fast when its pinned port is held by an unarmed LANE'D proxy (#1335/#964/#1660)", async () => { let spawnCalls = 0; await assert.rejects( ensureProxyRunning( @@ -1288,7 +1376,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" }), + readInstanceFile: () => recordedInstance({ origin: "http://127.0.0.1:8799", port: 8799, instanceId: "daemon-1", lane: "claude-native" }), sleep: () => Promise.resolve(), scriptPath: FP_SCRIPT, }, @@ -5628,11 +5716,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. const inst = await findLiveAttachableInstance( { host: "127.0.0.1", port: 0, passthrough: false, debug: false }, { fetchHealthInfo: async () => ({ ok: true, instanceId: "inst-1" }), - readInstanceFile: () => recordedInstance(), + readInstanceFile: () => recordedInstance({ lane: "zcode" }), attachDiag: (m) => diag.push(m), scriptPath: FP_SCRIPT, }, diff --git a/tests/plugin-agent.test.ts b/tests/plugin-agent.test.ts index f1d04059ec..f91c9a057c 100644 --- a/tests/plugin-agent.test.ts +++ b/tests/plugin-agent.test.ts @@ -1520,12 +1520,16 @@ test("plugin install/remove roundtrips for pi/omp/codex/opencode under a fake HO assert.match(pluginInstall("codex"), /installed/); const toml = fs.readFileSync(path.join(home, "config.toml"), "utf8"); assert.match(toml, /\[mcp_servers\.bili\]\ncommand = /); - assert.match(toml, /BILI_MCP_PROXY = "http:\/\/127\.0\.0\.1:8787"/); + // #1660: no baked origin — the MCP shell discovers the live proxy at + // startup (env > instance file > 8787), so the block cannot go stale. + assert.doesNotMatch(toml, /BILI_MCP_PROXY/); fs.writeFileSync(path.join(home, "config.toml"), toml + "\n[mcp_servers.other]\ncommand = \"x\"\n"); assert.match(pluginInstall("codex"), /already installed/); - fs.writeFileSync(path.join(home, "config.toml"), fs.readFileSync(path.join(home, "config.toml"), "utf8").replace("8787", "9999")); + // a user-tampered command (their own node path) is not canonical → + // refreshed back to the current canonical block + fs.writeFileSync(path.join(home, "config.toml"), fs.readFileSync(path.join(home, "config.toml"), "utf8").replace(JSON.stringify(process.execPath), JSON.stringify("/tampered/node"))); assert.match(pluginInstall("codex"), /refreshed/); - assert.match(fs.readFileSync(path.join(home, "config.toml"), "utf8"), /BILI_MCP_PROXY = "http:\/\/127\.0\.0\.1:8787"/); + assert.doesNotMatch(fs.readFileSync(path.join(home, "config.toml"), "utf8"), /tampered/); assert.match(pluginRemove("codex"), /removed/); const tomlAfter = fs.readFileSync(path.join(home, "config.toml"), "utf8"); assert.doesNotMatch(tomlAfter, /mcp_servers\.bili/); @@ -1542,8 +1546,8 @@ test("plugin install/remove roundtrips for pi/omp/codex/opencode under a fake HO assert.match(tomlEdge, /\[mcp_servers\.other\]\ncommand = "x"\n/); // #638: a malformed block (args as string - legal TOML, invalid codex - // schema) with a matching origin must NOT short-circuit to "already - // installed"; reinstall must self-heal it to the canonical block. + // schema). Legacy blocks carried a baked env origin — the heal must + // drop it, not preserve it (#1660). const selfRoot = path.dirname(path.dirname(path.resolve("src/plugin-install.ts"))); const malformed = `[mcp_servers.other]\ncommand = "x"\n[mcp_servers.bili]\ncommand = "node"\nargs = '[\"${path.join(selfRoot, "dist", "mcp.js")}\"]'\nenv = { BILI_MCP_PROXY = "http://127.0.0.1:8787" }\n`; fs.writeFileSync(path.join(home, "config.toml"), malformed); @@ -1552,6 +1556,7 @@ test("plugin install/remove roundtrips for pi/omp/codex/opencode under a fake HO const tomlHealed = fs.readFileSync(path.join(home, "config.toml"), "utf8"); assert.match(tomlHealed, /args = \[/); assert.doesNotMatch(tomlHealed, /args = '\[/); + assert.doesNotMatch(tomlHealed, /BILI_MCP_PROXY/, "legacy baked origin dropped on heal (#1660)"); assert.match(tomlHealed, /\[mcp_servers\.other\]\ncommand = "x"\n/); // A now-canonical block stays "already installed" on rerun. assert.match(pluginInstall("codex"), /already installed/); diff --git a/tests/plugin-install-opencode.test.ts b/tests/plugin-install-opencode.test.ts index 81aff3432f..5daa73f79b 100644 --- a/tests/plugin-install-opencode.test.ts +++ b/tests/plugin-install-opencode.test.ts @@ -117,8 +117,13 @@ test("pluginInstall/remove/status opencode end-to-end (dev form under tsx)", (t) const prevState = process.env.XDG_STATE_HOME; const prevOpen = process.env.OPENCODE_CONFIG; const prevMcp = process.env.BILI_MCP_PROXY; + const prevBin = process.env.BILI_CLIENT_BIN; delete process.env.OPENCODE_CONFIG; delete process.env.BILI_MCP_PROXY; + // Hermetic probe: an unresolvable bin fails soft to major 1, so the test + // never depends on whatever `opencode` the host PATH (or an npm test + // node_modules/.bin walk) happens to shadow in. + process.env.BILI_CLIENT_BIN = "/nonexistent/bili-oc-probe-pin"; const xdg = tempDir("bili-oc-xdg-"); const state = tempDir("bili-oc-state-"); process.env.XDG_CONFIG_HOME = xdg; @@ -132,6 +137,8 @@ test("pluginInstall/remove/status opencode end-to-end (dev form under tsx)", (t) else process.env.OPENCODE_CONFIG = prevOpen; if (prevMcp === undefined) delete process.env.BILI_MCP_PROXY; else process.env.BILI_MCP_PROXY = prevMcp; + if (prevBin === undefined) delete process.env.BILI_CLIENT_BIN; + else process.env.BILI_CLIENT_BIN = prevBin; rmrf(xdg); rmrf(state); }); diff --git a/tests/port-zone-live.test.ts b/tests/port-zone-live.test.ts new file mode 100644 index 0000000000..f3d165b68a --- /dev/null +++ b/tests/port-zone-live.test.ts @@ -0,0 +1,246 @@ +import test, { after } from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import net from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { ensureProxyRunning } from "../src/launcher.ts"; +import { portZoneFilePath, readZonePort } from "../src/instance.ts"; +import { ZONE_PORT_BASE } from "../src/config.ts"; + +// #1660 live regression: the sticky-zone lifecycle against REAL proxy +// processes — real spawn handshake, real EADDRINUSE ladder, real attach +// probe, real sticky follow. The mocked sequences in port-zone.test.ts pin +// the decision table; this file pins the WIRING: the bug class where a call +// site pre-resolves the port and the settle never fires (90cc7e8) only +// surfaces with a real child writing a real instance file. Gated exactly +// like the claude-native live e2e (#1248): the dedicated CI runner sets +// ACP_TEST_CLAUDE_NATIVE=1; locally loaded sandboxes skip. +const LIVE = process.env.ACP_TEST_CLAUDE_NATIVE === "1"; +const liveSkip = LIVE ? undefined : "set ACP_TEST_CLAUDE_NATIVE=1 (live proxy e2e; #1248)"; + +const root = path.resolve(import.meta.dirname, ".."); +const distCli = path.join(root, "dist", "index.js"); + +// CI's test step runs before `npm run build` — build on demand. +function ensureDistBuilt(): void { + if (!fs.existsSync(distCli)) { + execFileSync(process.execPath, [path.join(root, "node_modules", "tsup", "dist", "cli-default.js")], { + cwd: root, + stdio: "pipe", + timeout: 300_000, + }); + } + assert.ok(fs.existsSync(distCli), `build did not produce ${distCli}`); +} + +// Backstop cleanup: every test also kills eagerly in its own finally so the +// NEXT test's zone base is free (tests run serially within this file). +const cleanup: Array<() => void> = []; +after(() => { + for (const fn of cleanup.splice(0)) { + try { + fn(); + } catch {} + } +}); + +function trackKill(pid: number | undefined): void { + if (pid === undefined || pid <= 1) return; + cleanup.push(() => { + try { + process.kill(pid, "SIGKILL"); + } catch {} + }); +} + +function killNow(pid: number | undefined): void { + if (pid !== undefined && pid > 1) { + try { + process.kill(pid, "SIGKILL"); + } catch {} + } +} + +function freePort(): Promise { + return new Promise((resolve, reject) => { + const srv = net.createServer(); + srv.listen(0, "127.0.0.1", () => { + const port = (srv.address() as net.AddressInfo).port; + srv.close(() => resolve(port)); + }); + srv.once("error", reject); + }); +} + +/** A dumb port squatter: accepts nothing — destroys every connection so + * health probes fail fast instead of hanging on a silent socket. */ +async function squatted(port: number): Promise { + const srv = net.createServer((sock) => { + sock.on("error", () => {}); + sock.destroy(); + }); + await new Promise((resolve, reject) => { + srv.once("error", reject); + srv.listen(port, "127.0.0.1", () => resolve()); + }); + cleanup.push(() => { + try { + srv.close(); + } catch {} + }); + return srv; +} + +// Redirect the WHOLE view — this process's state-dir reads AND the spawned +// child's (the launcher builds the child env off process.env) — so +// port-zone.json, the instance file and the #707 starting marker stay in a +// throwaway sandbox. +async function withSandbox(fn: () => Promise): Promise { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-zone-live-")); + const prev = process.env.XDG_STATE_HOME; + process.env.XDG_STATE_HOME = path.join(home, "state"); + try { + return await fn(); + } finally { + if (prev === undefined) delete process.env.XDG_STATE_HOME; + else process.env.XDG_STATE_HOME = prev; + } +} + +function launch(opts: { lane?: string; port?: number; strictPort?: boolean } = {}) { + return ensureProxyRunning( + { + host: "127.0.0.1", + port: opts.port ?? 0, + strictPort: opts.strictPort, + passthrough: false, + debug: false, + lane: opts.lane, + }, + { scriptPath: distCli }, + ); +} + +test( + "zone live: lane'd port-0 launch binds the base, settles sticky; a repeat attaches", + { timeout: 180_000, skip: LIVE ? process.platform !== "linux" : liveSkip }, + async () => { + await withSandbox(async () => { + ensureDistBuilt(); + const h1 = await launch({ lane: "zcode" }); + trackKill(h1.child?.pid); + try { + assert.equal(h1.port, ZONE_PORT_BASE, "fresh lane'd launch binds the zone base"); + assert.equal(readZonePort("zcode"), ZONE_PORT_BASE, "the bound port settles sticky"); + const h2 = await launch({ lane: "zcode" }); + assert.equal(h2.attached, true, "repeat launch attaches to the live daemon"); + assert.equal(h2.origin, h1.origin); + } finally { + killNow(h1.child?.pid); + } + }); + }, +); + +test( + "zone live: squatter on the sticky port → ladder drift settles sticky; a repeat attaches at the drifted port", + { timeout: 240_000, skip: LIVE ? process.platform !== "linux" : liveSkip }, + async () => { + await withSandbox(async () => { + ensureDistBuilt(); + const h1 = await launch({ lane: "zcode" }); + const daemon1 = h1.child?.pid; + trackKill(daemon1); + let daemon2: number | undefined; + try { + assert.equal(h1.port, ZONE_PORT_BASE, "precondition: first launch on the base"); + killNow(daemon1); + await new Promise((r) => setTimeout(r, 300)); // kernel releases the listen socket + const squatter = await squatted(ZONE_PORT_BASE); + const h2 = await launch({ lane: "zcode" }); + daemon2 = h2.child?.pid; + trackKill(daemon2); + assert.equal(h2.port, ZONE_PORT_BASE + 1, "preferred base occupied → +1 ladder drift"); + assert.equal(readZonePort("zcode"), ZONE_PORT_BASE + 1, "sticky follows the drift"); + const h3 = await launch({ lane: "zcode" }); + assert.equal(h3.attached, true); + assert.equal(h3.port, ZONE_PORT_BASE + 1, "later launches follow the drift"); + // Eager close — the next test expects the zone base free; the + // after() backstop alone would hold it past this test's end. + squatter.close(); + } finally { + killNow(daemon1); + killNow(daemon2); + } + }); + }, +); + +test( + "zone live: explicit strictPort pin binds exactly and never settles a zone record", + { timeout: 180_000, skip: LIVE ? process.platform !== "linux" : liveSkip }, + async () => { + await withSandbox(async () => { + ensureDistBuilt(); + const port = await freePort(); + const h = await launch({ lane: "zcode", port, strictPort: true }); + trackKill(h.child?.pid); + try { + assert.equal(h.port, port, "the exact pin is the bound port"); + assert.equal(readZonePort("zcode"), undefined, "explicit pins stay out of the sticky file"); + assert.equal(fs.existsSync(portZoneFilePath()), false, "no zone file materialized"); + } finally { + killNow(h.child?.pid); + } + }); + }, +); + +test( + "zone live: a second lane spawns its own daemon past the first and keeps an independent sticky key", + { timeout: 240_000, skip: LIVE ? process.platform !== "linux" : liveSkip }, + async () => { + await withSandbox(async () => { + ensureDistBuilt(); + const h1 = await launch({ lane: "zcode" }); + const daemon1 = h1.child?.pid; + trackKill(daemon1); + try { + assert.equal(h1.port, ZONE_PORT_BASE); + const h2 = await launch({ lane: "kimi" }); + trackKill(h2.child?.pid); + try { + assert.equal(h2.attached, undefined, "cross-lane instances are never attach targets"); + assert.equal(h2.port, ZONE_PORT_BASE + 1, "second lane ladders past the first lane's daemon"); + assert.equal(readZonePort("zcode"), ZONE_PORT_BASE); + assert.equal(readZonePort("kimi"), ZONE_PORT_BASE + 1, "each lane settles its own sticky key"); + } finally { + killNow(h2.child?.pid); + } + } finally { + killNow(daemon1); + } + }); + }, +); + +test( + "zone live: an unlane'd launch is ephemeral and leaves no zone record", + { timeout: 180_000, skip: LIVE ? process.platform !== "linux" : liveSkip }, + async () => { + await withSandbox(async () => { + ensureDistBuilt(); + const h = await launch({}); + trackKill(h.child?.pid); + try { + assert.ok(h.port > 0); + assert.notEqual(h.port, ZONE_PORT_BASE, "unlane'd traffic never rides the zone base"); + assert.equal(fs.existsSync(portZoneFilePath()), false, "no sticky record without a lane"); + } finally { + killNow(h.child?.pid); + } + }); + }, +); diff --git a/tests/port-zone.test.ts b/tests/port-zone.test.ts new file mode 100644 index 0000000000..1db38219e9 --- /dev/null +++ b/tests/port-zone.test.ts @@ -0,0 +1,315 @@ +import test, { after } from "node:test"; +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { lanePreferredPort, portZoneFilePath, readZonePort, writeZonePort } from "../src/instance.ts"; +import type { ProxyInstanceFile } from "../src/instance.ts"; +import { ZONE_PORT_BASE, resolveZonePortBase } from "../src/config.ts"; +import { ensureProxyRunning, type SpawnChild, type SpawnFn } from "../src/launcher.ts"; + +// #1660: the self-managed port zone. Every lane'd launch tries the lane's +// sticky port first (a past +1-ladder drift it still points at), else the +// zone base; the spawn path settles the actually-bound port back sticky so +// later launches follow drift automatically. Pure file-backed functions — +// always driven against an explicit temp file here so tests never touch the +// developer's real state dir. + +function zoneFile(): string { + const dir = mkdtempSync(path.join(tmpdir(), "bili-port-zone-")); + return path.join(dir, "port-zone.json"); +} + +test("readZonePort/writeZonePort: round-trip, per-lane isolation, preserves other lanes", () => { + const file = zoneFile(); + try { + assert.equal(readZonePort("zcode", file), undefined, "no record yet"); + writeZonePort("zcode", 18788, file); + writeZonePort("claude", 18789, file); + assert.equal(readZonePort("zcode", file), 18788); + assert.equal(readZonePort("claude", file), 18789); + // a rewrite of one lane preserves the other + writeZonePort("zcode", 18790, file); + assert.equal(readZonePort("zcode", file), 18790); + assert.equal(readZonePort("claude", file), 18789); + const shape = JSON.parse(readFileSync(file, "utf8")) as { lanes: Record }; + assert.deepEqual(shape.lanes, { zcode: 18790, claude: 18789 }); + } finally { + rmSync(path.dirname(file), { recursive: true, force: true }); + } +}); + +test("readZonePort: tolerates garbage — missing file, invalid JSON, out-of-range values", () => { + const file = zoneFile(); + try { + assert.equal(readZonePort("zcode", file), undefined, "missing file"); + writeFileSync(file, "{ this is not json", "utf8"); + assert.equal(readZonePort("zcode", file), undefined, "corrupt JSON"); + writeFileSync(file, JSON.stringify({ lanes: { zcode: "18788", claude: 0, pi: 65536, dsh: 1.5 } }), "utf8"); + assert.equal(readZonePort("zcode", file), undefined, "string is not a port"); + assert.equal(readZonePort("claude", file), undefined, "0 is not a port"); + assert.equal(readZonePort("pi", file), undefined, "65536 is out of range"); + assert.equal(readZonePort("dsh", file), undefined, "non-integer is not a port"); + writeFileSync(file, JSON.stringify({ lanes: { zcode: 18788 } }), "utf8"); + assert.equal(readZonePort("other", file), undefined, "lane without a record"); + } finally { + rmSync(path.dirname(file), { recursive: true, force: true }); + } +}); + +test("writeZonePort: rejects invalid ports and never throws", () => { + const file = zoneFile(); + try { + writeZonePort("zcode", 0, file); + writeZonePort("zcode", 65536, file); + writeZonePort("zcode", 1.5, file); + writeZonePort("zcode", Number.NaN, file); + assert.equal(readZonePort("zcode", file), undefined, "nothing settled for invalid inputs"); + assert.doesNotThrow(() => writeZonePort("zcode", 18787, file)); + } finally { + rmSync(path.dirname(file), { recursive: true, force: true }); + } +}); + +test("lanePreferredPort: sticky record beats the base; base honors BILI_ZONE_PORT", () => { + const file = zoneFile(); + try { + assert.equal(lanePreferredPort("zcode", { BILI_ZONE_PORT: "20000" }), 20000, "env override of the base"); + writeZonePort("zcode", 18788, file); + // sticky lives in the DEFAULT state file — patch readZonePort's view by + // pointing the default path at the temp file via the module seam: the + // function reads portZoneFilePath() when no file is passed, so drive + // the two-arg forms directly for the composed semantics instead. + assert.equal(readZonePort("zcode", file), 18788, "sticky present in the temp zone file"); + assert.equal(lanePreferredPort("zcode", {}), ZONE_PORT_BASE, "default base without a sticky record (real state file untouched in tests)"); + } finally { + rmSync(path.dirname(file), { recursive: true, force: true }); + } +}); + +test("resolveZonePortBase: BILI_ZONE_PORT validated 1..65535, junk falls back to the default", () => { + assert.equal(ZONE_PORT_BASE, 18787, "the zone base sits below the Linux ephemeral range (32768-60999)"); + assert.equal(resolveZonePortBase({}), ZONE_PORT_BASE); + assert.equal(resolveZonePortBase({ BILI_ZONE_PORT: "20000" }), 20000); + assert.equal(resolveZonePortBase({ BILI_ZONE_PORT: "1" }), 1); + assert.equal(resolveZonePortBase({ BILI_ZONE_PORT: "65535" }), 65535); + assert.equal(resolveZonePortBase({ BILI_ZONE_PORT: "0" }), ZONE_PORT_BASE); + assert.equal(resolveZonePortBase({ BILI_ZONE_PORT: "65536" }), ZONE_PORT_BASE); + assert.equal(resolveZonePortBase({ BILI_ZONE_PORT: "not-a-port" }), ZONE_PORT_BASE); +}); + +test("portZoneFilePath: lives in the state dir", () => { + assert.equal(path.basename(portZoneFilePath()), "port-zone.json"); +}); + +// --------------------------------------------------------------------------- +// #1660 launch sequences: the sticky-zone lifecycle driven through +// ensureProxyRunning with mocked process edges. The single-shot tests in +// launcher.test.ts pin one decision each; these pin the REPEATED loop — +// spawn → settle → attach → drift → re-settle → attach-follows — the exact +// regression surface where a pre-resolved port silently skips the settle +// (fixed in 90cc7e8; only a repeated launch exposes the missing record). +// --------------------------------------------------------------------------- + +// ensureProxyRunning coordinates across processes via /proxy-starting +// (#707) and probes /instances — point the state dir at a throwaway so +// these tests never touch the real one (same posture as launcher.test.ts). +const prevZoneTestXdgState = process.env.XDG_STATE_HOME; +process.env.XDG_STATE_HOME = mkdtempSync(path.join(tmpdir(), "bili-zone-test-state-")); +after(() => { + if (prevZoneTestXdgState === undefined) delete process.env.XDG_STATE_HOME; + else process.env.XDG_STATE_HOME = prevZoneTestXdgState; +}); + +// A script fixture whose content hash matches the instances the sim records — +// instanceCompatible demands the spawn script's fingerprint to match. +const ZONE_FP_SCRIPT = path.join(tmpdir(), `bili-zone-fp-${process.pid}.js`); +writeFileSync(ZONE_FP_SCRIPT, "// zone sequence fingerprint fixture\n"); +const ZONE_FP_HASH = createHash("sha256").update(readFileSync(ZONE_FP_SCRIPT)).digest("hex"); + +function recordedZoneInstance(over: Partial = {}): ProxyInstanceFile { + return { + origin: `http://127.0.0.1:${ZONE_PORT_BASE}`, + instanceId: "zone-inst-1", + pid: process.pid, + startedAt: Date.now(), + host: "127.0.0.1", + port: ZONE_PORT_BASE, + passthrough: false, + mitmDomains: [], + modelWindows: {}, + codeFingerprint: ZONE_FP_HASH, + ...over, + }; +} + +function fakeZoneChild(pid: number): SpawnChild { + return { + pid, + unref() {}, + kill() { + return true; + }, + on() {}, + }; +} + +/** A one-daemon world: `live` is the currently recorded instance, `squatted` + * holds ports dumb listeners occupy (the daemon's own port also blocks), and + * a spawn binds the requested port or ladders +1 past busy ones — the same + * EADDRINUSE walk the real server does (#1335). The zone file is REAL: the + * sim's zonePreferredPort/writeZonePort delegate to it, so the full + * write→read sticky loop runs on disk. */ +function makeZoneSim(zoneFile: string, lane: string) { + const sim = { + live: undefined as ProxyInstanceFile | undefined, + squatted: new Set(), + spawns: [] as Array<{ args: string[]; env: NodeJS.ProcessEnv }>, + settles: [] as Array<[string, number]>, + pidSeq: 42100, + }; + const spawnImpl: SpawnFn = (_cmd, args, options) => { + sim.spawns.push({ args: [...args], env: options.env ?? {} }); + const want = Number(args[args.indexOf("--port") + 1]); + let bind = want; + while (sim.squatted.has(bind) || (sim.live !== undefined && bind === sim.live.port)) bind++; + const childPid = ++sim.pidSeq; + const token = options.env?.BILI_LAUNCH_TOKEN ?? `sim-token-${childPid}`; + // inst.pid must be a LIVE pid — probeLiveInstances drops records whose + // owner process is gone; the test process stands in for the daemon's. + sim.live = recordedZoneInstance({ + pid: process.pid, + port: bind, + origin: `http://127.0.0.1:${bind}`, + lane, + launchToken: token, + instanceId: `zone-sim-${childPid}`, + }); + return fakeZoneChild(childPid); + }; + const deps = { + fetchImpl: async (url: string) => + sim.live !== undefined && url.startsWith(sim.live.origin) ? { ok: true } : { ok: false }, + fetchHealthInfo: async (origin: string) => + sim.live !== undefined && sim.live.origin === origin + ? { ok: true, instanceId: sim.live.instanceId, watchdog: { armed: true } } + : undefined, + readInstanceFile: () => sim.live, + spawnImpl, + registerWatcher: async () => "ok" as const, + sleep: () => Promise.resolve(), + scriptPath: ZONE_FP_SCRIPT, + zonePreferredPort: (l: string) => lanePreferredPort(l, {}, zoneFile), + writeZonePort: (l: string, port: number) => { + sim.settles.push([l, port]); + writeZonePort(l, port, zoneFile); + }, + }; + return { sim, deps }; +} + +const spawnPortArg = (spawn: { args: string[] }): string => spawn.args[spawn.args.indexOf("--port") + 1]; + +function zoneDir(): { dir: string; zoneFile: string } { + const dir = mkdtempSync(path.join(tmpdir(), "bili-zone-seq-")); + return { dir, zoneFile: path.join(dir, "port-zone.json") }; +} + +test("zone sequence: settle → attach → drift → re-settle → attach follows the drift (#1660)", async () => { + const { dir, zoneFile } = zoneDir(); + const { sim, deps } = makeZoneSim(zoneFile, "zcode"); + const launch = () => + ensureProxyRunning({ host: "127.0.0.1", port: 0, passthrough: false, debug: false, lane: "zcode" }, deps); + try { + const h1 = await launch(); + assert.equal(sim.spawns.length, 1, "first launch spawns the lane daemon"); + assert.equal(h1.port, ZONE_PORT_BASE, "fresh lane'd launch binds the zone base"); + assert.equal(spawnPortArg(sim.spawns[0]), String(ZONE_PORT_BASE), "base is the spawn port, not an OS ephemeral"); + assert.deepEqual(sim.settles, [["zcode", ZONE_PORT_BASE]], "the bound port settles sticky"); + assert.equal(readZonePort("zcode", zoneFile), ZONE_PORT_BASE); + + const h2 = await launch(); + assert.equal(sim.spawns.length, 1, "repeat launch attaches instead of doubling"); + assert.equal(h2.attached, true); + assert.equal(h2.port, ZONE_PORT_BASE, "attachment rides the settled port"); + assert.deepEqual(sim.settles, [["zcode", ZONE_PORT_BASE]], "attach never re-settles"); + + sim.live = undefined; // daemon dies + sim.squatted.add(ZONE_PORT_BASE); // a squatter takes the sticky port + const h3 = await launch(); + assert.equal(sim.spawns.length, 2, "dead daemon + squatter forces a respawn"); + assert.equal(spawnPortArg(sim.spawns[1]), String(ZONE_PORT_BASE), "sticky port is still the preferred first try"); + assert.equal(h3.port, ZONE_PORT_BASE + 1, "the bind ladders +1 past the squatter"); + assert.deepEqual( + sim.settles, + [["zcode", ZONE_PORT_BASE], ["zcode", ZONE_PORT_BASE + 1]], + "the drifted port settles sticky", + ); + assert.equal(readZonePort("zcode", zoneFile), ZONE_PORT_BASE + 1); + + const h4 = await launch(); + assert.equal(sim.spawns.length, 2, "post-drift repeat attaches"); + assert.equal(h4.attached, true); + assert.equal(h4.port, ZONE_PORT_BASE + 1, "later launches follow the drift"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("zone sequence: a second lane never attaches cross-lane and settles its own sticky key (#1225/#1660)", async () => { + const { dir, zoneFile } = zoneDir(); + const { sim, deps } = makeZoneSim(zoneFile, "kimi"); + writeZonePort("zcode", ZONE_PORT_BASE, zoneFile); // lane one already settled… + sim.squatted.add(ZONE_PORT_BASE); // …and its daemon holds the base port + sim.live = recordedZoneInstance({ lane: "zcode", launchToken: "zcode-token" }); + try { + const h = await ensureProxyRunning( + { host: "127.0.0.1", port: 0, passthrough: false, debug: false, lane: "kimi" }, + deps, + ); + assert.equal(sim.spawns.length, 1, "a lane-mismatch instance is never an attach target"); + assert.equal(h.attached, undefined); + assert.equal(h.port, ZONE_PORT_BASE + 1, "the second lane ladders past the first lane's daemon"); + assert.deepEqual(sim.settles, [["kimi", ZONE_PORT_BASE + 1]], "the lane settles its own key"); + assert.equal(readZonePort("zcode", zoneFile), ZONE_PORT_BASE, "lane one's sticky record is untouched"); + assert.equal(readZonePort("kimi", zoneFile), ZONE_PORT_BASE + 1); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("zone sequence: an explicit strictPort pin is exact and stays out of the sticky file (#964/#1660)", async () => { + const { dir, zoneFile } = zoneDir(); + const { sim, deps } = makeZoneSim(zoneFile, "zcode"); + const pin = ZONE_PORT_BASE + 400; + try { + const h = await ensureProxyRunning( + { host: "127.0.0.1", port: pin, strictPort: true, passthrough: false, debug: false, lane: "zcode" }, + deps, + ); + assert.equal(sim.spawns.length, 1); + assert.equal(spawnPortArg(sim.spawns[0]), String(pin), "the exact pin is the spawn port"); + assert.equal(sim.spawns[0].env.BILI_STRICT_PORT, "1", "strictness crosses the process boundary"); + assert.equal(h.port, pin); + assert.deepEqual(sim.settles, [], "explicit pins never settle a zone record"); + assert.equal(readZonePort("zcode", zoneFile), undefined); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("zone sequence: an unlane'd launch is ephemeral and never touches the zone file (#1660)", async () => { + const { dir, zoneFile } = zoneDir(); + const { sim, deps } = makeZoneSim(zoneFile, "zcode"); + try { + const h = await ensureProxyRunning({ host: "127.0.0.1", port: 0, passthrough: false, debug: false }, deps); + assert.equal(sim.spawns.length, 1); + assert.ok(Number(spawnPortArg(sim.spawns[0])) > 0, "an OS-assigned ephemeral port"); + assert.equal(h.port, Number(spawnPortArg(sim.spawns[0]))); + assert.deepEqual(sim.settles, [], "no lane → no sticky write"); + assert.equal(readZonePort("zcode", zoneFile), undefined, "the zone file stays empty"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/tests/tunnel-guard.test.ts b/tests/tunnel-guard.test.ts index 6b63108877..badab200e2 100644 --- a/tests/tunnel-guard.test.ts +++ b/tests/tunnel-guard.test.ts @@ -382,6 +382,6 @@ test("integration: unresolvable /bili/ destination answers 502 transport-class, process.env.BILI_CONFIG_FILE = prevConfig; proxy.closeAllConnections?.(); await close(proxy); - try { rmSync(root, { recursive: true, force: true }); } catch { /* best-effort */ } + try { rmrf(root); } catch { /* best-effort */ } } }); diff --git a/tests/zcode-native.test.ts b/tests/zcode-native.test.ts index 517b2db7af..cb4152ad68 100644 --- a/tests/zcode-native.test.ts +++ b/tests/zcode-native.test.ts @@ -474,12 +474,12 @@ test('bootstrapZcodeNative respects zcode route:"none" without proxy bring-up (# } }); -test("resolveZcodeNativePort and zcodeDirectPrefixes map env into the lane (#1622)", async () => { - const { resolveZcodeNativePort, ZCODE_NATIVE_DEFAULT_PORT, zcodeDirectPrefixes } = await import("../src/config.ts"); +test("resolveZcodeNativePort: env-only explicit override, undefined without one (#1622/#1660)", async () => { + const { resolveZcodeNativePort, zcodeDirectPrefixes } = await import("../src/config.ts"); assert.equal(resolveZcodeNativePort({ BILI_ZCODE_PORT: "41234" }), 41234); - assert.equal(resolveZcodeNativePort({ BILI_ZCODE_PORT: "not-a-port" }), ZCODE_NATIVE_DEFAULT_PORT); - assert.equal(resolveZcodeNativePort({ BILI_ZCODE_PORT: "70000" }), ZCODE_NATIVE_DEFAULT_PORT); - assert.equal(resolveZcodeNativePort({}), ZCODE_NATIVE_DEFAULT_PORT); + assert.equal(resolveZcodeNativePort({ BILI_ZCODE_PORT: "not-a-port" }), undefined); + assert.equal(resolveZcodeNativePort({ BILI_ZCODE_PORT: "70000" }), undefined); + assert.equal(resolveZcodeNativePort({}), undefined, "#1660: no default — the zcode lane rides the zone preference"); const dir = mkdtempSync(path.join(tmpdir(), "zcode-native-config-")); const cfg = path.join(dir, "providers.json"); writeFileSync(cfg, JSON.stringify({