From 1a62ca8f9e5f7dc22554774e7c0d31b92551c335 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Thu, 1 Oct 2026 22:52:02 +0800 Subject: [PATCH 1/9] feat: claude lane mid-session proxy self-heal via MCP watchdog (#1821) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The zcode lane already respawns a dead proxy from its session-lived MCP child (30s tick x 3 failures); the claude lane's MCP shell had no watchdog, so a proxy death left every model request ECONNREFUSED until the next session's SessionStart hook re-ran. - new src/claude-mcp-entry.ts: mirrors zcode/mcp-entry.ts — session-lived stdio entry that probes healthUrl every 30s and, after 3 consecutive failures, re-runs ensureProxyRunning(lane:"claude") with zone port semantics and chooseWatchdogParentPid() so the respawned proxy still watches the claude host pid; on origin drift it repins the managed settings base URL (next session heals) and follows BILI_MCP_PROXY for its own tool calls. Attach posture (BILLION_CONTEXT_PROXY) and passthrough (BILI_NATIVE_CLAUDE=0) never respawn — user-owned proxies stay user-owned. No exit handoff needed: the proxy watches the host pid and the next hook drops dead pins. - plugin-install.ts: claudeInstall now registers dist/claude-mcp-entry.js instead of dist/mcp.js and migrates an existing legacy registration in place (remove+add); fresh/current/foreign registrations handled without clobbering. - tsup.config.ts: build the new entry. - tests: 20 new tests (watchdog semantics, posture gates, installer migration matrix). - docs: README en/zh note the mid-session self-heal. --- README.md | 2 +- README.zh-CN.md | 2 +- src/claude-mcp-entry.ts | 145 ++++++++++++ src/plugin-install.ts | 75 +++++- tests/claude-mcp-entry.test.ts | 409 +++++++++++++++++++++++++++++++++ tsup.config.ts | 2 +- 6 files changed, 625 insertions(+), 10 deletions(-) create mode 100644 src/claude-mcp-entry.ts create mode 100644 tests/claude-mcp-entry.test.ts diff --git a/README.md b/README.md index d0aef5889b..3455b626bf 100644 --- a/README.md +++ b/README.md @@ -235,7 +235,7 @@ Notes: - `kimi` reports runtime-info at bootstrap only (static headers can't carry per-request window/model values); subagent tool calls are routed by the proxy's outbound tool-use witness ring (#1685) — no model-visible 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` 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). **Known limitation (#2290):** the Claude Desktop app's Code tab (`CLAUDE_CODE_ENTRYPOINT=claude-desktop`) sets its own `ANTHROPIC_BASE_URL` on its embedded Claude Code, overriding the managed one — desktop sessions bypass the proxy entirely while the managed block's `DISABLE_AUTO_COMPACT=1` still applies, so they get neither bili compression nor native auto-compaction. The hook warns loudly at session start (and records it for `bili doctor`, which also flags machines where Claude Desktop is installed alongside the native lane); terminal sessions are unaffected. **Field-tested 2026-10-06 (#2290):** putting `HTTPS_PROXY` in the settings `env` block produced zero CONNECT traffic to a live MITM-enabled proxy on Claude Desktop 2.19675.1 / embedded CC 2.1.288 (Windows 11) — the variable reaches no network stack there, consistent with the CLI finding that CC's undici ignores proxy env vars (why `bili claude` uses the `/bili/` base-URL rewrite instead). As of that version there is no usable routing seam on the desktop Code tab; the lane stays tracked in [#2290](https://github.com/ranxianglei/billion-context/issues/2290) in case upstream changes behavior. Desktop-only users can restore native auto-compact with `bili plugin remove claude`. +- `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. Since #1821 the MCP shell also watches the proxy mid-session (30 s tick × 3 failures) and respawns a dead lane proxy itself, so model requests recover within ~90 s instead of a new session (same semantics as the zcode lane). Opt out with `BILI_NATIVE_CLAUDE=0` (passthrough). Mechanics: [TECHNICAL-NOTES.md](TECHNICAL-NOTES.md). **Known limitation (#2290):** the Claude Desktop app's Code tab (`CLAUDE_CODE_ENTRYPOINT=claude-desktop`) sets its own `ANTHROPIC_BASE_URL` on its embedded Claude Code, overriding the managed one — desktop sessions bypass the proxy entirely while the managed block's `DISABLE_AUTO_COMPACT=1` still applies, so they get neither bili compression nor native auto-compaction. The hook warns loudly at session start (and records it for `bili doctor`, which also flags machines where Claude Desktop is installed alongside the native lane); terminal sessions are unaffected. **Field-tested 2026-10-06 (#2290):** putting `HTTPS_PROXY` in the settings `env` block produced zero CONNECT traffic to a live MITM-enabled proxy on Claude Desktop 2.19675.1 / embedded CC 2.1.288 (Windows 11) — the variable reaches no network stack there, consistent with the CLI finding that CC's undici ignores proxy env vars (why `bili claude` uses the `/bili/` base-URL rewrite instead). As of that version there is no usable routing seam on the desktop Code tab; the lane stays tracked in [#2290](https://github.com/ranxianglei/billion-context/issues/2290) in case upstream changes behavior. Desktop-only users can restore native auto-compact with `bili plugin remove claude`. - `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 16f524a089..deb8692349 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -187,7 +187,7 @@ pi / omp / kimi / claude 没有客户端侧通道 —— 它们的配置条目 - OpenCode 旧会话、V1/V2 插件形态与全部注意事项:[OpenCode](CLIENTS.zh-CN.md#opencode)。 - `kimi` 仅在自举时上报 runtime-info(静态头无法承载逐请求窗口/模型值);子代理工具调用由代理的出站 tool_use 见证环路由(#1685)——模型看不到任何会话 id。 - `hermes` 的原生插件是 Python:健康检查通过后用环境变量把 hermes 的 httpx 栈指向代理,并经 `llm_request` 中间件打逐请求头。 -- `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)。**已知限制(#2290):** Claude Desktop 应用的 Code 标签页(`CLAUDE_CODE_ENTRYPOINT=claude-desktop`)会为其内嵌的 Claude Code 设置自己的 `ANTHROPIC_BASE_URL`,覆盖受管值——桌面会话完全绕过代理,而受管块的 `DISABLE_AUTO_COMPACT=1` 仍然生效,因此既没有 bili 压缩、也没有原生自动压缩。hook 会在会话开始时大声警告并记录下来供 `bili doctor` 展示(检测到本机装有 Claude Desktop 时,该 lane 也会显示 ⚠️ 提示);终端会话不受影响。**真机验证(2026-10-06,#2290):** 把 `HTTPS_PROXY` 写进 settings 的 `env` 块后,在 Claude Desktop 2.19675.1 / 内嵌 CC 2.1.288(Windows 11)上对一台开启 MITM 的存活代理**零 CONNECT 流量**——该变量没有到达应用内任何网络栈,与 CLI 侧「CC 的 undici 忽略 proxy env」的既有结论一致(这正是 `bili claude` 改用 `/bili/` base-URL 改写的原因)。截至该版本,桌面 Code 标签页不存在可用的路由缝隙;该 lane 继续在 [#2290](https://github.com/ranxianglei/billion-context/issues/2290) 跟踪,若上游行为变化再议。仅用桌面的用户可用 `bili plugin remove claude` 恢复原生自动压缩。 +- `claude` 有**原生姿态**(#964):受管 settings 块 + `SessionStart` hook + MCP shell;hook 骑自管端口区(#1660),每会话把受管 URL 重钉到存活 origin,端口漂移自愈。#1821 起 MCP shell 还在会话内守护代理(30s × 3 次失败),代理死亡时自行重生,lane 内模型请求 ~90s 内恢复而无需新开会话(与 zcode 车道同语义)。`BILI_NATIVE_CLAUDE=0` 退出(passthrough)。机制:[TECHNICAL-NOTES.zh-CN.md](TECHNICAL-NOTES.zh-CN.md)。**已知限制(#2290):** Claude Desktop 应用的 Code 标签页(`CLAUDE_CODE_ENTRYPOINT=claude-desktop`)会为其内嵌的 Claude Code 设置自己的 `ANTHROPIC_BASE_URL`,覆盖受管值——桌面会话完全绕过代理,而受管块的 `DISABLE_AUTO_COMPACT=1` 仍然生效,因此既没有 bili 压缩、也没有原生自动压缩。hook 会在会话开始时大声警告并记录下来供 `bili doctor` 展示(检测到本机装有 Claude Desktop 时,该 lane 也会显示 ⚠️ 提示);终端会话不受影响。**真机验证(2026-10-06,#2290):** 把 `HTTPS_PROXY` 写进 settings 的 `env` 块后,在 Claude Desktop 2.19675.1 / 内嵌 CC 2.1.288(Windows 11)上对一台开启 MITM 的存活代理**零 CONNECT 流量**——该变量没有到达应用内任何网络栈,与 CLI 侧「CC 的 undici 忽略 proxy env」的既有结论一致(这正是 `bili claude` 改用 `/bili/` base-URL 改写的原因)。截至该版本,桌面 Code 标签页不存在可用的路由缝隙;该 lane 继续在 [#2290](https://github.com/ranxianglei/billion-context/issues/2290) 跟踪,若上游行为变化再议。仅用桌面的用户可用 `bili plugin remove claude` 恢复原生自动压缩。 - `zcode` 有**原生姿态**(#1145):受管 `~/.zcode/cli/config.json` 块 + 每会话 provider `baseURL` 改写。完整机制:[CLIENTS.zh-CN.md](CLIENTS.zh-CN.md)。 - `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`。 diff --git a/src/claude-mcp-entry.ts b/src/claude-mcp-entry.ts new file mode 100644 index 0000000000..ee359bb2bb --- /dev/null +++ b/src/claude-mcp-entry.ts @@ -0,0 +1,145 @@ +// claude native MCP entry (#1821): spawned per-session by Claude Code as the +// "bili" MCP server the installer registers (plugin-install.ts). Serves the +// ACP tools over stdio like dist/mcp.js, plus a session-lived watchdog that +// respawns the lane proxy when it dies MID-SESSION: the model channel rides +// claude's own HTTP client against the static baked base URL, and nothing else +// re-arms it until the next SessionStart hook (which does not re-run mid-session). +// Mirrors src/zcode/mcp-entry.ts (30 s tick × 3 failures). No exit handoff is +// needed: the proxy watches the claude host pid (parent-gone anti-orphan) and +// the next hook drops dead pins via pid liveness (launcher.ts attach filter). +// Logs go through the shared bili.log tee because claude does not surface this +// child's stderr. + +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { resolveProxyOrigin, runMcpStdio } from "./mcp.js"; +import { configureLogger, log as teeLog } from "./logger.js"; +import { defaultLogFile } from "./paths.js"; +import { LAUNCHER_DEFAULT_HOST, ensureProxyRunning, healthUrl } from "./launcher.js"; +import { chooseWatchdogParentPid, planClaudeNativeBootstrap } from "./claude-native-bootstrap.js"; +import { repinClaudeManagedBaseUrl, readClaudeManagedBaseUrl } from "./plugin-install.js"; + +const WATCHDOG_INTERVAL_MS = 30000; +const WATCHDOG_FAILURE_LIMIT = 3; + +/** dist/claude-mcp-entry.js → sibling dist/index.js (the package bin) — the + * same guard as claude-native-bootstrap's proxyScriptPath: ensureProxyRunning's + * default script would re-invoke THIS script as the proxy. */ +function proxyScriptPath(): string { + return path.join(path.dirname(fileURLToPath(import.meta.url)), "index.js"); +} + +async function probeProxyHealth(origin: string): Promise { + try { + const res = await fetch(healthUrl(origin), { signal: AbortSignal.timeout(2000) }); + return res.ok; + } catch { + return false; + } +} + +export interface WatchdogDeps { + /** Test seam: liveness probe (default: GET /__bili/health). */ + probe?: (origin: string) => Promise; + /** Test seam: bring-up (default: ensureProxyRunning). */ + ensure?: typeof ensureProxyRunning; + /** Test seam: settings repin (default: repinClaudeManagedBaseUrl). */ + repin?: (origin: string) => string[]; + intervalMs?: number; + failureLimit?: number; +} + +export interface WatchdogState { + origin: string; +} + +export interface MutableWatchdogState extends WatchdogState { + failures: number; +} + +/** One watchdog pass: healthy → reset; dead `failureLimit` times in a row → + * bring the lane proxy back up with the SAME semantics as the SessionStart + * hook (explicit pin strict; zone mode port 0 so the launcher settles the + * sticky record), watching the CLAUDE host pid — not this child, so a child + * crash never kills a healthy proxy. A respawn on a drifted origin repins the + * managed settings (heals the NEXT session — the current one keeps dialing + * the base URL claude loaded at startup, the same #1660 constraint as the + * hook) and follows it in our own BILI_MCP_PROXY pin so bili tools keep working. */ +export async function watchdogTick(state: MutableWatchdogState, plan: { port: number; strict: boolean }, deps: WatchdogDeps, log: (msg: string) => void): Promise { + const probeFn = deps.probe ?? probeProxyHealth; + const limit = deps.failureLimit ?? WATCHDOG_FAILURE_LIMIT; + if (await probeFn(state.origin)) { + state.failures = 0; + return; + } + state.failures += 1; + if (state.failures < limit) return; + state.failures = 0; + const ensure = deps.ensure ?? ensureProxyRunning; + const handle = await ensure( + { + host: LAUNCHER_DEFAULT_HOST, + port: plan.strict ? plan.port : 0, + passthrough: false, + debug: false, + parentPid: chooseWatchdogParentPid(), + strictPort: plan.strict, + lane: "claude", + }, + { scriptPath: proxyScriptPath() }, + ); + if ((handle.refusedWatcher ?? false)) { + log(`WARNING: proxy at ${handle.origin} has NO session-lifecycle watchdog (#1322) — kill it or start a session-owned proxy to restore the lifecycle contract`); + } + if (handle.origin !== state.origin) { + const repin = deps.repin ?? repinClaudeManagedBaseUrl; + try { + const notes = repin(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)}`); + } + process.env.BILI_MCP_PROXY = handle.origin; + state.origin = handle.origin; + } + log(`proxy ${handle.attached ? "attached" : "respawned"} at ${handle.origin}`); +} + +export function startWatchdog(state: MutableWatchdogState, plan: { port: number; strict: boolean }, log: (msg: string) => void, deps: WatchdogDeps = {}): NodeJS.Timeout { + let busy = false; + const timer = setInterval(() => { + if (busy) return; + busy = true; + void watchdogTick(state, plan, deps, log) + .catch((err) => log(`watchdog error: ${err instanceof Error ? err.message : String(err)}`)) + .finally(() => { busy = false; }); + }, deps.intervalMs ?? WATCHDOG_INTERVAL_MS); + timer.unref?.(); + return timer; +} + +export async function main(opts: WatchdogDeps & { runStdio?: () => void } = {}): Promise { + if (process.env.NODE_TEST_CONTEXT !== undefined) return; + configureLogger(defaultLogFile()); + const log = (msg: string) => teeLog("info", `[bili-claude-mcp] ${msg}`); + const plan = planClaudeNativeBootstrap(process.env); + if (plan.action !== "start") { + // attach (BILLION_CONTEXT_PROXY / BILI_PROVIDER_REWRITES) or passthrough + // (opt-out): someone else owns routing — serve tools only, NEVER respawn + // (a second proxy beside an attach target would split sessions across two). + (opts.runStdio ?? runMcpStdio)(); + return; + } + // Track what THIS running claude dialed: the managed block's last-repinned + // URL wins (settings.json), then the installer pin / live discovery. + const state: MutableWatchdogState = { origin: readClaudeManagedBaseUrl() ?? resolveProxyOrigin(), failures: 0 }; + startWatchdog(state, plan, log, opts); + (opts.runStdio ?? runMcpStdio)(); +} + +if (process.argv[1] && /(?:^|[\\/])claude-mcp-entry\.(?:ts|js)$/.test(process.argv[1])) { + main().catch((err) => { + process.stderr.write(`[bili-claude-mcp] fatal: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`); + process.exit(1); + }); +} diff --git a/src/plugin-install.ts b/src/plugin-install.ts index b49ea52b4e..d8d92b1009 100644 --- a/src/plugin-install.ts +++ b/src/plugin-install.ts @@ -570,6 +570,16 @@ export function repinClaudeManagedBaseUrl(origin: string, env: NodeJS.ProcessEnv return notes; } +/** #1821: the live origin of the managed block — the port the last SessionStart + * hook repinned, i.e. what a RUNNING claude session dials. Undefined when the + * settings file holds no bili-managed ANTHROPIC_BASE_URL (foreign or absent). */ +export function readClaudeManagedBaseUrl(env: NodeJS.ProcessEnv = process.env): string | undefined { + const cur = (readJson(claudeSettingsFile(env)).env as Record | undefined)?.ANTHROPIC_BASE_URL; + if (typeof cur !== "string" || !isBiliClaudeBaseUrl(cur)) return undefined; + const i = cur.indexOf("/bili/"); + return i > 0 ? cur.slice(0, i) : undefined; +} + /** Pure merge of the #964 managed block into parsed settings (install path). * Never clobbers user keys: a foreign ANTHROPIC_BASE_URL or a non-"1" * DISABLE_AUTO_COMPACT is reported and skipped, not overwritten. Returns the @@ -760,14 +770,43 @@ function defaultWhereRunner(name: string): { stdout: string | null } { return { stdout: r.stdout ?? null }; } +// #1821: what to do about an existing "bili" MCP registration when installing. +// Ownership is content-based, exactly like every other managed block here: +// only a node-run command whose script is our entry (basename match — dev +// checkouts and pnpm stores rename the package dir) counts as ours; anything +// else keeps the name and is never touched. An unreadable .claude.json falls +// back to the legacy behavior (plain add; the CLI owns its own file errors). +function claudeMcpFaceAction(entryJs: string, stableOrigin: string): + { kind: "current" } | { kind: "fresh" } | { kind: "replace"; reason: string } | { kind: "foreign" } { + let data: Record; + try { + data = readJson(claudeMcpJson()); + } catch { + return { kind: "fresh" }; + } + const servers = typeof data.mcpServers === "object" && data.mcpServers !== null ? (data.mcpServers as Record) : {}; + const bili = servers.bili; + if (typeof bili !== "object" || bili === null) return { kind: "fresh" }; + const entry = bili as { command?: unknown; args?: unknown; env?: unknown }; + const isNodeCommand = typeof entry.command === "string" && /node(?:\.(?:exe|cmd))?$/i.test(path.basename(entry.command)); + const args = Array.isArray(entry.args) ? entry.args.filter((a): a is string => typeof a === "string") : []; + const ours = isNodeCommand && args.some((a) => /dist[\\/]claude-mcp-entry\.(?:js|mjs)$/.test(a)); + const legacy = isNodeCommand && args.some((a) => /dist[\\/]mcp\.(?:js|mjs)$/.test(a)); + if (!ours && !legacy) return { kind: "foreign" }; + if (!ours) return { kind: "replace", reason: "migrated from dist/mcp.js" }; + const pin = typeof entry.env === "object" && entry.env !== null ? (entry.env as Record).BILI_MCP_PROXY : undefined; + if (pin === stableOrigin && args.includes(entryJs)) return { kind: "current" }; + return { kind: "replace", reason: "re-pinned" }; +} + function claudeInstall(): string { if (process.env.BILI_NATIVE_CLAUDE === "0") { throw new Error("claude: install refused — BILI_NATIVE_CLAUDE=0 is set (clear it to install the native posture)"); } const root = selfPackageRoot(); - const mcpJs = path.join(root, "dist", "mcp.js"); + const mcpEntryJs = path.join(root, "dist", "claude-mcp-entry.js"); const bootstrapJs = path.join(root, "dist", "claude-native-bootstrap.js"); - requireDistFile(mcpJs); + requireDistFile(mcpEntryJs); requireDistFile(bootstrapJs); // Managed block first: the static URL + bootstrap hook + compaction off. @@ -789,13 +828,35 @@ function claudeInstall(): string { }); writeJson(file, data); - // MCP face: same registration path as before, but pinned to the STABLE - // port the hook brings up — never proxyOriginForInstall() (an ephemeral - // launcher proxy would go stale in this static config). + // MCP face: pinned to the STABLE port the hook brings up — never + // proxyOriginForInstall() (an ephemeral launcher proxy would go stale in + // this static config). #1821: the entry now carries the mid-session + // watchdog that respawns the lane proxy when it dies; pre-watchdog + // installs registered plain dist/mcp.js and are swapped in place below so + // an upgrade lands the self-heal without a manual reinstall dance. const stableOrigin = `http://127.0.0.1:${nativePort}`; const claude = resolveClaudeCli(process.env.CLAUDE?.trim() || "claude"); + const mcpAdd = ["mcp", "add", "bili", "--scope", "user", "-e", `BILI_MCP_PROXY=${stableOrigin}`, "--", process.execPath, mcpEntryJs]; + let mcpNote: string; try { - runClaudeCli(claude, ["mcp", "add", "bili", "--scope", "user", "-e", `BILI_MCP_PROXY=${stableOrigin}`, "--", process.execPath, mcpJs]); + const action = claudeMcpFaceAction(mcpEntryJs, stableOrigin); + switch (action.kind) { + case "current": + mcpNote = `MCP face current (${claudeMcpJson()}, pinned ${stableOrigin})`; + break; + case "fresh": + runClaudeCli(claude, mcpAdd); + mcpNote = `MCP face -> ${claudeMcpJson()} (pinned ${stableOrigin})`; + break; + case "replace": + runClaudeCli(claude, ["mcp", "remove", "bili", "--scope", "user"]); + runClaudeCli(claude, mcpAdd); + mcpNote = `MCP face -> ${claudeMcpJson()} (pinned ${stableOrigin}, ${action.reason})`; + break; + case "foreign": + mcpNote = `MCP face left untouched (foreign bili server at ${claudeMcpJson()})`; + break; + } } catch (err) { const stderr = err instanceof Error && "stderr" in err ? String((err as { stderr?: Buffer | string }).stderr ?? "") : ""; throw new Error(`claude: MCP registration failed (${stderr.trim() || (err instanceof Error ? err.message : String(err))}) — is the claude CLI on PATH? (the managed settings block at ${file} was written; rerun after fixing the CLI to complete the MCP face)`); @@ -815,7 +876,7 @@ function claudeInstall(): string { } catch (err) { throw new Error(`claude: /acp-cache command write failed (${err instanceof Error ? err.message : String(err)}) — the managed settings block at ${file} and the MCP face were written; fix the permissions and rerun`); } - return `claude: managed block -> ${file} (${notes.join("; ")}); /acp-cache command -> ${cmdFile} (${cmdNote}); MCP face -> ${claudeMcpJson()} (pinned ${stableOrigin}) — restart claude to activate`; + return `claude: managed block -> ${file} (${notes.join("; ")}); /acp-cache command -> ${cmdFile} (${cmdNote}); ${mcpNote} — restart claude to activate`; } function claudeRemove(): string { diff --git a/tests/claude-mcp-entry.test.ts b/tests/claude-mcp-entry.test.ts new file mode 100644 index 0000000000..ead76540ec --- /dev/null +++ b/tests/claude-mcp-entry.test.ts @@ -0,0 +1,409 @@ +// #1821: claude native MCP entry — watchdog state machine (proxy death → +// respawn with SessionStart-hook-equivalent semantics; origin drift → repin + +// follow), posture gating (attach/passthrough never respawn), and the +// installer's MCP face migration (legacy dist/mcp.js swap, current skip, +// foreign registration untouched). + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { main, startWatchdog, watchdogTick, type MutableWatchdogState, type WatchdogDeps } from "../src/claude-mcp-entry.ts"; +import { pluginInstall, readClaudeManagedBaseUrl, selfPackageRoot } from "../src/plugin-install.ts"; +import { LAUNCHER_DEFAULT_HOST, type LaunchOptions, type ProxyHandle } from "../src/launcher.ts"; +import { ZONE_PORT_BASE } from "../src/config.ts"; +import { rmrf } from "./tmp-rm.ts"; + +const ORIGIN = `http://127.0.0.1:${ZONE_PORT_BASE}`; +const DRIFTED = `http://127.0.0.1:${ZONE_PORT_BASE + 1}`; + +function sandbox(): { dir: string; settings: string; mcpJson: string } { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-claude-mcp-")); + process.env.CLAUDE_CONFIG_DIR = dir; + process.env.XDG_STATE_HOME = path.join(dir, "state"); + return { dir, settings: path.join(dir, "settings.json"), mcpJson: path.join(dir, ".claude.json") }; +} + +function withEnv(vars: Record, fn: () => void | Promise): void | Promise { + const prev: Record = {}; + for (const [k, v] of Object.entries(vars)) { + prev[k] = process.env[k]; + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + const restore = () => { + for (const [k, v] of Object.entries(prev)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + }; + const r = fn(); + if (r instanceof Promise) return r.finally(restore); + restore(); +} + +function tickFixture(origin: string = ORIGIN): { + state: MutableWatchdogState; + deps: WatchdogDeps; + logs: string[]; + ensureCalls: Array<{ opts: LaunchOptions; deps: Record }>; + repinCalls: string[]; + setProbe: (ok: boolean) => void; + setHandle: (h: Partial) => void; +} { + let probeOk = false; + let handle: Partial = { origin, attached: false }; + const logs: string[] = []; + const ensureCalls: Array<{ opts: LaunchOptions; deps: Record }> = []; + const repinCalls: string[] = []; + const deps: WatchdogDeps = { + probe: async () => probeOk, + ensure: async (opts, d) => { ensureCalls.push({ opts, deps: d }); return { port: 0, ...handle }; }, + repin: (o) => { repinCalls.push(o); return ["repinned"]; }, + failureLimit: 3, + }; + return { state: { origin, failures: 0 }, deps, logs, ensureCalls, repinCalls, setProbe: (v) => { probeOk = v; }, setHandle: (h) => { handle = h; } }; +} + +test("readClaudeManagedBaseUrl: extracts the repinned origin; foreign/absent → undefined", () => { + const box = sandbox(); + try { + delete process.env.BILI_MCP_PROXY; + assert.equal(readClaudeManagedBaseUrl(), undefined); + fs.writeFileSync(box.settings, JSON.stringify({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:19999/bili/https://api.anthropic.com" } })); + assert.equal(readClaudeManagedBaseUrl(), "http://127.0.0.1:19999"); + fs.writeFileSync(box.settings, JSON.stringify({ env: { ANTHROPIC_BASE_URL: "https://some-relay.example/v1" } })); + assert.equal(readClaudeManagedBaseUrl(), undefined); + } finally { + rmrf(box.dir); + delete process.env.CLAUDE_CONFIG_DIR; + delete process.env.XDG_STATE_HOME; + } +}); + +test("watchdogTick: healthy probe resets failures without touching bring-up", async () => { + const f = tickFixture(); + f.setProbe(true); + f.state.failures = 2; + await watchdogTick(f.state, { port: ZONE_PORT_BASE, strict: false }, f.deps, (m) => f.logs.push(m)); + assert.equal(f.state.failures, 0); + assert.equal(f.ensureCalls.length, 0); +}); + +test("watchdogTick: below the failure limit nothing happens", async () => { + const f = tickFixture(); + await watchdogTick(f.state, { port: ZONE_PORT_BASE, strict: false }, f.deps, (m) => f.logs.push(m)); + await watchdogTick(f.state, { port: ZONE_PORT_BASE, strict: false }, f.deps, (m) => f.logs.push(m)); + assert.equal(f.state.failures, 2); + assert.equal(f.ensureCalls.length, 0); +}); + +test("watchdogTick: third consecutive death respawns with hook-equivalent zone semantics", async () => { + const f = tickFixture(); + const plan = { port: ZONE_PORT_BASE, strict: false }; + const log = (m: string) => f.logs.push(m); + await watchdogTick(f.state, plan, f.deps, log); + await watchdogTick(f.state, plan, f.deps, log); + await watchdogTick(f.state, plan, f.deps, log); + assert.equal(f.ensureCalls.length, 1); + const { opts, deps } = f.ensureCalls[0]; + assert.equal(opts.host, LAUNCHER_DEFAULT_HOST); + assert.equal(opts.port, 0, "zone mode passes port 0 so the launcher settles the sticky record"); + assert.equal(opts.strictPort, false); + assert.equal(opts.passthrough, false); + assert.equal(opts.lane, "claude"); + assert.ok(opts.parentPid > 1, "watches a real parent pid"); + assert.equal(path.basename(String(deps.scriptPath)), "index.js", "spawns the package bin, not this entry"); + assert.equal(f.state.failures, 0, "counter resets after a bring-up attempt"); + assert.equal(f.repinCalls.length, 0, "same-origin respawn needs no repin"); + assert.match(f.logs.join("\n"), /respawned at http:\/\/127\.0\.0\.1:\d+/); +}); + +test("watchdogTick: explicit pin stays strict-port with the exact port", async () => { + const f = tickFixture(); + const plan = { port: 18801, strict: true }; + const log = (m: string) => f.logs.push(m); + for (let i = 0; i < 3; i++) await watchdogTick(f.state, plan, f.deps, log); + assert.equal(f.ensureCalls[0].opts.port, 18801); + assert.equal(f.ensureCalls[0].opts.strictPort, true); +}); + +test("watchdogTick: drifted respawn repins settings and follows in BILI_MCP_PROXY", async () => { + const prevPin = process.env.BILI_MCP_PROXY; + try { + delete process.env.BILI_MCP_PROXY; + const f = tickFixture(); + f.setHandle({ origin: DRIFTED, attached: false }); + const log = (m: string) => f.logs.push(m); + for (let i = 0; i < 3; i++) await watchdogTick(f.state, { port: ZONE_PORT_BASE, strict: false }, f.deps, log); + assert.deepEqual(f.repinCalls, [DRIFTED]); + assert.equal(process.env.BILI_MCP_PROXY, DRIFTED); + assert.equal(f.state.origin, DRIFTED); + } finally { + if (prevPin === undefined) delete process.env.BILI_MCP_PROXY; + else process.env.BILI_MCP_PROXY = prevPin; + } +}); + +test("watchdogTick: attached same-origin is a no-op beyond logging", async () => { + const f = tickFixture(); + f.setHandle({ origin: ORIGIN, attached: true }); + const log = (m: string) => f.logs.push(m); + for (let i = 0; i < 3; i++) await watchdogTick(f.state, { port: ZONE_PORT_BASE, strict: false }, f.deps, log); + assert.equal(f.repinCalls.length, 0); + assert.match(f.logs.join("\n"), /attached at/); +}); + +test("watchdogTick: refusedWatcher surfaces the #1322 warning", async () => { + const f = tickFixture(); + f.setHandle({ origin: ORIGIN, attached: true, refusedWatcher: true }); + const log = (m: string) => f.logs.push(m); + for (let i = 0; i < 3; i++) await watchdogTick(f.state, { port: ZONE_PORT_BASE, strict: false }, f.deps, log); + assert.match(f.logs.join("\n"), /NO session-lifecycle watchdog \(#1322\)/); +}); + +test("watchdogTick: a failing repin is non-fatal — state still follows the new origin", async () => { + const prevPin = process.env.BILI_MCP_PROXY; + try { + delete process.env.BILI_MCP_PROXY; + const f = tickFixture(); + f.setHandle({ origin: DRIFTED, attached: false }); + f.deps.repin = () => { throw new Error("settings unreadable"); }; + const log = (m: string) => f.logs.push(m); + for (let i = 0; i < 3; i++) await watchdogTick(f.state, { port: ZONE_PORT_BASE, strict: false }, f.deps, log); + assert.equal(f.state.origin, DRIFTED); + assert.equal(process.env.BILI_MCP_PROXY, DRIFTED); + assert.match(f.logs.join("\n"), /repin failed \(non-fatal\)/); + } finally { + if (prevPin === undefined) delete process.env.BILI_MCP_PROXY; + else process.env.BILI_MCP_PROXY = prevPin; + } +}); + +test("startWatchdog: fires on repeated death and survives via unref'd timer", async () => { + const f = tickFixture(); + const state: MutableWatchdogState = { origin: ORIGIN, failures: 0 }; + const timer = startWatchdog(state, { port: ZONE_PORT_BASE, strict: false }, (m) => f.logs.push(m), { ...f.deps, intervalMs: 5 }); + try { + const deadline = Date.now() + 5000; + while (f.ensureCalls.length === 0 && Date.now() < deadline) await new Promise((r) => setTimeout(r, 10)); + assert.ok(f.ensureCalls.length >= 1, "watchdog brought the proxy back"); + } finally { + clearInterval(timer); + } +}); + +test("main: NODE_TEST_CONTEXT short-circuits before anything runs", async () => { + let stdio = 0; + await withEnv({ NODE_TEST_CONTEXT: "1" }, async () => { + await main({ runStdio: () => { stdio += 1; } }); + }); + assert.equal(stdio, 0); +}); + +test("main: attach posture serves tools only, never arms the watchdog", async () => { + const box = sandbox(); + let stdio = 0; + const ensureCalls: unknown[] = []; + try { + await withEnv( + { NODE_TEST_CONTEXT: undefined, BILLION_CONTEXT_PROXY: "http://127.0.0.1:9999/v1", BILI_NATIVE_CLAUDE: undefined, BILLION_CONTEXT_PLUGIN: undefined, BILI_PROVIDER_REWRITES: undefined, BILI_MCP_PROXY: undefined }, + async () => { + await main({ + runStdio: () => { stdio += 1; }, + ensure: async () => { ensureCalls.push(1); return { origin: ORIGIN, port: 0 }; }, + intervalMs: 10, + failureLimit: 1, + }); + }, + ); + assert.equal(stdio, 1); + await new Promise((r) => setTimeout(r, 60)); + assert.equal(ensureCalls.length, 0, "attach posture must never respawn beside the user's own proxy"); + } finally { + rmrf(box.dir); + } +}); + +test("main: passthrough posture (opt-out) serves tools only", async () => { + const box = sandbox(); + let stdio = 0; + try { + await withEnv( + { NODE_TEST_CONTEXT: undefined, BILI_NATIVE_CLAUDE: "0", BILLION_CONTEXT_PROXY: undefined, BILLION_CONTEXT_PLUGIN: undefined, BILI_PROVIDER_REWRITES: undefined, BILI_MCP_PROXY: undefined }, + async () => { + await main({ runStdio: () => { stdio += 1; }, intervalMs: 10_000 }); + }, + ); + assert.equal(stdio, 1); + } finally { + rmrf(box.dir); + } +}); + +test("main: native posture arms the watchdog on the managed-block origin", async () => { + const box = sandbox(); + fs.writeFileSync(box.settings, JSON.stringify({ env: { ANTHROPIC_BASE_URL: `${ORIGIN}/bili/https://api.anthropic.com` } })); + let stdio = 0; + const probes: string[] = []; + try { + await withEnv( + { NODE_TEST_CONTEXT: undefined, BILI_NATIVE_CLAUDE: undefined, BILLION_CONTEXT_PROXY: undefined, BILLION_CONTEXT_PLUGIN: undefined, BILI_PROVIDER_REWRITES: undefined, BILI_MCP_PROXY: undefined }, + async () => { + await main({ + runStdio: () => { stdio += 1; }, + probe: async (o) => { probes.push(o); return true; }, + intervalMs: 5, + }); + const deadline = Date.now() + 5000; + while (probes.length === 0 && Date.now() < deadline) await new Promise((r) => setTimeout(r, 10)); + assert.ok(probes.length >= 1, "watchdog armed and probing"); + assert.equal(probes[0], ORIGIN, "tracks the origin the running session dialed"); + }, + ); + } finally { + rmrf(box.dir); + } +}); + +// — installer MCP face migration (fake claude CLI that logs its invocations) — + +function fakeClaudeLog(dir: string): { cli: string; logFile: string } { + const isWin = process.platform === "win32"; + const logFile = path.join(dir, "claude-cli.log"); + const script = path.join(dir, isWin ? "claude-fake.cmd" : "claude-fake"); + fs.writeFileSync(script, isWin ? `@echo %* >> ${logFile}\r\n@exit /b 0\r\n` : `#!/bin/sh\necho "$@" >> ${JSON.stringify(logFile)}\nexit 0\n`); + if (!isWin) fs.chmodSync(script, 0o755); + return { cli: script, logFile }; +} + +function cliLog(logFile: string): string[] { + if (!fs.existsSync(logFile)) return []; + return fs.readFileSync(logFile, "utf8").trim().split("\n").filter((l) => l.length > 0); +} + +function mcpFaceSandbox(): { box: ReturnType; cli: string; logFile: string; cleanup: () => void } { + const box = sandbox(); + const { cli, logFile } = fakeClaudeLog(box.dir); + const prevClaude = process.env.CLAUDE; + const prevOpt = process.env.BILI_NATIVE_CLAUDE; + process.env.CLAUDE = cli; + delete process.env.BILI_NATIVE_CLAUDE; + return { + box, cli, logFile, + cleanup: () => { + rmrf(box.dir); + if (prevClaude === undefined) delete process.env.CLAUDE; + else process.env.CLAUDE = prevClaude; + if (prevOpt === undefined) delete process.env.BILI_NATIVE_CLAUDE; + else process.env.BILI_NATIVE_CLAUDE = prevOpt; + }, + }; +} + +function writeMcpBili(box: { mcpJson: string }, entry: Record): void { + fs.mkdirSync(path.dirname(box.mcpJson), { recursive: true }); + fs.writeFileSync(box.mcpJson, JSON.stringify({ mcpServers: { bili: entry } }, null, 2)); +} + +test("installer: fresh machine registers the watchdog entry", () => { + const { box, logFile, cleanup } = mcpFaceSandbox(); + try { + const note = pluginInstall("claude"); + assert.match(note, /MCP face -> .*pinned http:\/\/127\.0\.0\.1:\d+/); + const calls = cliLog(logFile); + assert.equal(calls.length, 1); + assert.ok(calls[0].startsWith("mcp add bili --scope user"), calls[0]); + const expected = path.join(selfPackageRoot(), "dist", "claude-mcp-entry.js").replace(/\\/g, "/"); + assert.ok(calls[0].replace(/\\/g, "/").includes(expected), calls[0]); + } finally { + cleanup(); + } +}); + +test("installer: legacy dist/mcp.js registration is migrated (remove + add)", () => { + const { box, logFile, cleanup } = mcpFaceSandbox(); + try { + writeMcpBili(box, { + type: "stdio", + command: "node", + args: [path.join(selfPackageRoot(), "dist", "mcp.js")], + env: { BILI_MCP_PROXY: ORIGIN }, + }); + const note = pluginInstall("claude"); + assert.match(note, /migrated from dist\/mcp\.js/); + const calls = cliLog(logFile); + assert.equal(calls.length, 2); + assert.ok(calls[0].startsWith("mcp remove bili --scope user"), calls[0]); + assert.ok(calls[1].startsWith("mcp add bili --scope user"), calls[1]); + } finally { + cleanup(); + } +}); + +test("installer: current registration with matching pin is left alone", () => { + const { box, logFile, cleanup } = mcpFaceSandbox(); + try { + writeMcpBili(box, { + type: "stdio", + command: "node", + args: [path.join(selfPackageRoot(), "dist", "claude-mcp-entry.js")], + env: { BILI_MCP_PROXY: `http://127.0.0.1:${ZONE_PORT_BASE}` }, + }); + const note = pluginInstall("claude"); + assert.match(note, /MCP face current/); + assert.equal(cliLog(logFile).length, 0); + } finally { + cleanup(); + } +}); + +test("installer: our entry with a stale port pin gets re-pinned", () => { + const { box, logFile, cleanup } = mcpFaceSandbox(); + try { + writeMcpBili(box, { + type: "stdio", + command: "node", + args: [path.join(selfPackageRoot(), "dist", "claude-mcp-entry.js")], + env: { BILI_MCP_PROXY: "http://127.0.0.1:1" }, + }); + const note = pluginInstall("claude"); + assert.match(note, /re-pinned/); + const calls = cliLog(logFile); + assert.equal(calls.length, 2); + assert.ok(calls[0].startsWith("mcp remove bili --scope user"), calls[0]); + assert.ok(calls[1].startsWith("mcp add bili --scope user"), calls[1]); + } finally { + cleanup(); + } +}); + +test("installer: a foreign bili server keeps its registration untouched", () => { + const { box, logFile, cleanup } = mcpFaceSandbox(); + try { + writeMcpBili(box, { type: "stdio", command: "/usr/bin/python3", args: ["my-bili.py"] }); + const before = fs.readFileSync(box.mcpJson, "utf8"); + const note = pluginInstall("claude"); + assert.match(note, /foreign bili server/); + assert.equal(cliLog(logFile).length, 0); + assert.equal(fs.readFileSync(box.mcpJson, "utf8"), before); + } finally { + cleanup(); + } +}); + +test("installer: unreadable .claude.json falls back to plain add", () => { + const { box, logFile, cleanup } = mcpFaceSandbox(); + try { + fs.mkdirSync(path.dirname(box.mcpJson), { recursive: true }); + fs.writeFileSync(box.mcpJson, "{ not json"); + const note = pluginInstall("claude"); + assert.match(note, /MCP face -> .*pinned/); + const calls = cliLog(logFile); + assert.equal(calls.length, 1); + assert.ok(calls[0].startsWith("mcp add bili --scope user"), calls[0]); + } finally { + cleanup(); + } +}); diff --git a/tsup.config.ts b/tsup.config.ts index e25f2505f5..a82932d239 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -4,7 +4,7 @@ import { defineConfig } from "tsup"; export default [ defineConfig({ - entry: ["src/index.ts", "src/mcp.ts", "src/claude-native-bootstrap.ts", "src/agent/pi.ts", "src/agent/pi-native.ts", "src/agent/omp.ts", "src/agent/omp-native.ts", "src/agent/opencode.ts", "src/agent/opencode-native.ts", "src/agent/dsh-acp.ts", "src/agent/dsh-native.ts", "src/kimi/native-mcp.ts", "src/kimi/bootstrap-hook.ts", "src/zcode/mcp-entry.ts", "src/zcode/bootstrap-hook.ts"], + entry: ["src/index.ts", "src/mcp.ts", "src/claude-mcp-entry.ts", "src/claude-native-bootstrap.ts", "src/agent/pi.ts", "src/agent/pi-native.ts", "src/agent/omp.ts", "src/agent/omp-native.ts", "src/agent/opencode.ts", "src/agent/opencode-native.ts", "src/agent/dsh-acp.ts", "src/agent/dsh-native.ts", "src/kimi/native-mcp.ts", "src/kimi/bootstrap-hook.ts", "src/zcode/mcp-entry.ts", "src/zcode/bootstrap-hook.ts"], format: ["esm"], target: "node20", platform: "node", From 60c5c3a62bdf1bb2968a737fa54a902812c7fed9 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Thu, 1 Oct 2026 23:09:38 +0800 Subject: [PATCH 2/9] fix(claude-mcp): keep the watchdog counter hot across a failed bring-up (zcode parity) Review fix for #1874: the counter was reset BEFORE ensureProxyRunning, so a throwing bring-up cooled it down and cost another full failure cycle (~90 s) before retrying. zcode resets only after a completed bring-up and retries on the very next tick. Move the reset after the log line and pin the semantics with a regression test. --- src/claude-mcp-entry.ts | 5 ++++- tests/claude-mcp-entry.test.ts | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/claude-mcp-entry.ts b/src/claude-mcp-entry.ts index ee359bb2bb..f0be0c2fa6 100644 --- a/src/claude-mcp-entry.ts +++ b/src/claude-mcp-entry.ts @@ -74,7 +74,6 @@ export async function watchdogTick(state: MutableWatchdogState, plan: { port: nu } state.failures += 1; if (state.failures < limit) return; - state.failures = 0; const ensure = deps.ensure ?? ensureProxyRunning; const handle = await ensure( { @@ -103,6 +102,10 @@ export async function watchdogTick(state: MutableWatchdogState, plan: { port: nu state.origin = handle.origin; } log(`proxy ${handle.attached ? "attached" : "respawned"} at ${handle.origin}`); + // Cool the counter only once the bring-up actually completed — a failed + // attempt leaves it hot so the NEXT tick retries immediately (zcode parity): + // a transient spawn failure must not cost another full failure cycle. + state.failures = 0; } export function startWatchdog(state: MutableWatchdogState, plan: { port: number; strict: boolean }, log: (msg: string) => void, deps: WatchdogDeps = {}): NodeJS.Timeout { diff --git a/tests/claude-mcp-entry.test.ts b/tests/claude-mcp-entry.test.ts index ead76540ec..a1ea5c1b88 100644 --- a/tests/claude-mcp-entry.test.ts +++ b/tests/claude-mcp-entry.test.ts @@ -181,6 +181,26 @@ test("watchdogTick: a failing repin is non-fatal — state still follows the new } }); +test("watchdogTick: a failed bring-up keeps the counter hot — immediate retry on the next tick (zcode parity)", async () => { + const f = tickFixture(); + let failEnsure = true; + const ensureAttempts: number[] = []; + f.deps.ensure = async () => { + ensureAttempts.push(1); + if (failEnsure) throw new Error("spawn failed"); + return { port: 0, origin: ORIGIN, attached: false }; + }; + const plan = { port: ZONE_PORT_BASE, strict: false }; + const log = (m: string) => f.logs.push(m); + for (let i = 0; i < 3; i++) await watchdogTick(f.state, plan, f.deps, log).catch(() => {}); + assert.equal(ensureAttempts.length, 1); + assert.equal(f.state.failures, 3, "counter stays hot when the bring-up throws"); + failEnsure = false; + await watchdogTick(f.state, plan, f.deps, log); + assert.equal(ensureAttempts.length, 2, "no second failure cycle — retries on the very next tick"); + assert.equal(f.state.failures, 0); +}); + test("startWatchdog: fires on repeated death and survives via unref'd timer", async () => { const f = tickFixture(); const state: MutableWatchdogState = { origin: ORIGIN, failures: 0 }; From ce20dbb8075d7d4178cf1cec0063a92c1e8b2384 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Thu, 1 Oct 2026 23:11:49 +0800 Subject: [PATCH 3/9] =?UTF-8?q?docs:=20CONFIGURATION=20en/zh=20=E2=80=94?= =?UTF-8?q?=20claude's=20MCP=20face=20now=20points=20at=20dist/claude-mcp-?= =?UTF-8?q?entry.js=20(#1821)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review fix for #1874: both CONFIGURATION docs still said every no-plugin-API host installs the MCP bridge at dist/mcp.js; after this PR claude registers dist/claude-mcp-entry.js instead (codex keeps plain dist/mcp.js). The zh line also listed opencode among hosts WITHOUT a plugin API while the en line and the code (opencode-native) say otherwise — aligned to the en wording. --- CONFIGURATION.md | 2 +- CONFIGURATION.zh-CN.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index e6a77f5502..3ea8445deb 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -2092,7 +2092,7 @@ bili plugin remove pi # undo (original files backed up to *.bili-bak once) **Coexistence with the standalone `billion-context-pi` extension.** The two are mutually exclusive — both active means double compression. Three nets: the installer strip above (global settings), the `BILLION_CONTEXT_NATIVE=pi` marker the native entry sets synchronously at load (`billion-context-pi` **0.1.72+** re-reads it on every event and refuses; 0.1.71 and older check `BILLION_CONTEXT_PROXY` only at load time, before the native proxy exists), and a runtime scan: once its proxy is up, the pi-native entry reads both pi settings files and warns loudly about any co-resident legacy entry the installer never saw (project scope, or installed after the fact). -The installed plugin is a **thin** one (~5 KB, zero runtime deps): it detects the proxy (from the `/bili/` baseURL or `BILLION_CONTEXT_PROXY`), fetches tool schemas from the proxy, registers native tools, and forwards executions — the proxy remains the single compression authority, so plugin and proxy always match versions. Hosts without a plugin API (claude, codex) install the MCP bridge (`dist/mcp.js`) instead — same protocol underneath, though MCP has no slash-commands (no `/acp` panel command; claude additionally gets a model-mediated `/acp-cache` markdown command written to `/commands/acp-cache.md`, whose prompt drives the `acp_cache` MCP tool — the model pastes the report back verbatim). opencode has its own plugin API, so its install adds the native plugin tools and no MCP face by default (`--with-mcp` opts in; the entry carries no `BILI_MCP_PROXY` pin — `dist/mcp.js` discovers the live proxy via the instance file at call time, which survives the native plugin's ephemeral-port restarts, #926). +The installed plugin is a **thin** one (~5 KB, zero runtime deps): it detects the proxy (from the `/bili/` baseURL or `BILLION_CONTEXT_PROXY`), fetches tool schemas from the proxy, registers native tools, and forwards executions — the proxy remains the single compression authority, so plugin and proxy always match versions. Hosts without a plugin API (claude, codex) install the MCP bridge instead — claude gets `dist/claude-mcp-entry.js` (the same bridge plus the mid-session proxy watchdog that respawns a dead lane proxy, #1821), codex the plain `dist/mcp.js` — same protocol underneath, though MCP has no slash-commands (no `/acp` panel command; claude additionally gets a model-mediated `/acp-cache` markdown command written to `/commands/acp-cache.md`, whose prompt drives the `acp_cache` MCP tool — the model pastes the report back verbatim). opencode has its own plugin API, so its install adds the native plugin tools and no MCP face by default (`--with-mcp` opts in; the entry carries no `BILI_MCP_PROXY` pin — `dist/mcp.js` discovers the live proxy via the instance file at call time, which survives the native plugin's ephemeral-port restarts, #926). Kill switch: `BILLION_CONTEXT_PLUGIN=0` disables plugin mode entirely (wire-level injection resumes). diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 46e0b056e1..7ec741d7df 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -2063,7 +2063,7 @@ bili plugin remove pi # 撤销(原文件一次性备份为 *.bili-bak) `install pi` 还会替换**遗留的** billion-context 条目(旧的 `npm:billion-context-pi` 引用、过期的 `npm:billion-context@x.y.z`、残留的 dev 目录路径),确保只有恰好一个 bili 插件在生效。 -安装的插件是**薄**插件(约 5 KB,零运行时依赖):它检测代理(从 `/bili/` baseURL 或 `BILLION_CONTEXT_PROXY`)、从代理拉取工具 schema、注册原生工具、转发执行 —— 代理始终是唯一的压缩引擎,所以插件与代理永远版本一致。没有插件 API 的宿主(claude、codex、opencode)改装 MCP 桥(`dist/mcp.js`)—— 底层协议相同,但 MCP 没有斜杠命令(没有 `/acp`;claude 额外获得模型中介的 `/acp-cache` markdown 命令,写入 `/commands/acp-cache.md`,其提示词驱动 `acp_cache` MCP 工具 —— 模型把报告原样贴回)。 +安装的插件是**薄**插件(约 5 KB,零运行时依赖):它检测代理(从 `/bili/` baseURL 或 `BILLION_CONTEXT_PROXY`)、从代理拉取工具 schema、注册原生工具、转发执行 —— 代理始终是唯一的压缩引擎,所以插件与代理永远版本一致。没有插件 API 的宿主(claude、codex)改装 MCP 桥 —— claude 装 `dist/claude-mcp-entry.js`(同一桥加会话内代理守护,lane 代理死亡时自动重生,#1821),codex 装纯 `dist/mcp.js` —— 底层协议相同,但 MCP 没有斜杠命令(没有 `/acp`;claude 额外获得模型中介的 `/acp-cache` markdown 命令,写入 `/commands/acp-cache.md`,其提示词驱动 `acp_cache` MCP 工具 —— 模型把报告原样贴回)。 总开关:`BILLION_CONTEXT_PLUGIN=0` 彻底关闭插件模式(恢复 wire 层注入)。 From 68582d7fde5a3dfbc3957cc05bca434f667c200e Mon Sep 17 00:00:00 2001 From: ework-agent Date: Thu, 1 Oct 2026 23:31:35 +0800 Subject: [PATCH 4/9] test(claude-mcp): normalize the fake CLI log across platforms (Windows CI red) CI review of #1874: both windows-latest jobs failed in the 4 installer-matrix tests. On Windows runClaudeCli routes .cmd shims through the shell with per-token quoting (src/plugin-install.ts), so the fake claude's %* log lines come back as '"mcp" "add" ...' with CRLF endings instead of plain LF tokens. cliLog() asserted the Linux shape verbatim. Normalize quotes + line endings before asserting; production invocation is untouched (the real claude CLI gets identical argv after CommandLineToArgvW unquoting). --- tests/claude-mcp-entry.test.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/claude-mcp-entry.test.ts b/tests/claude-mcp-entry.test.ts index a1ea5c1b88..59ad6619ea 100644 --- a/tests/claude-mcp-entry.test.ts +++ b/tests/claude-mcp-entry.test.ts @@ -298,9 +298,16 @@ function fakeClaudeLog(dir: string): { cli: string; logFile: string } { return { cli: script, logFile }; } +// Log lines are platform-shaped: on Windows the fake runs through cmd.exe +// (%* comes back per-token-quoted with CRLF — runClaudeCli's .cmd shim path), +// so normalize quotes + line endings before asserting. function cliLog(logFile: string): string[] { if (!fs.existsSync(logFile)) return []; - return fs.readFileSync(logFile, "utf8").trim().split("\n").filter((l) => l.length > 0); + return fs.readFileSync(logFile, "utf8") + .replace(/"/g, "") + .split(/\r?\n/) + .map((l) => l.trim()) + .filter((l) => l.length > 0); } function mcpFaceSandbox(): { box: ReturnType; cli: string; logFile: string; cleanup: () => void } { From 417230c3db15e287b5f3d587f944c1c9d929cac5 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 11 Oct 2026 11:42:26 +0800 Subject: [PATCH 5/9] test(claude-mcp): adapt fixture to new-master launcher typings (#1821) master history rewrite landed a launcher API drift: ProxyHandle/LaunchOptions are no longer exported and LaunchOptions.parentPid is optional. The test now derives its types from ensureProxyRunning (Parameters/Awaited) and builds explicit handle literals. --- tests/claude-mcp-entry.test.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/tests/claude-mcp-entry.test.ts b/tests/claude-mcp-entry.test.ts index 59ad6619ea..889faee7fa 100644 --- a/tests/claude-mcp-entry.test.ts +++ b/tests/claude-mcp-entry.test.ts @@ -11,7 +11,10 @@ import os from "node:os"; import path from "node:path"; import { main, startWatchdog, watchdogTick, type MutableWatchdogState, type WatchdogDeps } from "../src/claude-mcp-entry.ts"; import { pluginInstall, readClaudeManagedBaseUrl, selfPackageRoot } from "../src/plugin-install.ts"; -import { LAUNCHER_DEFAULT_HOST, type LaunchOptions, type ProxyHandle } from "../src/launcher.ts"; +import { LAUNCHER_DEFAULT_HOST, ensureProxyRunning, type LauncherDeps } from "../src/launcher.ts"; + +type LaunchOpts = Parameters[0]; +type FakeHandle = { origin: string; attached?: boolean; refusedWatcher?: boolean }; import { ZONE_PORT_BASE } from "../src/config.ts"; import { rmrf } from "./tmp-rm.ts"; @@ -47,19 +50,19 @@ function tickFixture(origin: string = ORIGIN): { state: MutableWatchdogState; deps: WatchdogDeps; logs: string[]; - ensureCalls: Array<{ opts: LaunchOptions; deps: Record }>; + ensureCalls: Array<{ opts: LaunchOpts; deps: LauncherDeps | undefined }>; repinCalls: string[]; setProbe: (ok: boolean) => void; - setHandle: (h: Partial) => void; + setHandle: (h: FakeHandle) => void; } { let probeOk = false; - let handle: Partial = { origin, attached: false }; + let handle: FakeHandle = { origin, attached: false }; const logs: string[] = []; - const ensureCalls: Array<{ opts: LaunchOptions; deps: Record }> = []; + const ensureCalls: Array<{ opts: LaunchOpts; deps: LauncherDeps | undefined }> = []; const repinCalls: string[] = []; const deps: WatchdogDeps = { probe: async () => probeOk, - ensure: async (opts, d) => { ensureCalls.push({ opts, deps: d }); return { port: 0, ...handle }; }, + ensure: async (opts, d) => { ensureCalls.push({ opts, deps: d }); return { port: 0, origin: handle.origin, attached: handle.attached, refusedWatcher: handle.refusedWatcher }; }, repin: (o) => { repinCalls.push(o); return ["repinned"]; }, failureLimit: 3, }; @@ -108,12 +111,13 @@ test("watchdogTick: third consecutive death respawns with hook-equivalent zone s await watchdogTick(f.state, plan, f.deps, log); assert.equal(f.ensureCalls.length, 1); const { opts, deps } = f.ensureCalls[0]; + assert.ok(deps); assert.equal(opts.host, LAUNCHER_DEFAULT_HOST); assert.equal(opts.port, 0, "zone mode passes port 0 so the launcher settles the sticky record"); assert.equal(opts.strictPort, false); assert.equal(opts.passthrough, false); assert.equal(opts.lane, "claude"); - assert.ok(opts.parentPid > 1, "watches a real parent pid"); + assert.ok((opts.parentPid ?? 0) > 1, "watches a real parent pid"); assert.equal(path.basename(String(deps.scriptPath)), "index.js", "spawns the package bin, not this entry"); assert.equal(f.state.failures, 0, "counter resets after a bring-up attempt"); assert.equal(f.repinCalls.length, 0, "same-origin respawn needs no repin"); From c9d47ae57f3a277cc33a6d00a3c2d1fcb6dbf594 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 13 Oct 2026 00:09:10 +0800 Subject: [PATCH 6/9] fix(zcode-mcp): watchdog recovers dead lane-owned proxies, waits only on user pins (#1821) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The zcode watchdog treated every 'attached at bootstrap' proxy as externally owned and only logged 'waiting for it to recover' — but attached=true also fires when ensureProxyRunning finds a LANE-owned instance alive at bootstrap time, including one spawned by a concurrent session. A death of that proxy then stranded the session until the next SessionStart boot (external repro on v0.1.184/Windows). - native.ts: BootstrapMode gains externallyOwned — true ONLY for an explicit user pin (plan.mode === attach); exported ZcodeRouteApplied. - mcp-entry.ts: watchdog tick now recovers (ensureProxyRunning + re-route on origin drift) for lane-owned proxies and keeps the wait-only behavior for user pins; same-origin recovery logs 'recovered without a re-route'. Exported zcodeWatchdogTick/ZcodeWatchdogDeps/state types for tests. - Behavior change (old→new): zcode lane, proxy found alive at session start then dies mid-session: stranded until next session → auto-recovery within ~90s (30s x 3 failures), same semantics as the spawn case and as the claude lane in this PR. User-pin attach posture is unchanged. - Tests: new tests/zcode-mcp-entry.test.ts (8) + bootstrap externallyOwned assertions in tests/zcode-native.test.ts. --- src/zcode/mcp-entry.ts | 120 +++++++++++++++++---------- src/zcode/native.ts | 10 ++- tests/zcode-mcp-entry.test.ts | 147 ++++++++++++++++++++++++++++++++++ tests/zcode-native.test.ts | 22 +++++ 4 files changed, 256 insertions(+), 43 deletions(-) create mode 100644 tests/zcode-mcp-entry.test.ts diff --git a/src/zcode/mcp-entry.ts b/src/zcode/mcp-entry.ts index 47a062e6b4..92bd84f5bf 100644 --- a/src/zcode/mcp-entry.ts +++ b/src/zcode/mcp-entry.ts @@ -33,53 +33,91 @@ const WATCHDOG_INTERVAL_MS = 30000; const WATCHDOG_FAILURE_LIMIT = 3; const HANDOFF_TIMEOUT_MS = 5000; +export interface ZcodeWatchdogDeps { + readonly probe?: typeof probeProxyHealth; + readonly ensure?: (opts: Parameters[0]) => Promise<{ origin: string }>; + readonly route?: typeof routeZcodeConfig; + readonly activate?: typeof activateZcodePluginMode; + readonly repair?: (selfOrigin: string) => Promise; + readonly intervalMs?: number; + readonly failureLimit?: number; +} + +export interface ZcodeWatchdogState { + readonly origin: string; + readonly policy: ZcodeRoutePolicy; +} + +export interface MutableZcodeWatchdogState extends ZcodeWatchdogState { + failures: number; +} + +function buildEnsureOpts(): Parameters[0] { + // #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(); + return { host: LAUNCHER_DEFAULT_HOST, port: explicit ?? 0, passthrough: false, debug: false, strictPort: explicit !== undefined, lane: "zcode" }; +} + +async function defaultEnsure(opts: Parameters[0]): Promise<{ origin: string }> { + const handle = await ensureProxyRunning(opts, { scriptPath: nativeProxyScriptPath() }); + return { origin: handle.origin }; +} + +/** #1821: one watchdog tick. Healthy → counter reset. Unhealthy × limit: + * an externally-owned attach posture (explicit user pin) only waits — that + * proxy is not ours to respawn. Every other case (self-spawned OR attached + * to a lane-owned instance at bootstrap) runs the same ensureProxyRunning + * recovery the spawn path used, so a dead lane proxy heals mid-session + * instead of stranding the session until the next session boot. */ +export async function zcodeWatchdogTick(state: MutableZcodeWatchdogState, externallyOwned: boolean, deps: ZcodeWatchdogDeps, log: (msg: string) => void): Promise { + const probe = deps.probe ?? probeProxyHealth; + const repair = deps.repair ?? ((selfOrigin: string) => repairSharedStoreDrift({ selfOrigin, log })); + if (await probe(state.origin)) { + state.failures = 0; + } else if (state.failures + 1 < (deps.failureLimit ?? WATCHDOG_FAILURE_LIMIT)) { + state.failures += 1; + } else { + state.failures = 0; + if (externallyOwned) { + log(`attached proxy ${state.origin} unhealthy — user-owned attach posture, waiting for it to recover`); + } else { + const ensure = deps.ensure ?? defaultEnsure; + const { origin } = await ensure(buildEnsureOpts()); + if (origin !== state.origin) { + process.env.BILI_MCP_PROXY = origin; + const route = deps.route ?? routeZcodeConfig; + const routed = await route({ origin, log, policy: state.policy }); + if (!routed) throw new Error("proxy respawned but the zcode config rewrite failed"); + const activate = deps.activate ?? activateZcodePluginMode; + await activate(routed, { log }); + state.origin = origin; + log(`proxy respawned at ${origin} — config re-routed`); + } else { + log(`proxy ${origin} recovered without a re-route`); + } + } + } + await repair(state.origin); +} + function startWatchdog( - state: { origin: string; policy: ZcodeRoutePolicy }, - attached: boolean, + state: MutableZcodeWatchdogState, + externallyOwned: boolean, log: (msg: string) => void, + deps: ZcodeWatchdogDeps = {}, ): void { - let failures = 0; let busy = false; const timer = setInterval(() => { if (busy) return; busy = true; - void watchdogTick().catch((err) => log(`watchdog error: ${err instanceof Error ? err.message : String(err)}`)) + void zcodeWatchdogTick(state, externallyOwned, deps, log) + .catch((err) => log(`watchdog error: ${err instanceof Error ? err.message : String(err)}`)) .finally(() => { busy = false; }); - - async function watchdogTick(): Promise { - if (await probeProxyHealth(state.origin)) { - failures = 0; - } else { - failures += 1; - if (failures >= WATCHDOG_FAILURE_LIMIT) { - 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: explicit ?? 0, passthrough: false, debug: false, strictPort: explicit !== undefined, lane: "zcode" }, - { scriptPath: nativeProxyScriptPath() }, - ); - if (handle.origin !== state.origin) { - process.env.BILI_MCP_PROXY = handle.origin; - const routed = await routeZcodeConfig({ origin: handle.origin, log, policy: state.policy }); - if (!routed) throw new Error("proxy respawned but the zcode config rewrite failed"); - await activateZcodePluginMode(routed, { log }); - state.origin = handle.origin; - log(`proxy respawned at ${handle.origin} — config re-routed`); - } - } - failures = 0; - } - } - await repairSharedStoreDrift({ selfOrigin: state.origin, log }); - } - }, WATCHDOG_INTERVAL_MS); + }, deps.intervalMs ?? WATCHDOG_INTERVAL_MS); timer.unref?.(); } @@ -196,8 +234,8 @@ export async function main(): Promise { await activateZcodePluginMode(applied, { log }); // #1622: the watchdog respawn path must re-route with the SAME policy // (BILI_ZCODE_ROUTE / providers direct) — not the hardcoded default. - const state = { origin: applied.origin, policy: zcodePolicyFromEnv(process.env) }; - startWatchdog(state, bootstrap.attached, log); + const state = { origin: applied.origin, policy: zcodePolicyFromEnv(process.env), failures: 0 }; + startWatchdog(state, bootstrap.externallyOwned, log); installExitHandoff(state, log); runMcpStdio(); } diff --git a/src/zcode/native.ts b/src/zcode/native.ts index 1eb0f722fd..e4bbb41375 100644 --- a/src/zcode/native.ts +++ b/src/zcode/native.ts @@ -115,7 +115,7 @@ async function withConfigLock(dataDir: string, fn: () => T): Promise { } } -interface ZcodeRouteApplied { +export interface ZcodeRouteApplied { readonly origin: string; readonly port: number; readonly kind: ZcodeStoreKind; @@ -369,6 +369,12 @@ export type BootstrapMode = | { readonly mode: "active"; readonly attached: boolean; + /** #1821: true ONLY for an explicit user pin (attach posture) — a + * proxy this session does not own, which the MCP watchdog must + * never respawn. attached=true alone can also mean "a lane-owned + * proxy happened to be alive at bootstrap" — that one IS bili- + * managed and gets watchdog recovery. */ + readonly externallyOwned: boolean; readonly routed: ZcodeRouteApplied | undefined; }; @@ -477,7 +483,7 @@ export async function bootstrapZcodeNative(opts: BootstrapZcodeOptions = {}): Pr const routed = await routeZcodeConfig({ origin, env, dataDir, log, policy }); if (routed) log(`routed ${routed.wrapped.map((w) => w.id).join(", ")} via ${origin} → ${routed.upstream}`); - return { mode: "active", attached, routed }; + return { mode: "active", attached, externallyOwned: plan.mode === "attach", routed }; } async function defaultEnsureProxy(): Promise<{ origin: string; attached: boolean }> { diff --git a/tests/zcode-mcp-entry.test.ts b/tests/zcode-mcp-entry.test.ts new file mode 100644 index 0000000000..20f6fd26e3 --- /dev/null +++ b/tests/zcode-mcp-entry.test.ts @@ -0,0 +1,147 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { defaultZcodeRoutePolicy } from "../src/zcode/json-edit.ts"; +import type { ZcodeRouteApplied } from "../src/zcode/native.ts"; +import { main, zcodeWatchdogTick } from "../src/zcode/mcp-entry.ts"; +import type { MutableZcodeWatchdogState, ZcodeWatchdogDeps } from "../src/zcode/mcp-entry.ts"; + +const ORIGIN = "http://127.0.0.1:18787"; +const DRIFTED = "http://127.0.0.1:18789"; +const POLICY = defaultZcodeRoutePolicy(); + +function appliedFor(origin: string): ZcodeRouteApplied { + return { origin, port: Number(new URL(origin).port), kind: "new", file: "/store.json", upstream: "https://api.example.com", wrapped: [] }; +} + +interface TickFixture { + state: MutableZcodeWatchdogState; + deps: ZcodeWatchdogDeps; + logs: string[]; + ensureCalls: Array>[0]>; + routeOrigins: string[]; + repairCalls: string[]; + setHealthy: (h: boolean) => void; + setEnsureOrigin: (o: string) => void; + failRoute: (f: boolean) => void; +} + +function tickFixture(origin: string): TickFixture { + const state: MutableZcodeWatchdogState = { origin, policy: POLICY, failures: 0 }; + const logs: string[] = []; + const ensureCalls: TickFixture["ensureCalls"] = []; + const routeOrigins: string[] = []; + const repairCalls: string[] = []; + let healthy = false; + let ensureOrigin = origin; + let routeFails = false; + const deps: ZcodeWatchdogDeps = { + probe: async () => healthy, + ensure: async (opts) => { ensureCalls.push(opts); return { origin: ensureOrigin }; }, + route: async ({ origin: o }) => { if (routeFails) return undefined; routeOrigins.push(o); return appliedFor(o); }, + activate: async () => {}, + repair: async (selfOrigin) => { repairCalls.push(selfOrigin); }, + failureLimit: 3, + }; + return { + state, deps, logs, ensureCalls, routeOrigins, repairCalls, + setHealthy: (h: boolean) => { healthy = h; }, + setEnsureOrigin: (o: string) => { ensureOrigin = o; }, + failRoute: (f: boolean) => { routeFails = f; }, + }; +} + +async function runTicks(fx: TickFixture, externallyOwned: boolean, n: number): Promise { + for (let i = 0; i < n; i++) await zcodeWatchdogTick(fx.state, externallyOwned, fx.deps, (m) => fx.logs.push(m)); +} + +test("healthy tick resets the failure counter without any recovery", async () => { + const fx = tickFixture(ORIGIN); + await runTicks(fx, false, 2); + assert.equal(fx.state.failures, 2); + fx.setHealthy(true); + await runTicks(fx, false, 1); + assert.equal(fx.state.failures, 0); + assert.equal(fx.ensureCalls.length, 0); +}); + +test("below-limit failures never trigger recovery but still repair the store", async () => { + const fx = tickFixture(ORIGIN); + await runTicks(fx, false, 2); + assert.equal(fx.ensureCalls.length, 0); + assert.deepEqual(fx.repairCalls, [ORIGIN, ORIGIN]); +}); + +test("third consecutive failure respawns a dead lane proxy (#1821)", async () => { + const savedPort = process.env.BILI_ZCODE_PORT; + delete process.env.BILI_ZCODE_PORT; + try { + const fx = tickFixture(ORIGIN); + await runTicks(fx, false, 3); + assert.equal(fx.ensureCalls.length, 1); + const opts = fx.ensureCalls[0]; + assert.equal(opts.host, "127.0.0.1"); + assert.equal(opts.port, 0); + assert.equal(opts.strictPort, false); + assert.equal(opts.lane, "zcode"); + assert.equal(opts.passthrough, false); + // same-origin recovery: no re-route, counter reset + assert.equal(fx.routeOrigins.length, 0); + assert.equal(process.env.BILI_MCP_PROXY, undefined); + assert.equal(fx.state.failures, 0); + assert.ok(fx.logs.some((l) => l.includes("recovered without a re-route"))); + } finally { + if (savedPort === undefined) delete process.env.BILI_ZCODE_PORT; else process.env.BILI_ZCODE_PORT = savedPort; + } +}); + +test("an explicit BILI_ZCODE_PORT pin stays strict on respawn", async () => { + const saved = process.env.BILI_ZCODE_PORT; + process.env.BILI_ZCODE_PORT = "18801"; + try { + const fx = tickFixture(ORIGIN); + await runTicks(fx, false, 3); + assert.equal(fx.ensureCalls.length, 1); + assert.equal(fx.ensureCalls[0].port, 18801); + assert.equal(fx.ensureCalls[0].strictPort, true); + } finally { + if (saved === undefined) delete process.env.BILI_ZCODE_PORT; else process.env.BILI_ZCODE_PORT = saved; + } +}); + +test("origin drift re-routes the config and follows the new origin (#1821)", async () => { + const savedProxy = process.env.BILI_MCP_PROXY; + delete process.env.BILI_MCP_PROXY; + try { + const fx = tickFixture(ORIGIN); + fx.setEnsureOrigin(DRIFTED); + await runTicks(fx, false, 3); + assert.equal(fx.state.origin, DRIFTED); + assert.equal(process.env.BILI_MCP_PROXY, DRIFTED); + assert.deepEqual(fx.routeOrigins, [DRIFTED]); + assert.ok(fx.logs.some((l) => l.includes("config re-routed"))); + } finally { + if (savedProxy === undefined) delete process.env.BILI_MCP_PROXY; else process.env.BILI_MCP_PROXY = savedProxy; + } +}); + +test("a failed config rewrite throws so the watchdog error surfaces", async () => { + const fx = tickFixture(ORIGIN); + fx.setEnsureOrigin(DRIFTED); + fx.failRoute(true); + await assert.rejects(runTicks(fx, false, 3), /config rewrite failed/); +}); + +test("externally-owned attach posture never respawns — it waits (#1821)", async () => { + const fx = tickFixture(ORIGIN); + await runTicks(fx, true, 6); + assert.equal(fx.ensureCalls.length, 0); + assert.ok(fx.logs.some((l) => l.includes("user-owned attach posture"))); + assert.equal(fx.repairCalls.length, 6); + assert.equal(fx.state.failures, 0); +}); + +test("main() short-circuits under NODE_TEST_CONTEXT", async () => { + assert.notEqual(process.env.NODE_TEST_CONTEXT, undefined); + await main(); +}); diff --git a/tests/zcode-native.test.ts b/tests/zcode-native.test.ts index 037481d9ab..d4ec19845b 100644 --- a/tests/zcode-native.test.ts +++ b/tests/zcode-native.test.ts @@ -221,6 +221,7 @@ test("bootstrapZcodeNative attaches to a healthy proxy and routes", async () => assert.equal(out.mode, "active"); if (out.mode !== "active") return; assert.equal(out.attached, true); + assert.equal(out.externallyOwned, true); assert.ok(out.routed); assert.equal(out.routed.origin, origin); }); @@ -256,6 +257,7 @@ test("bootstrapZcodeNative spawns through the injected ensureProxy seam", async assert.equal(out.mode, "active"); if (out.mode !== "active") return; assert.equal(out.attached, false); + assert.equal(out.externallyOwned, false); assert.ok(out.routed); assert.equal(out.routed.origin, origin); }); @@ -264,6 +266,26 @@ test("bootstrapZcodeNative spawns through the injected ensureProxy seam", async } }); +test("bootstrap marks a lane-owned instance found alive at bootstrap as NOT externally owned (#1821)", async () => { + const dir = dataDir(); + try { + await withHealthServer(async (origin) => { + const out = await bootstrapZcodeNative({ + env: {}, + dataDir: dir, + log: () => {}, + ensureProxy: async () => ({ origin, attached: true }), + }); + assert.equal(out.mode, "active"); + if (out.mode !== "active") return; + assert.equal(out.attached, true); + assert.equal(out.externallyOwned, false); + }); + } finally { + rmrf(dir); + } +}); + test("bootstrap honors upstream env relocation: ZCODE_DATA_BASE_DIR is a base dir (#1151)", async () => { const base = mkdtempSync(path.join(tmpdir(), "zcode-native-base-")); try { From 844f192b82b00a65cbad2c59b6675dacef2817b3 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 13 Oct 2026 00:12:14 +0800 Subject: [PATCH 7/9] fix(zcode-mcp): redeclare origin mutable on the watchdog state (typecheck) --- src/zcode/mcp-entry.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/zcode/mcp-entry.ts b/src/zcode/mcp-entry.ts index 92bd84f5bf..269b5d67f3 100644 --- a/src/zcode/mcp-entry.ts +++ b/src/zcode/mcp-entry.ts @@ -49,6 +49,7 @@ export interface ZcodeWatchdogState { } export interface MutableZcodeWatchdogState extends ZcodeWatchdogState { + origin: string; failures: number; } From 15e9fcffca6cd03dbe1a1f79674d977fa110dd02 Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 16 Oct 2026 09:29:02 +0800 Subject: [PATCH 8/9] fix(ci): sync unused-export gate entry list with tsup entries (#1821) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI on the rebased head failed in unused-exports (gate #1440 P6, landed on master after this PR was written): 'INTERNAL_ONLY src/claude-mcp-entry.ts: WatchdogState'. Root cause is drift, not a dead symbol — this PR added src/claude-mcp-entry.ts as a tsup entry, and the gate's ENTRY_FILES list is contractually kept in sync with tsup.config.ts entry ('a missing entry here gets over-gated'); its zcode twin src/zcode/mcp-entry.ts is already listed. Add the missing entry; WatchdogState/MutableWatchdogState stay exported so the test import of MutableWatchdogSource keeps working. --- scripts/check-unused-exports.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/check-unused-exports.mjs b/scripts/check-unused-exports.mjs index fb016d4fb0..d171c8d7c0 100644 --- a/scripts/check-unused-exports.mjs +++ b/scripts/check-unused-exports.mjs @@ -24,6 +24,7 @@ const root = process.cwd(); const ENTRY_FILES = new Set([ "src/index.ts", "src/mcp.ts", + "src/claude-mcp-entry.ts", "src/claude-native-bootstrap.ts", "src/agent/pi.ts", "src/agent/pi-native.ts", From 17fad2ed998828b70bcab5f9c2b8ac8024974bc6 Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 16 Oct 2026 09:44:58 +0800 Subject: [PATCH 9/9] fix(ci): sync test-import-graph gate entry list with tsup entries (#1821) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second instance of the same drift: scripts/check-test-import-graph.mjs (#2989, landed on master after this PR's new tsup entry) keeps its own ENTRY_FILES list ('same list as scripts/check-unused-exports.mjs') that was missing src/claude-mcp-entry.ts, so the gate saw the module as unreachable from production and flagged tests/claude-mcp-entry.test.ts's import as an unlabeled retired-module pin. It is a live production entry (tsup.config.ts), not retired code — add it to the list. Branch also rebased onto current master (was based on Oct-11 master; two new CI gates landed since). --- scripts/check-test-import-graph.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/check-test-import-graph.mjs b/scripts/check-test-import-graph.mjs index c305f2753a..d60dd5171f 100644 --- a/scripts/check-test-import-graph.mjs +++ b/scripts/check-test-import-graph.mjs @@ -35,6 +35,7 @@ const root = process.cwd(); const ENTRY_FILES = new Set([ "src/index.ts", "src/mcp.ts", + "src/claude-mcp-entry.ts", "src/claude-native-bootstrap.ts", "src/agent/pi.ts", "src/agent/pi-native.ts",