diff --git a/README.md b/README.md index 330df3717e..274cde760a 100644 --- a/README.md +++ b/README.md @@ -249,7 +249,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: [docs/clients.md](docs/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. 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: [docs/technical-notes.md](docs/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, matching the CLI behavior of that era — note that newer builds (CC 2.1.301+) DO honour `HTTPS_PROXY` on the CLI, which is why `bili claude` routes via the `/bili/` base-URL rewrite — the launcher gives this lane no proxy and no CA at all, and a child that brings a proxy of its own gets the loopback hosts merged into `NO_PROXY`/`no_proxy` so that leg stays direct regardless of its proxy behavior (#3446). 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. **Account-bound features (#4693):** because the lane routes via a custom `ANTHROPIC_BASE_URL`, Claude Code treats the session as third-party/API-key and disables features bound to your Anthropic account/Cloud — **Remote Control** (`/remote-control`, driving a local session from mobile/desktop/web) disappears from the command list while bili routes traffic. Compression is unaffected; run plain `claude` without bili (or `bili plugin remove claude`) for sessions that need those features. This is inherent to the base-URL routing seam — no alternative interception point survives CC's undici stack (#2290) — not a config deletion. Desktop-only users can restore native auto-compact with `bili plugin remove claude`. Since #5095 the managed block also installs a `SubagentStart` hook (`node /dist/claude-subagent-hook.js`) that mints a per-dispatch lane token into each subagent's context: subagents that ride the parent's session id with no agent-id headers (the VS Code extension build, #4352) key onto their own `|sub:…:t:` compression lanes, so parallel same-type dispatches stop merging (and the token disappears from later requests once the first message folds — those fall back to the fingerprint lane). Uninstall removes the hook with the managed block. +- `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 by default — both configurable since #4006 via `watchdog.*` / `BILI_WATCHDOG_*`) and respawns a dead lane proxy itself, so model requests recover within ~90 s at the default cadence instead of a new session (same semantics as the zcode lane). Opt out with `BILI_NATIVE_CLAUDE=0` (passthrough). Mechanics: [docs/technical-notes.md](docs/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, matching the CLI behavior of that era — note that newer builds (CC 2.1.301+) DO honour `HTTPS_PROXY` on the CLI, which is why `bili claude` routes via the `/bili/` base-URL rewrite — the launcher gives this lane no proxy and no CA at all, and a child that brings a proxy of its own gets the loopback hosts merged into `NO_PROXY`/`no_proxy` so that leg stays direct regardless of its proxy behavior (#3446). 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. **Account-bound features (#4693):** because the lane routes via a custom `ANTHROPIC_BASE_URL`, Claude Code treats the session as third-party/API-key and disables features bound to your Anthropic account/Cloud — **Remote Control** (`/remote-control`, driving a local session from mobile/desktop/web) disappears from the command list while bili routes traffic. Compression is unaffected; run plain `claude` without bili (or `bili plugin remove claude`) for sessions that need those features. This is inherent to the base-URL routing seam — no alternative interception point survives CC's undici stack (#2290) — not a config deletion. Desktop-only users can restore native auto-compact with `bili plugin remove claude`. Since #5095 the managed block also installs a `SubagentStart` hook (`node /dist/claude-subagent-hook.js`) that mints a per-dispatch lane token into each subagent's context: subagents that ride the parent's session id with no agent-id headers (the VS Code extension build, #4352) key onto their own `|sub:…:t:` compression lanes, so parallel same-type dispatches stop merging (and the token disappears from later requests once the first message folds — those fall back to the fingerprint lane). Uninstall removes the hook with the managed block. - `zcode` has a native posture (#1145): managed `~/.zcode/cli/config.json` block + per-session provider `baseURL` rewrite. Full mechanics: [docs/clients.md](docs/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 3a480141fc..d88ae5489f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -195,7 +195,7 @@ pi / omp / kimi / claude 没有客户端侧通道 —— 它们的配置条目 - OpenCode 旧会话、V1/V2 插件形态与全部注意事项:[OpenCode](docs/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,端口漂移自愈。#1821 起 MCP shell 还在会话内守护代理(30s × 3 次失败),代理死亡时自行重生,lane 内模型请求 ~90s 内恢复而无需新开会话(与 zcode 车道同语义)。`BILI_NATIVE_CLAUDE=0` 退出(passthrough)。机制:[docs/technical-notes.zh-CN.md](docs/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 2.1.301 起)在 CLI 上会遵守 `HTTPS_PROXY`,这正是 `bili claude` 走 `/bili/` base-URL 改写的原因——launcher 不再为该 lane 设置代理、也不再设置 CA,而自带代理的子进程会把 loopback 主机合并进 `NO_PROXY`/`no_proxy`,确保无论子进程的代理行为如何,这一腿都保持直连(#3446)。截至该版本,桌面 Code 标签页不存在可用的路由缝隙;该 lane 继续在 [#2290](https://github.com/ranxianglei/billion-context/issues/2290) 跟踪,若上游行为变化再议。**账号绑定功能(#4693):** 由于该车道经自定义 `ANTHROPIC_BASE_URL` 路由,Claude Code 会把会话当作第三方/API-key 模式,从而关闭绑定你 Anthropic 账号/云端的功能——**Remote Control**(`/remote-control`,从手机/桌面/网页接管本机会话)会在 bili 路由期间从命令列表消失。压缩本身不受影响;需要这些功能的会话请直接用不带 bili 的原生 `claude`(或 `bili plugin remove claude`)。这是 base-URL 路由缝隙的固有取舍——没有别的拦截点能绕过 CC 的 undici 栈(#2290)——而非配置被删。仅用桌面的用户可用 `bili plugin remove claude` 恢复原生自动压缩。#5095 起受管块还会安装一个 `SubagentStart` hook(`node /dist/claude-subagent-hook.js`),给每次子代理派发铸一个随机 lane token 注入其上下文:骑着父会话 id 且无 agent-id 头的子代理(VS Code 扩展构建,#4352)按 `|sub:…:t:` 键控各自的压缩车道,并行同型派发不再合流(首条消息被折叠后 token 消失,后续请求回落到指纹车道)。卸载时随受管块一并移除。 +- `claude` 有**原生姿态**(#964):受管 settings 块 + `SessionStart` hook + MCP shell;hook 骑自管端口区(#1660),每会话把受管 URL 重钉到存活 origin,端口漂移自愈。#1821 起 MCP shell 还在会话内守护代理(默认 30s × 3 次失败——#4006 起两者经 `watchdog.*` / `BILI_WATCHDOG_*` 可配),代理死亡时自行重生,lane 内模型请求按默认节拍 ~90s 内恢复而无需新开会话(与 zcode 车道同语义)。`BILI_NATIVE_CLAUDE=0` 退出(passthrough)。机制:[docs/technical-notes.zh-CN.md](docs/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 2.1.301 起)在 CLI 上会遵守 `HTTPS_PROXY`,这正是 `bili claude` 走 `/bili/` base-URL 改写的原因——launcher 不再为该 lane 设置代理、也不再设置 CA,而自带代理的子进程会把 loopback 主机合并进 `NO_PROXY`/`no_proxy`,确保无论子进程的代理行为如何,这一腿都保持直连(#3446)。截至该版本,桌面 Code 标签页不存在可用的路由缝隙;该 lane 继续在 [#2290](https://github.com/ranxianglei/billion-context/issues/2290) 跟踪,若上游行为变化再议。**账号绑定功能(#4693):** 由于该车道经自定义 `ANTHROPIC_BASE_URL` 路由,Claude Code 会把会话当作第三方/API-key 模式,从而关闭绑定你 Anthropic 账号/云端的功能——**Remote Control**(`/remote-control`,从手机/桌面/网页接管本机会话)会在 bili 路由期间从命令列表消失。压缩本身不受影响;需要这些功能的会话请直接用不带 bili 的原生 `claude`(或 `bili plugin remove claude`)。这是 base-URL 路由缝隙的固有取舍——没有别的拦截点能绕过 CC 的 undici 栈(#2290)——而非配置被删。仅用桌面的用户可用 `bili plugin remove claude` 恢复原生自动压缩。#5095 起受管块还会安装一个 `SubagentStart` hook(`node /dist/claude-subagent-hook.js`),给每次子代理派发铸一个随机 lane token 注入其上下文:骑着父会话 id 且无 agent-id 头的子代理(VS Code 扩展构建,#4352)按 `|sub:…:t:` 键控各自的压缩车道,并行同型派发不再合流(首条消息被折叠后 token 消失,后续请求回落到指纹车道)。卸载时随受管块一并移除。 - `zcode` 有**原生姿态**(#1145):受管 `~/.zcode/cli/config.json` 块 + 每会话 provider `baseURL` 改写。完整机制:[docs/clients.zh-CN.md](docs/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`。机制:[docs/clients.zh-CN.md](docs/clients.zh-CN.md#codexopenai-codex-cli)。 - `jcode`、`aider` 无原生模式(无插件/MCP/工具注入接缝:#962、#1048)—— 用 `bili jcode` / `bili aider`。 diff --git a/docs/configuration.ja.md b/docs/configuration.ja.md index 80a4e18ec4..1e251e35d1 100644 --- a/docs/configuration.ja.md +++ b/docs/configuration.ja.md @@ -204,6 +204,9 @@ | `persist.tailTokens` | number | 16384 (0 disables message persistence) | BILI_PERSIST_TAIL_TOKENS | エクスポートの忠実性のために生テキストとして保持される最近のメッセージのトークンサイズ末尾。 | | `persist.epermAlertThreshold` | number | 5 | BILI_PERSIST_EPERM_ALERT_THRESHOLD | ログにアラートを出すまでの連続 EPERM 書き込み失敗回数。 | | `persist.epermAlertRepeatMs` | number | 0 (no repeats) | BILI_PERSIST_EPERM_ALERT_REPEAT_MS | EPERM アラートの繰り返し間隔。0 の場合は 1 回のみログ出力する。 | +| `watchdog` | object | {} (all defaults) | — | ネイティブレーンの proxy 再生 watchdog の間隔(セッションごとの zcode/claude/kimi MCP エントリ、#4006)。 | +| `watchdog.intervalMs` | number | 30000 (floor 1000) | BILI_WATCHDOG_INTERVAL_MS | レーン watchdog のヘルスプローブ間隔;外部から kill されたレーン proxy の最悪復旧ウィンドウ = interval × failureLimit(デフォルトで約 90 秒——#4006 で実測 64 秒)。1000 未満の値はデフォルトにフォールバック(秒/ミリ秒の誤入力ガード)。 | +| `watchdog.failureLimit` | number | 3 | BILI_WATCHDOG_FAILURE_LIMIT | レーン watchdog が proxy を再生するまでの連続プローブ失敗回数。 | | `storage` | object | {} (all defaults) | — | 統合 SQLite ストレージサイドカーの設定 (#2671)。 | | `storage.unified` | legacy\|shadow\|full\|sqlite | unset (sqlite) | BILI_STORAGE_UNIFIED | 階層型ストレージ移行スイッチ (#2671): shadow = ダイジェスト照合付き統合 SQLite ダブルライトのドライラン; full = ドロップイン読み取りパス (オーガニックインポート付きの統合優先読み込み、レガシーフォールバック); sqlite = ピュア SQLite モード - full と同じストレージ機構だが JSON エンベロープ書き込みはデフォルト OFF (SQLite インデックスが唯一の永続コピー; JSON エンベロープは書き込まれない)。デフォルト (どこでも未設定) は現在ピュア SQLite: ダブルライト fleet は #3818 以降ダイジェスト照合が安定して稼働しているため、JSON エンベロープはデフォルトでは書き込まれなくなった - 明示的な full は #3818 由来のダブルライトデフォルトを維持し、legacy は 1 行のエスケープハッチとして残る (将来の表記は同じ形: mysql = ネットワークバックエンド、json = エンベロープのみ)。ファイル階層は厳密に legacy/shadow/full/sqlite; 環境変数階層は 1/true (=shadow) と unified (=full) も受け入れ、ファイルより優先される。レーン起動ごとに 1 回のみ解決される - ホット編集には再起動が必要。暗号化 (BILI_ENCRYPTION_KEY) はサイドカーをハードブロックする。 | | `storage.backend` | sqlite\|mysql | unset (sqlite) | BILI_STORAGE_BACKEND | ストレージバックエンドの選択 (#3388 / #3931): 統合ストアは操作レベルの非同期 StorageBackend 契約を消費する。sqlite がデフォルト (Promise ラップされたアダプター背後の既存の UnifiedStore)。mysql は完全に配線済み (ステップ 2+3): openBackend("mysql", dsn) は MySQL 8.0 に対して実際の MysqlBackend を開く - 完全な契約サーフェス (CAS リファレンスカウント付きのインジェスト、読み取り、session_ext、リープジャーナル、アーカイブ/リストア/GC、チェックポイント、会話)、mysql2 は通常の依存関係としてバンドルされ、遅延ロードされる (mysql を選択しない起動では決してロードされない)。プロキシのホットパスは非同期シャドウファサードを通じて配線されている: セーブはシリアルバックエンドキューにエンキューされる (ウォーターマークデルタ、孤立/リープジャーナル、ダイジェストサンプリング - sqlite はゼロ await の同期高速パスを不変のまま維持)、同期読み取りは JSON エンベロープに乗る (サイドカーは ready() 経由で非同期にアタッチされる; viewFor/importRecord の同期ファサードは意図的にミスする)、レプリカ/ext/GC/エクスポート/フォークは非同期ツインを話す (#4911: フォークレーンはそれらを通じて lastLiveSeq + 行クローンに await する; フォールドアンカーバックフィル / スナップショットレンダリングのための同期ウィンドウ読み取りは意図的にエンベロープ提供される)。writerOff は sqlite のみ (エンベロープは mysql の同期読み取りパスである)。不明な名前は通知付きで sqlite にフォールバックする。レーン起動ごとに 1 回のみ解決される。 | @@ -1108,6 +1111,13 @@ - **Status:** ACTIVE - **Description:** ストリーム途中で中断するホスト向けのフェイクコンプリーションのセーフティネット(#371)— **オプトイン**方式で、`retries: 0`(デフォルト)は #371 以前のパススルー動作。`bufCapBytes` はバッファリングされたレスポンスに対する OOM ガード。`BILI_FAKE_COMPLETION_RETRIES`, `BILI_FAKE_BUF_CAP` と対応。 +### `watchdog` + +- **Type:** `{ intervalMs?: number; failureLimit?: number }` +- **Default:** `{ intervalMs: 30000, failureLimit: 3 }` +- **Status:** ACTIVE (#4006) +- **Description:** セッションごとのネイティブレーン proxy 再生 watchdog の間隔——tick は各クライアント派生 MCP エントリプロセス内(zcode #1145、claude #1821、kimi #963)で実行され、proxy 本体ではない。各 tick はレーン proxy のローカルヘルスエンドポイントをプローブする(タイムアウト 2 秒);`failureLimit` 回連続でプローブ失敗すると、エントリはセッション起動時に使用したのと同じ launcher パス経由で proxy を再生する(必要に応じて再ルーティング/再ピン留め)。したがって、外部から kill されたレーン proxy の最悪復旧ウィンドウ = interval × failureLimit(デフォルトで約 90 秒——#4006 で実測 64 秒)。両キーは env > ファイル > デフォルトで解決される;`intervalMs` は watchdog がアームされる際に一度だけ読み込まれる(次のセッションのエントリで有効)、`failureLimit` は各 tick で読み込まれる(設定ファイルの編集は実行中のエントリでも 1 tick 以内で有効)。`intervalMs` が 1000 未満の場合はデフォルトにフォールバック——秒/ミリ秒の誤入力でプローブがホットループに退行してはならない。対応変数 `BILI_WATCHDOG_INTERVAL_MS`、`BILI_WATCHDOG_FAILURE_LIMIT`。 + ### `codexCompact` / `ccrRetrievalTtlMs` / `decompressTmpCap` - **Type:** `string` ("intercept" | "pass") / `number` / `number` @@ -2057,6 +2067,8 @@ ACP ネイティブエージェント(現在は `pi` 拡張機能)は、プ | `BILI_UPSTREAM_PROXY` | `proxy` | unset (direct) | | `BILI_UPSTREAM_PROXY_MODE` | `upstreamProxyMode` | auto (unset behaves as direct) | | `BILI_UPSTREAM_TIMEOUT_MS` | `network.upstreamTimeoutMs` | 720000 | +| `BILI_WATCHDOG_FAILURE_LIMIT` | `watchdog.failureLimit` | 3 | +| `BILI_WATCHDOG_INTERVAL_MS` | `watchdog.intervalMs` | 30000 (floor 1000) | | `BILI_WS_OUTBOUND_BYTES` | `network.wsOutboundBytes` | 10485760 | | `PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | | `PI_ACP_DELEGATE_FORCE_ENABLE` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | diff --git a/docs/configuration.md b/docs/configuration.md index bae6ef4768..98ba0ad59b 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -205,6 +205,9 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `persist.tailTokens` | number | 16384 (0 disables message persistence) | BILI_PERSIST_TAIL_TOKENS | Token-size tail of recent messages kept as raw text for export fidelity. | | `persist.epermAlertThreshold` | number | 5 | BILI_PERSIST_EPERM_ALERT_THRESHOLD | Consecutive EPERM write failures before alerting in the log. | | `persist.epermAlertRepeatMs` | number | 0 (no repeats) | BILI_PERSIST_EPERM_ALERT_REPEAT_MS | Repeat interval for the EPERM alert; 0 logs it once. | +| `watchdog` | object | {} (all defaults) | — | Native-lane proxy respawn watchdog cadence (per-session zcode/claude/kimi MCP entries, #4006). | +| `watchdog.intervalMs` | number | 30000 (floor 1000) | BILI_WATCHDOG_INTERVAL_MS | Health-probe tick of the lane watchdogs; worst-case recovery window after an externally killed lane proxy = interval x failureLimit (~90 s at defaults - the 64 s measured in #4006). Values below 1000 fall back to the default (seconds-vs-ms typo guard). | +| `watchdog.failureLimit` | number | 3 | BILI_WATCHDOG_FAILURE_LIMIT | Consecutive failed probes before the lane watchdog respawns the proxy. | | `storage` | object | {} (all defaults) | — | Unified SQLite storage sidecar settings (#2671). | | `storage.unified` | legacy\|shadow\|full\|sqlite | unset (sqlite) | BILI_STORAGE_UNIFIED | Tiered storage-migration switch (#2671): shadow = unified SQLite double-write dry-run with digest reconciliation; full = drop-in read path (unified-first loads with organic import, legacy fallback); sqlite = pure-SQLite mode — same store machinery as full, but the JSON envelope writer defaults to OFF (the SQLite index is the only persistent copy; no JSON envelope is written). The default (absent everywhere) is now PURE-SQLITE: the dual-write fleet has run since #3818 with digest reconciliation holding, so JSON envelopes stop being written by default — explicit full keeps the historical #3818 dual-write default, and legacy remains the one-line escape hatch (future spellings follow the same shape: mysql = network backend, json = envelope-only). File tier is strict legacy/shadow/full/sqlite; the env tier also accepts 1/true (=shadow) and unified (=full) and wins over the file. Resolved once per lane boot - hot edits need a restart. Encryption (BILI_ENCRYPTION_KEY) hard-blocks the sidecar. | | `storage.backend` | sqlite\|mysql | unset (sqlite) | BILI_STORAGE_BACKEND | Storage backend selection (#3388 / #3931): the unified store consumes an operation-level async StorageBackend contract. sqlite is the default (the existing UnifiedStore behind a Promise-wrapped adapter). mysql is FULLY WIRED (steps 2+3): openBackend("mysql", dsn) opens the real MysqlBackend against MySQL 8.0 — the full contract surface (ingest with CAS refcounts, reads, session_ext, reap journal, archive/restore/gc, checkpoints, conversations), with mysql2 bundled as a regular dependency and loaded lazily (boots that never select mysql never load it). The proxy hot path is wired through the async shadow facade: saves enqueue onto a serial backend queue (watermark deltas, orphan/reap journal, digest sampling — sqlite keeps its zero-await sync fast path unchanged), SYNC reads ride the JSON envelope (the sidecar attaches asynchronously via ready(); viewFor/importRecord sync facades miss by design), replicas/ext/GC/export/fork speak the async twins (#4911: the fork lane awaits lastLiveSeq + the row clone through them; the sync window reads for fold-anchor backfill / snapshot render stay envelope-served by design). writerOff stays sqlite-only (the envelope is the mysql sync read path). Unknown names fall back to sqlite with a notice. Resolved once per lane boot. | @@ -1107,6 +1110,13 @@ Security boundary: the file controls ONLY *when* to upgrade and *which published - **Status:** ACTIVE - **Description:** Fake-completion safety net for hosts that abort mid-stream (#371) — **opt-in**, `retries: 0` (default) is the pre-#371 passthrough. `bufCapBytes` is the OOM guard on the buffered response. Twins `BILI_FAKE_COMPLETION_RETRIES`, `BILI_FAKE_BUF_CAP`. +### `watchdog` + +- **Type:** `{ intervalMs?: number; failureLimit?: number }` +- **Default:** `{ intervalMs: 30000, failureLimit: 3 }` +- **Status:** ACTIVE (#4006) +- **Description:** Cadence of the per-session native-lane proxy respawn watchdog — the tick runs inside each client-spawned MCP entry process (zcode #1145, claude #1821, kimi #963), NOT inside the proxy itself. Every tick probes the lane proxy's local health endpoint (2 s timeout); after `failureLimit` consecutive failed probes the entry respawns the proxy through the same launcher path used at session boot (re-routing/re-pinning as needed). Worst-case recovery window after an externally killed lane proxy is therefore interval × failureLimit (~90 s at defaults — the 64 s measured in #4006). Both keys resolve env > file > default; `intervalMs` is read once when the watchdog arms (takes effect on the next session's entry) while `failureLimit` is read per tick (a config-file edit takes effect within one tick even for a running entry). `intervalMs` below 1000 falls back to the default — a seconds-vs-ms typo must not degenerate the probe into a hot loop. Twins `BILI_WATCHDOG_INTERVAL_MS`, `BILI_WATCHDOG_FAILURE_LIMIT`. + ### `codexCompact` / `ccrRetrievalTtlMs` / `decompressTmpCap` - **Type:** `string` ("intercept" | "pass") / `number` / `number` @@ -2068,6 +2078,8 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `BILI_UPSTREAM_PROXY` | `proxy` | unset (direct) | | `BILI_UPSTREAM_PROXY_MODE` | `upstreamProxyMode` | auto (unset behaves as direct) | | `BILI_UPSTREAM_TIMEOUT_MS` | `network.upstreamTimeoutMs` | 720000 | +| `BILI_WATCHDOG_FAILURE_LIMIT` | `watchdog.failureLimit` | 3 | +| `BILI_WATCHDOG_INTERVAL_MS` | `watchdog.intervalMs` | 30000 (floor 1000) | | `BILI_WS_OUTBOUND_BYTES` | `network.wsOutboundBytes` | 10485760 | | `PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | | `PI_ACP_DELEGATE_FORCE_ENABLE` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | diff --git a/docs/configuration.zh-CN.md b/docs/configuration.zh-CN.md index 45861d8461..b002c2a56b 100644 --- a/docs/configuration.zh-CN.md +++ b/docs/configuration.zh-CN.md @@ -205,6 +205,9 @@ | `persist.tailTokens` | number | 16384 (0 disables message persistence) | BILI_PERSIST_TAIL_TOKENS | 为导出保真保留的最近消息原文 token 尾部大小。 | | `persist.epermAlertThreshold` | number | 5 | BILI_PERSIST_EPERM_ALERT_THRESHOLD | 连续 EPERM 写失败达到该次数后在日志中告警。 | | `persist.epermAlertRepeatMs` | number | 0 (no repeats) | BILI_PERSIST_EPERM_ALERT_REPEAT_MS | EPERM 告警的重复间隔;0 只记录一次。 | +| `watchdog` | object | {} (all defaults) | — | 原生车道 proxy 重生看门狗节拍(每会话的 zcode/claude/kimi MCP entry,#4006)。 | +| `watchdog.intervalMs` | number | 30000 (floor 1000) | BILI_WATCHDOG_INTERVAL_MS | 车道看门狗的健康探针节拍;车道 proxy 被外部杀死后的最坏恢复窗口 = interval × failureLimit(默认约 90 秒——#4006 实测 64 秒)。低于 1000 的值回退默认值(秒/毫秒笔误防护)。 | +| `watchdog.failureLimit` | number | 3 | BILI_WATCHDOG_FAILURE_LIMIT | 车道看门狗重生 proxy 前允许的连续失败探针次数。 | | `storage` | object | {} (all defaults) | — | 统一 SQLite 存储边车设置(#2671)。 | | `storage.unified` | legacy\|shadow\|full\|sqlite | unset (sqlite) | BILI_STORAGE_UNIFIED | 分层存储迁移开关(#2671):shadow = 统一 SQLite 双写干跑 + digest 对账;full = 平替读路径(unified-first 加载 + 有机导入 + legacy 兜底);sqlite = 纯 SQLite 模式 —— 与 full 同一套存储机构,但 JSON 信封写入默认 OFF(SQLite 索引是唯一持久副本,不写 JSON 信封)。默认值(两处均未设置)现在是纯 SQLite:双写车队自 #3818 起运行、digest 对账稳定,因此 JSON 信封默认不再写入 —— 显式 full 保留 #3818 的历史双写默认,legacy 仍是一行逃生口(未来拼写沿用同形:mysql = 网络后端,json = 纯信封)。文件层只接受 legacy/shadow/full/sqlite;环境变量层还接受 1/true(=shadow)与 unified(=full)并优先于文件。每个 lane 启动时解析一次 —— 热改动需重启生效。加密(BILI_ENCRYPTION_KEY)会硬阻断边车。 | | `storage.backend` | sqlite\|mysql | unset (sqlite) | BILI_STORAGE_BACKEND | 存储后端选择(#3388 / #3931):统一存储消费操作级的异步 StorageBackend 契约。sqlite 为默认(现有 UnifiedStore 套一层 Promise 包装适配器)。mysql 已完整接线(第二+三步):openBackend("mysql", dsn) 打开真正的 MysqlBackend,对接 MySQL 8.0 —— 完整契约面(带 CAS 引用计数的 ingest、读取、session_ext、收割台账、归档/恢复/GC、checkpoint、会话绑定),mysql2 作为常规依赖打包并按需懒加载(从不选 mysql 的启动永不加载它)。代理热路径经异步影子 facade 接线:保存进串行后端队列(水位 delta、孤儿/收割台账、digest 采样 —— sqlite 保持零 await 同步快车道不变),同步读走 JSON 信封(sidecar 经 ready() 异步挂载;viewFor/importRecord 同步面按设计 miss),replicas/ext/GC/export/fork 走异步孪生(#4911:fork 车道经它们 await lastLiveSeq + 行克隆;fold-anchor 回填/快照渲染用的同步窗口读按设计仍走信封)。writerOff 仅 sqlite(信封就是 mysql 的同步读路径)。未知名字回退 sqlite 并提示。每个 lane 启动时解析一次。 | @@ -1101,6 +1104,13 @@ - **状态:** ACTIVE - **说明:** 针对流中途被宿主掐断场景的 fake-completion 安全网(#371)—— **显式开启**,`retries: 0`(默认)即 #371 之前的透传行为。`bufCapBytes` 是缓冲响应的 OOM 护栏。对应 `BILI_FAKE_COMPLETION_RETRIES`、`BILI_FAKE_BUF_CAP`。 +### `watchdog` + +- **类型:** `{ intervalMs?: number; failureLimit?: number }` +- **默认:** `{ intervalMs: 30000, failureLimit: 3 }` +- **状态:** 生效(#4006) +- **说明:** 每会话原生 lane「代理重生看门狗」的节拍——tick 跑在客户端派生的 MCP 入口进程里(zcode #1145、claude #1821、kimi #963),不在代理进程内。每次 tick 探测 lane 代理的本地健康端点(2 秒超时);连续 `failureLimit` 次失败后,入口按会话启动时同一条 launcher 路径重生代理(按需重路由/重钉)。因此外部杀掉 lane 代理后的最坏恢复窗口 = 间隔 × 失败上限(默认约 90 秒——#4006 实测 64 秒)。两个键都按 env > 文件 > 默认解析:`intervalMs` 在看门狗装定时读取一次(下一会话的入口生效),`failureLimit` 每次 tick 读取(改配置文件一轮 tick 内对运行中的入口也生效)。`intervalMs` 低于 1000 回退默认——秒/毫秒笔误必须不会把探测变成热循环。对应 `BILI_WATCHDOG_INTERVAL_MS`、`BILI_WATCHDOG_FAILURE_LIMIT`。 + ### `codexCompact` / `ccrRetrievalTtlMs` / `decompressTmpCap` - **类型:** `string`("intercept" | "pass")/ `number` / `number` @@ -2045,6 +2055,8 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 | `BILI_UPSTREAM_PROXY` | `proxy` | unset (direct) | | `BILI_UPSTREAM_PROXY_MODE` | `upstreamProxyMode` | auto (unset behaves as direct) | | `BILI_UPSTREAM_TIMEOUT_MS` | `network.upstreamTimeoutMs` | 720000 | +| `BILI_WATCHDOG_FAILURE_LIMIT` | `watchdog.failureLimit` | 3 | +| `BILI_WATCHDOG_INTERVAL_MS` | `watchdog.intervalMs` | 30000 (floor 1000) | | `BILI_WS_OUTBOUND_BYTES` | `network.wsOutboundBytes` | 10485760 | | `PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | | `PI_ACP_DELEGATE_FORCE_ENABLE` | `pi.subagents` | {} (acp_delegate enabled with package defaults) | diff --git a/docs/lifecycle.md b/docs/lifecycle.md index 97c4400148..a4d3d44941 100644 --- a/docs/lifecycle.md +++ b/docs/lifecycle.md @@ -220,6 +220,13 @@ | `BILI_DSH_CONTEXT_TAB` | dsh.contextTab 的 env 层(#4237):`=0` 隐藏 DSH 顶栏「上下文」标签页(压缩及其余入口全部不受影响);其他值强制开并覆盖文件层;缺省按文件层(默认 true);下次页面加载 / dsh 重启生效 | | `BILI_DSH_MAX_TESTED_VERSION` | dsh native lane「高于已测最高版」启动提示的上限(#4545):从注入包上方最近的 node_modules/@deepseek-ai/dsh/package.json 读运行中的构建,**严格高于**上限才弹一条启动提示,建议先回滚;默认 0.2.0-rc.2(CI e2e 锚点),新版本验证通过后抬高;空串 = 关闭检查;只提示不拦截 | +### 2.10 原生车道看门狗(#4006) + +| 变量 | 一句话用途 | +|------|-----------| +| `BILI_WATCHDOG_INTERVAL_MS` | watchdog.intervalMs,默认 30000——每会话原生车道(zcode/claude/kimi MCP entry)proxy 重生看门狗的健康探针间隔;低于 1000 回退默认(秒/毫秒笔误防护);最坏恢复窗口 = interval × failureLimit(默认约 90 秒,#4006 实测 64 秒) | +| `BILI_WATCHDOG_FAILURE_LIMIT` | watchdog.failureLimit,默认 3——连续探测失败多少次后车道看门狗重生 proxy | + ## 3. 非环境变量的 BILI_* 标识符(勿与上表混淆) 以下共享 `BILI_` 前缀但是代码常量/工具表/错误码,不是环境变量,不在 CI 检查范围: diff --git a/src/claude-mcp-entry.ts b/src/claude-mcp-entry.ts index 2219903145..9ea8103547 100644 --- a/src/claude-mcp-entry.ts +++ b/src/claude-mcp-entry.ts @@ -4,7 +4,8 @@ // 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 +// Mirrors src/zcode/mcp-entry.ts (30 s tick × 3 failures by default — #4006 knobs). +// 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 @@ -18,12 +19,10 @@ import { configureLogRetention } from "./log-retention.js"; import { logRetentionPolicy } from "./knobs.js"; import { defaultLogFile } from "./paths.js"; import { LAUNCHER_DEFAULT_HOST, ensureProxyRunning, healthUrl } from "./launcher.js"; +import { laneWatchdogFailureLimit, laneWatchdogIntervalMs } from "./knobs.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. */ @@ -69,7 +68,7 @@ export interface MutableWatchdogState extends WatchdogState { * 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; + const limit = deps.failureLimit ?? laneWatchdogFailureLimit(); if (await probeFn(state.origin)) { state.failures = 0; return; @@ -118,7 +117,7 @@ export function startWatchdog(state: MutableWatchdogState, plan: { port: number; 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); + }, deps.intervalMs ?? laneWatchdogIntervalMs()); timer.unref?.(); return timer; } diff --git a/src/config.ts b/src/config.ts index e8c42325c5..16985e829d 100644 --- a/src/config.ts +++ b/src/config.ts @@ -2475,6 +2475,13 @@ type FileConfig = { repetition?: boolean | { enabled?: boolean; warn?: number; abort?: number; recovery?: boolean }; textRunThreshold?: number; }; + /** Native-lane proxy respawn watchdog cadence (#4006) — read in the per-session + * MCP entry processes (zcode/claude/kimi), not the proxy. `intervalMs` is the + * health-probe tick (default 30000, floor 1000); `failureLimit` is consecutive + * failed probes before a respawn (default 3); worst-case recovery window after + * an externally killed lane proxy = interval × failureLimit. Env + * BILI_WATCHDOG_INTERVAL_MS / BILI_WATCHDOG_FAILURE_LIMIT win over both. */ + watchdog?: { intervalMs?: number; failureLimit?: number }; /** CCR retrieval TTL in ms (#2030) — was BILI_CCR_RETRIEVAL_TTL_MS (default 600000). */ ccrRetrievalTtlMs?: number; /** Large-decompress temp-file cap (#2030) — was BILI_DECOMPRESS_TMP_CAP (default 50). */ @@ -2544,6 +2551,8 @@ const KNOWN_TOP_LEVEL_KEYS = new Set([ "cacheKeepalive", // #6003 phase 2: user-registerable egress body-rewrite pipeline. "egressTransforms", + // #4006: + "watchdog", ]); // Every field parseCompressSettings accepts — hint source for misplaced keys: diff --git a/src/kimi/native-mcp.ts b/src/kimi/native-mcp.ts index 7320f820c2..2ef8f1f4cc 100644 --- a/src/kimi/native-mcp.ts +++ b/src/kimi/native-mcp.ts @@ -8,6 +8,7 @@ import { runMcpStdio } from "../mcp.js"; import { fetchManifest } from "../agent/shared.js"; import { nativeProxyScriptPath } from "../agent/native-bootstrap.js"; import { LAUNCHER_DEFAULT_HOST, ensureProxyRunning } from "../launcher.js"; +import { laneWatchdogFailureLimit, laneWatchdogIntervalMs } from "../knobs.js"; import { activateKimiPluginMode, bootstrapKimiNative, @@ -19,9 +20,6 @@ import { type KimiRouteApplied, } from "./native.js"; -const WATCHDOG_INTERVAL_MS = 30000; -const WATCHDOG_FAILURE_LIMIT = 3; - function startWatchdog(applied: KimiRouteApplied, attached: boolean, log: (msg: string) => void): void { const state = { origin: applied.origin, applied }; let failures = 0; @@ -35,7 +33,7 @@ function startWatchdog(applied: KimiRouteApplied, attached: boolean, log: (msg: async function watchdogTick(): Promise { if (await probeProxyHealth(state.origin)) { failures = 0; return; } failures += 1; - if (failures < WATCHDOG_FAILURE_LIMIT) return; + if (failures < laneWatchdogFailureLimit()) return; if (attached) { log(`attached proxy ${state.origin} unhealthy — waiting for it to recover`); return; @@ -59,7 +57,7 @@ function startWatchdog(applied: KimiRouteApplied, attached: boolean, log: (msg: } failures = 0; } - }, WATCHDOG_INTERVAL_MS); + }, laneWatchdogIntervalMs()); timer.unref?.(); } diff --git a/src/knobs.ts b/src/knobs.ts index 32e49ad6a0..5ffc56675f 100644 --- a/src/knobs.ts +++ b/src/knobs.ts @@ -444,6 +444,31 @@ export function guardrailTextRunThreshold(): number { return n > 0 ? Math.floor(n) : 0; // 0 or negative = lane off } +// --- native-lane proxy respawn watchdog (#4006) — read in the per-session MCP +// entry processes (zcode/claude/kimi), which are bili processes spawned by the +// client host; both tiers resolve exactly as they do inside the proxy. --- + +const LANE_WATCHDOG_INTERVAL_DEFAULT_MS = 30_000; +const LANE_WATCHDOG_INTERVAL_FLOOR_MS = 1_000; +const LANE_WATCHDOG_FAILURE_LIMIT_DEFAULT = 3; + +/** BILI_WATCHDOG_INTERVAL_MS > watchdog.intervalMs > 30000. Health-probe tick of the + * per-session lane watchdogs (#1821/#963); worst-case recovery window after an + * externally killed lane proxy is interval × failureLimit (~90 s at defaults, #4006). + * Floor 1000 ms guards against a seconds-vs-ms typo degenerating the probe into a hot + * loop; below-floor values fall back to the default. */ +export function laneWatchdogIntervalMs(): number { + const v = tInt("BILI_WATCHDOG_INTERVAL_MS", loadConfigFile().watchdog?.intervalMs); + return Number.isFinite(v) && v >= LANE_WATCHDOG_INTERVAL_FLOOR_MS ? Math.floor(v) : LANE_WATCHDOG_INTERVAL_DEFAULT_MS; +} + +/** BILI_WATCHDOG_FAILURE_LIMIT > watchdog.failureLimit > 3. Consecutive failed probes + * before the lane watchdog respawns the proxy (#4006). */ +export function laneWatchdogFailureLimit(): number { + const v = tInt("BILI_WATCHDOG_FAILURE_LIMIT", loadConfigFile().watchdog?.failureLimit); + return Number.isFinite(v) && v >= 1 ? Math.floor(v) : LANE_WATCHDOG_FAILURE_LIMIT_DEFAULT; +} + /** BILI_PERSIST_ZSTD > persist.zstd > false (#1080 owner decision: plain JSON default). */ export function persistZstdEnabled(): boolean { const envRaw = process.env.BILI_PERSIST_ZSTD; diff --git a/src/zcode/mcp-entry.ts b/src/zcode/mcp-entry.ts index f44d160026..68dc8c6d55 100644 --- a/src/zcode/mcp-entry.ts +++ b/src/zcode/mcp-entry.ts @@ -18,6 +18,7 @@ import { closeLogger, configureLogger, log as teeLog } from "../logger.js"; import { configureLogRetention } from "../log-retention.js"; import { logRetentionPolicy } from "../knobs.js"; import { defaultLogFile } from "../paths.js"; +import { laneWatchdogFailureLimit, laneWatchdogIntervalMs } from "../knobs.js"; import { LAUNCHER_DEFAULT_HOST, ensureProxyRunning } from "../launcher.js"; import type { ZcodeRoutePolicy } from "./json-edit.js"; import { @@ -31,8 +32,6 @@ import { zcodePolicyFromEnv, } from "./native.js"; -const WATCHDOG_INTERVAL_MS = 30000; -const WATCHDOG_FAILURE_LIMIT = 3; const HANDOFF_TIMEOUT_MS = 5000; export interface ZcodeWatchdogDeps { @@ -84,7 +83,7 @@ export async function zcodeWatchdogTick(state: MutableZcodeWatchdogState, extern 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)) { + } else if (state.failures + 1 < (deps.failureLimit ?? laneWatchdogFailureLimit())) { state.failures += 1; } else { if (externallyOwned) { @@ -124,7 +123,7 @@ function startWatchdog( void zcodeWatchdogTick(state, externallyOwned, deps, log) .catch((err) => log(`watchdog error: ${err instanceof Error ? err.message : String(err)}`)) .finally(() => { busy = false; }); - }, deps.intervalMs ?? WATCHDOG_INTERVAL_MS); + }, deps.intervalMs ?? laneWatchdogIntervalMs()); timer.unref?.(); } diff --git a/tests/claude-mcp-entry.test.ts b/tests/claude-mcp-entry.test.ts index 889faee7fa..22f2270009 100644 --- a/tests/claude-mcp-entry.test.ts +++ b/tests/claude-mcp-entry.test.ts @@ -218,6 +218,34 @@ test("startWatchdog: fires on repeated death and survives via unref'd timer", as } }); +test("#4006: watchdogTick without an injected failureLimit resolves the knob live (env tier)", async () => { + const plan = { port: ZONE_PORT_BASE, strict: false }; + return withEnv({ BILI_WATCHDOG_FAILURE_LIMIT: "2", BILI_CONFIG_FILE: "/nonexistent/bili-claude-watchdog-test.json" }, async () => { + const f = tickFixture(); + delete f.deps.failureLimit; + await watchdogTick(f.state, plan, f.deps, (m) => f.logs.push(m)); + assert.equal(f.ensureCalls.length, 0, "first failure accumulates under limit 2"); + await watchdogTick(f.state, plan, f.deps, (m) => f.logs.push(m)); + assert.equal(f.ensureCalls.length, 1, "second consecutive failure respawns"); + assert.equal(f.state.failures, 0); + }); +}); + +test("#4006: startWatchdog resolves BILI_WATCHDOG_INTERVAL_MS when deps omit intervalMs", async () => { + const f = tickFixture(); + const state: MutableWatchdogState = { origin: ORIGIN, failures: 0 }; + return withEnv({ BILI_WATCHDOG_INTERVAL_MS: "1000", BILI_CONFIG_FILE: "/nonexistent/bili-claude-watchdog-test.json" }, async () => { + const timer = startWatchdog(state, { port: ZONE_PORT_BASE, strict: false }, (m) => f.logs.push(m), f.deps); + try { + const deadline = Date.now() + 5000; + while (f.ensureCalls.length === 0 && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50)); + assert.ok(f.ensureCalls.length >= 1, "respawn fired within the floor interval — the default 30s tick never would"); + } finally { + clearInterval(timer); + } + }); +}); + test("main: NODE_TEST_CONTEXT short-circuits before anything runs", async () => { let stdio = 0; await withEnv({ NODE_TEST_CONTEXT: "1" }, async () => { diff --git a/tests/knobs-config-precedence.test.ts b/tests/knobs-config-precedence.test.ts index 96109fc827..54289ae891 100644 --- a/tests/knobs-config-precedence.test.ts +++ b/tests/knobs-config-precedence.test.ts @@ -496,6 +496,38 @@ test("#3619 stagger knobs: undefined default (caller composes), ms file tier, du clearConfig(); }); +test("#4006 lane watchdog knobs: defaults 30000/3, file tier, env precedence, floors", () => { + clearConfig(); + assert.equal(knobs.laneWatchdogIntervalMs(), 30_000); + assert.equal(knobs.laneWatchdogFailureLimit(), 3); + + setConfig({ watchdog: { intervalMs: 5000, failureLimit: 2 } }); + assert.equal(knobs.laneWatchdogIntervalMs(), 5000); + assert.equal(knobs.laneWatchdogFailureLimit(), 2); + + withEnv({ BILI_WATCHDOG_INTERVAL_MS: "7000", BILI_WATCHDOG_FAILURE_LIMIT: "5" }, () => { + assert.equal(knobs.laneWatchdogIntervalMs(), 7000, "env wins over file"); + assert.equal(knobs.laneWatchdogFailureLimit(), 5); + }); + + // garbage / out-of-range values fall back to the default and never throw + setConfig({ watchdog: { intervalMs: "soon", failureLimit: 0 } }); + assert.equal(knobs.laneWatchdogIntervalMs(), 30_000); + assert.equal(knobs.laneWatchdogFailureLimit(), 3); + withEnv({ BILI_WATCHDOG_INTERVAL_MS: "junk", BILI_WATCHDOG_FAILURE_LIMIT: "-1" }, () => { + assert.equal(knobs.laneWatchdogIntervalMs(), 30_000); + assert.equal(knobs.laneWatchdogFailureLimit(), 3); + }); + // sub-second intervals floor out to the default (seconds-vs-ms typo guard) + withEnv({ BILI_WATCHDOG_INTERVAL_MS: "5" }, () => { + assert.equal(knobs.laneWatchdogIntervalMs(), 30_000); + }); + withEnv({ BILI_WATCHDOG_INTERVAL_MS: "1000" }, () => { + assert.equal(knobs.laneWatchdogIntervalMs(), 1000, "the floor itself is accepted"); + }); + clearConfig(); +}); + test("teardown", () => { if (previousConfigFile === undefined) delete process.env.BILI_CONFIG_FILE; else process.env.BILI_CONFIG_FILE = previousConfigFile; diff --git a/tests/zcode-mcp-entry.test.ts b/tests/zcode-mcp-entry.test.ts index 6935982d19..ec4f942ec7 100644 --- a/tests/zcode-mcp-entry.test.ts +++ b/tests/zcode-mcp-entry.test.ts @@ -156,6 +156,30 @@ test("externally-owned attach posture never respawns — it waits (#1821)", asyn assert.equal(fx.state.failures, 0); }); +test("#4006: without an injected failureLimit the tick resolves the knob live (env tier)", async () => { + const savedLimit = process.env.BILI_WATCHDOG_FAILURE_LIMIT; + const savedCfg = process.env.BILI_CONFIG_FILE; + process.env.BILI_CONFIG_FILE = "/nonexistent/bili-zcode-watchdog-test.json"; + process.env.BILI_WATCHDOG_FAILURE_LIMIT = "2"; + try { + const fx = tickFixture(ORIGIN); + fx.deps = { ...fx.deps, failureLimit: undefined }; + await runTicks(fx, false, 1); + assert.equal(fx.ensureCalls.length, 0, "first failure accumulates under limit 2"); + await runTicks(fx, false, 1); + assert.equal(fx.ensureCalls.length, 1, "second consecutive failure respawns"); + assert.equal(fx.state.failures, 0); + delete process.env.BILI_WATCHDOG_FAILURE_LIMIT; + const fx2 = tickFixture(ORIGIN); + fx2.deps = { ...fx2.deps, failureLimit: undefined }; + await runTicks(fx2, false, 2); + assert.equal(fx2.ensureCalls.length, 0, "env unset → built-in default limit 3 still accumulates"); + } finally { + if (savedLimit === undefined) delete process.env.BILI_WATCHDOG_FAILURE_LIMIT; else process.env.BILI_WATCHDOG_FAILURE_LIMIT = savedLimit; + if (savedCfg === undefined) delete process.env.BILI_CONFIG_FILE; else process.env.BILI_CONFIG_FILE = savedCfg; + } +}); + test("main() short-circuits under NODE_TEST_CONTEXT", async () => { assert.notEqual(process.env.NODE_TEST_CONTEXT, undefined); await main(); diff --git a/website/config-reference/process.yaml b/website/config-reference/process.yaml index 6a0632a4e6..813f13c443 100644 --- a/website/config-reference/process.yaml +++ b/website/config-reference/process.yaml @@ -380,6 +380,33 @@ entries: desc_en: "Repeat interval for the EPERM alert; 0 logs it once." desc_zh: "EPERM 告警的重复间隔;0 只记录一次。" desc_ja: "EPERM アラートの繰り返し間隔。0 の場合は 1 回のみログ出力する。" + - key: watchdog + type: object + default: "{} (all defaults)" + group: process + id: tt.watchdog + site_group: proc + desc_en: "Native-lane proxy respawn watchdog cadence (per-session zcode/claude/kimi MCP entries, #4006)." + desc_zh: "原生车道 proxy 重生看门狗节拍(每会话的 zcode/claude/kimi MCP entry,#4006)。" + desc_ja: "ネイティブレーンの proxy 再生 watchdog の間隔(セッションごとの zcode/claude/kimi MCP エントリ、#4006)。" + site_en: "watchdog — native-lane proxy respawn watchdog cadence: intervalMs 30000 (floor 1000) · failureLimit 3." + site_zh: "watchdog —— 原生车道 proxy 重生看门狗节拍:intervalMs 30000(下限 1000)· failureLimit 3。" + - key: watchdog.intervalMs + type: number + default: "30000 (floor 1000)" + env: BILI_WATCHDOG_INTERVAL_MS + group: process + desc_en: "Health-probe tick of the lane watchdogs; worst-case recovery window after an externally killed lane proxy = interval x failureLimit (~90 s at defaults - the 64 s measured in #4006). Values below 1000 fall back to the default (seconds-vs-ms typo guard)." + desc_zh: "车道看门狗的健康探针节拍;车道 proxy 被外部杀死后的最坏恢复窗口 = interval × failureLimit(默认约 90 秒——#4006 实测 64 秒)。低于 1000 的值回退默认值(秒/毫秒笔误防护)。" + desc_ja: "レーン watchdog のヘルスプローブ間隔;外部から kill されたレーン proxy の最悪復旧ウィンドウ = interval × failureLimit(デフォルトで約 90 秒——#4006 で実測 64 秒)。1000 未満の値はデフォルトにフォールバック(秒/ミリ秒の誤入力ガード)。" + - key: watchdog.failureLimit + type: number + default: "3" + env: BILI_WATCHDOG_FAILURE_LIMIT + group: process + desc_en: "Consecutive failed probes before the lane watchdog respawns the proxy." + desc_zh: "车道看门狗重生 proxy 前允许的连续失败探针次数。" + desc_ja: "レーン watchdog が proxy を再生するまでの連続プローブ失敗回数。" - key: storage type: object default: "{} (all defaults)" diff --git a/website/docs/index.html b/website/docs/index.html index 4b1172324e..7ae77bca79 100644 --- a/website/docs/index.html +++ b/website/docs/index.html @@ -300,6 +300,7 @@

Other top-level fields

  • network — transport timeouts, replays & the 429 egress governor: upstreamTimeoutMs 720000 · upstreamFirstByteMs 720000 · requestWatchdogMs 2× · replayRetryMax 3 · replayRetryBaseMs 1500 · keepAliveTimeoutMs 5000 · clientErrorBackstopMs 30000 · exposureLogIntervalMs 3600000 · streamKeepAliveMs 15000 · preflightHoldMs 30000 · preflightDeadEndCooldownMs 300000 · proxyKeepAliveMaxMs 55000 · throttle429Enabled true · throttle429MaxConsecutive 5 · throttle429BaseDelayMs 2000 · throttle429MaxDelayMs 30000 · throttle429Scope credential.
  • guardrails — pi/omp plugin tool-output + stream text-run guardrails: bashTimeout 60 · maxOutputBytes 50000 · repetition true · textRunThreshold 200.
  • persist — session persistence to disk: enabled true · zstd false · debounceMs 500 · maxDelayMs 5000 · tailTokens 16384 · epermAlertThreshold 5 · epermAlertRepeatMs 0.
  • +
  • watchdog — native-lane proxy respawn watchdog cadence: intervalMs 30000 (floor 1000) · failureLimit 3.
  • storage — unified storage sidecar: unified legacy — file tier selects the lane-wide storage mode; env BILI_STORAGE_UNIFIED wins when set.
  • sessions — max 256 (LRU) · gc { enabled false, maxAgeDays 7, maxTokens 1000000, intervalMs 3600000 } — GC is opt-in; user data is never pruned silently.
  • plugin.snapshotCapBytes — fork API snapshot cap (default 100 MiB; 0 disables snapshots).
  • diff --git a/website/main.js b/website/main.js index 19461eee64..ba226fea17 100644 --- a/website/main.js +++ b/website/main.js @@ -135,6 +135,7 @@ "tt.network": "network — transport timeouts, replays & the 429 egress governor: upstreamTimeoutMs 720000 · upstreamFirstByteMs 720000 · requestWatchdogMs 2× · replayRetryMax 3 · replayRetryBaseMs 1500 · keepAliveTimeoutMs 5000 · clientErrorBackstopMs 30000 · exposureLogIntervalMs 3600000 · streamKeepAliveMs 15000 · preflightHoldMs 30000 · preflightDeadEndCooldownMs 300000 · proxyKeepAliveMaxMs 55000 · throttle429Enabled true · throttle429MaxConsecutive 5 · throttle429BaseDelayMs 2000 · throttle429MaxDelayMs 30000 · throttle429Scope credential.", "tt.guardrails": "guardrails — pi/omp plugin tool-output + stream text-run guardrails: bashTimeout 60 · maxOutputBytes 50000 · repetition true · textRunThreshold 200.", "tt.persist": "persist — session persistence to disk: enabled true · zstd false · debounceMs 500 · maxDelayMs 5000 · tailTokens 16384 · epermAlertThreshold 5 · epermAlertRepeatMs 0.", + "tt.watchdog": "watchdog — native-lane proxy respawn watchdog cadence: intervalMs 30000 (floor 1000) · failureLimit 3.", "tt.storage": "storage — unified storage sidecar: unified legacy — file tier selects the lane-wide storage mode; env BILI_STORAGE_UNIFIED wins when set.", "tt.sessions": "sessions — max 256 (LRU) · gc { enabled false, maxAgeDays 7, maxTokens 1000000, intervalMs 3600000 } — GC is opt-in; user data is never pruned silently.", "tt.snap": "plugin.snapshotCapBytes — fork API snapshot cap (default 100 MiB; 0 disables snapshots).", @@ -393,6 +394,7 @@ "tt.network": "network —— 传输超时、重放与 429 出站治理:upstreamTimeoutMs 720000 · upstreamFirstByteMs 720000 · requestWatchdogMs 2× · replayRetryMax 3 · replayRetryBaseMs 1500 · keepAliveTimeoutMs 5000 · clientErrorBackstopMs 30000 · exposureLogIntervalMs 3600000 · streamKeepAliveMs 15000 · preflightHoldMs 30000 · preflightDeadEndCooldownMs 300000 · proxyKeepAliveMaxMs 55000 · throttle429Enabled true · throttle429MaxConsecutive 5 · throttle429BaseDelayMs 2000 · throttle429MaxDelayMs 30000 · throttle429Scope credential。", "tt.guardrails": "guardrails —— pi/omp 插件工具输出与流式 text-run 守卫:bashTimeout 60 · maxOutputBytes 50000 · repetition true · textRunThreshold 200。", "tt.persist": "persist —— 会话落盘持久化:enabled true · zstd false · debounceMs 500 · maxDelayMs 5000 · tailTokens 16384 · epermAlertThreshold 5 · epermAlertRepeatMs 0。", + "tt.watchdog": "watchdog —— 原生车道 proxy 重生看门狗节拍:intervalMs 30000(下限 1000)· failureLimit 3。", "tt.storage": "storage —— 统一存储边车:unified legacy —— 文件层选定全 lane 存储模式;设置了 BILI_STORAGE_UNIFIED 时环境变量优先。", "tt.sessions": "sessions —— max 256 (LRU) · gc { enabled false, maxAgeDays 7, maxTokens 1000000, intervalMs 3600000 } —— GC 为可选:用户数据不会被悄悄清理。", "tt.snap": "plugin.snapshotCapBytes —— fork API 快照上限(默认 100 MiB;0 禁用快照)。",