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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CLIENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,18 @@ two small node scripts that do the work around the client:
happens per session. Remove with `bili plugin remove zcode` (strips only
bili's entries, reverts `hooks.enabled` when it was the one to enable it,
and restores the provider store from its snapshot).
- **Open sessions after removal (#2155):** `bili plugin remove zcode` cannot
reach into already-open client windows — their MCP child is gone but the
proxy-side binding (session metadata) survives. Such zombie sessions are
detected after 5 consecutive nudged rounds with no plugin header, no bili
tools on the wire, and no compression: the session self-heals by
**degrading to proxy mode** — the ACP tools are re-injected wire-side and
the proxy owns compression again (the nudge stays). When wire injection is
unavailable (`compress.injectTool=false`) the nudge is suppressed instead
until a compression reduction resumes. A returning plugin header (client
restarted / reinstalled) restores plugin mode on the first request. The
remove command prints a note when live sessions were seen in the last 10
minutes; the web UI badges such sessions ("heal").
- **Per-session bootstrap:** each ZCode session spawns the MCP child as a
direct process; at startup it attaches to a healthy proxy
(`BILLION_CONTEXT_PROXY`) or spawns its own on an ephemeral port, then
Expand Down
1 change: 1 addition & 0 deletions CLIENTS.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ fork 继承同一面;Antigravity 自带用户插件系统 —— `plugins/<name>
三种对齐模式:`/bili/` URL 前缀、GUI「设置 → 网络」证书 MITM(HTTP 代理 + 根 CA 路径)、原生插件模式(`bili plugin install zcode`,#1145)。ZCode 的扩展面是 Claude-Code 形状但纯声明式:`~/.zcode/cli/config.json` 里的用户级 hooks 与 stdio MCP server,没有进程内 JS 接缝。所以原生通道随包带两个小 node 脚本,在客户端外围干活:

- **安装:** `bili plugin install zcode` 写 `~/.zcode/cli/config.json`:置 `hooks.enabled = true`、追加一条 `SessionStart` process hook(`node <root>/dist/zcode/bootstrap-hook.js`)、注册 stdio MCP server `mcp.servers.bili`(`node <root>/dist/zcode/mcp-entry.js`)。已存在的用户自有 `mcp.servers.bili` 条目**绝不覆盖** —— 安装器会响亮地拒绝。安装时不冻结任何 URL;路由按会话发生。卸载:`bili plugin remove zcode`(只剥离 bili 自己的条目、由 bili 启用的 `hooks.enabled` 予以还原、provider store 从快照恢复)。
- **卸载后的已开会话(#2155):**`bili plugin remove zcode` 无法触及已开着的客户端窗口 —— 它们的 MCP 子进程已死,但代理侧的会话绑定(session metadata)仍在。这类僵尸会话在连续 5 轮“有 nudge、无插件头、线上无 bili 工具、零压缩”后被检测到,随即**自愈降级为代理模式** —— ACP 工具改由代理线上回注、压缩重新由代理接管(nudge 保留)。若线上注入不可用(`compress.injectTool=false`)则改为静默 nudge,直到出现一次压缩缩减自动解除。插件头重现(客户端重启/重装)即在同一请求内恢复 plugin 模式。remove 命令在近 10 分钟内见过活跃会话时会打印提示;web UI 会为这类会话挂“自愈”徽标。
- **每会话自举:** 每个 ZCode 会话把 MCP 子进程作为直接子进程拉起;启动时附着到健康代理(`BILLION_CONTEXT_PROXY`)或在临时端口自拉起,然后在 mkdir 锁文件下对生效的 provider store 做幂等 JSON 手术:每个可路由 provider 条目的 `baseURL` 变为 `http://127.0.0.1:<port>/bili/<上游>`(你设的自定义 baseURL 原样保留在包装之内)。两代 store 都处理:legacy `~/.zcode/v2/config.json`(`provider.<id>.options.baseURL`)与 v3.14+ personal store `~/.zcode/v2/provider_config.json`(`config.providerConfigRules.providerRules[].config.api.baseUrl`)—— 两者并存时以新 store 为准(其中哪些条目路由、哪些被跳过见下方路由范围)。原始文件按每次用户编辑快照到 `<file>.bili-bak`(快照永远反映你最后一次真实状态,绝不记录 bili 自己的写入);其余所有键逐字节保留。旧世代客户端在启动时加载 provider 配置 —— 安装后重启一次 ZCode;新版构建可在会话中途感知路由变化(约 1 s 轮询)。`SessionStart` hook 机会性地跑同一套自举(仅附着 —— 绝不 spawn);它的非阻塞竞态被设计为可容忍:第一轮可以走 wire 模式,不变量是 `baseURL` 永不指向死端口。
- **Plugin 模式盖章:** MCP 子进程对着存活代理清单核验 ACP 工具列表之后,才给路由条目加 `headers["x-bili-plugin"] = "zcode"` —— 此前流量走 wire 模式。工具调用经每次调用的 `conversation_id` 参数绑定(#760)。
- **路由范围(#1622):** 原生模式包装**每一个**有可用 http(s) `baseURL` 的 provider 条目 —— 与进程内原生(pi/dsh)的「所有 provider 都吃压缩」语义一致 —— 而不是只包 bigmodel coding-plan 账号。无法安全包装的条目会被跳过并记录原因,而非静默丢弃:
Expand Down
44 changes: 44 additions & 0 deletions TECHNICAL-NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -298,3 +298,47 @@ so direct callers cannot corrupt a store either. Mixing *commands* is fine
mixing *writers* is what the guard forbids. `bili plugin update [client]`
is the one command that drives every lane through its own owner and prints
the per-lane update path (`bili plugin list` shows the same per-lane channel).

## Stuck-session self-heal — detection constants and remedies (#2155)

Three failure shapes share one detector family in `src/session-self-heal.ts`,
evaluated once per request (after `prepare`, on the nudge-carrying lanes only;
bypass and side lanes never earn credit):

- **D2 zombie plugin lane** — the plugin was uninstalled (or its MCP child
died) but already-open client windows keep the session plugin-bound
(sticky `metadata.pluginAgent`, `src/server.ts`). Signal: 5 consecutive
rounds (`SELF_HEAL_WINDOW`) that were nudged, carried **no** `x-bili-plugin`
header, declared **no** bili tools on the wire, and produced **no**
compression reduction. Remedy: **degrade to proxy mode** — the single
`pluginMode` flip (`pluginAgent !== undefined && !pluginLaneDegraded(session)`)
re-injects the ACP tools wire-side, re-arms the compress rewriter, CCR
stamping and absorb, and **keeps the nudge** (the tools are back). When wire
injection is unavailable (`compress.injectTool=false` → `degradeAvailable`
false) the remedy falls back to **suppress-nudge**. Recovery: the live
plugin header (`pluginLaneRestore`, hoisted BEFORE the `pluginMode` flip so
the first header-bearing request is already plugin mode — the sticky
`pluginAgent` must NOT be used as the restore signal or the degrade clears
one round after arming). The binding is kept, never erased.
- **D1 nudge idle** (non-plugin generalization) — 5 consecutive nudged rounds
with zero reduction and zero bili tool uses. Remedy: suppress the nudge at
all four `willInjectNudge` gates (`&& !nudgeSuppressed(session)`, covering
the emergency path too). Recovery: any compression reduction or bili tool
use lifts the suppression.
- **D3 gateway-killed summaries** — a **non-streaming** preflight summary that
dies with HTTP 524/504 (Cloudflare class) is not retried in place (the old
transient-retry path burned ~100 s per attempt against a dead gateway);
instead the session learns `metadata.preflightStreamSummary = true` on the
**first** hit and the summary is re-requested as SSE — the same learned
store as the manual `compress.streamSummary` knob (#2133), auto-armed.
The cascade is honored in both directions: an explicit `streamSummary:
false` anywhere (global → provider → model) is the operator's opt-out —
neither learn path arms and a stale learned flag is ignored
(`streamSummaryOff` in `PreflightDeps`).

Observability: `session.metadata.selfHeal = { detected, action, since }` is
exposed in `/__bili/sessions`, badged in the web UI ("heal"), and every
transition logs one `[self-heal]` line (detect + recovery). `bili plugin
remove <client>` best-effort queries the live proxy (instance file →
`GET /__bili/sessions`, 2.5 s timeout, silent on failure) and prints a note
when sessions of that client were active within the last **10 minutes**.
10 changes: 10 additions & 0 deletions TECHNICAL-NOTES.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,13 @@ bili 永不拥有用户数据:每个被启动的客户端都跑在**真实 home*
| **hermes** | `~/.hermes/plugins/billion-context/`(拷贝文件 + 指向全局 dist 的 `bili.json` sidecar) | **`bili plugin update hermes`** 重新拷文件;sidecar 跟随全局安装 |

这在代码里强制,不只是约定:自更新器(`src/update.ts` → `hostManagedInstall`)识别 pnpm 虚拟 store(`.pnpm`)或宿主 agent 树(pi / opencode / dsh / kimi / omp home)下的安装目录并**跳过**它们;`installViaTarball` 从结构上拒绝它们,直接调用方也无法损坏 store。混用*命令*没问题(`dsh plugin add` ≡ `bili plugin install dsh` —— 同一通道、同一记录);混用*写者*才是守卫禁止的事。`bili plugin update [client]` 是唯一能驱动每条 lane 走各自 owner 的命令,并打印逐 lane 更新路径(`bili plugin list` 显示同样的逐 lane 通道)。

## 会话卡死自愈 —— 检测常量与补救(#2155)

三种故障形态共享 `src/session-self-heal.ts` 里的同一族检测器,每请求评估一次(prepare 之后,仅有 nudge 的主车道;旁路/侧请求车道不积累信用):

- **D2 僵尸插件车道** —— 插件已卸载(或 MCP 子进程已死)但已开着的客户端窗口仍带着插件绑定(粘滞 `metadata.pluginAgent`)。信号:连续 5 轮(`SELF_HEAL_WINDOW`)被 nudge、**无** `x-bili-plugin` 头、线上**无** bili 工具声明、**零**压缩缩减。补救:**降级为代理模式** —— 单点 `pluginMode` 翻转(`pluginAgent !== undefined && !pluginLaneDegraded(session)`)线上回注 ACP 工具、重新接管压缩 rewriter/CCR 盖章/absorb,并**保留 nudge**(工具回来了)。线上注入不可用时(`compress.injectTool=false` → `degradeAvailable=false`)退为**静默 nudge**。恢复:**活的**插件头(`pluginLaneRestore`,在 `pluginMode` 翻转**之前**调用,首个带头请求即恢复 plugin 模式 —— 恢复信号绝不能用粘滞 `pluginAgent`,否则降级一轮后即被自己清掉)。绑定保留、永不抹除。
- **D1 nudge 空转**(非插件泛化)—— 连续 5 轮被 nudge 却零缩减、零 bili 工具调用。补救:在全部四处 `willInjectNudge` 门加 `&& !nudgeSuppressed(session)`(覆盖 emergency 路径)。恢复:任一次压缩缩减或 bili 工具调用即解除。
- **D3 网关杀摘要** —— **非流式** preflight 摘要以 HTTP 524/504(Cloudflare 类)死亡时不再原地重试(旧的 transient 重试对着死网关每次烧 ~100 秒);会话在**首次**命中即学习 `metadata.preflightStreamSummary = true` 并改用 SSE 重取摘要 —— 与手动 `compress.streamSummary` 旋钮(#2133)同一学习存储,自动武装。级联双向被尊重:任一级显式 `streamSummary: false`(global → provider → model)即操作员 opt-out —— 两条学习路径都不武装、已学习的旧标志被忽略(`PreflightDeps.streamSummaryOff`)。

可观测:`session.metadata.selfHeal = { detected, action, since }` 进 `/__bili/sessions`、web UI 挂"自愈"徽标、每次转换一行 `[self-heal]` 日志(检测+恢复)。`bili plugin remove <client>` 尽力查询活代理(instance 文件 → `GET /__bili/sessions`,2.5 秒超时,失败静默),该客户端近 **10 分钟**内有活跃会话时打印提示。
7 changes: 5 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import { startAdvisoryWatcher, getAdvisoryState, advisoryDeferring, advisoryBloc
import { startReleaseNotesWatcher } from "./update-notes.js";
import { resolveProxy } from "./upstream-proxy.js";
import { runMcpStdio } from "./mcp.js";
import { PLUGIN_AGENTS, isPluginAgent, pluginInstall, pluginRemove, pluginStatusAll, pluginUpdate, type PluginAgent } from "./plugin-install.js";
import { PLUGIN_AGENTS, isPluginAgent, pluginInstall, pluginRemove, pluginStatusAll, pluginUpdate, warnActivePluginSessions, type PluginAgent } from "./plugin-install.js";
import { runLaunch, runTestPi, isLaunchClient, type ClientName } from "./launcher.js";
import { exportSession } from "./export.js";
import { renderJson, renderText, runDiff } from "./acp-cache-diff.js";
Expand Down Expand Up @@ -486,7 +486,10 @@ export async function main(): Promise<void> {
}
if (pluginAction === "remove") {
try {
console.log(pluginRemove(pluginAgent!));
// #2155: best-effort note about still-open client windows.
const removed = pluginRemove(pluginAgent!);
const warn = await warnActivePluginSessions(pluginAgent!);
console.log(warn === "" ? removed : removed + "\n" + warn);
} catch (error) {
console.error(`bili plugin: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
Expand Down
30 changes: 29 additions & 1 deletion src/plugin-install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
import { applyEdits, modify as jsoncModify, parse as jsoncParse, type ParseError } from "jsonc-parser";
import { resolveDshHome, resolveHermesHome, resolveKimiHome, resolvePiHome } from "./client-config.js";
import { resolveClaudeNativePort } from "./config.js";
import { lanePreferredPort } from "./instance.js";
import { lanePreferredPort, readProxyInstanceFile } from "./instance.js";
import { DSH_PACKAGE, dshBundleInstalled, dshHasLegacyManagedBlock, dshProfileDependsOnBili, dshProfileDepSpec, dshProfileDirs, isRegistryDepSpec, planDshSpawn, refreshDshProfileBundles, runDshPlugin, stripLegacyManagedBlock } from "./dsh-channel.js";
import { fetchRegistryVersion } from "./update.js";
import { restoreKimiBackup, unrouteKimi } from "./kimi/native.js";
Expand Down Expand Up @@ -2145,6 +2145,34 @@ export function pluginRemove(agent: PluginAgent): string {
return agent === "pi" ? piRemove() : agent === "omp" ? ompRemove() : agent === "claude" ? claudeRemove() : agent === "codex" ? codexRemove() : agent === "dsh" ? dshRemove() : agent === "kimi" ? kimiRemove() : agent === "hermes" ? hermesRemove() : agent === "zcode" ? zcodeRemove() : opencodeRemove();
}

/** #2155 uninstall guardrail (advisory half): `bili plugin remove <agent>`
* should tell the user that already-open client windows keep talking to the
* proxy as zombie plugin sessions (their MCP subprocess died with the remove,
* but the session binding is sticky). The proxy side self-heals those sessions
* (degrade to proxy mode); this note closes the loop for the human. Best-effort:
* any failure (no proxy, endpoint down, odd shape) stays silent. */
export async function warnActivePluginSessions(agent: PluginAgent): Promise<string> {
try {
const inst = readProxyInstanceFile();
if (inst === undefined) return "";
const res = await fetch(inst.origin.replace(/\/$/, "") + "/__bili/sessions", { signal: AbortSignal.timeout(2500), headers: { accept: "application/json" } });
if (!res.ok) return "";
const data = (await res.json()) as { sessions?: Array<Record<string, unknown>> };
const sessions = Array.isArray(data.sessions) ? data.sessions : [];
const cutoff = Date.now() - 10 * 60 * 1000;
let live = 0;
for (const s of sessions) {
const hint = typeof s["clientHint"] === "string" ? s["clientHint"] : "";
const seen = typeof s["lastSeen"] === "string" ? Date.parse(s["lastSeen"]) : Number.NaN;
if (hint === agent && Number.isFinite(seen) && seen >= cutoff) live += 1;
}
if (live === 0) return "";
return `note: ${live} active ${agent} session(s) seen in the last 10 minutes — already-open client windows keep running; their plugin lane is gone and the proxy self-heals them to proxy mode (#2155). Reload/restart the client to fully detach.`;
} catch {
return "";
}
}

export function pluginStatusAll(): Array<{ agent: string; status: string; channel: string }> {
const checks: Array<[PluginAgent, () => string]> = [
["pi", piStatus],
Expand Down
Loading
Loading